简体   繁体   English

Keras:层顺序的输入 0 与层不兼容

[英]Keras: Input 0 of layer sequential is incompatible with the layer

I am trying to create a neural network model with one hidden layer and then trying to evaluate it, but I am getting an error that I am not able to understand clearly:我正在尝试创建一个带有一个隐藏层的神经网络模型,然后尝试对其进行评估,但我收到一个我无法清楚理解的错误:

ValueError: Input 0 of layer sequential_1 is incompatible with the layer: : expected min_ndim=2, found ndim=1. ValueError: 层序列 1 的输入 0 与层不兼容:预期 min_ndim=2,发现 ndim=1。 Full shape received: [30]收到的完整形状:[30]

It looks like I have an error with the dimensions of my input layer, but I can't quite spot what.看起来我的输入层的尺寸有误,但我不太明白是什么。 I've googled and looked on stackoverflow, but haven't found anything that worked so far.我用谷歌搜索并查看了stackoverflow,但到目前为止还没有找到任何有用的东西。 Any help please?请问有什么帮助吗?

Here's a minimal working example:这是一个最小的工作示例:

import tensorflow as tf

# Define Sequential model with 3 layers
input_dim = 30
num_neurons = 10
output_dim = 12
model = tf.keras.Sequential(
    [
        tf.keras.layers.Dense(input_dim, activation="relu", name="layer1"),
        tf.keras.layers.Dense(num_neurons, activation="relu", name="layer2"),
        tf.keras.layers.Dense(output_dim, name="layer3"),
    ]
)
model(tf.ones(input_dim))

Layers have an input and output dimension.层具有输入和输出维度。 For layers in the "middle" of the NN, they figure out their input domain from the output domain of the previous layer.对于神经网络“中间”的层,它们从前一层的输出域中找出它们的输入域。 The only exception is the first layer that has nothing to go by, and requires input_dim to be set.唯一的例外是第一层没有任何内容,需要设置input_dim Here is how to fix your code.这是修复代码的方法。 Note how we pass the dimensions.请注意我们如何传递维度。 First (hidden) layer is input_dim x num_neurons, second (output layer) num_neurons x output_dim第一个(隐藏)层是 input_dim x num_neurons,第二个(输出层)num_neurons x output_dim

You can stick more layers in between the two;您可以在两者之间粘贴更多层; they only require the first argument, their output dimension他们只需要第一个参数,他们的输出维度

also note I had to fix your last line as well, tf.ones needs to be a 2D shape num_observation x input_dim另请注意,我还必须修复您的最后一行,tf.ones 需要是 2D 形状 num_observation x input_dim

import tensorflow as tf

# Define Sequential model with 1 hidden layer
input_dim = 30
num_neurons = 10
output_dim = 12
model = tf.keras.Sequential(
    [
        tf.keras.layers.Dense(num_neurons, input_dim = input_dim, activation="relu", name="layer1"),
        tf.keras.layers.Dense(output_dim, name="layer3"),
    ]
)
model(tf.ones((1,input_dim)))

produces (for me; I think the numbers are essentially random initialization)产生(对我来说;我认为这些数字本质上是随机初始化)

<tf.Tensor: shape=(1, 12), dtype=float32, numpy=
array([[ 0.06973769, -0.1798143 , -0.2920275 ,  0.84811246,  0.44899416,
        -0.10300556,  0.00831143, -0.16158538,  0.13395026,  0.4352504 ,
         0.19114715,  0.44100884]], dtype=float32)>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM