python - 使用 conv1D “Error when checking input: expected conv1d_input to have 3 dimensions, but got array with shape (213412, 36)”

标签 python keras neural-network conv-neural-network lstm

我的输入只是一个带有 237124 行和 37 列的 csv 文件:

  • 第一个 36 个 列作为特征
  • 最后一个 列是 二进制类标签

  • 我正在尝试在 conv1D 模型上训练我的数据。

    我试图用一层 构建一个 CNN,但我遇到了一些问题。

    编译器输出:

    ValueError:Error when checking input: expected conv1d_9_input to have shape (213412, 36) but got array with shape (36, 1)



    代码:
    import pandas as pd
    import numpy as np
    import sklearn
    from sklearn import metrics
    from sklearn.model_selection import KFold
    from sklearn.metrics import confusion_matrix
    from sklearn.preprocessing import StandardScaler
    import keras
    from tensorflow.keras.models import Sequential
    from tensorflow.keras.layers import Dense, Flatten
    from tensorflow.keras.layers import Conv2D,Conv1D, MaxPooling2D,MaxPooling1D
    from tensorflow.keras.layers import Activation
    from tensorflow.keras.layers import Dropout,BatchNormalization
    
    dataset=pd.read_csv("C:/Users/User/Desktop/data.csv",encoding='cp1252')
    
    dataset.shape
    #output: (237124, 37)
    
    array = dataset.values
    X = array[:,0:36]
    Y = array[:,36]
    
    kf = KFold(n_splits=10)
    kf.get_n_splits(X)
    
    for trainindex, testindex in kf.split(X):
    Xtrain, Xtest = X[trainindex], X[testindex]
    Ytrain, Ytest = Y[trainindex], Y[testindex]
    
    Xtrain.shape[0]
    #output: 213412
    
    Xtrain.shape[1]
    #output: 36
    
    Ytrain.shape[0]
    #output: 213412
    
    n_timesteps, n_features, n_outputs =Xtrain.shape[0], Xtrain.shape[1], 
    Ytrain.shape[0]
    
    model = Sequential()
    model.add(Conv1D(filters=64, kernel_size=1, 
    activation='relu',input_shape=(n_timesteps,n_features)))
    
    model.add(Conv1D(filters=64, kernel_size=1, 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'])
    # fit network
    model.fit(Xtrain, Ytrain, epochs=10, batch_size=32, verbose=0)
    
    # Testing CNN model BY X test
    
    Predictions = model.predict(Xtest,batch_size =100)
    rounded = [round(x[0]) for x in Predictions]
    Y_predection = pd.DataFrame(rounded)
    Y_predection = Y_predection.iloc[:, 0]
    
    .
    .
    .
    

    我尝试以这种方式修改代码:
    Xtrain = np.expand_dims(Xtrain, axis=2) 
    

    但错误仍然相同。

    最佳答案

    我注意到您的代码有几个问题。

  • Xtrain - 需要是一个 3D 张量。因为别的,Conv1D 无法处理。因此,如果您有 2D 数据,则需要添加一个新维度以使其成为 3D。
  • 您的 input_shape 需要更改以反射(reflect)这一点。例如,如果您只添加了一个 channel ,它应该是 [n_features, 1]
  • # Here I'm assuming some dummy data
    # Xtrain => [213412, 36, 1] (Note that you need Xtrain to be 3D not 2D - So we're adding a channel dimension of 1)
    Xtrain = np.expand_dims(np.random.normal(size=(213412, 36)),axis=-1)
    # Ytrain => [213412, 10]
    Ytrain = np.random.choice([0,1], size=(213412,10))
    
    n_timesteps, n_features, n_outputs =Xtrain.shape[0], Xtrain.shape[1], Ytrain.shape[1]
    
    model = Sequential()
    model.add(Conv1D(filters=64, kernel_size=1, 
    activation='relu',input_shape=(n_features,1)))
    
    model.add(Conv1D(filters=64, kernel_size=1, 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'])
    # fit network
    model.fit(Xtrain, Ytrain, epochs=10, batch_size=32, verbose=0)
    

    关于python - 使用 conv1D “Error when checking input: expected conv1d_input to have 3 dimensions, but got array with shape (213412, 36)”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59106391/

    相关文章:

    python - 如何在 OpenCV 中使用 convertScaleAbs() 函数?

    python - Keras、Tensorflow - 计算指标时 K.epsilon 的含义是什么

    python - 将 3D 数组输入 Sequential 模型 Keras (Python)

    neural-network - 我如何决定在特定情况下使用哪种神经网络和学习方法?

    javascript - 显示带有自定义身份验证 header 的 IFrame IPython

    python - 如何使用python pandas读取json文件?

    python - 无法找出 keras 输入形状错误?

    machine-learning - 反向传播神经网络 - 错误不收敛

    python - Python 中的指针? ` x.pointerDest = y.pointerDest` ?

    python - Keras 中的特征提取