python - Tensorflow 维度问题:ValueError: Shapes (3, 1) and (None, 3) is incompatible
问题描述
我对 NN 很陌生,在拟合模型时遇到了一些尺寸问题。这是我的情况:
model_sigmoid = tf.keras.Sequential([
embedding_layer,
GlobalAveragePooling1D(),
Dense(3, activation="softmax")])
model_sigmoid.summary()
Model: "sequential_12"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
embedding (Embedding) (None, None, 100) 1195200
_________________________________________________________________
global_average_pooling1d_5 ( (None, 100) 0
_________________________________________________________________
dense_11 (Dense) (None, 3) 303
=================================================================
Total params: 1,195,503
Trainable params: 303
Non-trainable params: 1,195,200
___________________________________________
这是我想训练的模型(它是设置起始基线的模型)。这是一个带有嵌入层的多类分类问题:GloVe 100d embedding
model_sigmoid.compile(optimizer="adam", loss="categorical_crossentropy", metrics=["accuracy"])
history = model_sigmoid.fit(
train, epochs=10, batch_size=128,
validation_data=validation, verbose=1
)
train
并且validation
是我的训练和验证数据集的矢量化版本。
train_ds
<MapDataset shapes: ((None, 80), (3,)), types: (tf.int64, tf.float32)>
tweet, label = next(iter(train))
tweet
<tf.Tensor: shape=(1, 80), dtype=int64, numpy=
array([[ 6, 32, 1321, 3, 157, 383, 4, 18, 137, 1222, 6,
18, 181, 2770, 1024, 6781, 51, 6, 375, 240, 486, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0]])>
label
<tf.Tensor: shape=(3,), dtype=float32, numpy=array([1., 0., 0.], dtype=float32)>
如您所见,我的“X”是一个长度为 80 的序列,其整数对应于我的数据集中的初始单词。相反,我的“Y”是原始情绪值(负面、中性、正面)的编码版本。
当我调用 fit 操作时,我得到
ValueError: Shapes (3, 1) and (None, 3) are incompatible
我很确定错误出在 Y 上,但我真的不知道如何修复张量的形状。
解决方案
经过一些挖掘和更多的形状检查,我想出了如何解决上面的错误。
我在我的函数中添加了一个重塑调用:
def vectorize_text_and_reshape(text, label):
text = tf.expand_dims(text, -1)
return vectorizer(text), tf.reshape(label, [1,3])
train_ds = train_tf.map(vectorize_text_and_reshape)
val_ds = val_tf.map(vectorize_text_and_reshape)
test_ds = test_tf.map(vectorize_text_and_reshape)
我已经实现了vectorize_text_and_reshape
上面的函数来矢量化我的文本数据。我只需要在标签级别添加重塑调用。这将我的标签从 (3,) 形状变成了 (1,3)。
推荐阅读
- php - 在 PHP 的 while 循环中提交带有发布数据的表单
- postgresql - 带有字符串的货币值的 PostgreSQL 数据类型
- python - 向熊猫数据框添加一列
- appium - Appium Android 如何在 JAVA 中使用 TEXT 值
- docker - 如何使用 ubuntu:20.04 基础在 docker 中运行 wine(适用于 ubuntu:18.04 基础)
- expression - PhpStorm 为项目文件生成 MD5Sum
- payment-gateway - razorpay Add On 是如何工作的?我们可以在订阅中添加一次,并且以后无需更新即可使用?
- php - 如何在 laravel eloquent 的订单表中计算相同的产品?我是 Laravel 新用户
- javascript - 期望 Jest 中的超时被拒绝
- python - 一个程序来排序球员的分数,按降序显示他们的分数