层级sequential的输入0与层不兼容:期望输入形状的轴-1的值为8,但接收到的输入形状为(None, 71)

我是神经网络的新手。有人能帮我找出这段代码的错误吗?

from tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2Dfrom tensorflow.keras.losses import sparse_categorical_crossentropyfrom tensorflow.keras.optimizers import Adamfrom sklearn.model_selection import KFoldfrom numpy import loadtxtimport numpy as npimport pandas as pdfrom google.colab import filesuploaded = files.upload()dataset = loadtxt('mod_dfn.csv', delimiter=',')X = dataset[:,0:71]y = dataset[:,71]kfold = KFold(n_splits=10, shuffle=True)fold_no = 1for 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

我收到了这个错误

------------------------------------------------------------------------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 metrics9 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               raiseValueError: 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)

回答:

来自评论

您传递的数据具有71个特征(X=[:,0:71]),而您在第一层的输入特征中指定为8 (input_dim=8)。请将输入维度改为input_dim=71

如果您的最后一层输出为1作为二进制输出,那么Y的最后一维也应该为1

(转述自Kaveh)

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注