繁体   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