LoginSignup
13
14

More than 5 years have passed since last update.

TensorFlowチュートリアル - マンデルブロ集合(翻訳)

Posted at

TensorFlowのチュートリアル(Mandelbrot Set)
https://www.tensorflow.org/versions/master/tutorials/mandelbrot/index.html#mandelbrot-set
の翻訳です。
翻訳の誤りなどあればご指摘お待ちしております。


マンデルブロ集合の可視化は、機械学習ではありませんが、一般的な数学のためにTensorFlowを使用する方法の楽しい例です。これは実際には視覚化のかなり単純な実装ですが、要点を押さえています。 (後に、もっと本当に美しい画像を生成するために、以下より精巧な実装を提供することになるかもしれません。)

注:このチュートリアルは、本来 IPython notebook のために準備しました。

基本設定

始めにいくつかの import が必要です。

# Import libraries for simulation
import tensorflow as tf
import numpy as np

# Imports for visualization
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'):
  """Display an array of iteration counts as a
     colorful picture of a fractal."""
  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()))

セッションと変数の初期化

いじくりまわすために、しばしば対話型セッションを使用しますが、通常のセッションでも同様に動作します。

   sess = tf.InteractiveSession()

NumPyとTensorFlowは自由に混在させることができ、便利です。

# Use NumPy to create a 2D array of complex numbers on [-2,2]x[-2,2]

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

TensorFlowのテンソルを定義し初期化します。

xs = tf.constant(Z.astype("complex64"))
zs = tf.Variable(xs)
ns = tf.Variable(tf.zeros_like(xs, "float32"))

TensorFlowでは、変数は使用する前に明示的に初期化する必要があります。

tf.initialize_all_variables().run()

定義と計算の実行

複数の計算を指定し...

# Compute the new values of z: z^2 + x
zs_ = zs*zs + xs

# Have we diverged with this new value?
not_diverged = tf.complex_abs(zs_) < 4

# Operation to update the zs and the iteration count.
#
# Note: We keep computing zs after they diverge! This
#       is very wasteful! There are better, if a little
#       less simple, ways to do this.
#
step = tf.group(
  zs.assign(zs_),
  ns.assign_add(tf.cast(not_diverged, "float32"))
  )

...そして、200ステップそれを実行します

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

得られたものを見てみましょう。

DisplayFractal(ns.eval())

図

悪くないね!

13
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
14