A Neural Algorithm of Artistic Style : Neural Style Transfer with Eager Executon

2 篇文章 0 订阅
1 篇文章 0 订阅
简介

本文介绍为什么代码能够实现风格迁移的功能,重点在优化对象.
在这里插入图片描述在这里插入图片描述

地址

github地址:
https://github.com/tensorflow/models/blob/master/research/nst_blogpost/4_Neural_Style_Transfer_with_Eager_Execution.ipynb

我的重点
  • tensorflow中,怎么定制自己的求导函数,而不是使用优化器的minimize
  • tf.train.Optimizer.minimize的minimize包含了什么
  • opt.compute_gradients(loss, list_of_variables])
  • opt.apply_gradients(grads_and_vars, global_step=global_step,
    name=name)
解析
  • 由于tf.train.Optimizer.minimize会自动求导并将导数*学习率应用到网络的所有权重上
    这与A Neural Algorithm of Artistic Style的目的不合
    因此作者不使用minimize函数,而是自己求导数,并且自己将导数只应用到自己想要的地方,也就是最终的生成图
  • 由于 minimize其实包含了compute_gradients(求结果相对于某数的导数)与apply_gradients(将导数应用到某数上),
    因此只需要更改这两个函数即可.
  • 作者首先计算loss函数,也就是 α ∗ L c o n t e n t + β ∗ L s t y l e \alpha*L_{content}+\beta*L_{style} αLcontent+βLstyle.
    然后使用tf.gradient(total_loss, cfg['init_image'])计算loss对于初始化图像的导数,
    最后将导数以及学习率应用到初始化的图像上,用来不断改变初始化的图像,使其更加接近目标
    使用的函数为opt.apply_gradients([(grads, init_image)]),将导数应用到初始化图像上.
  • 计算梯度使用 tf.gradient函数
def compute_grads(cfg):
  with tf.GradientTape() as tape: 
    all_loss = compute_loss(**cfg)
  # Compute gradients wrt input image
  total_loss = all_loss[0]
  return tape.gradient(total_loss, cfg['init_image']), all_loss
  • 应用梯度使用opt.apply_gradients函数
opt.apply_gradients([(grads, init_image)])
clipped = tf.clip_by_value(init_image, min_vals, max_vals)
init_image.assign(clipped)
拓展
  • tf.gradients(loss, tf.variables)函数与computer_gradients(loss, val_list)函数相似,只是后者会返回这个时候被求导数的那个变量此时的值.
  • 例子
import tensorflow as tf
with tf.Graph().as_default():
    x = tf.Variable(initial_value=3., dtype='float32')
    w = tf.Variable(initial_value=4., dtype='float32')
    y = w*x
    grads = tf.gradients(y, [w])
    
    opt = tf.train.GradientDescentOptimizer(0.1)
    grads_vals = opt.compute_gradients(y, [w])

    sess=tf.Session()
    sess.run(tf.global_variables_initializer())
    print(sess.run(grads))
    print(sess.run(grads_vals))

  • 结果为
>>    [3.0]
      [(3.0, 4.0)]
感谢

https://www.cnblogs.com/marsggbo/p/10056057.html

As an AI language model, I am not able to write and save code files. However, I can explain the general steps and process of creating a style transfer program based on convolution neural network with Python. Style transfer is a technique that enables the transfer of style and texture of one image to another image, while preserving the content of the original image. This technique is based on convolution neural network models. The general steps to create a style transfer program are as follows: 1. Load and preprocess the content and style images. 2. Define the convolution neural network model architecture for the style transfer. 3. Define the loss functions to optimize the style transfer. 4. Train the model using the defined loss functions and optimizer. 5. Save the trained model weights in a separate file for future use. Here is a sample code for creating a style transfer program based on convolution neural network with Python: ``` # Import necessary libraries import tensorflow as tf import numpy as np import matplotlib.pyplot as plt # Load and preprocess the content and style images content_image = preprocess_image(content_path) style_image = preprocess_image(style_path) # Define the convolution neural network model architecture for the style transfer def style_transfer_model(content_image, style_image): # Define the input layers for content and style images content_input = tf.keras.layers.Input(shape=content_image.shape, name='content_image') style_input = tf.keras.layers.Input(shape=style_image.shape, name='style_image') # Build the convolution neural network model architecture # Add convolutional and pooling layers to extract features from content and style images # Add upsampling and convolutional layers to apply the learned style to the content image # Define the output layer as the stylized image output_image = ... # Define the model object model = tf.keras.models.Model(inputs=[content_input, style_input], outputs=output_image) return model # Define the loss functions to optimize the style transfer # Use mean squared error for content loss and Gram matrix for style loss def content_loss(content_features, generated_features): mse_loss = tf.reduce_mean(tf.square(content_features - generated_features)) return mse_loss def gram_matrix(input_tensor): channels = int(input_tensor.shape[-1]) a = tf.reshape(input_tensor, [-1, channels]) n = tf.shape(a)[0] gram = tf.matmul(a, a, transpose_a=True) return gram / tf.cast(n, tf.float32) def style_loss(style_features, generated_features): style_gram = gram_matrix(style_features) generated_gram = gram_matrix(generated_features) mse_loss = tf.reduce_mean(tf.square(style_gram - generated_gram)) return mse_loss # Train the model using the defined loss functions and optimizer model = style_transfer_model(content_image, style_image) content_features = ... style_features = ... generated_features = model([content_image, style_image]) content_loss_val = content_loss(content_features, generated_features) style_loss_val = style_loss(style_features, generated_features) total_loss = content_loss_val + style_loss_val optimizer = tf.keras.optimizers.Adam(learning_rate=0.001) model.compile(optimizer, loss=total_loss) model.fit(x=[content_image, style_image], y=target_image, epochs=10) # Save the trained model weights in a separate file for future use model.save_weights('style_transfer_weights.h5') ``` In this code, we first load and preprocess the content and style images. We then define the convolution neural network model architecture for style transfer and the loss functions for optimizing the style transfer. We train the model using the defined loss functions and optimizer, and finally save the trained model weights in a separate file for future use.
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值