閱讀646 返回首頁    go 阿裏雲 go 技術社區[雲棲]


TensorFlow教程之完整教程 2.9 曼德布洛特(Mandelbrot)集合

本文檔為TensorFlow參考文檔,本轉載已得到TensorFlow中文社區授權。


曼德布洛特(Mandelbrot)集合

雖然可視化曼德布洛特(Mandelbrot)集合與機器學習沒有任何關係,但這對於將TensorFlow應用在數學更廣泛的領域是一個有趣的例子。實際上,這是tensorflow一個非常直截了當的可視化運用。(我們最終也許會提供一種更加精心設計的運用方式來生成真正更加美麗的圖像。)

說明:本教程使用了IPython的notebook。

基本步驟

首先,我們需要導入一些庫。

# 導入仿真庫
import tensorflow as tf
import numpy as np

# 導入可視化庫
import PIL.Image
from cStringIO import StringIO
from IPython.display import clear_output, Image, display
import scipy.ndimage as nd

現在我們將定義一個函數來顯示迭代計算出的圖像。

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(f, fmt)
  display(Image(data=f.getvalue()))

會話(session)和變量(variable)初始化

為了操作的方便,我們常常使用交互式會話(interactive session),但普通會話(regular session)也能正常使用。

   sess = tf.InteractiveSession()

我們可以自由的混合使用NumPy和TensorFlow,這一點非常方便。

# 使用NumPy創建一個在[-2,2]x[-2,2]範圍內的2維複數數組

Y, X = np.mgrid[-1.3:1.3:0.005, -2:1:0.005]
Z = X+1j*Y

現在我們定義並初始化一組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()

定義並運行計算

現在我們指定更多的計算...

# 計算一個新值z: z^2 + x
zs_ = zs*zs + xs

# 這個新值會發散嗎?
not_diverged = tf.complex_abs(zs_) < 4

# 更新zs並且迭代計算。
#
# 說明:在這些值發散之後,我們仍然在計算zs,這個計算消耗特別大!
#      如果稍微簡單點,這裏有更好的方法來處理。
#
step = tf.group(
  zs.assign(zs_),
  ns.assign_add(tf.cast(not_diverged, "float32"))
  )

...繼續執行幾百個步驟

for i in range(200): step.run()

讓我們看看我們得到了什麼。

DisplayFractal(ns.eval())

jpeg

結果不錯!

最後更新:2017-08-22 16:04:14

  上一篇:go  TensorFlow教程之完整教程 2.10 偏微分方程
  下一篇:go  TensorFlow教程之完整教程 2.8 遞歸神經網絡