我有以下简单的数据集。它由9个特征组成,是一个二元分类问题。特征向量的示例如下所示。每行都有其对应的 0,1 标签。
30,82,1,2.73,172,117,2,2,655.94
30,174,1,5.8,256,189,3,2,587.28
98.99,84,2,0.84,577,367,3,2,1237.34
30,28,1,0.93,38,35,2,1,112.35
...
我知道CNN广泛用于图像分类,但我正在尝试将其应用于我手头的数据集。我正在尝试应用 5 个过滤器,每个过滤器的大小为 2。鉴于这些数据的形状,我一直坚持以正确的方式构建网络。这是我构建网络的函数。
def make_network(num_features,nb_classes):
model = Sequential()
model.add(Convolution1D(5,2,border_mode='same',input_shape=(1,num_features)))
model.add(Activation('relu'))
model.add(Convolution1D(5,2,border_mode='same'))
model.add(Activation('relu'))
model.add(Flatten())
model.add(Dense(2))
model.add(Activation('softmax'))
最后,我还将调用一个测试函数来测试我创建的模型的准确性。以下函数尝试实现这一点
def train_model(model, X_train, Y_train, X_test, Y_test):
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.3, nesterov=True)
model.compile(loss='binary_crossentropy', optimizer=sgd)
model.fit(X_train, Y_train, nb_epoch=100, batch_size=10,
validation_split=0.1, verbose=1)
print('Testing...')
res = model.evaluate(X_test, Y_test,
batch_size=batch_size, verbose=1, show_accuracy=True)
print('Test accuracy: {0}'.format(res[1]))
当我制作模型并向其传递训练函数时,出现以下错误
Using Theano backend.
Traceback (most recent call last):
File "./cnn.py", line 69, in <module>
train_model(model,x_train,y_train,x_test,y_test)
File "./cnn.py", line 19, in train_model
validation_split=0.1, verbose=1)
File "/usr/local/lib/python2.7/dist-packages/keras/models.py", line 413, in fit
sample_weight=sample_weight)
File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1011, in fit
batch_size=batch_size)
File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 938, in _standardize_user_data
exception_prefix='model input')
File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 96, in standardize_input_data
str(array.shape))
Exception: Error when checking model input: expected convolution1d_input_1 to have 3:(None, 1, 9) dimensions, but got array with shape (4604, 9)
我是Keras
的新手.我正在尝试从这里改编代码。任何帮助或指示将不胜感激。提前谢谢。
您的代码model.add(Convolution1D(5,2,border_mode='same',input_shape=(1,num_features)))
定义输入应为形状(batch_size, 1, num_features)
。然而,X_train
和X_test
可能处于形状(batch_size, 9)
,这是不一致的。
def train_model(model, X_train, Y_train, X_test, Y_test):
X_train = X_train.reshape(-1, 1, 9)
X_test = X_test.reshape(-1, 1, 9)
....