在前面一篇博客里,我们介绍了利用TensorFlow 和训练好的 Googlenet 来生成简单的单一通道的pattern,接下来,我们要进一步生成更为有趣的一些pattern,之前的简单的pattern都是基于单一通道,单一尺度的,现在我们来试试多尺度下生成的pattern

# 这部分代码和之前单一通道的一样
# 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 = 'mixed4d_3x3_bottleneck_pre_relu'
channel = 64 # start with a gray image with a little noise
img_noise = np.random.uniform(size=(224,224,3)) + 100.0 # Multiscale image generation
# 多尺度图像的生成
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) # octave_n 表示阶数
# octave_scale 表示尺度变化的倍数
def render_multiscale(t_obj, img0=img_noise, iter_n=10, step=1.0, octave_n=3, 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! 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)
# normalizing the gradient, so the same step size should work
g /= g.std()+1e-8 # for different layers and networks
img += g*step
print('.', end = ' ')
clear_output()
showarray(visstd(img)) render_multiscale(T(layer)[:,:,:,channel])

看看一些生成的效果图:

layer = ‘mixed4d_3x3_bottleneck_pre_relu’

channel = 100

octave_n=4, octave_scale=1.25

layer = ‘mixed4d_3x3_bottleneck_pre_relu’

channel = 60

octave_n=4, octave_scale=1.25

layer = ‘mixed4d_3x3_bottleneck_pre_relu’

channel = 139

octave_n=4, octave_scale=1.25

layer = ‘mixed4b_3x3_bottleneck_pre_relu’

channel = 24

octave_n=4, octave_scale=1.25

参考来源:

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. ng机器学习视频笔记(二) ——梯度下降算法解释以及求解θ

    ng机器学习视频笔记(二) --梯度下降算法解释以及求解θ (转载请附上本文链接--linhxx)   一.解释梯度算法 梯度算法公式以及简化的代价函数图,如上图所示. 1)偏导数 由上图可知,在a点 ...

  3. 机器学习之支持向量机(二):SMO算法

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

  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/7364636.html 前言 ...

  6. 机器学习:DeepDreaming with TensorFlow (三)

    我们看到,利用TensorFlow 和训练好的Googlenet 可以生成多尺度的pattern,那些pattern看起来比起单一通道的pattern你要更好,但是有一个问题就是多尺度的pattern ...

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

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

  8. 机器学习算法总结(十二)——流形学习(Manifold Learning)

    1.什么是流形 流形学习的观点:认为我们所能观察到的数据实际上是由一个低维流行映射到高维空间的.由于数据内部特征的限制,一些高维中的数据会产生维度上的冗余,实际上这些数据只要比较低的维度就能唯一的表示 ...

  9. Python3实现机器学习经典算法(二)KNN实现简单OCR

    一.前言 1.ocr概述 OCR (Optical Character Recognition,光学字符识别)是指电子设备(例如扫描仪或数码相机)检查纸上打印的字符,通过检测暗.亮的模式确定其形状,然 ...

随机推荐

  1. WPF遍历当前容器中某种控件的方法

    原文:WPF遍历当前容器中某种控件的方法 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/m0_37591671/article/details/79 ...

  2. 自己写的关于生产者与消费者模式,还有定时任务的demo

    为了加深对生产者消费者模式的理解,特意写了这个demo,里面还包含了一个自己写的定时任务.代码下载地址:http://download.csdn.net/detail/li_yan_fei/98115 ...

  3. C# .NET Socket

    C# .NET Socket 简单实用框架 背景: 首先向各位前辈,大哥哥小姐姐问一声好~ 这是我第一次写博客,目前为一个即将步入大四的学生,上学期在一家公司实习了半年,后期发现没有动力,而且由于薪水 ...

  4. diff_mysql_table_exec.py

    #!/usr/bin/env python #-*- encoding: utf8 -*- import mysql.connector import sys import re import dat ...

  5. angular组件间的信息传递

    原文 https://www.jianshu.com/p/82207f2249c1 大纲 1.父组件向子组件传递信息:通过属性 2.子组件向父组件传递信息:通过事件 3.父组件获取子组件的信息:通过调 ...

  6. VS2008的C++TR1库已经支持正则表达式

    作者:朱金灿 来源:http://blog.csdn.net/clever101 发现VS2008的C++ TR1库已经支持正则表达式了(注意装了VS 2008sp1采用TR1库的).下面简单做个测试 ...

  7. css3 实现水晶按钮

    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #ee432e), color-sto ...

  8. 【Record】9.16..9.23

  9. [Angular] Implementing a ControlValueAccessor

    So when you need to create a ControlValueAccessor? When you want to use a custom component as form c ...

  10. Gibbs 采样的应用

    Gibbs 采样的最大作用在于使得对高维连续概率分布的抽样由复杂变得简单. 可能的应用: 计算高维连续概率分布函数的数学期望, Gibbs 采样得到 n 个值,再取均值: 比如用于 RBM: