简体   繁体   English

层顺序的输入 0 与层不兼容:输入形状的预期轴 -1 具有值 8,但收到的输入具有形状(无,71)

[英]Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 8 but received input with shape (None, 71)

I'm new to NN.我是 NN 的新手。 Can anybody help me to find out the error of this code?有人可以帮我找出这段代码的错误吗?

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D
from tensorflow.keras.losses import sparse_categorical_crossentropy
from tensorflow.keras.optimizers import Adam
from sklearn.model_selection import KFold
from numpy import loadtxt
import numpy as np
import pandas as pd

from google.colab import files
uploaded = files.upload()

dataset = loadtxt('mod_dfn.csv', delimiter=',')

X = dataset[:,0:71]
y = dataset[:,71]

kfold = KFold(n_splits=10, shuffle=True)

fold_no = 1
for train, test in kfold.split(X, y):

  model = Sequential()
  model.add(Dense(12, input_dim=8, activation='relu'))
  model.add(Dense(8, activation='relu'))
  model.add(Dense(1, activation='sigmoid'))

  model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

  print('------------------------------------------------------------------------')
  print(f'Training for fold {fold_no} ...')

  history = model.fit(X[train], y[train], batch_size=10, epochs=150, verbose=0)

  scores = model.evaluate(X[test], y[test], verbose=0)
  print(f'Score for fold {fold_no}: {model.metrics_names[0]} of {scores[0]}; {model.metrics_names[1]} of {scores[1]*100}%')
  acc_per_fold.append(scores[1] * 100)
  loss_per_fold.append(scores[0])

  fold_no = fold_no + 1

I'm getting this error我收到这个错误

------------------------------------------------------------------------
Training for fold 1 ...
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-16-4ad6d644594b> in <module>()
     17 
     18   # Fit data to model
---> 19   history = model.fit(X[train], y[train], batch_size=10, epochs=150, verbose=0)
     20 
     21   # Generate generalization metrics

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

ValueError: in user code:

    /usr/local/lib/python3.7/dist-packages/keras/engine/training.py:853 train_function  *
        return step_function(self, iterator)
    /usr/local/lib/python3.7/dist-packages/keras/engine/training.py:842 step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/distribute/distribute_lib.py:1286 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:2849 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:3632 _call_for_each_replica
        return fn(*args, **kwargs)
    /usr/local/lib/python3.7/dist-packages/keras/engine/training.py:835 run_step  **
        outputs = model.train_step(data)
    /usr/local/lib/python3.7/dist-packages/keras/engine/training.py:787 train_step
        y_pred = self(x, training=True)
    /usr/local/lib/python3.7/dist-packages/keras/engine/base_layer.py:1020 __call__
        input_spec.assert_input_compatibility(self.input_spec, inputs, self.name)
    /usr/local/lib/python3.7/dist-packages/keras/engine/input_spec.py:254 assert_input_compatibility
        ' but received input with shape ' + display_shape(x.shape))

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

From comments来自评论

You are passing a data with 71 features (X=[:,0:71]) while you have specified in your first layers input features as 8 (input_dim=8) .您正在传递具有71特征(X=[:,0:71])而您在第一层8 (input_dim=8)输入特征指定为8 (input_dim=8) Change input dim to input_dim=71 .将输入 dim 更改为input_dim=71

If your last layer has 1 output as a binary, then last dimension of Y also should be 1 .如果你的最后一层有1个二进制输出,那么 Y 的最后一个维度也应该是1

(Paraphrased from Kaveh) (转述自卡维)

暂无
暂无

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

相关问题 层序的输入 0 与层不兼容:输入形状的预期轴 -1 具有值 3,但收到的输入具有形状 - Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 3 but received input with shape ValueError:层顺序的输入 0 与层不兼容:输入形状的预期轴 -1 具有值 3,但接收到的输入具有形状 - ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 3 but received input with shape 层密集的输入 0 与层不兼容:输入形状的预期轴 -1 具有值 3,但收到的输入形状为 (None, 1) - Input 0 of layer dense is incompatible with the layer: expected axis -1 of input shape to have value 3 but received input with shape (None, 1) ValueError: 层序 7 的输入 0 与层不兼容:输入形状的预期轴 -1 具有值 5,但接收到的形状(无,21) - ValueError: Input 0 of layer sequential_7 incompatible with the layer: expected axis -1 of input shape to have value 5 but received shape (None, 21) 'ValueError:层顺序的输入0与层不兼容:输入形状的预期轴-1具有值3但接收到输入 - 'ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 3 but received input 层顺序_13 的输入 0 与层不兼容:预期轴 1 输入形状的值为 3,但接收到的输入形状为 (None, 30, 90, 1) - Input 0 of layer sequential_13 incompatible with the layer: expected axis-1 inputshape to have value 3 but received input with shape (None, 30, 90, 1) ValueError:层顺序的输入 0 与层不兼容:输入形状的预期轴 -1 具有值 3 [None, 224, 224, 1] - ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 3 [None, 224, 224, 1] ValueError: ...与图层不兼容:输入形状的预期轴 -1 的值为 20,但接收到的输入形状为 (None, 20, 637) - ValueError: ...incompatible with the layer: expected axis -1 of input shape to have value 20 but received input with shape (None, 20, 637) “ValueError:……与图层不兼容:输入形状的预期轴 -1 的值为 8,但接收到的输入形状为(无、7、169)” - “ValueError: …incompatible with the layer: expected axis -1 of input shape to have value 8 but received input with shape (None, 7, 169)” ValueError:密集层的输入 0 与层不兼容:预期轴 -1 的值为 8,但接收到形状为 [None, 1] 的输入 - ValueError: Input 0 of layer dense is incompatible with the layer: expected axis -1 to have value 8 but received input with shape [None, 1]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM