Как отделить модель кодирования от модели декодирования в автоэнкодере? keras - PullRequest
0 голосов
/ 13 апреля 2020

Исходный код ниже работает нормально.

# The encoding process
input_img = Input(shape=(img_cols, img_cols, 1))
x = Conv2D(16, (3, 3), activation='relu', padding='same')(input_img)
x = MaxPooling2D(pool_size = (2, 2), padding='same')(x)
x = Conv2D( 8, kernel_size = (3, 3), activation='relu', padding='same')(x)
x = MaxPooling2D(pool_size = (2, 2), padding='same')(x)
x = Conv2D( 8, (3, 3), activation='relu', padding='same')(x)
encoded = MaxPooling2D(pool_size = (2, 2), padding='same')(x)

x1 = Conv2D(8, (3, 3), activation='relu', padding='same')(encoded)   ### 
x = UpSampling2D((2, 2))(x1)
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='adadelta', loss='binary_crossentropy')
autoencoder.fit(x_train, x_train, epochs=10, batch_size=128, shuffle=True) #

Однако я хочу отделить модель кода от модели декодирования, как показано ниже:

encoder=Model(inputs=input_img, outputs=encoded)
decoder=Model(inputs=x1,outputs=decoded )
autoencoder_outputs = decoder(encoder(input_img))
autoencoder= Model(input_img, autoencoder_outputs, name='AE')
autoencoder.summary()

Это не работает для меня , Я новичок в keras и python

я получаю следующую ошибку:

График отключен: невозможно получить значение для тензорного тензора ("input_13: 0", shape = (None , 28, 28, 1), dtype = float32) на уровне "input_13". Следующие предыдущие слои были доступны без проблем: []

Ответы [ 2 ]

1 голос
/ 13 апреля 2020

Это ваш обновленный воспроизводимый код:

Все ваши входные фигуры были неправильно размещены. В узком месте вы проходили тензор с формой (8,8,8). Вы можете получить представление из резюме ().

from tensorflow.keras.layers import *
from tensorflow.keras.models import *
import numpy as np
# The encoding process

img_cols = 64

input_img = Input(shape=(img_cols, img_cols, 1))
x = Conv2D(16, (3, 3), activation='relu', padding='same')(input_img)
x = MaxPooling2D(pool_size = (2, 2), padding='same')(x)
x = Conv2D( 8, kernel_size = (3, 3), activation='relu', padding='same')(x)
x = MaxPooling2D(pool_size = (2, 2), padding='same')(x)
x = Conv2D( 8, (3, 3), activation='relu', padding='same')(x)
encoded = MaxPooling2D(pool_size = (2, 2), padding='same')(x)

x1 = Conv2D(8, (3, 3), activation='relu', padding='same')(encoded)   ### 
x = UpSampling2D((2, 2))(x1)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = UpSampling2D((2, 2))(x)
x = Conv2D(16, (3, 3), activation='relu', padding = 'same')(x)
x = UpSampling2D((2, 2))(x)
decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x)

autoencoder = Model(input_img, decoded)
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')

autoencoder.summary()
x_train = np.zeros((10,64,64,1))
y_train =  np.zeros((10,64,64,1))
autoencoder.fit(x_train, x_train, epochs=10, batch_size=128, shuffle=True) 

# second approach

input_img = Input(shape=(img_cols, img_cols, 1))
x = Conv2D(16, (3, 3), activation='relu', padding='same')(input_img)
x = MaxPooling2D(pool_size = (2, 2), padding='same')(x)
x = Conv2D( 8, kernel_size = (3, 3), activation='relu', padding='same')(x)
x = MaxPooling2D(pool_size = (2, 2), padding='same')(x)
x = Conv2D( 8, (3, 3), activation='relu', padding='same')(x)
encoded = MaxPooling2D(pool_size = (2, 2), padding='same')(x)

reduced_dim = 8
filters = 8
input_decoder = Input(shape = (reduced_dim, reduced_dim, 8) )
x1 = Conv2D(8, (3, 3), activation='relu', padding='same')(input_decoder)   ### 
x = UpSampling2D((2, 2))(x1)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = UpSampling2D((2, 2))(x)
x = Conv2D(16, (3, 3), activation='relu', padding = 'same')(x)
x = UpSampling2D((2, 2))(x)
decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x)

encoder=Model(inputs=input_img, outputs=encoded)
decoder=Model(inputs=input_decoder, outputs=decoded )
autoencoder_outputs = decoder(encoder(input_img))
autoencoder= Model(input_img, autoencoder_outputs, name='AE')
autoencoder.summary()
Model: "model_9"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_10 (InputLayer)        [(None, 64, 64, 1)]       0         
_________________________________________________________________
conv2d_49 (Conv2D)           (None, 64, 64, 16)        160       
_________________________________________________________________
max_pooling2d_21 (MaxPooling (None, 32, 32, 16)        0         
_________________________________________________________________
conv2d_50 (Conv2D)           (None, 32, 32, 8)         1160      
_________________________________________________________________
max_pooling2d_22 (MaxPooling (None, 16, 16, 8)         0         
_________________________________________________________________
conv2d_51 (Conv2D)           (None, 16, 16, 8)         584       
_________________________________________________________________
max_pooling2d_23 (MaxPooling (None, 8, 8, 8)           0         
_________________________________________________________________
conv2d_52 (Conv2D)           (None, 8, 8, 8)           584       
_________________________________________________________________
up_sampling2d_21 (UpSampling (None, 16, 16, 8)         0         
_________________________________________________________________
conv2d_53 (Conv2D)           (None, 16, 16, 8)         584       
_________________________________________________________________
up_sampling2d_22 (UpSampling (None, 32, 32, 8)         0         
_________________________________________________________________
conv2d_54 (Conv2D)           (None, 32, 32, 16)        1168      
_________________________________________________________________
up_sampling2d_23 (UpSampling (None, 64, 64, 16)        0         
_________________________________________________________________
conv2d_55 (Conv2D)           (None, 64, 64, 1)         145       
=================================================================
Total params: 4,385
Trainable params: 4,385
Non-trainable params: 0
_________________________________________________________________
Epoch 1/10
1/1 [==============================] - 0s 1ms/step - loss: 0.6931
Epoch 2/10
1/1 [==============================] - 0s 1ms/step - loss: 0.6931
Epoch 3/10
1/1 [==============================] - 0s 1ms/step - loss: 0.6931
Epoch 4/10
1/1 [==============================] - 0s 1ms/step - loss: 0.6931
Epoch 5/10
1/1 [==============================] - 0s 1ms/step - loss: 0.6931
Epoch 6/10
1/1 [==============================] - 0s 1ms/step - loss: 0.6931
Epoch 7/10
1/1 [==============================] - 0s 1ms/step - loss: 0.6931
Epoch 8/10
1/1 [==============================] - 0s 1ms/step - loss: 0.6931
Epoch 9/10
1/1 [==============================] - 0s 2ms/step - loss: 0.6931
Epoch 10/10
1/1 [==============================] - 0s 2ms/step - loss: 0.6931
Model: "AE"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_11 (InputLayer)        [(None, 64, 64, 1)]       0         
_________________________________________________________________
model_10 (Model)             (None, 8, 8, 8)           1904      
_________________________________________________________________
model_11 (Model)             (None, 64, 64, 1)         2481      
=================================================================
Total params: 4,385
Trainable params: 4,385
Non-trainable params: 0
0 голосов
/ 13 апреля 2020

Модель должна иметь вход keras.layers.Input.

decoder=Model(inputs=x1,outputs=decoded )

Здесь x1 не является входом. Он связан с графом энкодера, поэтому эта ошибка.

...