过拟合:

真实的应用中,并不是让模型尽量模拟训练数据的行为,而是希望训练数据对未知做出判断。

模型过于复杂后,模型会积极每一个噪声的部分,而不是学习数据中的通用 趋势。当一个模型的参数比训练数据还要多的时候,这个模型就可以记忆这个所以训练数据的结果,而使损失函数为0.

避免过拟合的常用方法:正则化。在损失函数中加入刻画模型复杂程度的指标。损失函数:

J(θ)

引入正则化损失:J(θ)+λR(ω)

λ代表模型复杂损失在总损失的比列,R(ω)刻画的是模型的复杂程度。

模型的复杂程度由权重决定,一般。

常用的刻画模型复杂程度的函数R(ω)包括两种L1型正则和L2型正则。

loss=tf.ruduce_mean(tf.square(y_-y)+tf.contrib.layers.l2_ragularizer(lambda)(w))-----L2型正则的变量定义。、

除了引入正则化损失,还有避免过拟合的方法就是 加大训练数据 和 使用 Dropout。

 import tensorflow as tf
from sklearn.datasets import load_digits #从sklearn的数据集引入手写字体数据集
from sklearn.model_selection import train_test_split # 作用:将数据集划分为 训练集和测试集
from sklearn.preprocessing import LabelBinarizer #数据的预处理
#binarizer二值化 '''数据下载''' digits=load_digits() #导入手写字体的datasets
X=digits.data #获得其特征向量
y=digits.target #获得样本label
y=LabelBinarizer().fit_transform(y) #二值化[0,1,1....]
'''扩展sklearn.proprocessing.LabelBinarizer().fit_transform()'''
#lb=preprocessing.LabelBinarizer()
#>>> lb.fit_transform(['yes', 'no', 'no', 'yes'])
#array([[1],
# [0],
# [0],
# [1]])
X_train,X_test,y_train,y_test =train_test_split(X,y,test_size=.3)
# test_size:float-获得多大比重的测试样本 (默认:0.25)---int - 获得多少个测试样本
#数据集被划分为训练集和测试集,label必须二值化因为分类的结果就是binarizer '''生成层 函数'''
def add_layer(input,in_size,out_size,n_layer='layer',activation_function=None):
layer_name='layer %s' % n_layer
'''补充知识'''
#tf.name_scope:Wrapper for Graph.name_scope() using the default graph.
#scope名字的作用域
#sprase:A string (not ending with '/') will create a new name scope, in which name is appended to the prefix of all operations created in the context.
#If name has been used before, it will be made unique by calling self.unique_name(name).
with tf.name_scope('weights'):
Weights=tf.Variable(tf.random_normal([in_size,out_size]),name='w')
tf.summary.histogram(layer_name+'/wights',Weights)
#tf.summary.histogram:output summary with histogram直方图
#tf,random_normal正太分布
with tf.name_scope('biases'):
biases=tf.Variable(tf.zeros([1,out_size])+0.1)
tf.summary.histogram(layer_name+'/biases',biases)
#tf.summary.histogram:k
with tf.name_scope('Wx_plus_b'):
Wx_plus_b=tf.matmul(input,Weights)+biases
'''引入dropout,dropout添加在每一层的激活函数前'''
Wx_plus_b=tf.nn.dropout(Wx_plus_b,keep_prob)
#keep_prob 每个元素被留下来的概率
if activation_function==None:
outputs=Wx_plus_b
else:
outputs=activation_function(Wx_plus_b)
tf.summary.histogram(layer_name+'/output',outputs)
return outputs
'''准确率''' '''占位符'''
keep_prob = tf.placeholder(tf.float32)
xs=tf.placeholder(tf.float32,[None,64])
ys=tf.placeholder(tf.float32,[None,10]) '''添加层'''
l1=add_layer(xs,64,50,'l1',activation_function=tf.nn.softmax ) #据说其他激活函数会出错
prediction=add_layer(l1,50,10,activation_function=tf.nn.softmax)
#sotmax激活函数,用于分类函数 '''计算'''
#交叉熵cross_entropy损失函数,参数分别为实际的预测值和实际的label值y,re
'''补充知识'''
#reduce_mean()
# 'x' is [[1., 1. ]]
# [2., 2.]]
#tf.reduce_mean(x) ==> 1.5
#tf.reduce_mean(x, 0) ==> [1.5, 1.5]
#tf.reduce_mean(x, 1) ==> [1., 2.]
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys*tf.log(prediction),reduction_indices=[1]))
tf.summary.scalar('loss',cross_entropy)
'''补充知识'''
#reduce_sum
# 'x' is [[1, 1, 1]]
# [1, 1, 1]]
#tf.reduce_sum(x) ==> 6
#tf.reduce_sum(x, 0) ==> [2, 2, 2]
#tf.reduce_sum(x, 1) ==> [3, 3]
#tf.reduce_sum(x, 1, keep_dims=True) ==> [[3], [3]]
#tf.reduce_sum(x, [0, 1]) ==> 6
train_step=tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
merged=tf.summary.merge_all()
'''Session_begin'''
with tf.Session() as sess: #merged:tf.summary.merge_all:Merges all summaries collected in the default graph.
print("merged initialize sunccessfulliy")
train_writer=tf.summary.FileWriter('logs/train',sess.graph)
print("train_writer initialize sunccessfulliy")
test_writer=tf.summary.FileWriter('logs/test',sess.graph)
print("test_writer initialize sunccessfulliy")
sess.run(tf.global_variables_initializer())
print("variables initialize sunccessfulliy")
for i in range(1000):
#batch_xs,batch_ys=mnist.train.next_batch(100) #逐个batch去取数据
sess.run(train_step,feed_dict={xs:X_train,ys:y_train,keep_prob:0.6})
if(i%50==0):
#print(compute_accuracy(mnist.test.images,mnist.test.labels))
#train_result=sess.run(merged,feed_dict={xs:X_train,ys:y_train,keep_prob:1})
#test_result=sess.run(merged,feed_dict={xs:X_test,ys:y_test,keep_prob:1})
#train_writer.add_summary(train_result,i)
#test_writer.add_summary(test_result,i)
print(sess.run(cross_entropy,feed_dict={xs:X_test,ys:y_test,keep_prob:1}))
print("the {}".format(i))

tensorflow学习4-过拟合-over-fitting的更多相关文章

  1. Tensorflow学习教程------过拟合

    Tensorflow学习教程------过拟合   回归:过拟合情况 / 分类过拟合 防止过拟合的方法有三种: 1 增加数据集 2 添加正则项 3 Dropout,意思就是训练的时候隐层神经元每次随机 ...

  2. tensorflow学习2-线性拟合和神经网路拟合

    线性拟合的思路: 线性拟合代码: import tensorflow as tf import numpy as np import matplotlib.pyplot as plt #%%图形绘制 ...

  3. 截图:【炼数成金】深度学习框架Tensorflow学习与应用

    创建图.启动图 Shift+Tab Tab 变量介绍: F etch Feed 简单的模型构造 :线性回归 MNIST数据集 Softmax函数 非线性回归神经网络   MINIST数据集分类器简单版 ...

  4. 深度学习-tensorflow学习笔记(2)-MNIST手写字体识别

    深度学习-tensorflow学习笔记(2)-MNIST手写字体识别超级详细版 这是tf入门的第一个例子.minst应该是内置的数据集. 前置知识在学习笔记(1)里面讲过了 这里直接上代码 # -*- ...

  5. tensorflow学习笔记——使用TensorFlow操作MNIST数据(2)

    tensorflow学习笔记——使用TensorFlow操作MNIST数据(1) 一:神经网络知识点整理 1.1,多层:使用多层权重,例如多层全连接方式 以下定义了三个隐藏层的全连接方式的神经网络样例 ...

  6. tensorflow学习笔记——自编码器及多层感知器

    1,自编码器简介 传统机器学习任务很大程度上依赖于好的特征工程,比如对数值型,日期时间型,种类型等特征的提取.特征工程往往是非常耗时耗力的,在图像,语音和视频中提取到有效的特征就更难了,工程师必须在这 ...

  7. TensorFlow学习笔记——LeNet-5(训练自己的数据集)

    在之前的TensorFlow学习笔记——图像识别与卷积神经网络(链接:请点击我)中了解了一下经典的卷积神经网络模型LeNet模型.那其实之前学习了别人的代码实现了LeNet网络对MNIST数据集的训练 ...

  8. tensorflow学习笔记——VGGNet

    2014年,牛津大学计算机视觉组(Visual Geometry Group)和 Google DeepMind 公司的研究员一起研发了新的深度卷积神经网络:VGGNet ,并取得了ILSVRC201 ...

  9. tensorflow学习笔记——使用TensorFlow操作MNIST数据(1)

    续集请点击我:tensorflow学习笔记——使用TensorFlow操作MNIST数据(2) 本节开始学习使用tensorflow教程,当然从最简单的MNIST开始.这怎么说呢,就好比编程入门有He ...

  10. TensorFlow学习笔记10-卷积网络

    卷积网络 卷积神经网络(Convolutional Neural Network,CNN)专门处理具有类似网格结构的数据的神经网络.如: 时间序列数据(在时间轴上有规律地采样形成的一维网格): 图像数 ...

随机推荐

  1. es定制排序搜索结果

    GET /company/employee/_search { "query": { "constant_score": { "filter" ...

  2. 催希凡javaweb 学习28天

    看到这样的博客,自己也在看传智播客的视频,收藏一下 催希凡javaweb 学习28天 http://www.cnblogs.com/Prozhu/category/824899.html

  3. 27-5-LTDC控制LCD显示屏

    1.显示原理 (1).液晶显示是分2层显示的,配置层级结构体参数再将数据输出到混合器合成,显示再液晶上. (2).LTDC初始化结构体 控制 LTDC 涉及到非常多的寄存器,利用 LTDC 初始化结构 ...

  4. R的常用命令

    mean(x) 求x的均值 sd(x) 求x的标准差 plot(x,y) 图形展示x和y的关系 ls() 查看当前所有加载到内存中的对象 rm(x) 删除当前内存中的对象x length(x) 求x的 ...

  5. 宝塔Linux面板5.9平滑升级到6.8版

    昨天ytkah重新安装python后宝塔面板里的首页/软件管理/面板设置出现了问题,点击直接500错误,试着执行sh update.sh也是无法解决,因为5.9无法直接从面板那升级到6.x,用河妖的方 ...

  6. Python3学习之路~4.3 装饰器

    定义:本质是函数,装饰其他函数就是为其他函数添加附加功能. 原则: 不能修改被装饰函数的源代码 不能修改被装饰函数的调用方式 实现装饰器知识储备: 函数即“变量” 高阶函数 把一个函数名当做实参传递给 ...

  7. jmeter报错:内存溢出

    使用jmeter进行压力测试时,经常会遇到内存溢出错误: 2018-08-28 09:01:26,686 ERROR o.a.j.JMeter: Uncaught exception: java.la ...

  8. 前端框架之Vue(9)-组件基础&vue-cli

    组件基础 基本示例 这里有一个 Vue 组件的示例: <!DOCTYPE html> <html lang="en"> <head> <m ...

  9. aop 日志统一处理

    AOP是Aspect Oriented Programing的简称,面向切面编程.AOP适合于那些具有横切逻辑的应用:如性能监测,访问控制,事务管理.缓存.对象池管理以及日志记录.AOP将这些分散在各 ...

  10. 高并发负载均衡——nginx与lvs

    一.企业级web项目架构 一.企业级web项目架构图 二.架构分析 客户端通过企业防火墙发送请求 在App服务器如tomcat接收客户端请求前,面对高并发大数据量访问的企业架构,会通过加入负载均衡主备 ...