我有以下简单的数据集。它由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
的新手。我试图改编here的代码。任何帮助或指针将不胜感激。提前谢谢。
答案 0 :(得分:1)
您的代码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)
....