提问人:MAGY 提问时间:10/4/2023 最后编辑:MAGY 更新时间:10/4/2023 访问量:22
卷积自动编码器输入形状值错误的网格搜索
Gridsearch on convolutional autoencoder input shape value error
问:
我尝试使用网格搜索优化卷积自动编码器。不幸的是,我遇到了一个我不太理解的错误,并且我卡住了。错误写在下面,似乎形状有错误,但我不明白。整个代码写在下面,可以运行,因为它直接下载 mnist-dataset。 我将不胜感激任何帮助,并提前感谢! 此致 MAGY
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D
from tensorflow.keras.models import Model
from tensorflow.keras.datasets import mnist
from sklearn.model_selection import GridSearchCV
from tensorflow.keras.wrappers.scikit_learn import KerasClassifier
from tensorflow.keras.optimizers import Adam
# Laden des MNIST-Datensatzes und Vorbereitung
(train_images, _), (test_images, _) = mnist.load_data()
train_images = train_images.astype('float32') / 255.0
test_images = test_images.astype('float32') / 255.0
train_images = np.reshape(train_images, (len(train_images), 28, 28, 1))
test_images = np.reshape(test_images, (len(test_images), 28, 28, 1))
# Funktion zur Erstellung des Autoencoders
def create_autoencoder(optimizer='adam', encoding_dim=32):
input_img = Input(shape=(28, 28, 1))
# Encoder
x = Conv2D(16, (3, 3), activation='relu', padding='same')(input_img)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(encoding_dim, (3, 3), activation='relu', padding='same')(x)
encoded = MaxPooling2D((2, 2), padding='same')(x)
# Decoder
x = Conv2D(encoding_dim, (3, 3), activation='relu', padding='same')(encoded)
x = UpSampling2D((2, 2))(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = UpSampling2D((2, 2))(x)
x = Conv2D(16, (3, 3), activation='relu')(x)
x = UpSampling2D((2, 2))(x)
decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x)
autoencoder = Model(input_img, decoded)
autoencoder.compile(optimizer=optimizer, loss='binary_crossentropy')
return autoencoder
# Wrapper, um das Autoencoder-Modell mit GridSearchCV zu verwenden
model = KerasClassifier(build_fn=create_autoencoder, verbose=0)
# Hyperparameter-Raster definieren
param_grid = {
'optimizer': ['adam', 'sgd'],
'encoding_dim': [32, 64]
}
# Rastersuche durchführen
grid_search = GridSearchCV(estimator=model, param_grid=param_grid, cv=3)
grid_search.fit(train_images, train_images)
# Beste Kombination von Hyperparametern anzeigen
print("Beste Kombination von Hyperparametern:")
print(grid_search.best_params_)
# Autoencoder-Modell mit den besten Hyperparametern erstellen
best_autoencoder = create_autoencoder(
optimizer=grid_search.best_params_['optimizer'],
encoding_dim=grid_search.best_params_['encoding_dim']
)
# Autoencoder trainieren
best_autoencoder.fit(train_images, train_images, epochs=10, batch_size=128)
# Autoencoder auf Testdaten anwenden
decoded_images = best_autoencoder.predict(test_images)
# Beispiel: Anzeigen eines Originalbildes und des rekonstruierten Bildes
import matplotlib.pyplot as plt
n = 10 # Anzahl der Bilder zum Anzeigen
plt.figure(figsize=(20, 4))
for i in range(n):
# Originalbild
ax = plt.subplot(2, n, i + 1)
plt.imshow(test_images[i].reshape(28, 28))
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
# Rekonstruiertes Bild
ax = plt.subplot(2, n, i + 1 + n)
plt.imshow(decoded_images[i].reshape(28, 28))
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()
值错误: 所有 12 次拟合都失败了。 您的模型很可能配置错误。 您可以尝试通过设置 error_score='raise' 来调试错误。
以下是有关故障的更多详细信息:
12 拟合失败,出现以下错误: 回溯(最近一次调用最后一次):
文件 “/usr/local/lib/python3.8/dist-packages/sklearn/model_selection/_validation.py”,第 729 行,_fit_and_score estimator.fit(X_train, y_train, **fit_params) 文件“/usr/local/lib/python3.8/dist-packages/keras/wrappers/scikit_learn.py”,第 246 行,适合 raise ValueError(“y 的无效形状:” + str(y.shape)) ValueError:y 的形状无效:(40000, 28, 28, 1)
我检查了 test_images.shape,它是 (10000, 28, 28, 1) 而不是 (40000,28,28,1)
答: 暂无答案
评论