这是我在调用 model.fit 时在第一个时期遇到的错误:
Exception has occurred: ValueError
Layer "functional" expects 2 input(s), but it received 1 input tensors. Inputs received: [<tf.Tensor 'data:0' shape=(None, 128) dtype=float32>]
File "D:\workspace\Machine Learning 545\PSU_classes\cs445_group_project\code\Keras Music Genres Classification\encoder_decoder_feature_extractor.py", line 177, in train_encoder_decoder_model
model.fit(x = X_train,
File "D:\workspace\Machine Learning 545\PSU_classes\cs445_group_project\code\Keras Music Genres Classification\encoder_decoder_feature_extractor.py", line 217, in <module>
trained_model = train_encoder_decoder_model(encoder_decoder_model, X_train, y_train, X_test, y_test)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: Layer "functional" expects 2 input(s), but it received 1 input tensors. Inputs received: [<tf.Tensor 'data:0' shape=(None, 128) dtype=float32>]"
这是我的模型:
def define_encoder_decoder_model(num_features):
# Define the encoder
encoder_inputs = Input(shape=(None, num_features))
encoder_hidden1 = Dense(100, activation='relu')(encoder_inputs)
encoder_hidden2 = Dense(50, activation='relu')(encoder_hidden1)
encoder_lstm = LSTM(25, return_state=True)
encoder_outputs, state_h, state_c = encoder_lstm(encoder_hidden2)
encoder_states = [state_h, state_c]
# Define the decoder
decoder_inputs = Input(shape=(None, 25))
decoder_hidden1 = Dense(50, activation='relu')(decoder_inputs)
decoder_hidden2 = Dense(100, activation='relu')(decoder_hidden1)
decoder_lstm = LSTM(num_features, return_sequences=True, return_state=True)
decoder_outputs, _, _ = decoder_lstm(decoder_hidden2, initial_state=encoder_states)
decoder_dense = Dense(num_features, activation='softmax')
decoder_outputs = decoder_dense(decoder_outputs)
# Define the model that will turn encoder_inputs and decoder_inputs into decoder_outputs
model = Model([encoder_inputs, decoder_inputs], decoder_outputs)
# Compile the model
model.compile(optimizer='adam', loss='categorical_crossentropy',
metrics=['accuracy', 'precision', 'recall', 'f1_score'])
# Summary of the model
model.summary()
return modeltype here
这就是我调用 model.fit 的方式:
def train_encoder_decoder_model(model, X_train, y_train, X_test, y_test):
"""
Trains an encoder-decoder model using the provided data.
Args:
model: The encoder-decoder model to train.
X_train: The input training data.
y_train: The target training data.
X_test: The input test data.
y_test: The target test data.
Returns:
The trained encoder-decoder model.
"""
print("shapes: X_train:", np.shape(X_train)," y_train: ", np.shape(y_train)," X_test: ", np.shape(X_test)," y_test: ", np.shape(y_test))
# Train the model
# append to a file the training log for each epoch
file_logger = FileLogger('training.log')
y_train_T = tf.convert_to_tensor(np.array([y_train]).T)
y_test_T = tf.convert_to_tensor(np.array([y_test]).T)
#x_train = tf.convert_to_tensor(X_train)
y_train = X_train
y_test = X_test
model.fit(x = X_train,
y= y_train,
batch_size=100,
epochs=100,
verbose=2,
validation_data=(X_test, y_test),
callbacks=[file_logger])
return model
这是一个编码器-解码器模型,因此 X_train 数据集等于 y_train,X_test、y_test 也相同。在第一种情况下,训练集的形状是 (799,128),测试数据集是 (299,128)。这些特征表示为“float64”值。
我正在 Visual Studio Code 下运行代码。我将数据预处理为标准化和缩放的数据集,然后将其分为训练数据集和测试数据集,构建我的编码器-解码器模型(请参阅上面的方法),然后尝试训练模型。我得到的是 model.fit“Epoch 1/100”的输出以及上面显示的错误消息。
这个错误是什么以及如何解决?
您的模型是一种编码器-解码器架构,需要两个输入:一个用于编码器,一个用于解码器。
具体:
encoder_inputs (shape (None, num_features))
decoder_inputs (shape (None, 25))
但是,在 model.fit() 调用中,您只提供单个输入 (X_train),这就是模型抛出错误的原因 ->
expects 2 input(s), but it received 1
要解决此问题,您需要确保将两个输入传递给 model.fit() 函数:一个用于编码器,一个用于解码器。以下是如何做到这一点的示例:
1- 确保 X_train 和 y_train 的形状正确以匹配模型的预期:
X_train 应该是编码器的输入。 y_train 应该是解码器的输入。
既然您提到编码器和解码器使用相同的数据,您可以调整 train_encoder_decoder_model 函数来处理此问题:
def train_encoder_decoder_model(model, X_train, y_train, X_test, y_test):
# Create decoder inputs which is the same as y_train but shifted by one timestep
decoder_input_data = np.zeros_like(X_train)
decoder_input_data[:, 1:] = X_train[:, :-1]
# Now, y_train should be the actual outputs you expect from the decoder.
y_train_T = np.array([y_train]).T
# The same logic applies for the test data
decoder_input_test = np.zeros_like(X_test)
decoder_input_test[:, 1:] = X_test[:, :-1]
y_test_T = np.array([y_test]).T
model.fit(x=[X_train, decoder_input_data],
y=y_train_T,
batch_size=100,
epochs=100,
verbose=2,
validation_data=([X_test, decoder_input_test], y_test_T),
callbacks=[file_logger])
return model
您还需要更新 model.fit() 中的模型输入:
model.fit(x=[X_train, decoder_input_data], # Two inputs
y=y_train_T, # Target output
batch_size=100,
epochs=100,
verbose=2,
validation_data=([X_test, decoder_input_test], y_test_T), # Two inputs for validation
callbacks=[file_logger])