输出为独热向量的简单TensorFlow/Keras模型报错:形状不兼容
解决MLP分类器输出层与标签形状不匹配问题
问题根源
你的代码仅对训练数据集执行了.batch(batch_size)批次处理,但验证数据集val_dataset未做批次划分。模型训练时,训练集按32个样本为一批输入,每个批次的标签形状为(32,10);而验证集未做batch处理时会逐个样本输入,此时标签形状被自动调整为(10,1),与模型输出的(1,10)形状不兼容,触发报错。
修复方案
给验证数据集也添加批次处理即可:
val_dataset = val_dataset.batch(batch_size)
完整修正代码
import numpy as np import tensorflow as tf # Generate example dataset X = np.random.rand(1000, 1) # One-dimensional input y = np.random.randint(0, 10, size=(1000,)) # Random integer labels X_val = np.random.rand(1000, 1) # One-dimensional input y_val = np.random.randint(0, 10, size=(1000,)) # Random integer labels # Convert integer labels to one-hot vectors y_one_hot = tf.one_hot(y, depth=10) # Assuming 10 classes y_val_one_hot = tf.one_hot(y_val, depth=10) # Create a zipped dataset train_dataset = tf.data.Dataset.from_tensor_slices((X, y_one_hot)) val_dataset = tf.data.Dataset.from_tensor_slices((X_val, y_val_one_hot)) # Define batch size batch_size = 32 # Shuffle and batch the training dataset train_dataset = train_dataset.shuffle(buffer_size=100).batch(batch_size) # 给验证数据集添加批次处理 val_dataset = val_dataset.batch(batch_size) # Define the MLP model model = tf.keras.models.Sequential([ tf.keras.layers.Dense(64, activation='relu', input_shape=(1,)), tf.keras.layers.Dense(32, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') # Output layer with softmax activation for one-hot vectors ]) # Compile the model model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=[tf.keras.metrics.Precision()]) # Train the model model.fit(train_dataset, epochs=10, validation_data=val_dataset)
可选优化方案
如果不想处理one-hot编码,可以改用SparseCategoricalCrossentropy损失函数,直接使用整数标签,省去one-hot转换步骤:
# 去掉one-hot转换步骤 train_dataset = tf.data.Dataset.from_tensor_slices((X, y)).shuffle(100).batch(batch_size) val_dataset = tf.data.Dataset.from_tensor_slices((X_val, y_val)).batch(batch_size) # 编译时修改损失函数 model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(), metrics=[tf.keras.metrics.Precision()])
内容的提问来源于stack exchange,提问作者user3651203
相关产品推荐
相关产品推荐

