python深度学习Tensorflow基础(二)

Tensorflow基础

  • Tensorflow基础
    • Tensorflow基本概念
      • 变量
      • 占位符
      • 实现数据流图及可视化

Tensorflow基础

Tensorflow基本概念

变量

1、Tensorflow中变量的使用其具体格式为:

tf.Variable(initial_value=None, trainable=True, collections=None, validate_shape=True, caching_device=None, name=None, variable_def=None, dtype=None, expected_shape=None, import_scope=None, constraint=None

·initial_value:一个Tensor类型或者是能够转化为Tensor的python对象类型。它是这个变量的初始值。这个初始值必须指定形状信息,不然后面的参数validate_shape需要设置为false。当然,也能够传入一个无参数可调用并且返回指定初始值的对象,在这种情况下,dtype必须指定。
·trainable:如果设置为True(默认也为True),这个变量可以被优化器类(optimizer)自动修改Variable的值;如果设置为False,则说明Variable只能手工修改,不允许使用优化器类自动修改。
·collections:图的collection键列表,新的变量被添加到这些collection中。默认是[GraphKeys.GLOBAL_VARIABLES]。
·validate_shape:如果是False的话,就允许变量能够被一个形状未知的值初始化,默认是True,表示必须知道形状。
·caching_device:可选,描述设备的字符串,表示哪个设备用来为读取缓存。默认是变量的device。
·name:可选,变量的名称。
·dtype:如果被设置,初始化的值就会按照这里的类型来定。

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

#创建模型的权重及偏置
weights = tf.Variable(tf.random_normal([784,200],stddev = 0.35),name = "weights")
biases = tf.Variable(tf.zeros([200]),name = "biases")
#初始化变量
init_op = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init_op)



#保存模型变量
saver = tf.train.Saver()
saver.save(sess,'./tmpmodel/',global_step=100)


#恢复模型变量
saver = tf.train.import_meta_graph('./tmpmodel/-100.meta')
saver.restore(sess,tf.train.latest_checkpoint('./tmpmodel/'))
#查看恢复后的变量
print(sess.run('biases:0'))

2、共享变量
TensorFlow提供了tf.variable_scope和tf.get_variable两个API,实现了共享模型变量。tf.get_variable(,,):表示创建或返回指定名称的模型变量,其中name表示变量名称,shape表示变量的维度信息,initializer表示变量的初始化方法。tf.variable_scope():表示变量所在的命名空间,其中scope_name表示命名空间的名称。

def conv_relu(input,kernel_shape,bias_shape):
    #创建变量"weights"
    weights = tf.get_variable("weights",kernel_shape,initializer=tf.random_normal_initializer())
    #创建变量"biases"
    biases = tf.get_variable("biases",bias_shape,initializer=tf.constant_initializer(0.0))
    conv = tf.nn.conv2d(input,weights,strides=[1,1,1,1],padding='SAME')
    return tf.nn.relu(conv+biases)
#定义卷积层
#input_images只是一个名称用于表示参数input
with tf.variable_scope("conv1"):
    relu1 = conv_relu(input_images,[5,5,32,32],[32])
with tf.variable_scope("conv2"):
    relu1 = conv_relu(relu1,[5,5,32,32],[32])

3、变量与常量的区别
Constant一般是常量,可以被赋值给Variables,Constant保存在graph中,如果graph重复载入,那么Constant也会重复载入,这样非常浪费资源。如非必要,尽量不使用其保存大量数据。而Variables在每个session中都是单独保存的,甚至可以单独存在一个参数服务器上。

const = tf.constant(1.0,name="constant")
print(tf.get_default_graph().as_graph_def())

运行结果为:

node {
  name: "constant"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_FLOAT
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_FLOAT
        tensor_shape {
        }
        float_val: 1.0
      }
    }
  }
}

占位符

占位符可以理解为先占一个位置,可以用来保存数据。
一般格式:
tf.placeholder(dtype, shape=None, name=None)

参数说明如下。
·dtype:将要被feed的元素类型。
·shape:(可选)将要被feed的tensor的形状,如果不指定,可以feed进任何形状的tensor。
·name:(可选)这个操作的名字。

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import numpy as np

x = tf.placeholder(tf.float32,shape=(2,3))
y = tf.reshape(x,[3,2])
z = tf.matmul(x,y)
print(z)
with tf.Session() as sess:
    #print(sess.run(y))
    rand_array_x = np.random.rand(2,3)
    rand_array_y = np.random.rand(3, 2)
    print(sess.run(z,feed_dict={x:rand_array_x,y:rand_array_y}))

实现数据流图及可视化

一般可视化:

a = tf.constant(2,name="input_a")
b = tf.constant(2,name="input_b")
c = tf.multiply(a,b,name="mul_c")
d = tf.add(a,b,name="add_d")
e = tf.add(c,d,name="add_e")
sess = tf.Session()
output = sess.run(e)
print(output)
writer = tf.summary.FileWriter('./feigu/tmp',sess.graph)
writer.close()
sess.close()

使用这条命令打开浏览器。

tensorboard --logdir=/Users/-------/Desktop/01

更好的可视化:

graph = tf.Graph()
with graph.as_default():
    in_1 = tf.placeholder(tf.float32,shape=[],name="input_a")
    in_2 = tf.placeholder(tf.float32, shape=[], name="input_b")
    const = tf.constant(3,dtype=tf.float32,name="static_value")
    with tf.name_scope("Transformation"):
        with tf.name_scope("A"):
            A_mul = tf.multiply(in_1,const)
            A_out = tf.subtract(A_mul,in_1)
        with tf.name_scope("B"):
            B_mul = tf.multiply(in_2, const)
            B_out = tf.subtract(B_mul, in_2)
        with tf.name_scope("C"):
            C_div = tf.div(A_out, B_out)
            C_out = tf.add(C_div, const)
        with tf.name_scope("B"):
            D_div = tf.div(B_out, A_out)
            D_out = tf.subtract(D_div, const)
            out = tf.maximum(C_out,D_out)
writer = tf.summary.FileWriter('./feigu/tmp1',graph=graph)
writer.close()

浏览器同上。

你可能感兴趣的:(python深度学习Tensorflow基础(二))