首页 > 解决方案 > DNN 中的错误:层序贯_10 的输入 0 与层不兼容

问题描述

描述

ValueError:层序 10 的输入 0 与层不兼容:输入形状的预期轴 -1 具有值 21,但接收到形状的输入(无,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)

标签: pythonnumpytensorflowkerasdeep-learning

解决方案


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

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 的大小和层数、查看效果等,然后尽情享受吧!


推荐阅读