Python 1D CNN模型-model.fit()中的错误

时间:2020-05-08 12:57:35

标签: python keras cnn datashape

我正在尝试通过处理ECG信号以诊断睡眠呼吸暂停来构建一维CNN模型。

我正在使用sklearn库,在train_test_split中遇到错误。这是我的代码:

# loading the file
with open("ApneaData.csv") as csvDataFile:
    csvReader = csv.reader(csvDataFile)
    for line in csvReader:
        lis.append(line[0].split())  # create a list of lists

# making a list of all x-variables
for i in range(1, len(lis)):
    data.append(list(map(int, lis[i])))

# a list of all y-variables (either 0 or 1)
target = Extract(data)  # sleep apn or not

# converting to numpy arrays
data = np.array(data)
target = np.array(target)

# stacking data into 3D
loaded = dstack(data)
change = dstack(target)


trainX, testX, trainy, testy = train_test_split(loaded, change, test_size=0.3)

# the model
verbose, epochs, batch_size = 0, 10, 32
n_timesteps, n_features, n_outputs = trainX.shape[0], trainX.shape[1], trainy.shape[0]
model = Sequential()
model.add(Conv1D(filters=64, kernel_size=3, activation='relu', input_shape=(n_timesteps,n_features)))
model.add(Conv1D(filters=64, kernel_size=3, activation='relu'))
model.add(Dropout(0.5))
model.add(MaxPooling1D(pool_size=2))
model.add(Flatten())
model.add(Dense(100, activation='relu'))
model.add(Dense(n_outputs, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

# fitting the model
model.fit(trainX, trainy, epochs=epochs, batch_size=batch_size, verbose=verbose)

# evaluate model
_, accuracy = model.evaluate(testX, testy, batch_size=batch_size, verbose=0)

我得到了错误:

ValueError: Error when checking input: expected conv1d_15_input to have shape (11627, 6001) but got array with shape (6001, 1)

我不明白我在做什么错?任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

我认为n_timesteps和n_features应该是shape [1]和shape [2],第一维是样本数

答案 1 :(得分:0)

首先

# a list of all y-variables (either 0 or 1)
target = Extract(data)  # sleep apn or not

这表明您正在执行二进制分类,并且似乎您尚未应用单热编码。因此,您的最后一层应为S型。

第一维表示样本数。所以, trainX = tranX.reshape(trainX.shape[0], trainX.shape[1], -1) (如果尚不存在,请添加第三维)

n_timesteps, n_features, n_outputs = trainX.shape[1], trainX.shape[2], 1

最后,更改您的模型。

model.add(Dense(n_outputs, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])