当我尝试运行此代码时:-
import pandas as pd
import tensorflow as tf
from sklearn.model_selection import train_test_split
dataset = pd.read_csv ("/content/dataset/cancer.csv")
x = dataset.drop(columns = ["diagnosis(1=m, 0=b)"])
y = dataset["diagnosis(1=m, 0=b)"]
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Dense(256, input_shape = x_train.shape, activation="sigmoid"))
model.add(tf.keras.layers.Dense(256, activation="sigmoid"))
model.add(tf.keras.layers.Dense(1, activation="sigmoid"))
model.compile(optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"])
model.fit(x_train, y_train, epochs=1000)
在 Epoch 1 上,我收到错误:-
Epoch 1/1000
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-45-a5e6a9bff808> in <cell line: 1>()
----> 1 model.fit(x_train, y_train, epochs=1000)
1 frames
/usr/local/lib/python3.10/dist-packages/keras/src/engine/training.py in tf__train_function(iterator)
13 try:
14 do_return = True
---> 15 retval_ = ag__.converted_call(ag__.ld(step_function), (ag__.ld(self), ag__.ld(iterator)), None, fscope)
16 except:
17 do_return = False
ValueError: in user code:
File "/usr/local/lib/python3.10/dist-packages/keras/src/engine/training.py", line 1377, in train_function *
return step_function(self, iterator)
File "/usr/local/lib/python3.10/dist-packages/keras/src/engine/training.py", line 1360, in step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "/usr/local/lib/python3.10/dist-packages/keras/src/engine/training.py", line 1349, in run_step **
outputs = model.train_step(data)
File "/usr/local/lib/python3.10/dist-packages/keras/src/engine/training.py", line 1126, in train_step
y_pred = self(x, training=True)
File "/usr/local/lib/python3.10/dist-packages/keras/src/utils/traceback_utils.py", line 70, in error_handler
raise e.with_traceback(filtered_tb) from None
File "/usr/local/lib/python3.10/dist-packages/keras/src/engine/input_spec.py", line 298, in assert_input_compatibility
raise ValueError(
ValueError: Input 0 of layer "sequential_10" is incompatible with the layer: expected shape=(None, 455, 30), found shape=(None, 30)
你能帮我了解发生了什么事吗?感谢您的帮助。
代码中的问题是由于神经网络模型使用了不准确的输入形状而引起的。这是导致此错误的代码行:
model.add(tf.keras.layers.Dense(256, input_shape=x_train.shape, activation="sigmoid"))
您使用了
input_shape=x_train.shape
,它与数据集中的特征数量不对应。
要解决此问题,您应该指定与数据集中的 30 个要素相符的正确输入形状。这是修改后的代码行:
model.add(tf.keras.layers.Dense(256, input_shape=(30,), activation="sigmoid"))