Tensorflow基本语法

一、tf.Variables()

import tensorflow as tf

Weights = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
sess.run(Weights)

tf.Variable()与tf.get_variable()区别
使用tf.Variable时,如果检测到命名冲突,系统会自己处理。使用tf.get_variable()时,系统不会处理冲突,而会报错
w_1 = tf.Variable(3, name="w_1")
w_2 = tf.Variable(1, name="w_1")
print(w_1.name)
print(w_2.name)
#输出
#w_1:0
#w_1_1:0,由于命名相同,系统自行处理
 
w_1 = tf.get_variable(name="w_1",initializer=1)
w_2 = tf.get_variable(name="w_1",initializer=2)
#会报错,因为名字相同错误信息
#ValueError: Variable w_1 already exists, disallowed. Did
#you mean to set reuse=True in VarScope?

 tf.Variable() 使用TF在默认的图中创建节点,这个节点是一个变量。Variable第一个参数表示初始化的值,如:state = tf.Variable(0 , name='counter')

 tf.get_variable():和tf.Variable最大的区别在于tf.Variable的变量名是一个可选项,通过name=’v’的形式给出。但是tf.get_variable必须指定变量名

 

 tf.random_uniform():生成的值在该 [minval, maxval) 范围内遵循均匀分布。下限 minval 包含在范围内,而上限 maxval 被排除在外

 tf.random_normal():函数用于从服从指定正态分布的数值中取出指定个数的值。tf.random_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)

  shape: 输出张量的形状,必选,如shape = ([2, 3])

 

  mean: 正态分布的均值,默认为0

  stddev: 正态分布的标准差,默认为1.0

  dtype: 输出的类型,默认为tf.float32

  seed: 随机数种子,是一个整数,当设置之后,每次生成的随机数都一样

  name: 操作的名称

 

 tf.truncated_normal():

  tf.truncated_normal(shape, mean, stddev) :shape表示生成张量的维度,mean是均值,stddev是标准差。这个函数产生正太分布,均值和标准差自己设定

  这是一个截断的产生正太分布的函数,就是说产生正太分布的值如果与均值的差值大于两倍的标准差,那就重新生成

  和一般的正太分布的产生随机数据比起来,这个函数产生的随机数与均值的差距不会超过两倍的标准差,但是一般的别的函数是可能的

 

# -*- coding: utf-8 -*-)
import tensorflow as tf

w1 = tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1))

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    # sess.run(tf.initialize_all_variables())  #比较旧一点的初始化变量方法
    print(w1)
    print(sess.run(w1))

'''
Tensor("Variable/read:0", shape=(2, 3), dtype=float32)
[[-0.8113182   1.4845988   0.06532937]
 [-2.4427042   0.0992484   0.5912243 ]]
'''

 

二、tf.Session()

import tensorflow

matrix1 = tf.constant([[3,3]])#一行两列
matrix2 = tf.constant([[2],[2]])#两行一列

product = tf.matmul(matrix1, matrix2)

sess = tf.Session()
result = sess.run(product)

print(result)
#[[12]]

 tf.Sess()称之为会话的上下文,用于执行图。

 

三、tf.placehold()

input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)

output = tf.mul(input1, input2)#乘法

with tf.Session() as sess:
	print(sess.run(output, feed_dict={input1:[7], input2:[2]}))

#在sess.run()的时候用feed_dict来给变量赋值

 占位符:tf.placeholder 告诉系统,这里有一个值/向量/矩阵,现在我没法给你具体数值,不过我正式运行的时候会补上的!

 

四、tf.clip_by_value的用法

 tf.clip_by_value(A, min, max):把张量A中每一个元素值都限制在min和max之间。小于min的让它等于min,大于max的让它等于max。在min和max之间的保持不变

import tensorflow as tf
import numpy as np 
A = np.array([[1,1,2,4], [3,4,8,5]])

with tf.Session() as sess:
    print(sess.run(tf.clip_by_value(A, 2, 5)))

'''
[[2 2 2 4]
 [3 4 5 5]]
'''

 

五、tf.get_default_graph()

import tensorflow as tf
a = tf.constant( [1.0, 2.0], name='a' )

a.graph
#<tensorflow.python.framework.ops.Graph object at 0x000000001FBEED30>

tf.get_default_graph()
#<tensorflow.python.framework.ops.Graph object at 0x000000001FBEED30>

b = tf.constant( [3.0, 4.0], name='b' )

b.graph
#<tensorflow.python.framework.ops.Graph object at 0x000000001FBEED30>

c = a + b
c.graph
#<tensorflow.python.framework.ops.Graph object at 0x000000001FBEED30>

#从上面的看:a,b,c都在一张计算图上,即默认的计算图

 

六、tf.Graph()

import tensorflow as tf
 
g1 = tf.Graph()
with g1.as_default():#设g1为默认图
          #在计算图g1中定义变量"v",并设置初始值为0,shape指定变量维度
          v = tf.get_variable( 'v', shape=[1], initializer=tf.zeros_initializer( ) )
 
g2 = tf.Graph()#生成新的计算图
with g2.as_default():#设g2为默认图
          #在计算图g2中定义变量"v",并设置初始值为1
          v = tf.get_variable( 'v',shape=[1], initializer=tf.ones_initializer() )
 
#在计算图g1中读取变量'v'的取值
with tf.Session( graph=g1 ) as sess:
          tf.global_variables_initializer().run()
          with tf.variable_scope('', reuse=True):
                    #在计算图g1中,变量'v'的取值应该为0,所以下面这行会输出[0.]
                    print( sess.run(tf.get_variable('v')) )
                    
 
#在计算图g2中读取变量'v'的取值
with tf.Session(graph=g2) as sess:
          tf.global_variables_initializer().run()
          with tf.variable_scope('', reuse=True):
                    #在计算图g2中,变量'v'的取值应该为1,所以下面这行会输出[1.]
                    print(sess.run(tf.get_variable('v')))

 

  

 

 

posted @ 2018-07-24 10:03  1直在路上1  阅读(1026)  评论(0编辑  收藏  举报