ValueError:“顺序”的输入0;与该层不兼容:预期形状=(无,81),发现形状=(无,77)
我正在尝试培训神经网络,但我会收到以下错误:
ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 81), found shape=(None, 77)
我试图找到解决方案,但无法做到。有人可以帮我吗?
这是与建议的代码相同的代码
from sklearn.preprocessing import StandardScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.wrappers.scikit_learn import KerasRegressor
from tensorflow.keras.callbacks import EarlyStopping
# Scaling the data
ss = StandardScaler()
X_train_sc = ss.fit_transform(X_train)
X_test_sc = ss.transform(X_test)
# Creating our model's structure
model = Sequential()
model.add(Dense(64, activation='relu', input_shape=(81,)))
model.add(Dropout(0.18))
model.add(Dense(32, activation='relu'))
model.add(Dropout(0.15))
model.add(Dense(1, activation='sigmoid'))
es = EarlyStopping(monitor='val_loss', patience=5)
# Compiling the model
model.compile(loss='bce',
optimizer='adam',
metrics=['binary_accuracy'])
# Fitting the model
history = model.fit(X_train_sc,
y_train,
batch_size = 256,
validation_data =(X_test_sc, y_test),
epochs = 500,
verbose = 0,
callbacks=[es])
,我已将代码编辑为:
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.wrappers.scikit_learn import KerasRegressor
from tensorflow.keras.callbacks import EarlyStopping
import tensorflow as tf
samples = 500
X_train_sc = tf.random.normal((samples, 81))
y_train = tf.random.uniform((samples, ), maxval=2, dtype=tf.int32)
# Creating our model's structure
model = Sequential()
model.add(Dense(64, activation='relu', input_shape=(81,)))
model.add(Dropout(0.18))
model.add(Dense(32, activation='relu'))
model.add(Dropout(0.15))
model.add(Dense(1, activation='sigmoid'))
es = EarlyStopping(monitor='val_loss', patience=5)
# Compiling the model
model.compile(loss='bce',
optimizer='adam',
metrics=['binary_accuracy'])
# Fitting the model
history = model.fit(X_train_sc,
y_train,
batch_size = 32,
epochs = 2,
verbose = 0)
但是,当我尝试找到准确性时,我会得到与下面相同的错误:
# Scoring
train_score = model.evaluate(X_train_sc,
y_train,
verbose=1)
test_score = model.evaluate(X_test_sc,
y_test,
verbose=1)
labels = model.metrics_names
print('')
print(f'Training Accuracy: {train_score[1]}')
print(f'Testing Accuracy: {test_score[1]}')
16/16 [==============================] - 0s 2ms/step - loss: 0.6613 - binary_accuracy: 0.6040
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_7572/1082894889.py in <module>
3 y_train,
4 verbose=1)
----> 5 test_score = model.evaluate(X_test_sc,
6 y_test,
7 verbose=1)
~\Anaconda3\lib\site-packages\keras\utils\traceback_utils.py in error_handler(*args, **kwargs)
65 except Exception as e: # pylint: disable=broad-except
66 filtered_tb = _process_traceback_frames(e.__traceback__)
---> 67 raise e.with_traceback(filtered_tb) from None
68 finally:
69 del filtered_tb
~\Anaconda3\lib\site-packages\tensorflow\python\framework\func_graph.py in autograph_handler(*args, **kwargs)
1145 except Exception as e: # pylint:disable=broad-except
1146 if hasattr(e, "ag_error_metadata"):
-> 1147 raise e.ag_error_metadata.to_exception(e)
1148 else:
1149 raise
ValueError: in user code:
File "C:\Users\sadik\Anaconda3\lib\site-packages\keras\engine\training.py", line 1525, in test_function *
return step_function(self, iterator)
File "C:\Users\sadik\Anaconda3\lib\site-packages\keras\engine\training.py", line 1514, in step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "C:\Users\sadik\Anaconda3\lib\site-packages\keras\engine\training.py", line 1507, in run_step **
outputs = model.test_step(data)
File "C:\Users\sadik\Anaconda3\lib\site-packages\keras\engine\training.py", line 1471, in test_step
y_pred = self(x, training=False)
File "C:\Users\sadik\Anaconda3\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
raise e.with_traceback(filtered_tb) from None
File "C:\Users\sadik\Anaconda3\lib\site-packages\keras\engine\input_spec.py", line 264, in assert_input_compatibility
raise ValueError(f'Input {input_index} of layer "{layer_name}" is '
ValueError: Input 0 of layer "sequential_4" is incompatible with the layer: expected shape=(None, 81), found shape=(None, 77)
I am trying to train a neural network but I am getting the following error:
ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 81), found shape=(None, 77)
I tried to find the solution to this but am unable to do so. Can someone please help me?
Here Is the code of the same
from sklearn.preprocessing import StandardScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.wrappers.scikit_learn import KerasRegressor
from tensorflow.keras.callbacks import EarlyStopping
# Scaling the data
ss = StandardScaler()
X_train_sc = ss.fit_transform(X_train)
X_test_sc = ss.transform(X_test)
# Creating our model's structure
model = Sequential()
model.add(Dense(64, activation='relu', input_shape=(81,)))
model.add(Dropout(0.18))
model.add(Dense(32, activation='relu'))
model.add(Dropout(0.15))
model.add(Dense(1, activation='sigmoid'))
es = EarlyStopping(monitor='val_loss', patience=5)
# Compiling the model
model.compile(loss='bce',
optimizer='adam',
metrics=['binary_accuracy'])
# Fitting the model
history = model.fit(X_train_sc,
y_train,
batch_size = 256,
validation_data =(X_test_sc, y_test),
epochs = 500,
verbose = 0,
callbacks=[es])
As suggested I have edited the code to:
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.wrappers.scikit_learn import KerasRegressor
from tensorflow.keras.callbacks import EarlyStopping
import tensorflow as tf
samples = 500
X_train_sc = tf.random.normal((samples, 81))
y_train = tf.random.uniform((samples, ), maxval=2, dtype=tf.int32)
# Creating our model's structure
model = Sequential()
model.add(Dense(64, activation='relu', input_shape=(81,)))
model.add(Dropout(0.18))
model.add(Dense(32, activation='relu'))
model.add(Dropout(0.15))
model.add(Dense(1, activation='sigmoid'))
es = EarlyStopping(monitor='val_loss', patience=5)
# Compiling the model
model.compile(loss='bce',
optimizer='adam',
metrics=['binary_accuracy'])
# Fitting the model
history = model.fit(X_train_sc,
y_train,
batch_size = 32,
epochs = 2,
verbose = 0)
But when I try to find the accuracy I get the same error as shown below:
# Scoring
train_score = model.evaluate(X_train_sc,
y_train,
verbose=1)
test_score = model.evaluate(X_test_sc,
y_test,
verbose=1)
labels = model.metrics_names
print('')
print(f'Training Accuracy: {train_score[1]}')
print(f'Testing Accuracy: {test_score[1]}')
16/16 [==============================] - 0s 2ms/step - loss: 0.6613 - binary_accuracy: 0.6040
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_7572/1082894889.py in <module>
3 y_train,
4 verbose=1)
----> 5 test_score = model.evaluate(X_test_sc,
6 y_test,
7 verbose=1)
~\Anaconda3\lib\site-packages\keras\utils\traceback_utils.py in error_handler(*args, **kwargs)
65 except Exception as e: # pylint: disable=broad-except
66 filtered_tb = _process_traceback_frames(e.__traceback__)
---> 67 raise e.with_traceback(filtered_tb) from None
68 finally:
69 del filtered_tb
~\Anaconda3\lib\site-packages\tensorflow\python\framework\func_graph.py in autograph_handler(*args, **kwargs)
1145 except Exception as e: # pylint:disable=broad-except
1146 if hasattr(e, "ag_error_metadata"):
-> 1147 raise e.ag_error_metadata.to_exception(e)
1148 else:
1149 raise
ValueError: in user code:
File "C:\Users\sadik\Anaconda3\lib\site-packages\keras\engine\training.py", line 1525, in test_function *
return step_function(self, iterator)
File "C:\Users\sadik\Anaconda3\lib\site-packages\keras\engine\training.py", line 1514, in step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "C:\Users\sadik\Anaconda3\lib\site-packages\keras\engine\training.py", line 1507, in run_step **
outputs = model.test_step(data)
File "C:\Users\sadik\Anaconda3\lib\site-packages\keras\engine\training.py", line 1471, in test_step
y_pred = self(x, training=False)
File "C:\Users\sadik\Anaconda3\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
raise e.with_traceback(filtered_tb) from None
File "C:\Users\sadik\Anaconda3\lib\site-packages\keras\engine\input_spec.py", line 264, in assert_input_compatibility
raise ValueError(f'Input {input_index} of layer "{layer_name}" is '
ValueError: Input 0 of layer "sequential_4" is incompatible with the layer: expected shape=(None, 81), found shape=(None, 77)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题在于您的输入数据的形状与第一层中定义的形状不同。确保数据的功能维度对应于模型第一层中的输入形状。这是一个示例:
因此,如果您的功能维度为77,则将
input_shape =(81,)
更改为input_shape =(77,)
。The problem is that your input data does not have the same shape that you defined in your first layer. Make sure the features dimension of your data corresponds to the input shape in the model's first layer. Here is an example:
So, if your feature dimension is 77 then change
input_shape=(81,)
toinput_shape=(77,)
.