搭建神经网络模型进行训练时配置多个特征输入值

在搭建神经网络模型进行训练时,如果你有多个输入特征(如多个 X_train 数据),可以将它们组织成一个字典并传递给 model.fit。下面是一个示例代码,展示如何在字典中提供多个 X_train 数据:

示例代码

假设你有两个输入特征 X_train1X_train2,以及对应的验证集 X_val1X_val2

import numpy as np
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense, Concatenate
from tensorflow.keras.callbacks import EarlyStopping

# 示例数据
num_samples = 1000
num_features1 = 500
num_features2 = 50

X_train1 = np.random.rand(num_samples, num_features1)
X_train2 = np.random.rand(num_samples, num_features2)
y_train = np.random.rand(num_samples)

X_val1 = np.random.rand(200, num_features1)
X_val2 = np.random.rand(200, num_features2)
y_val = np.random.rand(200)

# 定义神经网络输入
input1 = Input(shape=(num_features1,), name='input1')
input2 = Input(shape=(num_features2,), name='input2')

# 定义每个输入的隐藏层
x1 = Dense(128, activation='relu')(input1)
x2 = Dense(128, activation='relu')(input2)

# 连接隐藏层
merged = Concatenate()([x1, x2])

# 添加全连接层
x = Dense(128, activation='relu')(merged)
x = Dense(64, activation='relu')(x)
output = Dense(1, activation='linear')(x)

# 定义模型
model = Model(inputs=[input1, input2], outputs=output)

# 编译模型
model.compile(optimizer='adam', loss='mean_squared_error')

# 定义早期停止回调
early_stopping = EarlyStopping(monitor='val_loss', patience=10)

# 训练模型
history = model.fit(
    {'input1': X_train1, 'input2': X_train2},  # 多个输入特征以字典形式提供
    y_train,
    validation_data=({'input1': X_val1, 'input2': X_val2}, y_val),  # 验证集也以字典形式提供
    batch_size=256,
    epochs=200,
    callbacks=[early_stopping],
    verbose=1
)

# 模型训练完成后,可以查看训练历史
print(history.history)

说明

  1. 输入层:我们为每个输入特征定义了一个 Input 层。
  2. 隐藏层:每个输入特征都有自己的隐藏层。
  3. 连接层:通过 Concatenate 层将不同输入特征的隐藏层连接起来。
  4. 输出层:最终的输出层用于预测目标变量。
  5. 编译模型:使用 Adam 优化器和均方误差(MSE)作为损失函数进行编译。
  6. 早期停止回调:定义了一个 EarlyStopping 回调,以防止过拟合。
  7. 训练模型:在 model.fit 中,我们以字典形式提供多个输入特征和验证数据。

这种方法可以灵活地处理多个输入特征的数据,在进行训练时将它们传递给模型。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容