Tensorflow 如何解决model.predict()中的值错误?

Tensorflow 如何解决model.predict()中的值错误?,tensorflow,conv-neural-network,keras-layer,intrusion-detection,Tensorflow,Conv Neural Network,Keras Layer,Intrusion Detection,我是神经网络问题的新手。我已经搜索了几个小时,但不明白该如何解决此问题!我正在使用nsl kdd数据集,用于卷积神经网络入侵检测系统 我遇到了这个问题:ValueError:layer density_14的输入0与该层不兼容:输入形状的轴-1应具有值3904,但收到的输入具有形状[None,3712] 形状: x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1)) #(125973, 122, 1) x_t

我是神经网络问题的新手。我已经搜索了几个小时,但不明白该如何解决此问题!我正在使用nsl kdd数据集,用于卷积神经网络入侵检测系统

我遇到了这个问题:ValueError:layer density_14的输入0与该层不兼容:输入形状的轴-1应具有值3904,但收到的输入具有形状[None,3712]

形状:

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)
x_列车(1259731222)

y_列车(125973,5)

x_检验(22544116)

y_测试(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)
型号:

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)
编译:

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)

问题:问题在于测试集的维度与训练集的维度相同。测试集应该看起来像是从培训集中抽取了一个样本。因此,如果您的训练集具有维度
x_train.shape=(125973,122)
y_train.shape=(125973,5)
。然后您的测试集应该具有维度
x\u test.shape=(sample\u num,122)
y\u test.shape=(sample\u num,5)

可能的解决方案:如果您不想使用测试集,那么这是一种简单的测试方法,可以在
.fit()
中进行验证拆分。

因此:
model.fit(x\u-train,Y\u-train,epochs=5,batch\u-size=32)

将变成这样:
model.fit(x\u-train,Y\u-train,epochs=5,batch\u-size=32,validation\u-split=0.2)


这将切掉20%的训练数据并用于测试。然后,在每个历元之后,TensorFlow将打印网络在验证数据上的执行情况,以便您可以看到您的模型在以前从未见过的数据上的执行情况。

问题:问题是您的测试集确实与您的训练集具有相同的维度。测试集应该看起来像是从培训集中抽取了一个样本。因此,如果您的训练集具有维度
x_train.shape=(125973,122)
y_train.shape=(125973,5)
。然后您的测试集应该具有维度
x\u test.shape=(sample\u num,122)
y\u test.shape=(sample\u num,5)

可能的解决方案:如果您不想使用测试集,那么这是一种简单的测试方法,可以在
.fit()
中进行验证拆分。

因此:
model.fit(x\u-train,Y\u-train,epochs=5,batch\u-size=32)

将变成这样:
model.fit(x\u-train,Y\u-train,epochs=5,batch\u-size=32,validation\u-split=0.2)


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

您的x_测试应该与x_train具有相同的尺寸。
x_列=(125973、122、1)

x_测试=(22544116,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, 122, 1))
y1 = np.random.randint(100, size =(125973,5), dtype = np.int32)
y2 = np.random.randint(2, size =(22544, ), 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)
您的模型如下所示:

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

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

pred = model.predict(x2)
pred
输出:

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

您的x_测试应具有与x_列车相同的尺寸。
x_列=(125973、122、1)

x_测试=(22544116,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, 122, 1))
y1 = np.random.randint(100, size =(125973,5), dtype = np.int32)
y2 = np.random.randint(2, size =(22544, ), 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)
您的模型如下所示:

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

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

pred = model.predict(x2)
pred
输出:

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

非常感谢你,它成功了!但另一个问题是,现在损失如此之高。你能就这个问题向我提出一些建议吗?这将非常有帮助。再次感谢:)损失在减少吗?看一下报纸。还有,检查一下这个。我已经找到了问题所在。非常感谢你一次又一次:)你帮了我大忙:DDone兄弟!:谢谢你,它很管用!但另一个问题是,现在损失如此之高。你能就这个问题向我提出一些建议吗?这将非常有帮助。再次感谢:)损失在减少吗?看一下报纸。还有,检查一下这个。我已经找到了问题所在。非常感谢你一次又一次:)你帮了我大忙:DDone兄弟!:太感谢你了@Leon Shams!这也很有帮助:)非常感谢@Leon Shams!这也很有帮助:)