2016-07-14 43 views
2

我有以下簡單的數據集。它由9個特徵組成,它是一個二元分類問題。下面顯示了一個特徵向量的例子。每行有其相應的0,1標籤。Keras建立一個網絡9維特徵向量

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

重塑從X_train輸入(4604,9)〜(4604,1,9) – y300

回答

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) 

    .... 
+0

感謝。這確實奏效。我只希望有更多關於數據形成的例子。 – broccoli