我尝试实现自定义损失功能。损失函数的目标是最大程度地减少: 损失= max(y_actual,y_predicted)/ min(y_actual,y_predicted)
整个脚本如下:
def get_model():
model = Sequential()
model.add(Dense(512, activation = 'relu', input_dim = len(X[0])))
model.add(Dense(512,input_dim = 200, activation = 'relu'))
model.add(Dense(1, activation = 'relu'))
optimizer = keras.optimizers.RMSprop(0.02)
model.compile(loss=custom_loss, optimizer = optimizer)
return model
def custom_loss(y_actual, y_predicted):
error = []
for i in range(len(y_actual)):
if y_predicted[i] > y_actual[i]:
error.append(y_predicted[i]/y_actual[i])
else:
error.append(y_actual[i]/y_predicted[i])
return K.mean(error)
if __name__ == '__main__':
run = 1
X = np.load("vectors.npy")
with open("target2.pickle", "rb") as file:
target_dict = pickle.load(file)
target_strings = [*target_dict]
Y = np.array([])
for str in target_strings:
val = target_dict.get(str)
Y = np.append(Y, val)
for i in range(run):
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2)
model = get_model()
model.fit(X_train, Y_train, verbose=1, epochs = 10)
其中custom_loss(y_actual,y_predicted)是我尝试实现的损失函数。但是,当我运行代码时,出现以下错误:
/.local/lib/python3.8/site-packages/tensorflow/python/keras/backend.py:2261 mean
if x.dtype.base_dtype == dtypes_module.bool:
AttributeError: 'list' object has no attribute 'dtype'
我真的很感谢您的投入,并告诉我是否需要更多信息。
答案 0 :(得分:1)
错误的原因是您正在向tf.keras.backend.Mean传递列表,但是该函数需要张量。
首先,我认为您需要将该列表转换为具有特定dtype的张量。