簡體   English   中英

將3D數據擬合為Keras順序模型層的輸入

[英]Fitting 3D data as Input into Keras Sequential Model Layer

我是機器學習和Keras領域的新手。 實際上,我曾與scikit-learn合作,但Keras似乎有點復雜。 我的問題是我有一些3D數據,並希望將其適合於Dense層(我也嘗試過使用Conv2D和Conv1D層)。 我所做的如下:

arr1 = np.random.random((30,2))
arr2 = np.random.random((30,2))
arr3 = np.random.random((30,2))
arr4 = np.random.random((30,2))
arr5 = np.random.random((30,2))
arr6 = np.random.random((30,2))

x_matrix = np.dstack(
    (arr1
    ,arr2
    ,arr3
    ,arr4
    ,arr5
    ,arr6)
).swapaxes(1,2)
print(x_matrix.shape)

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(x_matrix, y_matrix, test_size=0.33, random_state=42)

from keras.models import Sequential
model = Sequential()

from keras.layers import Dense, Conv2D, Conv1D, Flatten

model = Sequential()

model.add(Dense(6, activation='sigmoid', input_shape=(6,2)))

model.compile(loss='categorical_crossentropy',
              optimizer='sgd',
              metrics=['accuracy'])

model.fit(np.array(X_train), np.array(y_train), epochs=20, batch_size=1)#
score = model.evaluate(X_test, y_test)

print(score)

我在合適的步驟遇到了錯誤。 錯誤如下:

ValueError: Error when checking target: expected dense_1 to have 3 dimensions, but got array with shape (20, 2)

對於Conv1D層,我嘗試了以下方法:

model.add(Conv1D(6, (2),  activation='sigmoid', input_shape=(6 ,2)))

並提出了錯誤:

ValueError: Error when checking target: expected conv1d_1 to have 3 dimensions, but got array with shape (20, 2)

Conv2D似乎更復雜,我可能不需要此作為我的輸入層,但是通過下面的調用,我仍然遇到相同的錯誤。

model.add(Conv2D(6, (2,2),  activation='sigmoid', input_shape=(20,6 ,2)))

ValueError: Error when checking input: expected conv2d_1_input to have 4 dimensions, but got array with shape (20, 6, 2)

我要問的是:如何使用Keras將這樣的數據擬合到神經網絡中?

首先,您必須了解您的數據是什么以及您想如何使用它。

然后,您決定如何調整數據的形狀以及使用哪些圖層。

但是,有一些重要的約定:

  • 數據中的第一維是“樣本/示例”的數量。 自創建形狀(30,6,2)以來,您決定擁有30個樣本,每個樣本都具有形狀(6,2) -這就是為什么了解數據和要執行的操作很重要的原因。
  • X和Y必須具有相同數量的樣本。 因此,如果X中有30個樣本,那么Y中也肯定也有30個樣本,但是似乎您的數據認為它有20個樣本。 在消息中看到target形狀: (20,2) <-這是Y的形狀。
  • 其他尺寸是免費的,但是:
    • 密集層將僅在最后一個維度上起作用,而其他維度則保持不變:輸出形狀為(30,6,units)
    • Conv1D層將3D輸入解釋為:( (samples, length, input_channels) ,輸出形狀為(samples, modified_length, filters)
    • Conv2D圖層需要4D輸入:( (samples, width, heigth, input_channels) ,並將輸出(samples, modified_width, modified_height, filters)
  • 模型的輸出形狀必須與Y的形狀匹配。在這里,再次,您必須了解Y是什么,並確保您准備好與之匹配的模型。
  • 如果在模型中的某些時候,你需要讓你的3D數據成為2D,你需要使用一個Flatten ,一個Reshape ,一個GlobalMaxPooling1DGlobalAveragePooling1D層。

提示:使用model.summary()查看每一層的輸出形狀以及最終的輸出形狀。

提示2:首先明確定義數據和目標,然后定義X和Y的形狀,然后定義模型的形狀。

暫無
暫無

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

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