1
$\begingroup$

I am trying to train an autoencoder with images. But at the time of training, I get an error, what am I doing wrong? I am using Colab.

import keras
from keras import layers

# This is the size of our encoded representations
encoding_dim = 32  # 32 floats -> compression of factor 24.5, assuming the input is 784 floats

#28*28=784  tamaño de images de nmist
#256*256=65536   tamaño de images mias
#60*60=3600 anime dataset

ancho=60
alto=60
n_pixels=alto*ancho

# This is our input image
input_img = keras.Input(shape=(n_pixels,3,))

# "encoded" is the encoded representation of the input
encoded = layers.Dense(encoding_dim, activation='relu')(input_img)
# "decoded" is the lossy reconstruction of the input
decoded = layers.Dense(n_pixels, activation='sigmoid')(encoded)


# This model maps an input to its reconstruction
autoencoder = keras.Model(input_img, decoded)

# This model maps an input to its encoded representation
encoder = keras.Model(input_img, encoded)




# This is our encoded (32-dimensional) input
encoded_input = keras.Input(shape=(encoding_dim,))#la salid del encoder osea la entrada del decoder
# Retrieve the last layer of the autoencoder model
decoder_layer = autoencoder.layers[-1]
# Create the decoder model
decoder = keras.Model(encoded_input, decoder_layer(encoded_input))


import glob
import numpy as np
from PIL import Image
nnn=0
X_data = []
xx_data=np.zeros((2,alto*ancho,3))
files = glob.glob(r"/content/anime/images/*.jpg")
for my_file in files:
    print(my_file)
    nnn+=1
    if (nnn>1):
        break
    image = Image.open(my_file).convert('RGB')
    #image = np.array(image)
    image=image.resize((resolution,resolution))
    custom_imagen_arr=       np.asarray(list(image.getdata()))
    custom_imagen_arr = custom_imagen_arr.astype('float32') /255

    custom_imagen_arr = custom_imagen_arr.reshape((len(custom_imagen_arr), np.prod(custom_imagen_arr.shape[1:]))) 
    xx_data[nnn]=custom_imagen_arr
    #xx_data[nnn]np.append(xx_data[nnn],custom_imagen_arr)
print('X_data shape:', np.array(X_data).shape)


autoencoder.compile(optimizer='adam', loss='mse')
from keras.datasets import mnist
import numpy as np
autoencoder.fit(xx_data,xx_data,
                epochs=3,
                batch_size=6,
                verbose=1)

This is the error I'm getting:

Epoch 1/3
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-8-b39056cf9eb9> in <module>()
      6                 epochs=3,
      7                 batch_size=6,
----> 8                 verbose=1)

10 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
    971           except Exception as e:  # pylint:disable=broad-except
    972             if hasattr(e, "ag_error_metadata"):
--> 973               raise e.ag_error_metadata.to_exception(e)
    974             else:
    975               raise

ValueError: in user code:

    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:806 train_function  *
        return step_function(self, iterator)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:796 step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:1211 run
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:2585 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:2945 _call_for_each_replica
        return fn(*args, **kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:789 run_step  **
        outputs = model.train_step(data)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:749 train_step
        y, y_pred, sample_weight, regularization_losses=self.losses)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/compile_utils.py:204 __call__
        loss_value = loss_obj(y_t, y_p, sample_weight=sw)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/losses.py:149 __call__
        losses = ag_call(y_true, y_pred)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/losses.py:253 call  **
        return ag_fn(y_true, y_pred, **self._fn_kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/util/dispatch.py:201 wrapper
        return target(*args, **kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/losses.py:1195 mean_squared_error
        return K.mean(math_ops.squared_difference(y_pred, y_true), axis=-1)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/gen_math_ops.py:10399 squared_difference
        "SquaredDifference", x=x, y=y, name=name)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/op_def_library.py:744 _apply_op_helper
        attrs=attr_protos, op_def=op_def)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/func_graph.py:593 _create_op_internal
        compute_device)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py:3485 _create_op_internal
        op_def=op_def)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py:1975 __init__
        control_input_ops, op_def)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py:1815 _create_c_op
        raise ValueError(str(e))

    ValueError: Dimensions must be equal, but are 3600 and 3 for '{{node mean_squared_error/SquaredDifference}} = SquaredDifference[T=DT_FLOAT](functional_1/dense_1/Sigmoid, IteratorGetNext:1)' with input shapes: [?,3600,3600], [?,3600,3]
$\endgroup$

0

Browse other questions tagged or ask your own question.