我们看到,利用TensorFlow 和训练好的Googlenet 可以生成多尺度的pattern,那些pattern看起来比起单一通道的pattern你要更好,但是有一个问题就是多尺度的pattern里高频分量太多,显得图像的噪点很多,为了解决这个问题,可以进一步的引入一个先验平滑函数,这样每次迭代的时候可以对图像进行模糊,去除高频分量,这样一般来说需要更多的迭代次数,另一种方式就是每次迭代中增强低频分量的梯度,这种技术被称为: 拉普拉斯金字塔分解,这里我们就要用到这种技术,我们称为:Laplacian Pyramid Gradient Normalization,利用LPGN,可以使生成的多尺度pattern图像更加平滑:

Laplacian Pyramid Gradient Normalization

# boilerplate code
from __future__ import print_function
import os
from io import BytesIO
import numpy as np
from functools import partial
import PIL.Image
from IPython.display import clear_output, Image, display, HTML import tensorflow as tf # !wget https://storage.googleapis.com/download.tensorflow.org/models/inception5h.zip && unzip inception5h.zip model_fn = 'tensorflow_inception_graph.pb' # creating TensorFlow session and loading the model
graph = tf.Graph()
sess = tf.InteractiveSession(graph=graph)
with tf.gfile.FastGFile(model_fn, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
t_input = tf.placeholder(np.float32, name='input') # define the input tensor
imagenet_mean = 117.0
t_preprocessed = tf.expand_dims(t_input-imagenet_mean, 0)
tf.import_graph_def(graph_def, {'input':t_preprocessed}) layers = [op.name for op in graph.get_operations() if op.type=='Conv2D' and 'import/' in op.name]
feature_nums = [int(graph.get_tensor_by_name(name+':0').get_shape()[-1]) for name in layers] print('Number of layers', len(layers))
print('Total number of feature channels:', sum(feature_nums)) # Picking some internal layer. Note that we use outputs before applying the ReLU nonlinearity
# to have non-zero gradients for features with negative initial activations.
layer = 'mixed4b_3x3_bottleneck_pre_relu'
channel = 24 # picking some feature channel to visualize # start with a gray image with a little noise
img_noise = np.random.uniform(size=(224,224,3)) + 100.0 def showarray(a, fmt='jpeg'):
a = np.uint8(np.clip(a, 0, 1)*255)
f = BytesIO()
PIL.Image.fromarray(a).save(f, fmt)
display(Image(data=f.getvalue())) def visstd(a, s=0.1):
# Normalize the image range for visualization
return (a-a.mean())/max(a.std(), 1e-4)*s + 0.5 def T(layer):
# Helper for getting layer output tensor
return graph.get_tensor_by_name("import/%s:0"%layer) def tffunc(*argtypes):
# Helper that transforms TF-graph generating function into a regular one.
# See "resize" function below.
placeholders = list(map(tf.placeholder, argtypes))
def wrap(f):
out = f(*placeholders)
def wrapper(*args, **kw):
return out.eval(dict(zip(placeholders, args)), session=kw.get('session'))
return wrapper
return wrap # Helper function that uses TF to resize an image
def resize(img, size):
img = tf.expand_dims(img, 0)
return tf.image.resize_bilinear(img, size)[0,:,:,:]
resize = tffunc(np.float32, np.int32)(resize) def calc_grad_tiled(img, t_grad, tile_size=512):
# Compute the value of tensor t_grad over the image in a tiled way.
# Random shifts are applied to the image to blur tile boundaries over
# multiple iterations.
sz = tile_size
h, w = img.shape[:2]
sx, sy = np.random.randint(sz, size=2)
img_shift = np.roll(np.roll(img, sx, 1), sy, 0)
grad = np.zeros_like(img)
for y in range(0, max(h-sz//2, sz),sz):
for x in range(0, max(w-sz//2, sz),sz):
sub = img_shift[y:y+sz,x:x+sz]
g = sess.run(t_grad, {t_input:sub})
grad[y:y+sz,x:x+sz] = g
return np.roll(np.roll(grad, -sx, 1), -sy, 0) # Laplacian Pyramid Gradient Normalization k = np.float32([1,4,6,4,1])
k = np.outer(k, k)
k5x5 = k[:,:,None,None]/k.sum()*np.eye(3, dtype=np.float32) def lap_split(img):
# Split the image into lo and hi frequency components
with tf.name_scope('split'):
lo = tf.nn.conv2d(img, k5x5, [1,2,2,1], 'SAME')
lo2 = tf.nn.conv2d_transpose(lo, k5x5*4, tf.shape(img), [1,2,2,1])
hi = img-lo2
return lo, hi def lap_split_n(img, n):
# Build Laplacian pyramid with n splits
levels = []
for i in range(n):
img, hi = lap_split(img)
levels.append(hi)
levels.append(img)
return levels[::-1] def lap_merge(levels):
# Merge Laplacian pyramid
img = levels[0]
for hi in levels[1:]:
with tf.name_scope('merge'):
img = tf.nn.conv2d_transpose(img, k5x5*4, tf.shape(hi), [1,2,2,1]) + hi
return img def normalize_std(img, eps=1e-10):
# Normalize image by making its standard deviation = 1.0
with tf.name_scope('normalize'):
std = tf.sqrt(tf.reduce_mean(tf.square(img)))
return img/tf.maximum(std, eps) def lap_normalize(img, scale_n=4):
# Perform the Laplacian pyramid normalization
img = tf.expand_dims(img,0)
tlevels = lap_split_n(img, scale_n)
tlevels = list(map(normalize_std, tlevels))
out = lap_merge(tlevels)
return out[0,:,:,:] def render_lapnorm(t_obj, img0=img_noise, visfunc=visstd,
iter_n=10, step=1.0, octave_n=3, octave_scale=1.4, lap_n=4):
t_score = tf.reduce_mean(t_obj) # defining the optimization objective
t_grad = tf.gradients(t_score, t_input)[0] # behold the power of automatic differentiation!
# build the laplacian normalization graph
lap_norm_func = tffunc(np.float32)(partial(lap_normalize, scale_n=lap_n)) img = img0.copy()
for octave in range(octave_n):
if octave>0:
hw = np.float32(img.shape[:2])*octave_scale
img = resize(img, np.int32(hw))
for i in range(iter_n):
g = calc_grad_tiled(img, t_grad)
g = lap_norm_func(g)
img += g*step
print('.', end = ' ')
clear_output()
showarray(visfunc(img)) render_lapnorm(T(layer)[:,:,:,channel])
# render_lapnorm(T(layer)[:,:,:,65])
# render_lapnorm(T('mixed3b_1x1_pre_relu')[:,:,:,101])
# render_lapnorm(T(layer)[:,:,:,65]+T(layer)[:,:,:,139], octave_n=4)

生成的效果图如下所示:

Deepdream

最后,我们再来看看Deep dream的生成,

def render_deepdream(t_obj, img0=img_noise,
iter_n=10, step=1.5, octave_n=4, octave_scale=1.4):
t_score = tf.reduce_mean(t_obj) # defining the optimization objective
t_grad = tf.gradients(t_score, t_input)[0] # behold the power of automatic differentiation! # split the image into a number of octaves
img = img0
octaves = []
for i in range(octave_n-1):
hw = img.shape[:2]
lo = resize(img, np.int32(np.float32(hw)/octave_scale))
hi = img-resize(lo, hw)
img = lo
octaves.append(hi) # generate details octave by octave
for octave in range(octave_n):
if octave>0:
hi = octaves[-octave]
img = resize(img, hi.shape[:2])+hi
for i in range(iter_n):
g = calc_grad_tiled(img, t_grad)
img += g*(step / (np.abs(g).mean()+1e-7))
print('.',end = ' ')
clear_output()
showarray(img/255.0) img0 = PIL.Image.open('1.jpg')
img0 = np.float32(img0)
showarray(img0/255.0) # render_deepdream(T(layer)[:,:,:,139], img0)
# render_deepdream(tf.square(T('mixed4c')), img0)

原图如下所示:

生成的效果图如下所示:

参考来源

https://nbviewer.jupyter.org/github/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/deepdream/deepdream.ipynb#multiscale

机器学习:DeepDreaming with TensorFlow (三)的更多相关文章

  1. 机器学习: DeepDreaming with TensorFlow (一)

    在TensorFlow 的官网上,有一个很有趣的教程,就是用 TensorFlow 以及训练好的深度卷积神经(GoogleNet)网络去生成一些有趣的pattern,通过这些pattern,可以更加深 ...

  2. 周志华-机器学习西瓜书-第三章习题3.5 LDA

    本文为周志华机器学习西瓜书第三章课后习题3.5答案,编程实现线性判别分析LDA,数据集为书本第89页的数据 首先介绍LDA算法流程: LDA的一个手工计算数学实例: 课后习题的代码: # coding ...

  3. 机器学习之支持向量机(三):核函数和KKT条件的理解

    注:关于支持向量机系列文章是借鉴大神的神作,加以自己的理解写成的:若对原作者有损请告知,我会及时处理.转载请标明来源. 序: 我在支持向量机系列中主要讲支持向量机的公式推导,第一部分讲到推出拉格朗日对 ...

  4. Google机器学习课程基于TensorFlow : https://developers.google.cn/machine-learning/crash-course

    Google机器学习课程基于TensorFlow  : https://developers.google.cn/machine-learning/crash-course         https ...

  5. Andrew Ng机器学习课程笔记(三)之正则化

    Andrew Ng机器学习课程笔记(三)之正则化 版权声明:本文为博主原创文章,转载请指明转载地址 http://www.cnblogs.com/fydeblog/p/7365475.html 前言 ...

  6. 系统学习机器学习之神经网络(三)--GA神经网络与小波神经网络WNN

    系统学习机器学习之神经网络(三)--GA神经网络与小波神经网络WNN 2017年01月09日 09:45:26 Eason.wxd 阅读数 14135更多 分类专栏: 机器学习   1 遗传算法1.1 ...

  7. 机器学习:DeepDreaming with TensorFlow (二)

    在前面一篇博客里,我们介绍了利用TensorFlow 和训练好的 Googlenet 来生成简单的单一通道的pattern,接下来,我们要进一步生成更为有趣的一些pattern,之前的简单的patte ...

  8. .NET平台机器学习组件-Infer.NET(三) Learner API—数据映射与序列化

             所有文章分类的总目录:http://www.cnblogs.com/asxinyu/p/4288836.html 微软Infer.NET机器学习组件:http://www.cnblo ...

  9. ML.NET 发布0.11版本:.NET中的机器学习,为TensorFlow和ONNX添加了新功能

    微软发布了其最新版本的机器学习框架:ML.NET 0.11带来了新功能和突破性变化. 新版本的机器学习开源框架为TensorFlow和ONNX添加了新功能,但也包括一些重大变化, 这也是发布RC版本之 ...

随机推荐

  1. redis学习笔记之虚拟内存

    首先说明下redis的虚拟内存与os的虚拟内存不是一码事,但是思路和目的都是相同的.就是暂时把不经常访问的数据从内存交换到磁盘中,从而腾出宝贵的 内存空间用于其他需要访问的数据.尤其是对于redis这 ...

  2. [TypeStyle] Add type safety to CSS using TypeStyle

    TypeStyle is the only current CSS in JS solution that is designed with TypeSafety and TypeScript dev ...

  3. css3-10 如何控制元素的显示和隐藏(display和visibility的区别是什么)

    css3-10 如何控制元素的显示和隐藏(display和visibility的区别是什么) 一.总结 一句话总结:使用的时候直接在元素的样式中设置display和visibility属性即可.推荐使 ...

  4. YUV与RGB格式转换

    YUV格式具有亮度信息和色彩信息分离的特点,但大多数图像处理操作都是基于RGB格式. 因此当要对图像进行后期处理显示时,需要把YUV格式转换成RGB格式. RGB与YUV的变换公式如下: YUV(25 ...

  5. Perl读写Excel简单操作

    Perl读写Excel简单操作 使用模块 Spreadsheet::ParseExcel Spreadsheet::WriteExcel 读Excel #!/usr/bin/perl -w use s ...

  6. 利用函数的惰性载入提高 javascript 代码性能

    在 javascript 代码中,因为各浏览器之间的行为的差异,我们经常会在函数中包含了大量的 if 语句,以检查浏览器特性,解决不同浏览器的兼容问题.例如,我们最常见的为 dom 节点添加事件的函数 ...

  7. 一起学Python:TCP简介

    TCP介绍 TCP协议,传输控制协议(英语:Transmission Control Protocol,缩写为 TCP)是一种面向连接的.可靠的.基于字节流的传输层通信协议,由IETF的RFC 793 ...

  8. MySQL建立双向主备复制server配置方法

    1.环境描写叙述 serverA(主) 192.85.1.175 serverB(从) 192.85.1.176 Mysql版本号:5.1.61 系统版本号:System OS:ubuntu 10.1 ...

  9. php实现 合并表记录(需求是最好的老师)

    php实现 合并表记录(需求是最好的老师) 一.总结 一句话总结:php数组,桶. 1.fgets的作用? 读取一行 0 1 2.如何读取一行中的两个数? fgets()读取一行后explode以空格 ...

  10. Guava中TreeRangeMap基本使用

    RangeMap跟一般的Map一样.存储键值对,依照键来取值.不同于Map的是键的类型必须是Range,也既是一个区间.RangeMap在Guava中的定义是一个接口: public interfac ...