我认为我的 Keras 多输出编码有问题,与 Sequential 模型相比,这会导致高损失。请帮我看看哪一部分是错的。
import os, random, string, pandas, math, numpy
import tensorflow as tf
from tensorflow import keras
训练数据:
feature_data = [] # common feature data
label_data = [] # for multiple outputs
single_data = [] # for single output
size = 10000
features = ['x1', 'x2']
labels = ['y1', 'y2']
for i in range(size):
a = random.random()
b = random.random()
c = math.sin(a)
d = math.cos(b)
feature = [a, b]
label = [c, d]
feature_data.append(feature)
label_data.append(label)
single_data.append(c)
这是我的单输出模型,效果很好:loss < 2e-05
single = keras.Sequential([
keras.layers.Dense(2, input_shape=(2,), activation=tf.nn.softmax),
keras.layers.Dense(4, activation=tf.nn.softmax),
keras.layers.Dense(1)])
optimizer = tf.optimizers.RMSprop(learning_rate=0.001)
single.compile(loss='mse', optimizer=optimizer, metrics=['mae'])
single.fit(x=feature_data, y=single_data, epochs=100, batch_size=100)
这应该是相同的多输出模型,但损失非常高:0.1
def build_model():
input_shape=(2, )
inputs = keras.Input(shape=input_shape)
outputs = []
for label in labels:
u = keras.layers.Dense(2, input_shape=input_shape, activation=tf.nn.softmax)(inputs)
v = keras.layers.Dense(4, activation=tf.nn.softmax)(u)
w = keras.layers.Dense(1, name=label)(v)
outputs.append(w)
model = keras.Model(inputs = inputs, outputs = outputs)
optimizer = tf.optimizers.RMSprop(learning_rate=0.001)
model.compile(loss='mse', optimizer=optimizer, metrics=['mae'])
return model
model = build_model()
model.fit(x=feature_data, y=label_data, epochs=100, batch_size=100)
我猜输入层或标签数据格式有问题,但仍然不知道如何修复它。请帮忙。