For those who are not familiar with machine learning but want to calculate within the range that they can understand, let's try Fibonacci sequence with TensorFlow.
Fibonacci sequence
For example, to calculate
u = 1
v = 0
for i in range(100):
print i, v
u = u + v
v = u - v
You can do it like this.
TensorFlow
import tensorflow as tf
Suppose you want to read with.
Variable First, let's change the variables u and v to TensorFlow variables. To do this, use Variable as follows:
u = tf.Variable(1, "int64")
v = tf.Variable(0, "int64")
I chose int64 as an overflow countermeasure, but unfortunately, an overflow occurs in Section 93. If this is omitted, it will be treated as int32.
It sounds like you can print it with print u
, but unfortunately you won't get what you expect. TensorFlow is divided into a phase of defining variables, functions and procedures, and a phase of actually processing data.
Use tf.Session to actually process the data. Variables need to be initialized at the beginning of the session. Use tf.initialize_all_variables for this. And you can get the values of u and v by doing the following.
init = tf.initialize_all_variables()
with tf.Session() as sess:
sess.run(init)
print sess.run(v)
Take values and execute procedures with sess.run.
The rest is the value update part. Use tf.assign for assignment. Use tf.add and tf.sub for addition and subtraction. And let's define a procedure called substitution.
update_u = tf.assign(u, tf.add(u, v)) # u = u + v
update_v = tf.assign(v, tf.sub(u, v)) # v = u - v
To summarize the above story,
import tensorflow as tf
u = tf.Variable(tf.cast(1,"int64"))
v = tf.Variable(tf.cast(0,"int64"))
update_u = tf.assign(u, tf.add(u,v))
update_v = tf.assign(v, tf.sub(u,v))
init = tf.initialize_all_variables()
with tf.Session() as sess:
sess.run(init)
for i in range(100):
print i, sess.run(v)
sess.run(update_u)
sess.run(update_v)
When I run it, somehow the CPU somehow displays a log that starts with I, but since it is Info, I don't care.
If you haven't touched TensorFlow yet, let's do something.
Recommended Posts