You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TensorFlow函数式API:如何为给定神经网络提供正确形状的输入示例

TensorFlow函数式模型输入形状说明与示例

你的模型包含两个输入分支inputA和inputB,每个输入的单个样本形状为(240, 1),因此在调用model.fit()时,需要传入两组形状为(batch_size, 240, 1)的输入数据,其中batch_size是你指定的批量大小(如32、64等)。

具体代码示例

import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Input, LSTM, Concatenate, Dense

# 定义你提供的模型
inputA = Input(shape=(240, 1))
inputB = Input(shape=(240, 1))

layerA1 = LSTM(60, return_sequences=True)(inputA)
layerB1 = LSTM(60, return_sequences=True)(inputB)

layerA2 = LSTM(60, return_sequences=True)(layerA1)
layerB2 = LSTM(60, return_sequences=True)(layerB1)

layerA3 = LSTM(60, return_sequences=False)(layerA2)
layerB3 = LSTM(60, return_sequences=False)(layerB2)

x = Concatenate()([layerA3, layerB3])
output = Dense(5, activation='linear', name='dense')(x)
model = tf.keras.Model([inputA, inputB], output)

# 生成符合要求的输入数据
batch_size = 32
# inputA的批量数据:形状 (32, 240, 1)
x_a = np.random.rand(batch_size, 240, 1)
# inputB的批量数据:形状 (32, 240, 1)
x_b = np.random.rand(batch_size, 240, 1)
# 对应的标签数据:形状 (32, 5),匹配输出层Dense(5)
y_labels = np.random.rand(batch_size, 5)

# 编译并训练模型
model.compile(optimizer='adam', loss='mean_squared_error')
model.fit([x_a, x_b], y_labels, epochs=5, batch_size=batch_size)

关键说明

  • 每个输入的第一维是批量大小,由你根据硬件性能和训练需求自定义;
  • 输入必须以列表形式传入model.fit(),顺序要和模型定义的[inputA, inputB]一致;
  • 标签数据的形状需匹配输出层Dense(5),即每个样本对应5个数值,批量形状为(batch_size, 5)。

内容的提问来源于stack exchange,提问作者BAR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 10:55:04