import tensorflow as tf
一、初体验
node1 = tf.constant([[1,2,3],[4,5,6]])
node2 = tf.constant([[1,2,3],[4,5,6]])
node3 = tf.add(node1,node2)
node3
<tf.Tensor: shape=(2, 3), dtype=int32, numpy=
array([[ 2, 4, 6],
[ 8, 10, 12]], dtype=int32)>
node3.numpy()
array([[ 2, 4, 6],
[ 8, 10, 12]], dtype=int32)
node3.dtype
tf.int32
node3.shape
TensorShape([2, 3])
node3.get_shape()
TensorShape([2, 3])
二、常量
a = tf.constant(1)
a
<tf.Tensor: shape=(), dtype=int32, numpy=1>
b = tf.constant(2.0)
b
<tf.Tensor: shape=(), dtype=float32, numpy=2.0>
a = tf.cast(a,tf.float32)
tf.add(a,b).numpy()
3.0
三、变量
v1 = tf.Variable([1,2])
v1
<tf.Variable 'Variable:0' shape=(2,) dtype=int32, numpy=array([1, 2], dtype=int32)>
v2 = tf.Variable([3,4],tf.float32)
v2
<tf.Variable 'Variable:0' shape=(2,) dtype=int32, numpy=array([3, 4], dtype=int32)>
tf.Variable(a)
<tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>
v2
<tf.Variable 'Variable:0' shape=(2,) dtype=int32, numpy=array([3, 4], dtype=int32)>
v2.assign(v2+1)
<tf.Variable 'UnreadVariable' shape=(2,) dtype=int32, numpy=array([4, 5], dtype=int32)>
v2.assign_add([2,1])
<tf.Variable 'UnreadVariable' shape=(2,) dtype=int32, numpy=array([6, 6], dtype=int32)>
v2.assign_sub([1,2])
<tf.Variable 'UnreadVariable' shape=(2,) dtype=int32, numpy=array([5, 4], dtype=int32)>
四、tf2执行tf1代码
import tensorflow.compat.v1 as tf
tf.disable_eager_execution()
node1 = tf.constant(3)
node2 = tf.constant(4)
node3 = node1 + node2
node3
<tf.Tensor 'add:0' shape=() dtype=int32>
sess = tf.Session()
sess.run(node3)
7
sess.close()
五、会话模式
5.1三种对话模式
tens1 = tf.constant([1])
sess = tf.Session()
print(sess.run(tens1))
sess.close()
[1]
tens1 = tf.constant(1)
sess = tf.Session()
try:
print(sess.run(tens1))
except:
...
finally:
sess.close()
1
tens1 = tf.constant(1)
with tf.Session() as sess:
print(sess.run(tens1))
1
5.2指定默认的对话
- 指定了默认会话可以通过tf.Tensor.eval函数来计算一个张量的取值
tens1 = tf.constant(1)
sess = tf.Session()
with sess.as_default():
print(tens1.eval())
1
tens1 = tf.constant(1)
sess = tf.Session()
print(sess.run(tens1))
print(tens1.eval(session=sess))
1
1
tens1 = tf.constant(1)
sess = tf.InteractiveSession()
print(tens1.eval())
1
六、变量的初始化
node1 = tf.Variable(3.0)
node2 = tf.Variable(4.0)
result = node1+node2
node1_init = node1.initializer
node2_init = node2.initializer
sess = tf.Session()
sess.run(node1_init)
sess.run(node2_init)
print(sess.run([result,node1,node2]))
[7.0, 3.0, 4.0]
node1 = tf.Variable(3.0)
node2 = tf.Variable(4.0)
result = node1+node2
init = tf.global_variables_initializer()
sess.run(init)
print(sess.run(result))
7.0
七、占位符 placeholder
x = tf.placeholder(tf.float32)
x_value = float(input())
123
with tf.Session() as sess:
result = sess.run(x,feed_dict={x:x_value})
print(result)
123.0
|