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. Linux内核调试方法总结之内核通知链

    Linux内核通知链notifier 1.内核通知链表简介(引用网络资料)    大多数内核子系统都是相互独立的,因此某个子系统可能对其它子系统产生的事件感兴趣.为了满足这个需求,也即是让某个子系统在 ...

  2. ORACLE DG在线日志修改

    ORACLE DG在线日志修改 SQL>select SEQUENCE#,first_time,next_time,APPLIED, THREAD# from v$archived_log or ...

  3. BeautifulSoup模块学习文档

    一.BeautifulSoup简介 1.BeautifulSoup模块 Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档 ...

  4. 双系统(win10+ubuntu)卸载Ubuntu系统

    之前装的双系统,Win10 和Ubuntu ,系统引导使用的是Ubuntu的Grup的引导, 直接删除Ubuntu会导致引导丢失,会很麻烦,win10直接会挂掉,后期恢复需要重建引导 安全删除思路,先 ...

  5. spring-data-elasticsearch使用出现的一些小问题

    问题一failed to load elasticsearch nodes : org.elasticsearch.index.mapper.MapperParsingException: No ty ...

  6. DP---DAG、背包、LIS、LCS

    DP是真的难啊,感觉始终不入门路,还是太弱了┭┮﹏┭┮ DAG上的DP ​ 一般而言,题目中如果存在明显的严格偏序关系,并且求依靠此关系的最大/最小值,那么考虑是求DAG上的最短路或者是最长路.(据说 ...

  7. Java之九九乘法表

    public class MultiplicationTable { public static void main(String[] args) { for(int i=1;i<=9;i++) ...

  8. 使用class 自动创建设备节点

    #include <linux/init.h>// __init __exit #include <linux/module.h> // module_init module_ ...

  9. Codeforces 191C (LCA+树上差分算法)

    题面 传送门 题目大意: 给出一棵树,再给出k条树上的简单路径,求每条边被不同的路径覆盖了多少次 分析 解决这个问题的经典做法是树上差分算法 它的思想是把"区间"修改转化为左右端点 ...

  10. Python所有转义字符总汇

    转义字符就是让程序按照已经设置好的字符输出,不然程序当成其他的输出了,下面总结所有python转义字符 \\ 反斜杠符号\' 单引号\" 双引号\a 响铃\b 退格(Backspace)\e ...