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代表了正则化项的权重,也就是公式
中的λ,其中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) #可以让每个被保存模型的文件名末尾加上训练的轮数来进行记录
tensorflow函数介绍(3)的更多相关文章
- tensorflow函数介绍(4)
1.队列的实现: import tensorflow as tf q=tf.FIFOQueue(2,'int32') #创建一个先进先出队列,指定队列中最多可以保存两个元素,并指定类型为整数. #先进 ...
- tensorflow函数介绍(2)
参考:tensorflow书 1.模型的导出: import tensorflow as tf v1=tf.Variable(tf.constant(2.0),name="v1") ...
- tensorflow函数介绍(1)
tensorflow中的tensor表示一种数据结构,而flow则表现为一种计算模型,两者合起来就是通过计算图的形式来进行计算表述,其每个计算都是计算图上的一个节点,节点间的边表示了计算之间的依赖关系 ...
- tensorflow函数介绍 (5)
1.tf.ConfigProto tf.ConfigProto一般用在创建session的时候,用来对session进行参数配置: with tf.Session(config=tf.ConfigPr ...
- Tensorflow | 基本函数介绍 简单详细的教程。 有用, 很棒
http://blog.csdn.net/xxzhangx/article/details/54606040 Tensorflow | 基本函数介绍 2017-01-18 23:04 1404人阅读 ...
- python strip()函数 介绍
python strip()函数 介绍,需要的朋友可以参考一下 函数原型 声明:s为字符串,rm为要删除的字符序列 s.strip(rm) 删除s字符串中开头.结尾处,位于 rm删除 ...
- PHP ob_start() 函数介绍
ob_start() 函数介绍: http://www.nowamagic.net/php/php_ObStart.php ob_start()作用: http://zhidao.baidu.com/ ...
- Python开发【第三章】:Python函数介绍
一. 函数介绍 1.函数是什么? 在学习函数之前,一直遵循面向过程编程,即根据业务逻辑从上到下实现功能,其往往用一长段代码来实现指定功能,开发过程中最常见的操作就是粘贴复制,也就是将之前实现的代码块复 ...
- row_number() OVER(PARTITION BY)函数介绍
OVER(PARTITION BY)函数介绍 开窗函数 Oracle从8.1.6开始提供分析函数,分析函数用于计算基于组的某种聚合值,它和聚合函数的不同之处是:对于每个 ...
随机推荐
- 洛谷P4127同类分布
传送 我们要在dfs的板子里记录哪些量呢?当前填的所有数的和sum?当前填的数构成的数值all? sum可以留下,数值就扔掉叭.数值最大是1e18,要是留下,在g数组里有一维的大小是1e18.也许可以 ...
- set集合 浅层拷贝会和深层拷贝
一.什么是set集合 集合是无序的,不重复的数据集合,它里面的元素是可哈希的(不可变类型),但是集合本身是不可哈希(所以集合做不了字典的键)的.以下是集合最重要的两点: 1.去重,把一个列表变成集合, ...
- 《图解 TCP-IP(第 5 版)》
第一章 网络基础知识 计算机网络根据规模可以分为:广域网(WAN: Wide Area Network)和局域网(LAN: Local Area Network) 协议的标准化: 国际标准化组织(IS ...
- 网页禁用表单的自动完成功能禁用密码自动填充autocomplete
网页中表单的自动完成功能,有时候很方便,但是有时候并不想让浏览器记忆表单,比如禁用密码域自动填充功能, 网页禁用表单的自动完成功能是由input元素的autocomplete属性控制,关闭表单的自动完 ...
- 阶段1 语言基础+高级_1-3-Java语言高级_1-常用API_1_第4节 ArrayList集合_14-ArrayList集合的常用方法和循环
常用的方法记下来 刚创建好,什么都不放的 add添加方法肯定是成功的. 加了这么多的值都没有用返回值,输出的结果可以看到都是添加成功的 获取索引值 ALT+回车键,推荐使用本地变量去接收 这样左边就会 ...
- try...catch语句
程序的异常:Throwable 严重问题Error我们不处理,这种问题一般都是很严重的,比如内存溢出 问题Exception 编译期问题不是RuntimeException的异常必须进行处理,如果不处 ...
- SharpBrowser
SharpBrowser is the fastest open source C# web browser there is! Slightly faster than Google Chrome ...
- vue组件父子间通信之综合练习--假的聊天室
<!doctype html> <html> <head> <meta charset="UTF-8"> <title> ...
- vue复合组件----注册表单
<!doctype html> <html> <head> <meta charset="UTF-8"> <title> ...
- day17跨文件夹导入模块,模块的两种被执行方式,包,直接使用包中模块,包的管理
复习 ''' 1.模块 -- 一系列功能的集合体,用文件来管理一系列有联系的功能,该文件我们称之为模块,文件名就是模块名 -- import | from...import 来导入模块,从而使用模块中 ...