我是机器学习和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的神经网络中?
1 回答
首先,您必须了解您的数据是什么以及您想要用它做什么 .
然后,您决定如何对数据进行整形以及使用哪些图层 .
但是有一些重要的约定:
数据中的第一个维度是"samples/examples"的数量 . 由于您创建了一个形状
(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
,GlobalMaxPooling1D
或GlobalAveragePooling1D
图层 .提示:使用
model.summary()
查看每个图层的输出形状以及最终的输出形状 .提示2:首先清楚地定义您的数据和目标,然后是X和Y的形状,然后是模型的形状 .