Tensorflow 本着建模和计算分开的原则:
一般要include的库们
In [10]:
import numpy as py
import tensorflow as tf
import matplotlib as plt
Variable: 一般是要被train的东西,初始化后就等着被程序更新
In [11]:
W = tf.Variable([.3], dtype=tf.float32)
b = tf.Variable([-.3], dtype=tf.float32)
x = tf.placeholder(tf.float32)
linear_model = W * x + b
Place Holder: 一般放实时进入的数据,以用来train model
In [12]:
a = tf.placeholder(tf.float32)
b = tf.placeholder(tf.float32)
adder_node = a + b # + provides a shortcut for tf.add(a, b)
除了variable和placeholder以外,还需要各种各样的node (常数,运算等)
constant Node:
In [14]:
node1 = tf.constant(3.0, dtype=tf.float32)
node2 = tf.constant(4.0) # also tf.float32 implicitly
add Node:
In [16]:
node3 = tf.add(node1, node2)
node4 = a + b
一切的grpth完成后,需要用session来执行graph以启动正式的运算
In [17]:
sess = tf.Session()
print(sess.run([node1, node2]))
In [18]:
print(sess.run(adder_node, {a: 3, b: 4.5}))
print(sess.run(adder_node, {a: [1, 3], b: [2, 4]}))
In [19]:
add_and_triple = adder_node * 3.
print(sess.run(add_and_triple, {a: 3, b: 4.5}))
对于定义的variable,需要进行初始化操作
In [21]:
init = tf.global_variables_initializer()
sess.run(init)
In [22]:
print(sess.run(linear_model, {x: [1, 2, 3, 4]}))
In [ ]: