我正在做一些机器学习的在线课程,我们在DNN模型中使用以下评分函数进行回归:
def r_squared(y_true, y_pred):
# 1 - ((y_i - y_hat_i)^2 / (y_i - y_sum)^2)
numerator = tf.reduce_sum(tf.square(tf.subtract(y_true, y_pred)))
denominator = tf.reduce_sum(tf.square(tf.subtract(y_pred, tf.reduce_mean(y_true))))
r2 = tf.clip_by_value(tf.subtract(1.0, tf.div(numerator, denominator)), clip_value_min = 0.0, clip_value_max = 1.0)
return r2
... later ...
model.compile(loss = "mse", # mean-square-error,
optimizer = optimizer(lr = learning_rate),
metrics = [r_squared])现在,当模型和所有东西都正常工作时,我想进行网格搜索,以确定模型的最佳参数。但是,当尝试将r_squared函数与网格搜索作为记分器一起使用时,我得到了几个错误:
grid = GridSearchCV(estimator = estimator,
param_grid = param_grid,
n_jobs = 1,
verbose = 1,
cv = folds,
scoring = make_scorer(FeedForward.r_squared, greater_is_better=True))结果如下:
TypeError: Input 'y' of 'Sub' Op has type float64 that does not match type float32 of argument 'x'.在这附近:
r2 = tf.clip_by_value(tf.subtract(1.0, tf.div(numerator, denominator)), clip_value_min = 0.0, clip_value_max = 1.0)因此,我按如下方式更改了这行:
r2 = tf.clip_by_value(tf.subtract(1.0, tf.div(tf.cast(numerator, tf.float32), tf.cast(denominator, tf.float32))), clip_value_min = 0.0, clip_value_max = 1.0)这将导致:
ValueError: scoring must return a number, got Tensor("mul:0", shape=(), dtype=float32) (<class 'tensorflow.python.framework.ops.Tensor'>) instead. (scorer=score)虽然我理解错误并可以在调试器中确认它,但我发现自己无法解决这个问题,即使在googling上搜索错误也无法解决问题。这可能是因为--不必提--对tensorflow还不够熟悉。
那么如何从张量中得到值呢?我到底是在做正确的事情,还是别的什么地方错了?
发布于 2019-06-17 16:40:42
问题是混合使用TensorFlow/Keras和scikit-learn。Keras指标需要使用keras.backend函数来实现,但是scikit-learn函数不是符号的,必须使用numpy来实现。
幸运的是,scikit learn已经实现了R^2分数作为sklearn.metrics.r2_score,所以你可以这样使用它:
from sklearn.metrics import r2_score
grid = GridSearchCV(estimator = estimator,
param_grid = param_grid,
n_jobs = 1,
verbose = 1,
cv = folds,
scoring = make_scorer(r2_score, greater_is_better=True))您的Keras指标不需要更改,您必须保留该指标的两个实现,这有点奇怪,但它就是这样的。
https://stackoverflow.com/questions/56625762
复制相似问题