#import module import tensorflow as tf #常量constant #tf.constant()函数定义 #def constant(value,dtype=None,shape=None,name='Const',verify_shape=False): #value:符合tf中定义的数据类型的常数值或者常数列表 #dtype:数据类型,可选 #shape:常量的形状,可选 #name:常量的名字,可选 #verify_shape:常量的形状是否可以被更改,默认不可更改 #Simple hello world using TensorFlow #The op is added as a node to the default graph #The value returned by the constructor represents the output of the Constant op.
hello=tf.constant("Hello,TensorFlow!") # Constant 1-D Tensor populated with value list. tensor1 = tf.constant([1, 2, 3, 4, 5, 6, 7])
# Constant 2-D tensor populated with scalar value -1. tensor2 = tf.constant(-1.0, shape=[2, 3])
#变量Variable #tf.Variable()函数定义 #def Variable(initializer,name): #initializer:是初始化参数 #name:可自定义的变量名 tensor3=tf.Variable(tf.random_normal(shape=[4,3],mean=0,stddev=1),name='tensor3') #def random_normal(shape,mean=0.0,stddev=1.0,dtype=dtypes.float32,seed=None,name=None): #shape:变量的形状,必选,shape=[4,3],4行3列矩阵 #mean:正态分布(the normal distribution)的均值E(x),默认是0 #stddev:正态分布的标准差sqrt(D(x)),默认是1.0 #dtype:输出的类型,默认为tf.float32 #seed:随机数种子,是一个整数,当设置后,每次运行的时候生成的随机数都一样 #name:操作的名称 #Start tf session #推荐适用with tf.Session() as sess,因为它创建完Session后可以自动关闭上下文 #一个Session对象封装了Operation执行对象的环境,并对Tensor对象进行计算 with tf.Session() as sess: #Run graph print(sess.run(hello)) print(sess.run(tensor1)) print(sess.run(tensor2)) #必须要加上这句,初始化全局变量,否则会报错Attempting to use uninitialized value tensor3 sess.run(tf.global_variables_initializer()) print(sess.run(tensor3))
#must have if define variable,使用变量Variable必须使用 init=tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) for _ in range(3): sess.run(update) print(sess.run(state))