首页 > 解决方案 > Python/TensorFlow/Keras - Input to reshape is a tensor with 300 values, but the requested shape has 200 [[{{node decoder_1/reshape_1/Reshape}}]]

问题描述

I want to transform my data from 2d to 3d for it I've created Autoencoder where code(hidden layer) has 3 neurons. When training starts it throws exception.

import numpy as np
import tensorflow as tf
from tensorflow.keras import layers
from sklearn.datasets import make_circles

input_vector = layers.Input(shape=(1,2))
encoded = layers.Dense(3,activation="relu")(input_vector)

input_encoded = layers.Input(shape=(3,))
x = layers.Dense(3,activation="relu")(input_encoded)
decoded = layers.Reshape((1,2))(x)

encoder = tf.keras.Model(input_vector, encoded, name="encoder")
decoder = tf.keras.Model(input_encoded, decoded, name="decoder")
autoencoder = tf.keras.Model(input_vector, decoder(encoder(input_vector)), name="autoencoder")

autoencoder.compile(optimizer='adam', loss='binary_crossentropy')

count = 1000
X, y = make_circles(n_samples=count, noise=0.05)
x_test, y = make_circles(n_samples=count, noise=0.05)

X = np.reshape(X,(count,1,2))
x_test = np.reshape(x_test,(count,1,2))

autoencoder.fit(X, X,
                epochs=5,
                batch_size=100,
                shuffle=True,
                validation_data=(x_test, x_test))

Actual result it throws exception

---------------------------------------------------------------------------
InvalidArgumentError: Input to reshape is a tensor with 300 values, but the requested shape has 200
     [[{{node decoder_1/reshape_1/Reshape}}]]

标签: pythontensorflowkerasautoencodertf.keras

解决方案


替换x = layers.Dense(3,activation="relu")(input_encoded)x = layers.Dense(2,activation="relu")(input_encoded)将解决您的问题。

原因是输入layers.Reshape((1,2))应该是形状的(100, 2)(在您的情况下,100 是批量大小),但是您输入的是形状张量,(100, 3)因此输入了错误。


推荐阅读