DNN 中的错误:层序贯_10 的输入 0 与层不兼容

Posted

技术标签:

【中文标题】DNN 中的错误:层序贯_10 的输入 0 与层不兼容【英文标题】:Error in DNN: Input 0 of layer sequential_10 is incompatible with the layer 【发布时间】:2021-07-03 01:55:10 【问题描述】:

说明

ValueError: 层顺序_10 的输入 0 与层不兼容:输入形状的预期轴 -1 具有值 21,但接收到形状为 (None, 22) 的输入

我正在为帕金森预测创建一个 DNN 模型。数据集来自 UCI 存储库。我将数据集切成 195 行和 23 列。有 22 个特征和一个类别标签属性表示正面或负面。当我尝试用 keras 拟合模型时,它显示输入形状的预期轴 -1 的值为 21,但接收到的输入形状为(无,22)。

代码

from numpy import loadtxt
from keras.models import Sequential
from keras.layers import Dense
dataset = loadtxt(r'/parkinsons.data - Copy.csv',delimiter=',')
X = dataset[:, 0:22]
y = dataset[:, 22]
X.shape
model = Sequential()
model.add(Dense(21, input_dim=21, activation='relu'))
model.add(Dense(21, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X, y, epochs=150, batch_size=10)

错误

Epoch 1/150
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-67-39d59395a0a6> in <module>()
----> 1 model.fit(X, y, epochs=150, batch_size=10)

9 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
    975           except Exception as e:  # pylint:disable=broad-except
    976             if hasattr(e, "ag_error_metadata"):
--> 977               raise e.ag_error_metadata.to_exception(e)
    978             else:
    979               raise

ValueError: in user code:

    /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/training.py:805 train_function  *
        return step_function(self, iterator)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/training.py:795 step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/distribute/distribute_lib.py:1259 run
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/distribute/distribute_lib.py:2730 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/distribute/distribute_lib.py:3417 _call_for_each_replica
        return fn(*args, **kwargs)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/training.py:788 run_step  **
        outputs = model.train_step(data)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/training.py:754 train_step
        y_pred = self(x, training=True)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/base_layer.py:998 __call__
        input_spec.assert_input_compatibility(self.input_spec, inputs, self.name)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/input_spec.py:259 assert_input_compatibility
        ' but received input with shape ' + display_shape(x.shape))

    ValueError: Input 0 of layer sequential_10 is incompatible with the layer: expected axis -1 of input shape to have value 21 but received input with shape (None, 22)

【问题讨论】:

尝试将 inp_dim 改为 22。或者用 21 个样本进行切片 【参考方案1】:

我建议您通过调整此过程来创建模型:

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

# Sequential malli, 3 kerrosta
model = keras.Sequential(
    [
        layers.Dense(21, activation="relu", name="layer1"),
        layers.Dense(21, activation="relu", name="layer2"),
        layers.Dense(1, activation="sigmoid", name="layer3"),
    ]
)

#Maaritellaan eli let's define the training...
model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])

#Create the test data
x=tf.random.normal([195, 23],0,1,tf.float32,seed=1)
y=tf.random.normal([195, 1],0,1,tf.float32,seed=1)

model.fit(x,y,epochs=5,batch_size=2)

print("Valmista eli ready!")

...如果你得到类似的结果:

...您知道您可以从基本元素创建和训练 DNN。然后尝试训练您的数据、研究性能、更改 DNN 的大小和层数、查看效果等,然后尽情享受吧!

【讨论】:

但是我怎样才能用那个数据集训练模型.. tf.random.normal 在测试数据中的目的是什么??? 我编写了上面的代码,以便您能够创建和训练 DNN。因此,首先将代码“按原样”复制并粘贴到您的编辑器上并运行它以验证您获得与我相同的结果。如果是,则将 x=tf.random.normal... 替换为 x=dataset[:, 0:22] 并将 y=ft.random.normal... 替换为 y=dataset[:, 22]。当然,在此之前添加 loadtext 命令等来导入您自己的数据。请检查您是否确实读取了正确的列,我的意思是您是否应该写 x=dataset[:, 0:21],但不要在意,在其他一切正常后检查。

以上是关于DNN 中的错误:层序贯_10 的输入 0 与层不兼容的主要内容,如果未能解决你的问题,请参考以下文章

ValueError: 层序贯_17 的输入 0 与层不兼容:预期 ndim=3,发现 ndim=2。收到的完整形状:[无,121]

ValueError 层序贯_13的输入0与层不兼容:预期ndim = 3,发现ndim = 4收到完整形状:(无,无,无,无)

层 lstm_9 的输入 0 与层不兼容:预期 ndim=3,发现 ndim=4。收到的完整形状:[None, 300, 300, 1]

ValueError:lstm_45 层的输入 0 与层不兼容:预期 ndim=3,发现 ndim=4。收到的完整形状:(无,无,无,128)

ValueError: 层 lstm_12 的输入 0 与层不兼容:预期 ndim=3,发现 ndim=4

层 lstm_9 的输入 0 与层不兼容:预期 ndim=3,发现 ndim=4。收到的完整形状:[None, 2, 4000, 256]