def tensor_demo():
"""
张量的演示
:return:
"""
tensor1 = tf.constant(4.0)
tensor2 = tf.constant([1, 2, 3, 4])
linear_squares = tf.constant([[4], [9], [16], [25]], dtype=tf.int32)
print("tensor1:\n", tensor1)
print("tensor2:\n", tensor2)
print("linear_squares:\n", linear_squares)
# 生成常用张量
tensor3 = tf.zeros(shape=(3, 4))
print("tensor3:\n", tensor3)
tensor4 = tf.ones(shape=(2, 3, 4))
print("tensor4:\n", tensor4)
tensor5 = tf.random_normal(shape=(2, 3), mean=1.75, stddev=0.2)
print("tensor5:\n", tensor5)
with tf.compat.v1.Session() as sess:
print("tensor3_value:\n", tensor3.eval())
print("tensor4_value:\n", tensor4.eval())
print("tensor4_value:\n", tensor5.eval())
return None
def tensoredit_demo():
"""
张量类型的修改
:return:
"""
linear_squares = tf.constant([[4], [9], [16], [25]], dtype=tf.int32)
print("linear_squares_before:\n", linear_squares)
l_cast = tf.cast(linear_squares, dtype=tf.float32)
print("linear_squares_after:\n", linear_squares)
print("l_cast:\n", l_cast)
return None
def editstaticshape_demo():
"""
更新/改变静态形状
:return:
"""
a = tf.compat.v1.placeholder(dtype=tf.float32, shape=[None, None])
b = tf.compat.v1.placeholder(dtype=tf.float32, shape=[None, 10])
c = tf.compat.v1.placeholder(dtype=tf.float32, shape=[3, 2])
print("a:\n", a)
print("b:\n", b)
print("c:\n", c)
# 更新形状未确定的部分
a.set_shape([2, 3])
b.set_shape([2, 10])
print("a:\n", a)
print("b:\n", b)
return None;
def editshape_demo():
"""
更新/改变动态形状
不会改变原始的tensor
返回新的改变类型后的tensor
:return:
"""
a = tf.compat.v1.placeholder(dtype=tf.float32, shape=[None, None])
print("a:\n", a)
a.set_shape([2, 3])
print("a_setShape:\n", a)
# 元素个数没有变,还是2*3*1=6个
a_reshape = tf.reshape(a,shape=[2,3,1])
print("a_reshape:\n", a_reshape)
print("a:\n", a)
return None;
def variable_demo():
"""
变量的演示
变量需要显式初始化,才能运行值
:return:
"""
# 创建变量
# 使用命名空间可以使图的结构更加清晰
with tf.variable_scope("myscope"):
a = tf.Variable(initial_value=50)
b = tf.Variable(initial_value=40)
with tf.variable_scope("yourscope"):
c= tf.add(a,b)
print("a:\n",a)
print("b:\n",b)
print("c:\n",c)
# 初始化变量
init = tf.global_variables_initializer()
# 开启会话
with tf.Session() as sess:
sess.run(init)
a_value,b_value,c_value=sess.run([a,b,c])
print("a_value:\n",a_value)
print("b_value:\n",b_value)
print("c_value:\n",c_value)
return None