簡體   English   中英

Tensorflow 尺寸問題:ValueError:形狀 (3, 1) 和 (None, 3) 不兼容

[英]Tensorflow dimension issue: ValueError: Shapes (3, 1) and (None, 3) are incompatible

我對 NN 很陌生,在安裝 model 時遇到了一些尺寸問題。 這是我的情況:

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
___________________________________________

這是我想訓練的 model(設置起始基線是 model)。 這是一個帶有嵌入層的多類分類問題: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
    )

trainvalidation是我的訓練和驗證數據集的矢量化版本。

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 上,但我真的不知道如何修復張量的形狀。

經過一些挖掘和更多的形狀檢查,我想出了如何解決上面的錯誤。

我在 function 中添加了一個重塑調用:

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 function 來對我的文本數據進行矢量化。 我只需要在 label 級別添加重塑調用。 這將我的 label 從 (3,) 形狀變成了 (1,3)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM