层“sequential”的输入 0 与层不兼容:预期 shape=(None, 60), found shape=(5, 174)
Posted
技术标签:
【中文标题】层“sequential”的输入 0 与层不兼容:预期 shape=(None, 60), found shape=(5, 174)【英文标题】:Input 0 of layer "sequential_3" is incompatible with the layer: expected shape=(None, 60), found shape=(5, 174) 【发布时间】:2022-01-16 03:46:22 【问题描述】:我正在对 1000 个以微笑作为输入的分子进行二进制分类。我的数据集来自
data = slice(1000)
data1 = df[data]
tokenizer = tf.keras.preprocessing.text.Tokenizer(
vocab_size, filters="", char_level=True)
tokenizer.fit_on_texts(data1.smiles)
seqs = tokenizer.texts_to_sequences(data1.smiles)
padded_seqs = tf.keras.preprocessing.sequence.pad_sequences(seqs, padding="post")
然后我建立了密集模型,并将交叉熵作为损失函数。
model = Sequential()
model.add(Dense(60, input_dim=60, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
# Compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
model.summary()
estimators = []
estimators.append(('standardize', StandardScaler()))
estimators.append(('mlp', KerasClassifier(build_fn= lambda: model, epochs=100,
batch_size=5, verbose=0)))
pipeline = Pipeline(estimators)
kfold = StratifiedKFold(n_splits=10, shuffle=True)
results = cross_val_score(pipeline,padded_seqs,data1.HIV_active, cv=kfold)
print("Standardized: %.2f%% (%.2f%%)" % (results.mean()*100, results.std()*100))
我的错误日志如下
/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:3: DeprecationWarning:
KerasClassifier is deprecated, use Sci-Keras (https://github.com/adriangb/scikeras)
instead.
This is separate from the ipykernel package so we can avoid doing imports until
Standardized: nan% (nan%)
/usr/local/lib/python3.7/dist-packages/sklearn/model_selection/_validation.py:372:
FitFailedWarning:
10 fits failed out of a total of 10.
The score on these train-test partitions for these parameters will be set to nan.
If these failures are not expected, you can try to debug them by setting
error_score='raise'.
Below are more details about the failures:
10 fits failed with the following error:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/dist-packages/sklearn/model_selection/_validation.py",
line 681, in _fit_and_score
estimator.fit(X_train, y_train, **fit_params)
File "/usr/local/lib/python3.7/dist-packages/sklearn/pipeline.py", line 394, in fit
self._final_estimator.fit(Xt, y, **fit_params_last_step)
File "/usr/local/lib/python3.7/dist-packages/keras/wrappers/scikit_learn.py", line 232, in fit
return super(KerasClassifier, self).fit(x, y, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/keras/wrappers/scikit_learn.py", line 164, in fit
history = self.model.fit(x, y, **fit_args)
File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 67, in error_handler
raise e.with_traceback(filtered_tb) from None
File "/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py", line 1129, in autograph_handler
raise e.ag_error_metadata.to_exception(e)
ValueError:在用户代码中:
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 878, in train_function *
return step_function(self, iterator)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 867, in step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 860, in run_step **
outputs = model.train_step(data)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 808, in train_step
y_pred = self(x, training=True)
File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 67, in error_handler
raise e.with_traceback(filtered_tb) from None
File "/usr/local/lib/python3.7/dist-packages/keras/engine/input_spec.py", line 263, in assert_input_compatibility
raise ValueError(f'Input input_index of layer "layer_name" is '
ValueError: Input 0 of layer "sequential_3" is incompatible with the layer: expected shape=(None, 60), found shape=(5, 174)
warnings.warn(some_fits_failed_message, FitFailedWarning)
ValueError: 是主要错误。很抱歉代码太长。请告诉我我的问题是否可以理解或措辞错误。
【问题讨论】:
【参考方案1】:你输入padded_seqs.shape
的形状是(1000, 174)
,所以输入形状应该是174,使用这个:
model.add(tf.keras.layers.Dense(60, input_dim=(174), activation='relu'))
【讨论】:
对其他人来说,它有效。谢谢! (因为我不能投票)以上是关于层“sequential”的输入 0 与层不兼容:预期 shape=(None, 60), found shape=(5, 174)的主要内容,如果未能解决你的问题,请参考以下文章
ValueError: 层 lstm_12 的输入 0 与层不兼容:预期 ndim=3,发现 ndim=4
ValueError:层顺序的输入 0 与层不兼容:输入形状的预期轴 -1 具有值 3,但接收到的输入具有形状
层 lstm_9 的输入 0 与层不兼容:预期 ndim=3,发现 ndim=4。收到的完整形状:[None, 2, 4000, 256]
ValueError: 层序号_29 的输入 0 与层不兼容:预期 ndim=3,发现 ndim=2。收到的完整形状:[无,22]
ValueError: 层 lstm_21 的输入 0 与层不兼容:预期 ndim=3,发现 ndim=2。收到的完整形状:(无,546)
ValueError:层顺序的输入 0 与层不兼容::预期 min_ndim=4,发现 ndim=3。收到的完整形状:[8, 28, 28]