Python:keras形狀不比對錯誤(Python: keras shape mismatch error)
我正在嘗試在keras建構一個非常簡單的多層感覺器(MLP):
model = Sequential()
model.add(Dense(16, 8, init='uniform', activation='tanh'))
model.add(Dropout(0.5))
model.add(Dense(8, 2, init='uniform', activation='tanh'))
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='mean_squared_error', optimizer=sgd)
model.fit(X_train, y_train, nb_epoch=1000, batch_size=50)
score = model.evaluate(X_test, y_test, batch_size=50)
我的訓練資料形狀: X_train.shape給出(34180, 16)
标簽屬于具有形狀的二進制類: y_train.shape給出(34180,)
是以我的keras代碼應該産生以下連接配接的網絡: 16x8 => 8x2
這會産生形狀不比對誤差:
ValueError: Input dimension mis-match. (input[0].shape[1] = 2, input[1].shape[1] = 1)
Apply node that caused the error: Elemwise{sub,no_inplace}(Elemwise{Composite{tanh((i0 + i1))}}[(0, 0)].0, )
Inputs types: [TensorType(float64, matrix), TensorType(float64, matrix)]
Inputs shapes: [(50, 2), (50, 1)]
Inputs strides: [(16, 8), (8, 8)]
在model.fit(X_train, y_train, nb_epoch=1000, batch_size=50) Epoch 0處。 我在監督Keras中顯而易見的事情嗎?
編輯:我在這裡經曆了這個問題,但沒有解決我的問題
I am trying to build a very simple multilayer perceptron (MLP) in keras:
model = Sequential()
model.add(Dense(16, 8, init='uniform', activation='tanh'))
model.add(Dropout(0.5))
model.add(Dense(8, 2, init='uniform', activation='tanh'))
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='mean_squared_error', optimizer=sgd)
model.fit(X_train, y_train, nb_epoch=1000, batch_size=50)
score = model.evaluate(X_test, y_test, batch_size=50)
My training data shape: X_train.shape gives (34180, 16)
The labels belong to binary class with shape: y_train.shape gives (34180,)
So my keras code should produce the network with following connection: 16x8 => 8x2
which produces the shape mismatch error:
ValueError: Input dimension mis-match. (input[0].shape[1] = 2, input[1].shape[1] = 1)
Apply node that caused the error: Elemwise{sub,no_inplace}(Elemwise{Composite{tanh((i0 + i1))}}[(0, 0)].0, )
Inputs types: [TensorType(float64, matrix), TensorType(float64, matrix)]
Inputs shapes: [(50, 2), (50, 1)]
Inputs strides: [(16, 8), (8, 8)]
At Epoch 0 at line model.fit(X_train, y_train, nb_epoch=1000, batch_size=50). Am I overseeing something obvious in Keras?
EDIT: I have gone through the question here but does not solve my problem
原文:https://stackoverflow.com/questions/31997366
更新時間:2020-01-13 14:20
最滿意答案
我有同樣的問題,然後發現這個線程;
看來你需要聲明一個最終的輸出層2或者任何數量的類别,标簽需要是一個分類類型,其實質上這是每個觀察的二進制向量,例如一個3類輸出向量[0,2,1, 0,1,0]變為[[1,0,0],[0,0,1],[0,1,0],[1,0,0],[0,1,0],[1 ,0,0]。
np_utils.to_categorical函數為我解決了這個問題;
from keras.utils import np_utils, generic_utils
y_train, y_test = [np_utils.to_categorical(x) for x in (y_train, y_test)]
I had the same problem and then found this thread;
It appears for you to state a final output layer of 2 or for any number of categories the labels need to be of a categorical type where essentially this is a binary vector for each observation e.g a 3 class output vector [0,2,1,0,1,0] becomes [[1,0,0],[0,0,1],[0,1,0],[1,0,0],[0,1,0],[1,0,0]].
The np_utils.to_categorical function solved this for me;
from keras.utils import np_utils, generic_utils
y_train, y_test = [np_utils.to_categorical(x) for x in (y_train, y_test)]
2015-10-04
相關問答
錯誤不是關于模型而是關于圖像生成器。 預設情況下 , flow_from_directory 會進行分類,并根據目錄生成一個類輸出,是以您可以獲得類似于(32, 2) flow_from_directory (32, 2)内容,即模型需要實際圖像時,每個圖像都是類标簽。 class_mode:“分類”,“二進制”,“稀疏”,“輸入”或“無”之一。 預設值:“分類”。 确定傳回的标簽數組的類型:“分類”将是2D單熱編碼标簽。 是以,您希望flow方法中的class_mode="input"作為目标返
...
model.predict接受一批樣本,如果你給它一個形狀錯誤的樣本,它會将第一個次元解釋為批處理。 一個簡單的解決方案是添加值為1的次元: q_network.predict(obs.reshape(1, 8))
model.predict takes a batch of samples, if you give it a single sample with the wrong shape, it will interpret the first dimension as the batc
...
您的模型已被初始化(并經過訓練)以接收來自形狀(N,28)矩陣的輸入。 它預計有28列。 解決此問題的方法是重塑您的單個輸入行以比對: z = z[:, np.newaxis].T #(1,28) shape
要麼: z = z.reshape(1,-1) #reshapes to (1,whatever is in there)
z = z.reshape(-1,28) #probably better, reshapes to (amount of samples, input_dim)
...
最近的API更改https://groups.google.com/forum/#!topic/keras-users/iWVrWpR_eaQ後,示例http://keras.io/examples/尚未更新。 確定安裝了最新版本的Keras: sudo pip install git+git://github.com/fchollet/keras.git --upgrade
并使用來自同一存儲庫的更新示例https://github.com/fchollet/keras/tree/master
...
事實上,這個函數期望的是一維張量,并且你有一個二維張量。 keras.backend.squeeze(x, axis=-1)确實有keras.backend.squeeze(x, axis=-1)函數。 你也可以使用keras.backend.reshape(x, (-1,)) 如果您在手術後需要回到舊的形狀,您可以: keras.backend.expand_dims(x) keras.backend.reshape(x,(-1,1)) Indeed, the function is expec
...
我有同樣的問題,然後發現這個線程; https://github.com/fchollet/keras/issues/68 看來你需要聲明一個最終的輸出層2或者任何數量的類别,标簽需要是一個分類類型,其實質上這是每個觀察的二進制向量,例如一個3類輸出向量[0,2,1, 0,1,0]變為[[1,0,0],[0,0,1],[0,1,0],[1,0,0],[0,1,0],[1 ,0,0]。 np_utils.to_categorical函數為我解決了這個問題; from keras.utils impo
...
正如@ djk47463的評論中所提到的,您的輸出現在每個樣本有919個值,因為這是網絡最後一層中的機關數。 要更正此問題,請将最後一個圖層的機關設定為1,或者添加一個輸出次元為1的新最終圖層。 As mentioned in @djk47463's comment, your output is now has 919 values per sample, because that is the number of units in the last layer of your network.
...
不比對是在預期的輸出次元(98,10)和您正在使用的資料的次元(98,1)之間 那是因為你正在使用一個應該在10級資料庫上進行分類的示例代碼。 如果您想進行預測,請将最後一層更改為 model.add(Dense(output_dim=1, init="glorot_uniform"))
另外,我認為您的成本函數會有問題。 如果您有連續資料,則不應使用絕對百分比錯誤。 改變這個 model.compile(loss="mean_absolute_percentage_error", optimi
...
你不想要32個大小為39的數組,你想要一個大小的數組(32,39)。 是以,您必須将input_shape更改為(None,39),None将允許您動态更改batch_size,并将batch_x更改為形狀為numpy的數組(32,39)。 You don't want 32 arrays of size 39, you want one array of size (32, 39). So you must change input_shape to (None, 39), the None a
...
您的ImageDataGenerator沒有問題。 如錯誤消息中所述,模型輸出的形狀與其目标的形狀之間存在不比對。 您使用class_mode = 'binary' ,是以您的模型的預期輸出是單個值,但它會産生shape的輸出(batch_size, 64, 64, 4)因為您的模型中沒有其他卷積層。 嘗試這樣的事情: model.add(Convolution2D(4, 4, 4, border_mode='same', input_shape=(64, 64,3), activation='r
...