如何解决model.predict中的ValueError?

问题描述

我是神经网络方面的新手。我已经搜索了几个小时,但不知道该怎么办才能解决此问题!我正在使用nsl-kdd数据集开发具有卷积神经网络的入侵检测系统。

我遇到了这个问题: ValueError:密集层14的输入0与该层不兼容:输入形状的预期轴-1的值为3904,但接收到形状为[None,3712]的输入

形状:

x_train (125973,122)

y_train (125973,5)

x_test (22544,116)

y_test (22544,)

重塑后:

x_train = np.reshape(x_train,(x_train.shape[0],x_train.shape[1],1)) #(125973,122,1)

x_test = np.reshape(x_test,(x_test.shape[0],x_test.shape[1],1)) #(22544,116,1)

型号:

model = Sequential()
model.add(Convolution1D(64,3,padding="same",activation="relu",input_shape = (x_train.shape[1],1)))
model.add(MaxPooling1D(pool_size=(2)))
model.add(Flatten())
model.add(Dense(128,activation="relu"))
model.add(Dropout(0.5))
model.add(Dense(5,activation="softmax"))

编译:

model.compile(optimizer = 'adam',loss = 'categorical_crossentropy',metrics = ['accuracy'])
model.fit(x_train,Y_train,epochs = 5,batch_size = 32)

pred = model.predict(x_test)  #problem is occurring for this line
y_pred= np.argmax(pred,axis = 1)

documentation

解决方法

问题:问题是您的测试集确实具有与训练集相同的尺寸。测试集看起来应该好像是从训练集中抽取的样本一样。因此,如果您的训练集的维度为x_train.shape = (125973,122)y_train.shape = (125973,5)。然后,您的测试集应具有尺寸x_test.shape = (sample_num,122)y_test.shape = (sample_num,5)

可能的解决方案:如果您不想使用自己的测试集,可以通过.fit()中的验证拆分来轻松进行测试。

所以这:model.fit(x_train,Y_train,epochs = 5,batch_size = 32)
会变成这样:model.fit(x_train,batch_size = 32,validation_split=0.2)

这将砍掉您训练数据的20%并将其用于测试。然后,在每个时期之后,TensorFlow将打印网络如何对该验证数据执行操作,以便您可以查看模型如何处理从未见过的数据。

,

您的x_test应该具有与x_train相同的尺寸。
x_train =(125973,122,1)

x_test =(22544,116,1)#第二个参数必须与火车组匹配

代码示例:

import tensorflow as tf
import pandas as pd 
import numpy as np
from tensorflow.keras.layers import *
from tensorflow.keras import *


x1 = np.random.uniform(100,size =(125973,122,1))
x2 = np.random.uniform(100,size =(22544,1))
y1 = np.random.randint(100,5),dtype = np.int32)
y2 = np.random.randint(2,),dtype = np.int32)

def create_model2():
    model = Sequential()
    model.add(Convolution1D(64,3,padding="same",activation="relu",input_shape = (x1.shape[1],1)))
    model.add(MaxPooling1D(pool_size=(2)))
    model.add(Flatten())
    model.add(Dense(128,activation="relu"))
    model.add(Dropout(0.5))
    model.add(Dense(5,activation="softmax"))
    
    model.compile(optimizer = 'adam',loss = 'categorical_crossentropy',metrics = ['accuracy'])
    return model

model = create_model2()
tf.keras.utils.plot_model(model,'my_first_model.png',show_shapes=True)

您的模型如下所示:

this

现在,如果使用测试集创建模型,并保持尺寸为(22544,116,1)。
您会得到一个看起来像这样的模型。
由于尺寸不同,每层的预期输入和输出也不同。

this

当您具有适当的测试尺寸时,输出将按预期工作:

pred = model.predict(x2)
pred

输出:

array([[1.,0.,0.],[1.,...,0.]],dtype=float32)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...