#定义 graph
#常量
hello = tf.constant("hello world")
a = tf.constant(1)
b = tf.constant(2)
c = tf.add(a,b)
graph执行时须在Session中。
# coding:utf-8
import numpy as np
import tensorflow as tf
hello = tf.constant("hello world")
a = tf.constant(1)
b = tf.constant(2)
c = tf.add(a,b)
d = a+b
e = a*b
f = tf.mul(a,b)
with tf.Session() as sess:
print sess.run([a, b, c, d, e, f])
out is:[1, 2, 3, 3, 2, 2]
with tf.Session() as sess:
print sess.run([a, b, c, d, e, f])
等于:
sess=tf.Session()
print sess.run([a, b, c, d, e, f])
sess.close()
为了便于使用诸如 IPython 之类的 Python 交互环境, 可以使用 InteractiveSession 代替 Session 类, 使用 Tensor.eval() 和 Operation.run() 方法代替 Session.run(). 这样可以避免使用一个变量来持有会话.
变量:
# 创建一个变量, 初始化为标量 0.
state = tf.Variable(0, name="counter")
# 启动图后, 变量必须先经过`初始化` (init) op 初始化,
# 首先必须增加一个`初始化` op 到图中.
init_op = tf.initialize_all_variables()
在1.1.0版本改为:tf.global_variables_initializer()
查看版本:
print tf.VERSION
占位符:
feed:
feed 使用一个 tensor 值临时替换一个操作的输出结果. 你可以提供 feed 数据作为 run() 调用的参数. feed 只在调用它的方法内有效, 方法结束, feed 就会消失. 最常见的用例是将某些特殊的操作指定为 “feed” 操作, 标记的方法是使用 tf.placeholder() 为这些操作创建占位符.
a = tf.placeholder(tf.int16)
b = tf.placeholder(tf.int16)
#把a,b定义成为tf.int16类型的占位符,并没有放具体的数值进去。
with tf.Session() as sess:
#在Session中为a,b赋值
printsess.run(add, feed_dict={a: 2, b: 3})
矩阵:
matrix1 = tf.constant([[1., 1.]])
matrix2 = tf.constant([[2.],[2.]])
矩阵相乘用matmul
product = tf.matmul(matrix1, matrix2)
out:[[ 12.]]
TensorFlow 随机数生成函数:
1.正太分布:从正态分布中输出随机值。
tf.random_normal(shape,
mean=0.0,
stddev=1.0,
dtype=dtypes.float32,
seed=None,
name=None):
shape: 一维的张量,也是输出的张量。
mean: 正态分布的均值。
stddev: 正态分布的标准差。
dtype: 输出的类型。
seed: 一个整数,当设置之后,每次生成的随机数都一样。
name: 操作的名字
2.正态分布:从截断的正态分布中输出随机值。
truncated_normal(shape,
mean=0.0,
stddev=1.0,
dtype=dtypes.float32,
seed=None,
name=None):
生成的值服从具有指定平均值和标准偏差的正态分布,如果生成的值大于平均值2个标准偏差的值则丢弃重新选择。
如果x的取值在区间(μ-2σ,μ+2σ)之外则重新进行选择。这样保证了生成的值都在均值附近。
a = tf.Variable(tf.random_normal([2,2],stddev=1,seed=1))
b = tf.Variable(tf.random_normal([2,2],stddev=1,seed=2))
c = tf.Variable(tf.truncated_normal([2,2],stddev=1,seed=1))
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
print sess.run(a)
print sess.run(b)
print sess.run(c)
[[-0.81131822 1.48459876]
[ 0.06532937 -2.44270396]]
[[-0.85811085 -0.19662298]
[ 0.13895047 -1.22127688]]
[[-0.81131822 1.48459876]
[ 0.06532937 0.0992484 ]]
3.平均分布
random_uniform(shape,
minval=0,
maxval=None,
dtype=dtypes.float32,
seed=None,
name=None):
4.Gamma分布:
random_gamma(shape,
alpha,
beta=None,
dtype=dtypes.float32,
seed=None,
name=None):