雖然可視化曼德布洛特(Mandelbrot)集合與機(jī)器學(xué)習(xí)沒(méi)有任何關(guān)系,但這對(duì)于將TensorFlow應(yīng)用在數(shù)學(xué)更廣泛的領(lǐng)域是一個(gè)有趣的例子。實(shí)際上,這是tensorflow一個(gè)非常直截了當(dāng)?shù)目梢暬\(yùn)用。(我們最終也許會(huì)提供一種更加精心設(shè)計(jì)的運(yùn)用方式來(lái)生成真正更加美麗的圖像。)
說(shuō)明:本教程使用了IPython的notebook。
首先,我們需要導(dǎo)入一些庫(kù)。
# 導(dǎo)入仿真庫(kù)
import tensorflow as tf
import numpy as np
# 導(dǎo)入可視化庫(kù)
import PIL.Image
from cStringIO import StringIO
from IPython.display import clear_output, Image, display
import scipy.ndimage as nd
現(xiàn)在我們將定義一個(gè)函數(shù)來(lái)顯示迭代計(jì)算出的圖像。
def DisplayFractal(a, fmt='jpeg'):
"""顯示迭代計(jì)算出的彩色分形圖像。"""
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(f, fmt)
display(Image(data=f.getvalue()))
為了操作的方便,我們常常使用交互式會(huì)話(huà)(interactive session),但普通會(huì)話(huà)(regular session)也能正常使用。
sess = tf.InteractiveSession()
我們可以自由的混合使用NumPy和TensorFlow,這一點(diǎn)非常方便。
# 使用NumPy創(chuàng)建一個(gè)在[-2,2]x[-2,2]范圍內(nèi)的2維復(fù)數(shù)數(shù)組
Y, X = np.mgrid[-1.3:1.3:0.005, -2:1:0.005]
Z = X+1j*Y
現(xiàn)在我們定義并初始化一組TensorFlow的張量 (tensors)。
xs = tf.constant(Z.astype("complex64"))
zs = tf.Variable(xs)
ns = tf.Variable(tf.zeros_like(xs, "float32"))
TensorFlow在使用之前需要你明確給定變量的初始值。
tf.initialize_all_variables().run()
現(xiàn)在我們指定更多的計(jì)算...
# 計(jì)算一個(gè)新值z(mì): z^2 + x
zs_ = zs*zs + xs
# 這個(gè)新值會(huì)發(fā)散嗎?
not_diverged = tf.complex_abs(zs_) < 4
# 更新zs并且迭代計(jì)算。
#
# 說(shuō)明:在這些值發(fā)散之后,我們?nèi)匀辉谟?jì)算zs,這個(gè)計(jì)算消耗特別大!
# 如果稍微簡(jiǎn)單點(diǎn),這里有更好的方法來(lái)處理。
#
step = tf.group(
zs.assign(zs_),
ns.assign_add(tf.cast(not_diverged, "float32"))
)
...繼續(xù)執(zhí)行幾百個(gè)步驟
for i in range(200): step.run()
讓我們看看我們得到了什么。
DisplayFractal(ns.eval())
http://wiki.jikexueyuan.com/project/tensorflow-zh/images/mandelbrot_output.jpg" alt="jpeg" />
結(jié)果不錯(cuò)!
原文:Mandelbrot Set 翻譯:ericxk 校對(duì):tensorfly