初识
Tensorflow里面的Python语言中的Tensor是numpy ndarray对象。
# 创建一个变量, 初始化为标量 0.
state = tf.Variable(0, name="counter")
# 创建一个 op, 其作用是使 state 增加 1
one = tf.constant(1)
new_value = tf.add(state, one)
#赋值
update = tf.assign(state, new_value)
# 启动图, 运行 op
with tf.Session() as sess:
#初始化参数
tf.global_variables_initializer().run()
# 打印 'state' 的初始值
print sess.run(state)
# 运行 op, 更新 'state', 并打印 'state'
for _ in range(3):
sess.run(update)
print sess.run(state)
# 输出:
# 0
# 1
# 2
# 3
可见,直接sess.run(Tensor)
可以或者直接返回该Tensor的结果。显然,我们可以传入更多的Tensor来同时返回更多的结果。比如下面同时传入mul和intermed张量。
input1 = tf.constant(3.0)
input2 = tf.constant(2.0)
input3 = tf.constant(5.0)
intermed = tf.add(input2, input3)
mul = tf.mul(input1, intermed)
with tf.Session() as sess:
result = sess.run([mul, intermed])
print result
# 输出:
# [array([ 21.], dtype=float32), array([ 7.], dtype=float32)]
发现了吗?前面都是除了constant就是variable,觉得没啥意思,功能有点挫。TF还提供了tf.placeholder()
,这东西看名字就知道是占位符啊。有啥用啊,可以随时替换节点的输出。其可以设置该变量的类型,数据的维度之类的。比如tf.placeholder(‘uint8’,[None,None,3]),就可以处理任何3个通道的图片。placeholder要与feed连用。feed就是给placeholder创建的占位符喂入数据。
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.mul(input1, input2)
with tf.Session() as sess:
print sess.run([output], feed_dict={input1:[7.], input2:[2.]})
# 输出:
# [array([ 14.], dtype=float32)]
Mnist例子初步
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
x = tf.placeholder(tf.float32,[None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x,W) + b)
#compute cross-entropy
y_ = tf.placeholder(tf.float32,[None,10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
with tf.Session()