赞
踩
Python版本:Python 3.8.16
TensorFlow版本:2.6.0
import tensorflow as tf
# 导入InceptionV3模型
inception_model = tf.keras.applications.InceptionV3(weights='imagenet', include_top=True)
# 打印模型结构
inception_model.summary()
conv_layers = []
for layer in inception_model.layers:
if isinstance(layer, tf.keras.layers.Conv2D):
conv_layers.append(layer)
for conv_layer in conv_layers:
print(conv_layer.name, conv_layer.output_shape)
inception_model.get_layer("conv2d_76").output_shape
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import PIL.Image #反归一化 def deprocess(img): img = 255*(img + 1.0)/2.0 return tf.cast(img, tf.uint8) #导入了预训练模型 InceptionV3 base_model = tf.keras.applications.InceptionV3(include_top=False, weights='imagenet') #希望最大化激活值的层的名称 names = ['mixed3'] layers = [base_model.get_layer(name).output for name in names] #通过输入 InceptionV3 模型的输入和 layers 列表的输出来创建的 dream_model = tf.keras.Model(inputs=base_model.input, outputs=layers) # dream_model.summary() # exit(0) #计算给定图像和模型的激活层的平均值,并将其累加到总损失中 def calc_loss(img, model): img_batch = tf.expand_dims(img, axis=0) layer_activations = model(img_batch) if len(layer_activations) == 1: layer_activations = [layer_activations] losses = [] for act in layer_activations: loss = tf.math.reduce_mean(act) losses.append(loss) return tf.reduce_sum(losses) #通过对给定图像应用梯度上升来执行 DeepDream 算法。在 __call__() 方法中,使用 GradientTape 监听图像变量并计算损失和梯度。梯度被规范化后添加到图像中,以便最大化损失。 class DeepDream(tf.Module): def __init__(self, model): self.model = model @tf.function( input_signature=( tf.TensorSpec(shape=[None,None,3], dtype=tf.float32), tf.TensorSpec(shape=[], dtype=tf.int32), tf.TensorSpec(shape=[], dtype=tf.float32),) ) def __call__(self, img, steps, step_size): print("Tracing") loss = tf.constant(0.0) for n in tf.range(steps): with tf.GradientTape() as tape: #对输入的图像 img 启用梯度跟踪 tape.watch(img) #计算损失值,该损失值反映了要最大化的特定层的激活值。 loss = calc_loss(img, self.model) #计算图像梯度 gradients = tape.gradient(loss, img) #梯度标准化,避免梯度爆炸 gradients /= tf.math.reduce_std(gradients) + 1e-8 #将图像加上梯度乘以步长的值,实现梯度上升。 img = img + gradients*step_size #将图像的像素值裁剪到 [-1,1] 的范围内,防止像素值超出范围 img = tf.clip_by_value(img, -1, 1) return loss, img deepdream = DeepDream(dream_model) def run_deep_dream_simple(img, steps=100, step_size=0.01): #使用 Inception V3 模型提供的预处理函数,对输入图像进行预处理。 img = tf.keras.applications.inception_v3.preprocess_input(img) #输入图像转换成 TensorFlow 张量 img = tf.convert_to_tensor(img) step_size = tf.convert_to_tensor(step_size) #初始化剩余迭代次数为总迭代次数。 steps_remaining = steps step = 0 while steps_remaining: if steps_remaining>100: run_steps = tf.constant(100) else: run_steps = tf.constant(steps_remaining) steps_remaining -= run_steps step += run_steps loss, img = deepdream(img, run_steps, tf.constant(step_size)) print ("Step {}, loss {}".format(step, loss)) result = deprocess(img) return result original_img=PIL.Image.open('40784_93822_18.jpg') original_img=np.array(original_img) dream_img = run_deep_dream_simple(img=original_img, steps=1000, step_size=0.01) plt.figure("test") plt.imshow(dream_img) plt.show() plt.imsave('1.png',dream_img.numpy())
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。