keras調用自己訓練的模型,並且從中間層輸入(give input to intermediate layer and get final output)

相同問題見:https://stackoverflow.com/questions/52800025/keras-give-input-to-intermediate-layer-and-get-final-output(《Keras give input to intermediate layer and get final output》)

方法一:model.layers[idx]

比如你想從原網絡的第三層開始輸入自己的數據,則:

idx = 3  # index of desired layer
input_shape = model.layers[idx].get_input_shape_at(0) # get the input shape of desired layer
layer_input = Input(shape=input_shape) # a new input tensor to be able to feed the desired layer

# create the new nodes for each layer in the path
x = layer_input
for layer in model.layers[idx:]:
    x = layer(x)

# create the model
new_model = Model(layer_input, x)

方法二:model.get_layer(name=‘layer_name’) 

以在MNIST上構建變分自編碼器爲例,第一步:構建變分自編碼器(推斷網絡+生成網絡)訓練,並保存好訓練好的模型結構及網絡參數,第二步:想根據自己的愛好從一個單位正態分佈裏面採集了隨機值,輸入到解碼器,看看生成器的生成效果:

第一步:

#! -*- coding: utf-8 -*-

'''用Keras實現的VAE
   目前只保證支持Tensorflow後端
   改寫自
   https://github.com/keras-team/keras/blob/master/examples/variational_autoencoder.py
'''
from __future__ import print_function

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm

from keras.layers import Input, Dense, Lambda
from keras.models import Model
from keras import backend as K
from keras import metrics
from keras.datasets import mnist
from keras.utils import to_categorical
from keras.models import model_from_json

batch_size = 100
original_dim = 784
latent_dim = 2 # 隱變量取2維只是爲了方便後面畫圖
intermediate_dim = 256
epochs = 50
epsilon_std = 1.0
num_classes = 10

# 加載MNIST數據集
(x_train, y_train_), (x_test, y_test_) = mnist.load_data()
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
x_train = x_train.reshape((len(x_train), np.prod(x_train.shape[1:])))
x_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:])))
y_train = to_categorical(y_train_, num_classes)
y_test = to_categorical(y_test_, num_classes)

# 算p(Z|X)的均值和方差
x = Input(shape=(original_dim,))
h = Dense(intermediate_dim, activation='relu')(x)


# 重參數技巧
z_mean = Dense(latent_dim)(h)
z_log_var = Dense(latent_dim)(h)

# 重參數層,相當於給輸入加入噪聲
def sampling(args):
    z_mean, z_log_var = args
    epsilon = K.random_normal(shape=(K.shape(z_mean)[0], latent_dim), mean=0.,
                              stddev=epsilon_std)
    return z_mean + K.exp(z_log_var / 2) * epsilon


z = Lambda(sampling, output_shape=(latent_dim,))([z_mean, z_log_var])

# 解碼層,也就是生成器部分
decoder_h = Dense(intermediate_dim, activation='relu')
decoder_mean = Dense(original_dim, activation='sigmoid')
h_decoded = decoder_h(z)
x_decoded_mean = decoder_mean(h_decoded)

# 建立模型
vae = Model(x, x_decoded_mean)

# xent_loss是重構loss,kl_loss是KL loss
xent_loss = original_dim * metrics.binary_crossentropy(x, x_decoded_mean)
kl_loss = - 0.5 * K.sum(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1)
vae_loss = K.mean(xent_loss + kl_loss)

# add_loss是新增的方法,用於更靈活地添加各種loss
vae.add_loss(vae_loss)
vae.compile(optimizer='rmsprop')
vae.summary()

vae.fit(x_train,
        shuffle=True,
        epochs=epochs,
        batch_size=batch_size,
        validation_data=(x_test, None))


# 構建encoder
encoder = Model(x, z_mean)

# 保存模型結構及網絡參數值
model_jason=vae.to_json()
with open("/media/pci/NewDisk2/zwl/GACProject/LaneKeeping/lane_xushi/zwl/model.json", "w") as json_file:
    json_file.write(model_jason)
vae.save_weights('/media/pci/NewDisk2/zwl/GACProject/LaneKeeping/lane_xushi/zwl/model.h5')

# 然後可視化並觀察各個數字在隱空間的分佈
x_test_encoded = encoder.predict(x_test, batch_size=batch_size)
plt.figure(figsize=(6, 6))
plt.scatter(x_test_encoded[:, 0], x_test_encoded[:, 1], c=y_test_)
plt.colorbar()
plt.show()

第二步:

最驚人的是我們現在可以生成新的字符了。由於變分自編碼器包括推斷網絡(編碼器)+生成網絡(解碼器),所以如何將我們隨機的隨機數從VAE的中間層(即生成器輸入)輸入呢?

#! -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm

from keras.layers import Input, Dense, Lambda
from keras.models import Model
from keras import backend as K
from keras import metrics
from keras.datasets import mnist
from keras.utils import to_categorical
from keras.models import model_from_json
from keras.models import load_model
latent_dim=2

#重載網絡結構及參數
vae = model_from_json(open('/media/pci/NewDisk2/zwl/GACProject/LaneKeeping/lane_xushi/zwl/model.json','r').read(),custom_objects={'latent_dim':2,'epsilon_std':1.0})
vae.load_weights('/media/pci/NewDisk2/zwl/GACProject/LaneKeeping/lane_xushi/zwl/model.h5')
print(vae.summary())
# decoder=Model(inputs=model.input,outputs=model.layers[3].output)

#建立網絡層
decoder_input = Input(shape=(latent_dim,))
x=decoder_input
x=vae.get_layer("dense_4")(x)
x=vae.get_layer("dense_5")(x)

# 構建生成器
generator=Model(decoder_input,x)

# 觀察隱變量的兩個維度變化是如何影響輸出結果的
n = 15  # figure with 15x15 digits
digit_size = 28
figure = np.zeros((digit_size * n, digit_size * n))

# 用正態分佈的分位數來構建隱變量對
grid_x = norm.ppf(np.linspace(0.05, 0.95, n))
grid_y = norm.ppf(np.linspace(0.05, 0.95, n))

for i, yi in enumerate(grid_x):
    for j, xi in enumerate(grid_y):
        z_sample = np.array([[xi, yi]])
        x_decoded = generator.predict(z_sample)
        digit = x_decoded[0].reshape(digit_size, digit_size)
        figure[i * digit_size: (i + 1) * digit_size,
               j * digit_size: (j + 1) * digit_size] = digit

plt.figure(figsize=(10, 10))
plt.imshow(figure, cmap='Greys_r')
plt.show()

重點在於:

x=vae.get_layer("dense_4")(x)
x=vae.get_layer("dense_5")(x)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章