Tensorflow学习1:基本使用

.eval() 和 sess.run()区别:

最主要的区别就在于使用.eval()只能获取这个tensor的值,而使用sess.run()可以同时获取多个tensor中的值,

1
2
3
4
5
6
7
8
t = tf.constant(42.0)
u = tf.constant(37.0)
tu = tf.mul(t, u)
ut = tf.mul(u, t)
with sess.as_default():
tu.eval() # runs one step
ut.eval() # runs one step
sess.run([tu, ut]) # evaluates both tensors in a single step

变量 和 两种Session()定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#第一种 session()定义方式
import tensorflow as tf
a = 3
# Create a variable.
w = tf.Variable([[0.5,1.0]])
x = tf.Variable([[2.0],[1.0]])

y = tf.matmul(w, x)


#variables have to be explicitly initialized before you can run Ops
init_op = tf.global_variables_initializer()
with tf.Session() as sess: #第一种 session()定义
sess.run(init_op)
print (y.eval())
Tensor("Variable_11/read:0", shape=(1, 2), dtype=float32)
[[ 2.]]

计算操作需要在 Session()——会话(计算图的区域) 中进行;
而且在使用 variable 时还需要 初始化全局变量操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 第二种 Session() 定义
import tensorflow as tf
# 初始化生成一个 均值为-1,方差为4的矩阵
norm = tf.random_normal([2, 3], mean=-1, stddev=4)

# Shuffle the first dimension of a tensor
c = tf.constant([[1, 2], [3, 4], [5, 6]])
shuff = tf.random_shuffle(c)

# Each time we run these ops, different results are generated
sess = tf.Session() #第二种 session()定义方式
print (sess.run(norm))
print (sess.run(shuff))
sess.close() #这种方法没有明确的区域,所以要关闭来指定作用域
[[ 3.78657341 -3.94182277 -3.65419507]
    [-7.0396409  -5.51102114  3.56082773]]
[[5 6]
 [1 2]
 [3 4]]

三种variable初始化方式

1
2
3
4
#第一种
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
1
2
3
4
#第二种
init = tf.initialize_all_variables()
with tf.Session() as sess:
init.run()
1
2
3
#第三种,一步到位
with tf.Session() as sess:
tf.initialize_all_variables().run()

矩阵 和 常量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# float32
tf.zeros([3, 4], int32) ==> [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

# 'tensor' is [[1, 2, 3], [4, 5, 6]]
tf.zeros_like(tensor) ==> [[0, 0, 0], [0, 0, 0]]
tf.ones([2, 3], int32) ==> [[1, 1, 1], [1, 1, 1]]

# 'tensor' is [[1, 2, 3], [4, 5, 6]]
tf.ones_like(tensor) ==> [[1, 1, 1], [1, 1, 1]]

# Constant 1-D Tensor populated with value list.
tensor = tf.constant([1, 2, 3, 4, 5, 6, 7]) => [1 2 3 4 5 6 7]

# Constant 2-D tensor populated with scalar value -1.
tensor = tf.constant(-1.0, shape=[2, 3]) => [[-1. -1. -1.]
[-1. -1. -1.]]

tf.linspace(10.0, 12.0, 3, name="linspace") => [ 10.0 11.0 12.0]

# 令'start' is 3
# 'limit' is 18
# 'delta' is 3
tf.range(start, limit, delta) ==> [3, 6, 9, 12, 15]

对比 Numpy 操作,发现区别并不大

累加 演示

1
2
3
4
5
6
7
8
9
10
state = tf.Variable(0)
new_value = tf.add(state, tf.constant(1))
update = tf.assign(state, new_value)

with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(sess.run(state))
for _ in range(3):
sess.run(update)
print(sess.run(state))

0
1
2
3

train.Saver() 保存 Session() 操作

1
2
3
4
5
6
7
8
9
10
11
12
#tf.train.Saver
w = tf.Variable([[0.5,1.0]])
x = tf.Variable([[2.0],[1.0]])
y = tf.matmul(w, x)
init_op = tf.global_variables_initializer()
saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(init_op)
# Do some work with the model.
# Save the variables to disk.
save_path = saver.save(sess, "C://tensorflow//model//test")
print ("Model saved in file: ", save_path)

Model saved in file: C://tensorflow//model//test

convert_to_tensor() 转换 numpy 的语法为 tensorflow 类型

1
2
3
4
5
import numpy as np
a = np.zeros((3,3))
ta = tf.convert_to_tensor(a)
with tf.Session() as sess:
print(sess.run(ta))
[[ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]]

不推荐使用,还是建议使用 tensorflow 语法

Fetch and Feed

Fetch 把多个op放在一个数组中一起run

1
2
3
4
5
6
7
8
9
10
11
# Fetch
imput1 = tf.constant(3.0)
imput2 = tf.constant(2.0)
imput3 = tf.constant(1.0)

add = tf.add(imput1, imput2)
mul = tf.multiply(imput1, imput2)

with tf.Session() as sess:
res = sess.run([add, mul])
print(res)
[5.0, 6.0]

Feed 在运行时,用字典结构给占位符赋值

1
2
3
4
5
6
7
8
9
imput1 = tf.placeholder(tf.float32)
imput2 = tf.placeholder(tf.float32)
output = tf.add(imput1, imput2)

with tf.Session() as sess:
print(sess.run(output, feed_dict={
imput1:[1],
imput2:[2]
}))

使用flags定义命令行参数

tf定义了tf.app.flags,用于支持接受命令行传递参数,相当于接受argv。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import tensorflow as tf

#第一个是参数名称,第二个参数是默认值,第三个是参数描述
tf.app.flags.DEFINE_string('str_name', 'def_v_1',"descrip1")
tf.app.flags.DEFINE_integer('int_name', 10,"descript2")
tf.app.flags.DEFINE_boolean('bool_name', False, "descript3")

FLAGS = tf.app.flags.FLAGS

#必须带参数,否则:'TypeError: main() takes no arguments (1 given)'; main的参数名随意定义,无要求
def main(_):
print(FLAGS.str_name)
print(FLAGS.int_name)
print(FLAGS.bool_name)

if __name__ == '__main__':
tf.app.run() #执行main函数

执行:

1
2
3
4
5
6
7
8
9
10
//不带参数时:
[root@test]# python tt.py
def_v_1
10
False
//给定参数时:
[root@test]# python tt.py --str_name test_str --int_name 99 --bool_name True
test_str
99
True

꧁༺The༒End༻꧂