【发布时间】:2019-10-30 17:16:34
【问题描述】:
我正在做一些机器学习的在线课程,我们在 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 函数与 gridsearch 作为记分器一起使用时,我遇到了几个错误:
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)
虽然我了解错误并且可以在调试器中确认它,但我发现即使使用谷歌搜索错误也无法解决问题。这可能是由于 - 无需提及 - 对 tensorflow 还不够熟悉。
那么如何从张量中获取值?我在这里做的是正确的事情,还是有其他问题?
【问题讨论】:
标签: python tensorflow keras scikit-learn deep-learning