def custom_metric(y_prem):
def score_func(y_true, y_pred):
diff = y_pred - y_true
return tf.reduce_sum(diff[y_prem>=y_pred])
return score_func
model = tf.keras.models.Sequential([
tf.keras.layers.Dense(32, input_shape=[len(X_train[0, :])], activation='tanh'),
tf.keras.layers.Dense(8, input_shape=[len(X_train[0, :])], activation='linear'),
tf.keras.layers.Dense(4, input_shape=[len(X_train[0, :])], activation='tanh'),
tf.keras.layers.Dense(1, activation='relu'),
])
model.compile(optimizer='adam', loss='mean_squared_error', metrics=[custom_metric(y_prem)])
model.summary()
model.fit(X_train_minmax, y_train, epochs=30, batch_size=len(y_train))
y_prem 和 y_train 大小相同(50646)
我試圖定義這個自定義度量函式,其中 y_prem 是預測大小的向量。我只想在 pred 低于 y_prem 的索引上對 pred 和 true 之間的差異求和,但是當我訓練模型時,我收到一條錯誤訊息:
File "C:/Users/zehavi kelman/PycharmProjects/Accident_predicting/simpego_test.py", line 61, in score_func *
return K.sum(diff[y_prem>=y_pred])
ValueError: Shapes (50646, 1) and (50646, 50646) are incompatible
我該如何解決?
uj5u.com熱心網友回復:
我不確定你想做什么,但我實作了一個不輸出錯誤訊息的可重現示例(注意x和y形狀):
import tensorflow as tf
x = tf.random.uniform(shape=[50646, 5], minval=0, maxval=1)
y = tf.random.uniform(shape=[50646, 1], minval=0, maxval=1)
y_prem = tf.random.uniform(shape=[50646, 1], minval=0, maxval=1)
def custom_metric(y_prem):
def score_func(y_true, y_pred):
diff = y_pred - y_true
return tf.reduce_sum(diff[y_prem>=y_pred])
return score_func
model = tf.keras.models.Sequential([
tf.keras.layers.Dense(32, input_shape=[len(x[0, :])], activation='tanh'),
tf.keras.layers.Dense(8, activation='linear'),
tf.keras.layers.Dense(4, activation='tanh'),
tf.keras.layers.Dense(1, activation='relu'),
])
model.compile(optimizer='adam', loss='mean_squared_error', metrics=[custom_metric(y_prem)])
model.summary()
model.fit(x, y, epochs=30, batch_size=len(y))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/441957.html
