2017-07-07 12 views
1

我在我的虛擬數據集中有12個長度爲200的矢量,每個矢量代表一個樣本。比方說x_train是一個形狀爲(12, 200)的數組。如何塑造我的輸入數據以用於kev中的Conv1D?

當我這樣做:

model = Sequential() 
model.add(Conv1D(2, 4, input_shape=(1, 200))) 

我得到的錯誤:

ValueError: Error when checking model input: expected conv1d_1_input to have 3 dimensions, but got array with shape (12, 200) 

如何正確地塑造我的輸入數組?

這裏是我的更新腳本:

data = np.loadtxt('temp/data.csv', delimiter=' ') 
trainData = [] 
testData = [] 
trainlabels = [] 
testlabels = [] 

with open('temp/trainlabels', 'r') as f: 
    trainLabelFile = list(csv.reader(f)) 

with open('temp/testlabels', 'r') as f: 
    testLabelFile = list(csv.reader(f)) 

for i in range(2): 
    for idx in trainLabelFile[i]: 
     trainData.append(data[int(idx)]) 
     # append 0 to labels for neg, 1 for pos 
     trainlabels.append(i) 

for i in range(2): 
    for idx in testLabelFile[i]: 
     testData.append(data[int(idx)]) 
     # append 0 to labels for neg, 1 for pos 
     testlabels.append(i) 

# print(trainData.shape) 
X = np.array(trainData) 
Y = np.array(trainlabels) 
X2 = np.array(testData) 
Y2 = np.array(testlabels) 

model = Sequential() 
model.add(Conv1D(1, 1, input_shape=(12, 1, 200))) 

opt = 'adam' 
model.compile(loss='mean_squared_error', optimizer=opt, metrics=['accuracy']) 

model.fit(X, Y, epochs=epochs) 

現在我得到一個新的錯誤:

ValueError: Input 0 is incompatible with layer conv1d_1: expected ndim=3, found ndim=4 
+0

Ref。到這個環節,有一個很好的解釋。 https://stackoverflow.com/questions/43235531/convolutional-neural-network-conv1d-input-shape?rq=1 –

回答

1

Keras documentation,它被寫input_shape是一個三維張量形狀​​。含義如下:

  1. batch_size是樣本數。這是你的12
  2. steps是數據的時間維度。您可以將其設置爲1,因爲數據中只有一個通道。
  3. input_dim是一個樣本的維數。這是你的200

回答您的問題是將您的數據重塑爲(12,1,200)

+0

我試過,但我只是再次出現錯誤:ValueError:檢查模型目標時出錯:預計conv1d_1到有3個維度,但有形狀(12,1)。我是否也必須更改我的input_shape參數? – user1816679

+0

是的。這是告訴keras輸入形狀爲'(12,1,200)'的唯一方法。 –

+0

@ user1816679如果您不想指定訓練樣本的數量,則編寫'input_shape =(None,1,200))'。 –

2

您需要根據Conv1D圖層輸入格式重塑您的輸入數據 -​​。嘗試

x_train = x_train.reshape(x_train.shape[0], 1, x_train.shape[1])