Keras 为 9 维特征向量构建网络

Keras building a network for 9 dimensional feature vector

我有以下简单的数据集。它由 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 中的代码。任何帮助或指示将不胜感激。提前致谢。

您的代码 model.add(Convolution1D(5,2,border_mode='same',input_shape=(1,num_features))) 定义输入的形状应为 (batch_size, 1, num_features)。但是,X_trainX_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)

    ....