1
我有一個多類分類問題。說我有一個特徵矩陣:沿單個特徵行的Keras卷積
A B C D
1 -1 1 -6
2 0.5 0 11
7 3.7 1 1
4 -50 1 0
和標籤:
LABEL
0
1
2
0
2
我想嘗試一起Keras每個單一特徵行應用於卷積核。說nb_filter = 2和batch_size = 3。所以我期望卷積層的輸入形狀爲(3,4),輸出形狀爲(3,3)(因爲它適用於AB,BC,CD)。
這裏是我的嘗試與Keras(V1.2.1,Theano後端):
def CreateModel(input_dim, num_hidden_layers):
from keras.models import Sequential
from keras.layers import Dense, Dropout, Convolution1D, Flatten
model = Sequential()
model.add(Convolution1D(nb_filter=10, filter_length=1, input_shape=(1, input_dim), activation='relu'))
model.add(Dense(3, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam')
model.summary()
return model
def OneHotTransformation(y):
from keras.utils import np_utils
return np_utils.to_categorical(y)
X_train = X_train.values.reshape(X_train.shape[0], 1, X_train.shape[1])
X_test = X_test.values.reshape(X_test.shape[0], 1, X_test.shape[1]),
y_train = OneHotTransformation(y_train)
clf = KerasClassifier(build_fn=CreateModel, input_dim=X_train.shape[1], num_hidden_layers=1, nb_epoch=10, batch_size=500)
clf.fit(X_train, y_train)
形狀:
print X_train.shape
print X_test.shape
print y_train.shape
輸出:
(45561, 44)
(11391, 44)
(45561L,)
當我嘗試運行此我得到的代碼和例外:
ValueError: Error when checking model target: expected dense_1 to have 3 dimensions, but got array with shape (45561L, 3L)
我試圖重塑y_train:
y_train = y_train.reshape(y_train.shape[0], 1, y_train.shape[1])
這讓我異常:
ValueError: Error when checking model target: expected dense_1 to have 3 dimensions, but got array with shape (136683L, 2L)
- 是這種做法與Convolution1D正確實現我的目標是什麼?
- 如果#1是,我該如何解決我的代碼?
我已經閱讀了很多github問題和一些問題(1,2),但它並沒有真正的幫助。
謝謝。
UPDATE1: 根據Matias Valdenegro的評論。 下面是重塑 'X' 之後和 'Y' onehot編碼後的形狀:
print X_train.shape
print X_test.shape
print y_train.shape
輸出:
(45561L, 1L, 44L)
(11391L, 1L, 44L)
(45561L, 3L)
UPDATE2:再次由於Matias的Valdenegro。確定它是一個複製粘貼問題後,重新塑形是在創建模型後完成的。代碼應該如下所示:
def CreateModel(input_dim, num_hidden_layers):
from keras.models import Sequential
from keras.layers import Dense, Dropout, Convolution1D, Flatten
model = Sequential()
model.add(Convolution1D(nb_filter=10, filter_length=1, input_shape=(1, input_dim), activation='relu'))
model.add(Dense(3, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam')
model.summary()
return model
def OneHotTransformation(y):
from keras.utils import np_utils
return np_utils.to_categorical(y)
clf = KerasClassifier(build_fn=CreateModel, input_dim=X_train.shape[1], num_hidden_layers=1, nb_epoch=10, batch_size=500)
X_train = X_train.values.reshape(X_train.shape[0], 1, X_train.shape[1])
X_test = X_test.values.reshape(X_test.shape[0], 1, X_test.shape[1]),
y_train = OneHotTransformation(y_train)
clf.fit(X_train, y_train)
正如你可以在我的問題中看到的,我嘗試了不重塑y_train。它也拋出異常。 – shda
@shda問題中的形狀與重塑後的預期不符,你確定它們是正確的嗎? –
對不起,這些都是形狀整形之前。我會更新我的問題。 – shda