tensorflow函数介绍(3)

时间:2023-03-09 05:38:42
tensorflow函数介绍(3)
tf.nn.softmax_cross_entropy_with_logits(logits,labels)      #其中logits为神经网络最后一层输出,labels为实际的标签,该函数返回经过softmax转换之后并与实际值相比较得到的交叉熵损失函数的值,该函数返回向量

1、tf.nn.softmax_cross_entropy_with_logits的例子:

import tensorflow as tf
logits=tf.constant([[1.0,2.0,3.0],[1.0,2.0,3.0],[1.0,2.0,3.0]])
y=tf.nn.softmax(logits) #计算给定输入的softmax值
y_=tf.constant([[0.0,0.0,1.0],[0.0,0.0,1.0],[0.0,0.0,1.0]])
cross_entropy = -tf.reduce_sum(y_*tf.log(y)) #计算交叉熵损失函数的值,返回向量,并通过tf.reduce_sum来计算均值
cross_entropy2=tf.reduce_sum(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y_)) #直接计算交叉熵损失函数值
init=tf.global_variables_initializer()
sess=tf.Session()
sess.run(init)
print(sess.run(y))
print(sess.run(cross_entropy)) #输出结果和下面的一致
print(sess.run(cross_entropy2))

 2、在tensorboard上显示运行图:

import tensorflow as tf
a = tf.constant(10,name="a")
b = tf.constant(90,name="b")
y = tf.Variable(a+b*2,name='y')
init=tf.global_variables_initializer()
with tf.Session() as sess:
merged = tf.summary.merge_all()
writer = tf.summary.FileWriter('/Users/jk/Desktop/2',sess.graph) #自定义tensor到给定路径中
sess.run(init)
print(sess.run(y))

通过在终端输入如下:

cd 路径

tensorboard --logdir=路径

浏览器输入:http://localhost:6006/     得到tensorboard展示

3、创建dropout层

hidden1 = nn_layer(x, 784, 500, 'layer1')   #返回激活层的输出
with tf.name_scope('dropout'):
keep_prob = tf.placeholder(tf.float32)
tf.summary.scalar('dropout_keep_probability', keep_prob) #添加到图
dropped = tf.nn.dropout(hidden1, keep_prob) #dropout

4、参数的正则化 tf.contrib.layers.l2_regularizer(lambda)(w)

返回给定参数的L1或L2正则化项的值

w=tf.Variable(tf.random_normal([2,1],stddev=1,seed=1))
x=tf.constant([1.,2.],shape=[1,2])
y=tf.matmul(x,w)
y_=tf.constant([1.,2.],shape=[1,2])
lam=0.5
loss=tf.reduce_mean(tf.square(y_-y))+tf.contrib.layers.l2_regularizer(lam)(w)
tf.add_to_collection('loss',loss)
z=tf.add_n(tf.get_collection('loss'))
with tf.Session() as less:
init=tf.global_variables_initializer()
sess.run(init)
print(sess.run(loss)) #输出总损失函数值
print(sess.run(z)) #z是一般程序中较为常用的加入collection并给予输出的方式

  上述代码中的loss为损失函数,由两个部分组成,第一部分是均方误差损失函数,第二部分是正则化,用于防止模型过度模拟训练数据中的随机噪音。lam代表了正则化项的权重,也就是公式tensorflow函数介绍(3)中的λ,其中w为需要计算正则化损失的参数。

  由于上述的定义方式会导致损失函数loss的定义很长,会导致可读性差,因而这时候就用到tensorflow提供的集合(collection),通过在一个计算图(graph)保存一组tensor。以如下代码为例:

import tensorflow as tf
def get_weight(shape,lam): #通过collection逐个将每层的参数的正则化项进行收集
var=tf.Variable(tf.random_normal(shape),dtype=tf.float32)
tf.add_to_collection('losses',tf.contrib.layers.l2_regularizer(lam)(var))
return var
x=tf.placeholder(tf.float32,shape=[None,2]) #设置placeholder作为每次的输入层
y_=tf.placeholder(tf.float32,shape=[None,1])
layer_dimension=[2,10,10,10,1] #每一层的结点数
n_layers=len(layer_dimension)
cur_layer=x #当前层
in_dimension=layer_dimension[0]
for i in range(1,n_layers):
out_dimension=layer_dimension[i] #提取当前输出层维度
weight=get_weight([in_dimension,out_dimension],0.001) #生成每层的权重,并汇总每层的正则化项
bias=tf.Variable(tf.constant(0.1,shape=[out_dimension]))
cur_layer=tf.nn.relu(tf.matmul(cur_layer,weight)+bias) #计算每层经过激活函数relu后得到的输出值
in_dimension=layer_dimension[i] #提取下一层的输入层维度
mse_loss=tf.reduce_mean(tf.square(y_-cur_layer))
tf.add_to_collection('losses',mse_loss) #将平方损失函数加入汇总损失函数
loss=tf.add_n(tf.get_collection('losses')) #提取集合losses里的所有部分都加起来
with tf.Session() as sess:
init=tf.global_variables_initializer()
sess.run(init)
print(sess.run(loss,feed_dict={x:[[1.,2.],[2.,3.]],y_:[[2.],[2.]]})) #通过对占位符x和y_进行赋值,得到最终的损失值

在如上运行完成后,再重新定义一次如下tf.placeholder()后,再进行一次sess.run(loss,feed_dict=....)却会报错,尚未找到原因。。。。(都是泪)

x=tf.placeholder(tf.float32,shape=[None,2])   #设置placeholder作为每次的输入层
y_=tf.placeholder(tf.float32,shape=[None,1])

5、优化时设置记录全局步骤的单值,用于进一步的minimize

global_step = tf.Variable(0, name='global_step', trainable=False)       #设置global_step变量不可训练
train_op = optimizer.minimize(loss, global_step=global_step)

6、计算准确率的常用套路(以mnist数字识别为例)

import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
mnist=input_data.read_data_sets('data/',one_hot=True)
trainimg=mnist.train.images
trainlabel=mnist.train.labels
testimg=mnist.test.images
testlabel=mnist.test.labels
x=tf.placeholder(tf.float32,[None,784])
y=tf.placeholder(tf.float32,[None,10])
w=tf.Variable(tf.zeros([784,10]))
b=tf.Variable(tf.zeros([10]))
pred=tf.nn.softmax(tf.matmul(x,w)+b)
cost=tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred),reduction_indices=[1])) #计算交叉熵损失,reduce_sum为计算累加和,reduction_indices为计算的维度
optm=tf.train.GradientDescentOptimizer(0.01).minimize(cost)
corr=tf.equal(tf.argmax(pred,1),tf.argmax(y,1)) #返回预测值和实际值是否相同
accr=tf.reduce_mean(tf.cast(corr,tf.float32)) #tf.cast()的作用是将corr的格式转为float32,然后通过tf.reduce_mean来计算平均准确率
sess=tf.Session()
training_epochs=100
training_epochs=100
batch_size=100
display_step=5
init=tf.global_variables_initializer()
sess.run(init)
for epoch in range(training_epochs):
avg_cost=0.
num_batch=int(mnist.train.num_examples/batch_size)
for i in range(num_batch):
batch_xs,batch_ys=mnist.train.next_batch(batch_size)
sess.run(optm,feed_dict={x:batch_xs,y:batch_ys})
avg_cost+=sess.run(cost,feed_dict={x:batch_xs,y:batch_ys})/num_batch
if epoch % display_step==0:
train_acc=sess.run(accr,feed_dict={x:batch_xs,y:batch_ys})
test_acc=sess.run(accr,feed_dict={x:mnist.test.images,y:mnist.test.labels})
print('Epoch:%03d/%03d cost:%.9f Train accuracy: %.3f Test Accuracy: %.3f' %(epoch,training_epochs,avg_cost,train_acc,test_acc)) #字符串中%03d表示将对象epoch设定为长度为3的整型,%.3f表示取3位有效小数。%g表示保证6位有效数字前提下用小数方式,否则用科学计数法

注:上面的这段代码运行的话需要去掉注释

7、定义损失函数+优化器选择的常用套路

cross_entropy=tf.nn.softmax_cross_entropy_with_logits(logits,ground_truth_input)
cross_entropy_mean=tf.reduce_mean(cross_entropy)
train_step=tf.train.GradientDescentOptimizer(learning_rate).minimize(corss_entropy_mean)

8、每轮epoch均保存一次模型

with tf.Session() as sess:
init=tf.global_variables_initializer()
sess.run(init)
for i in range(training_steps):
xs,ys=mnist.train.next_batch(batch_size)
_,loss_value,step=sess.run([train_op,loss,global_step],feed_dict={x:xs,y_:ys})
if i%1000==0:
print('after %d training steps,loss on training batch is %g.' %(step,loss_value))
saver.save(sess,os.path.join(model_save_path,model_name),global_step=global_step) #可以让每个被保存模型的文件名末尾加上训练的轮数来进行记录