tensorflow学习笔记: 曼德布洛特(MANDELBROT)集

# -*- coding:utf-8 -*-
# 曼德布罗特集合
# 导入仿真库
import tensorflow as tf
import numpy as np

# 导入可视化库
#若使用anaconda安装pil,则会在import tensorflow时提示错误,因此直接将PIL包安装在lib目录下
import PIL.Image
# 2.7上面是from StringIO,3.6上面是from io
from io import StringIO
from IPython.display import clear_output, Image, display
import scipy.ndimage as nd
from tensorflow.python.ops.gen_math_ops import _complex_abs

def DisplayFractal(a, fmt='jpeg'):
    a_cyclic = (6.28 * a / 20.0).reshape(list(a.shape)+[1])
    img = np.concatenate([10+20*np.cos(a_cyclic), 30+50*np.sin(a_cyclic), 155-80*np.cos(a_cyclic)], 2)
    
    img[a==a.max()]=0
    a=img
    a=np.uint8(np.clip(a, 0, 255))
    f = StringIO()
    #下面路径若使用空,会有错误
    PIL.Image.fromarray(a).save("test",fmt)
    display(Image(data=f.getvalue()))
    
if __name__=='__main__':
    
    sess = tf.InteractiveSession()
    
    Y,X = np.mgrid[-1.3:1.3:0.005, -2:1:0.005]
    Z = X+1j*Y
    
    xs = tf.constant(Z.astype('complex64'))
    zs = tf.Variable(xs)
    ns = tf.Variable(tf.zeros_like(xs, 'float32'))
    
    tf.initialize_all_variables().run()
    
    zs_ = zs*zs + xs
    
    #原文此处使用的是tf.complex_abs,但貌似就没有这个函数,只在gen_math_ops中有_complex_abs这个函数
    not_diverged = _complex_abs(zs)<4
    
    
    step = tf.group(zs.assign(zs_), ns.assign_add(tf.cast(not_diverged, 'float32')))
    
    for i in range(200):
        step.run()
    DisplayFractal(ns.eval())
                    

你可能感兴趣的:(python,ai,tensorflow)