簡體   English   中英

如何解決,tensorflow.python.framework.errors_impl.InvalidArgumentError?

[英]How to solve, tensorflow.python.framework.errors_impl.InvalidArgumentError?

import tensorflow as tf
import numpy as np
from sklearn.model_selection import train_test_split

np.random.seed(4213)

data = np.random.randint(low=1,high=29, size=(500, 160, 160, 10)) 
labels = np.random.randint(low=0,high=5, size=(500, 160, 160)) 
nclass = len(np.unique(labels))
print (nclass)

samples, width, height, nbands = data.shape


X_train, X_test, y_train, y_test = train_test_split(data, labels, test_size=0.25, random_state=421)

print (X_train.shape)
print (y_train.shape)

arch = tf.keras.applications.VGG16(input_shape=[width, height, nbands],
                      include_top=False,
                      weights=None)

model = tf.keras.Sequential()
model.add(arch)
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(nclass))

model.compile(optimizer = tf.keras.optimizers.Adam(0.0001),
              loss=tf.keras.losses.SparseCategoricalCrossentropy(),
              metrics=[tf.keras.metrics.SparseCategoricalAccuracy()])
    

model.fit(X_train,
          y_train,                                 
          epochs=3,
          batch_size=32,
          verbose=2)


res = model.predict(X_test)
print(res.shape)

運行上述代碼進行semantic segmentation時,出現異常:

InvalidArgumentError
 Incompatible shapes: [32,160,160] vs. [32]
     [[node Equal (defined at c...:38) ]] [Op:__inference_train_function_1815]


tensorflow.python.framework.errors_impl.InvalidArgumentError

您的問題來自最后一層的大小(為避免這些錯誤,總是希望對N_IMAGESWIDTHHEIGHTN_CHANNELSN_CLASSES使用 python 常量):

用於圖像分類

您應該為每個圖像分配一個 label。 嘗試切換labels

import tensorflow as tf
import numpy as np
from sklearn.model_selection import train_test_split

np.random.seed(4213)

N_IMAGES, WIDTH, HEIGHT, N_CHANNELS = (500, 160, 160, 10)
N_CLASSES  = 5

data = np.random.randint(low=1,high=29, size=(N_IMAGES, WIDTH, HEIGHT, N_CHANNELS)) 
labels = np.random.randint(low=0,high=N_CLASSES, size=(N_IMAGES)) 
#...

用於語義分割

確保您的分類器(網絡的最后一層)具有相應的大小。 在這種情況下,每個像素需要 1 個 class:

#...
model = tf.keras.Sequential()
model.add(arch)
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(width * height))
model.add(tf.keras.layers.Reshape([width , height]))
#...

這是你能得到的最簡單的。 相反,您可以設置多個反卷積層來充當分類器,或者您甚至可以翻轉arch架構並使用它來生成分類結果。 正交地,您可以對標簽執行one_hot編碼,從而將它們擴展N_CLASSES ,有效地增加最后一層中的神經元數量。

暫無
暫無

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

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