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)># 通过.numpy()获取值
node3.numpy()array([[ 2, 4, 6],
[ 8, 10, 12]], dtype=int32)node3.dtypetf.int32node3.shapeTensorShape([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 tftf.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)7sess.close()五、会话模式
5.1三种对话模式
# 1.会话模式一
tens1 = tf.constant([1])
sess = tf.Session()
print(sess.run(tens1))
sess.close()[1]# 2.会话模式二
tens1 = tf.constant(1)
sess = tf.Session()
try:
print(sess.run(tens1))
except:
...
finally:
sess.close()1# 3.会话模式三
tens1 = tf.constant(1)
with tf.Session() as sess:
print(sess.run(tens1))15.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# tf.InteractiveSession() 这个函数会自动将生成的会话注册为默认会话
tens1 = tf.constant(1)
sess = tf.InteractiveSession()
print(tens1.eval())1六、变量的初始化
node1 = tf.Variable(3.0)
node2 = tf.Variable(4.0)
result = node1+node2 # tf.add(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
- 类似于python中的%s
x = tf.placeholder(tf.float32)x_value = float(input())123with tf.Session() as sess:
result = sess.run(x,feed_dict={x:x_value})
print(result)123.0










