def myloss(matrix_true, matrix_pre):
loss = tf.reduce_sum(matrix_true - matrix_pre)
return loss
例如上面这一段,matrix_true和matrix_true都是[100, 3]的矩阵,但是在model.fit的时候
history = model.fit(x_train, y_train, epochs=30)
报错
InvalidArgumentError: Index out of range using input dim 2; input has only 2 dims [Op:StridedSlice] name: strided_slice/
另外,自定义损失函数里面的参数顺序是怎样的呢?
为了方便起见,将矩阵改成3*3的,下面是完整的代码
import tensorflow as tf
import numpy as np
from tensorflow import keras
import copy
print(tf.__version__)
x = tf.Variable([[3., 0., 5.], [0., 5., 4.], [3., 3., 0.]])
y = tf.Variable([[3., 0., 6.], [0., 4., 4.], [3., 2., 0.]])
def myloss(matrix_true, matrix_pre):
loss = tf.reduce_sum(matrix_true - matrix_pre)
return loss
model = keras.models.Sequential([
keras.layers.Dense(3, activation='relu', input_shape=x.shape[1:]),
keras.layers.Dense(3, activation='relu'),
keras.layers.Dense(3, activation='relu'),
])
op = keras.optimizers.SGD(0.01)
model.summary()
model.compile(loss=myloss, optimizer=op)
history = model.fit(x, y, epochs=10)
不知道是不是我定义的变量的问题,即便是改成预测值是一维的,也无法成功运行
#%%
import tensorflow as tf
import numpy as np
from tensorflow import keras
print(tf.__version__)
#%%
x = tf.Variable([[3., 0., 5.], [0., 5., 4.], [3., 3., 0.]])
# y = tf.Variable([[3., 0., 6.], [0., 4., 4.], [3., 2., 0.]])
z = tf.Variable([[2.], [3.], [4.]])
def myloss(y_true, y_pred):
loss = tf.reduce_sum(y_true - y_pred)
return loss
model = keras.models.Sequential([
keras.layers.Dense(3, activation='relu', input_shape=x.shape[1:]),
keras.layers.Dense(3, activation='relu'),
keras.layers.Dense(1),
])
op = keras.optimizers.SGD(0.01)
model.summary()
model.compile(loss=myloss, optimizer=op)
#%%
history = model.fit(x, z, epochs=10)