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)的更多相关文章

  1. tensorflow函数介绍(4)

    1.队列的实现: import tensorflow as tf q=tf.FIFOQueue(2,'int32') #创建一个先进先出队列,指定队列中最多可以保存两个元素,并指定类型为整数. #先进 ...

  2. tensorflow函数介绍(2)

    参考:tensorflow书 1.模型的导出: import tensorflow as tf v1=tf.Variable(tf.constant(2.0),name="v1") ...

  3. tensorflow函数介绍(1)

    tensorflow中的tensor表示一种数据结构,而flow则表现为一种计算模型,两者合起来就是通过计算图的形式来进行计算表述,其每个计算都是计算图上的一个节点,节点间的边表示了计算之间的依赖关系 ...

  4. tensorflow函数介绍 (5)

    1.tf.ConfigProto tf.ConfigProto一般用在创建session的时候,用来对session进行参数配置: with tf.Session(config=tf.ConfigPr ...

  5. Tensorflow | 基本函数介绍 简单详细的教程。 有用, 很棒

     http://blog.csdn.net/xxzhangx/article/details/54606040 Tensorflow | 基本函数介绍 2017-01-18 23:04 1404人阅读 ...

  6. python strip()函数 介绍

    python strip()函数 介绍,需要的朋友可以参考一下   函数原型 声明:s为字符串,rm为要删除的字符序列 s.strip(rm)        删除s字符串中开头.结尾处,位于 rm删除 ...

  7. PHP ob_start() 函数介绍

    ob_start() 函数介绍: http://www.nowamagic.net/php/php_ObStart.php ob_start()作用: http://zhidao.baidu.com/ ...

  8. Python开发【第三章】:Python函数介绍

    一. 函数介绍 1.函数是什么? 在学习函数之前,一直遵循面向过程编程,即根据业务逻辑从上到下实现功能,其往往用一长段代码来实现指定功能,开发过程中最常见的操作就是粘贴复制,也就是将之前实现的代码块复 ...

  9. row_number() OVER(PARTITION BY)函数介绍

      OVER(PARTITION BY)函数介绍 开窗函数               Oracle从8.1.6开始提供分析函数,分析函数用于计算基于组的某种聚合值,它和聚合函数的不同之处是:对于每个 ...

随机推荐

  1. CyclicBarrier 源码分析

    CyclicBarrier CyclicBarrier 是一个同步辅助类,它允许一组线程互相等待,直到到达某个公共屏障点 (common barrier point) 之后同时释放执行.CyclicB ...

  2. element-ui走马灯如何实现图片自适应 长度和高度 自适应屏幕大小

    最近写用vue2.0写一个项目,用到了走马灯效果,由于项目赶时间,想偷下懒,第一次引用了element组件(纯JS也可以写的出来,赶时间嘛,懂得....),结果用了发现一个问题,element的组件( ...

  3. ETCD分布式锁实现选主机制(Golang实现)

    ETCD分布式锁实现选主机制(Golang) 为什么要写这篇文章 做架构的时候,涉及到系统的一个功能,有一个服务必须在指定的节点执行,并且需要有个节点来做任务分发,想了半天,那就搞个主节点做这事呗,所 ...

  4. 应用安全 - 代码审计 - JavaScript

    JavaScript Prototype污染

  5. layer.msg()自动关闭后刷新页面

    layer.msg("2秒就消失哦", { time: 2000 }, function () {                    window.location.href ...

  6. 链表两数相加(add two numbers)

    问题 给出两个 非空 的链表用来表示两个非负的整数.其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字. 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它 ...

  7. 管理MySQL 从入门到出门

    MySQL 中的数据库(Database)就像是一个容器,其中包含了各种对象.例如,数据表(Table).视图(View).存储过程(Stored Procedure)以及触发器(Trigger)等. ...

  8. docker--docker介绍

    2 docker 介绍 2.1 容器技术 在计算机的世界中,容器拥有一段漫长且传奇的历史.容器与管理程序虚拟化 (hypervisor virtualization,HV)有所不同,管理程序虚拟化通过 ...

  9. python基础-3 集合 三元运算 深浅拷贝 函数 Python作用域

    上节课总结 1 运算符 in 字符串 判断  : “hello” in "asdasfhelloasdfsadf" 列表元素判断:"li" in ['li', ...

  10. AngularJs——基础小知识(二)

    AngularJs的过滤器 1.Currency :过滤器(金额货币格式化)