(1)Hello World之tensorflow
from __future__ import print_function
import tensorflow as tf
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(hello))
1.from future import print_function 这行代码主要是解决python2.X和python3.X之间 print 方法的差异,即python3.X中print方法开始需要加上括号后,这样写可以优化代码的兼容性。
2.导包tensorflow,定义别名为tf。
3.tf.constant()方法:创建一个定值向量。
tf.constant(
value, # 常量值
dtype=None, #输出类型
shape=None, #输出向量的可选维度
name='Const', #向量的名称
verify_shape=False #布尔值,用于验证值的shape
)
4.tf.Session(),顾名思义,可以理解为开始一个运算的对话,当我们在一个session当中需要计算的任务结束了,就可以通过相应的方法结束这个session。一般来讲,session的生命周期如下所示:
#1.创建
ses = tf.Session()
#2.科学计算
ses.run(...)
#3.关闭
ses.close()
#Using the context manager.
with tf.Session() as sess:
sess.run(...)
(2)tensorflow 常见的几个操作
Basic constant operations
import tensorflow as tf
a = tf.constant(2)
b = tf.constant(3)
with tf.Session() as sess:
print "a: %i" % sess.run(a), "b: %i" % sess.run(b)
print "Addition with constants: %i" % sess.run(a+b)
print "Multiplication with constants: %i" % sess.run(a*b)
运行程序,输出的结果是:
Basic Operations with variable as graph input
a = tf.placeholder(tf.int16)
b = tf.placeholder(tf.int16)
add = tf.add(a, b)
mul = tf.multiply(a, b)
with tf.Session() as sess:
# Run every operation with variable input
print "Addition with variables: %i" % sess.run(add, feed_dict={a: 2, b: 3})
print "Multiplication with variables: %i" % sess.run(mul, feed_dict={a: 2, b: 3})
placeholder,翻译过来是“占位符”的意思,就是在开始2行代码并没有确定a和b具体的值,后面的feed_dict才是真正赋值的时候。
程序运行输出的结果是:
Addition with variables: 5
Multiplication with variables: 6
矩阵相乘
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)
with tf.Session() as sess:
result = sess.run(product)
print result
运行程序,输出的结果是:
[[ 12.]]
Tensorflow Eager API的基本使用
Eager Execution 的优点如下:
- 快速调试即刻的运行错误并通过 Python 工具进行整合
- 借助易于使用的 Python 控制流支持动态模型
- 为自定义和高阶梯度提供强大支持
- 适用于几乎所有可用的 TensorFlow 运算
也就是说当你启动 Eager Execution 时,运算会即刻执行,无需 Session.run() 就可以把它们的值返回到 Python。
from __future__ import absolute_import, division, print_function
import numpy as np
import tensorflow as tf
# Set Eager API
print("Setting Eager mode...")
tf.enable_eager_execution()
tfe = tf.contrib.eager
运行程序,得到如下结果:
Setting Eager mode...
从上面程序看,我们没有调用run()方法就可以运行程序。
2.
# Full compatibility with Numpy
print("Mixing operations with Tensors and Numpy Arrays")
# Define constant tensors
a = tf.constant([[2., 1.],
[1., 0.]], dtype=tf.float32)
print("Tensor:\n a = %s" % a)
b = np.array([[3., 0.],
[5., 1.]], dtype=np.float32)
print("NumpyArray:\n b = %s" % b)
输出结果如下:
print("Iterate through Tensor 'a':")
for i in range(a.shape[0]):
for j in range(a.shape[1]):
print(a[i][j])
输出结果如下:
Iterate through Tensor 'a':
tf.Tensor(2.0, shape=(), dtype=float32)
tf.Tensor(1.0, shape=(), dtype=float32)
tf.Tensor(1.0, shape=(), dtype=float32)
tf.Tensor(0.0, shape=(), dtype=float32)