运维小白成长之路 2022-03-19 16:13 采纳率: 100%
浏览 907
已结题

一维卷积神经网络训练时遇到报错:Vexpected conv1d_input to have 3 dimensions, but got array with shape (20430, 2048)

数据集:一个2051*22700大小的一个无人机信号数据集,每一列表示一个无人机信号,一个信号用2048个数值表示,即前2048行是无人机的信号,后3行是标签,但只需要用到最后一行的标签即可,这行标签将无人机的信号分成了10个类
源代码:


```python
import numpy as np
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense,Conv1D,MaxPooling1D,Flatten
from sklearn.model_selection import StratifiedKFold

def decode(datum):
    y = np.zeros((datum.shape[0],1))  ##datum.shape[0]表示datum的行数,这里y是一个大小为22700×1,数值全是0的矩阵
    for i in range(datum.shape[0]):  ##for i in rang(22700)
        y[i] = np.argmax(datum[i])  ##对于一维数组来说,np.argmax是取最大值的索引,例如:[0,0,0,0,1]的索引是4,[1,0,0,0,0]的索引是0
    return y  ##这里返回的y是一个大小为22700×1,将无人机信号数据分成10类的矩阵

def encode(datum):
    return to_categorical(datum)  ##数据类型的转变,例如:0为[1,0,0,0,0,0,0,0,0,0],9为[0,0,0,0,0,0,0,0,0,1]

np.random.seed(1)

print("Loading Data ...")
Data = np.loadtxt("F:\毕设资料\RF_Data.csv", delimiter=",")  ## 读取数据,指定分隔符  Data的大小:2051×22700

print("Preparing Data ...")
x = np.transpose(Data[0:2048,:])  ## x=Data的1~2048行的转置(即行与列交换)  x的大小:22700×2048  每一行表示一个无人机信号
Label = np.transpose(Data[2050:2051,:]); Label = Label.astype(int)  ##十类标签:0代表没有无人机信号,1~4代表Bebop无人机4种模式信号,2~8代表AR无人机4种模式信号,9代表Phantom 3无人机信号  大小:22700×1
y = encode(Label)  ##数据类型的转变,例如:0为[1,0,0,0,0,0,0,0,0,0],9为[0,0,0,0,0,0,0,0,0,1]  y的大小:22700×10  每一行表示一个无人机信号的标签

cvscores    = []
cnt         = 0
kfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=1)  ##将数据随机分成10份,9份拿去训练,1份拿去验证,随机数种子为1  k折交叉验证
for train, test in kfold.split(x, decode(y)):  ##10次循环,每次训练的数据为20430个,验证的数据为2270个  x[train].shape=(20430,2048)  y[train]=(20430,10)
    cnt = cnt + 1
    print(cnt)
    model = Sequential()  ##运用Sequential模型
    #x[train]=x[train].reshape((x[train].shape[0],x[train].shape[1],1))
    #x[test]=x[test].reshape((x[test].shape[0],x[test].shape[1],1))
    #y[train]=y[train].reshape((y[train].shape[0],1))
    #y[test]=y[test].reshape((y[test].shape[0],1))
    model.add(Conv1D(16, 7, activation='relu', padding='same', input_shape=(2048, 1)))  ##一个特征,特征长度为2048
    model.add(Conv1D(16, 7, activation='relu', padding='same'))
    model.add(MaxPooling1D(3))
    model.add(Conv1D(64, 7, activation='relu', padding='same'))
    model.add(Conv1D(64, 7, activation='relu', padding='same'))
    model.add(MaxPooling1D(3))
    model.add(Conv1D(64, 7, activation='relu', padding='same'))
    model.add(Conv1D(64, 7, activation='relu', padding='same'))
    model.add(MaxPooling1D(3))
    model.add(Flatten())
    model.add(Dense(10, activation = 'sigmoid'))  ##10个分类
    model.compile(loss = 'mse', optimizer = 'adam', metrics = ['accuracy'])  ##损失函数为mse(均方差),优化器为adam,训练指标为accuracy
    #model.summary()
    model.fit(x[train], y[train], epochs = 200, batch_size = 10, verbose = 0)  ##x[train]为训练数据,y[train]为目标值,epochs定义训练轮次,batch_size定义每一个批次训练多少数据,verbose定义训练中输出信息的频繁程度(0为最少)
    scores = model.evaluate(x[test], y[test], verbose = 0)  ##验证作用,x[test]为输入数据,y[test]为数据的标签,会返回损失值和指标值
    print(scores[1]*100)
    cvscores.append(scores[1]*100)
    y_pred = model.predict(x[test])  ##对x[test]进行预测,x[test]的个数为2270个
    np.savetxt("Results_3%s.csv" % cnt, np.column_stack((y[test], y_pred)), delimiter=",", fmt='%s')  ##保存数组,数组为y[test]和y_pred的合并数组

遇到的问题:

```python
Loading Data ...
Preparing Data ...
1
WARNING:tensorflow:From C:\Users\acer\anaconda3\envs\python36\lib\site-packages\tensorflow\python\ops\init_ops.py:1251: calling VarianceScaling.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.
Instructions for updating:
Call initializer instance with the dtype argument instead of passing it to the constructor
Traceback (most recent call last):
  File "F:/python(cheche)/BYSJ/shit.py", line 50, in <module>
    model.fit(x[train], y[train], epochs = 200, batch_size = 10, verbose = 0)  ##x[train]为训练数据,y[train]为目标值,epochs定义训练轮次,batch_size定义每一个批次训练多少数据,verbose定义训练中输出信息的频繁程度(0为最少)
  File "C:\Users\acer\anaconda3\envs\python36\lib\site-packages\tensorflow\python\keras\engine\training.py", line 709, in fit
    shuffle=shuffle)
  File "C:\Users\acer\anaconda3\envs\python36\lib\site-packages\tensorflow\python\keras\engine\training.py", line 2651, in _standardize_user_data
    exception_prefix='input')
  File "C:\Users\acer\anaconda3\envs\python36\lib\site-packages\tensorflow\python\keras\engine\training_utils.py", line 376, in standardize_input_data
    'with shape ' + str(data_shape))
ValueError: Error when checking input: expected conv1d_input to have 3 dimensions, but got array with shape (20430, 2048)

  • 写回答

2条回答 默认 最新

  • ash062 2022-03-19 22:41
    关注

    39行input_shape = (2048, 1)是说单个个样本shape,因此模型的输入数据shape应为(n, 2048, 1),可将52行改为

    model.fit(x[train].reshape(20430, 2048, 1), y[train], epochs = 200, batch_size = 10, verbose = 0)  ##x[train]为训练数据,y[train]为目标值,epochs定义训练轮次,batch_size定义每一个批次训练多少数据,verbose定义训练中输出信息的频繁程度(0为最少)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 3月28日
  • 已采纳回答 3月20日
  • 修改了问题 3月19日
  • 创建了问题 3月19日

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题