LinearRegressionWithRegularization
在线性回归的基础上加上正则项:
# -*-coding:utf-8 -*-
'''
Created on 2016年12月15日 @author: lpworkdstudy
'''
import numpy as np
from numpy.core.multiarray import dtype
import matplotlib.pyplot as plt filename = "ex1data1.txt"
alpha = 0.01 f = open(filename,"r")
data = []
y = []
for item in f:
item = item.rstrip().split(",")
data.append(item[:-1])
y.append(item[-1:])
Data = np.array(data,dtype= "float64")
Y = np.array(y,dtype = "float64")
Y = (Y-Y.mean())/(Y.max()-Y.min())
One = np.ones(Data.shape[0],dtype = "float64")
Data = np.insert(Data, 0, values=One, axis=1)
for i in range(1,Data.shape[1]):
Data[:,i] = (Data[:,i]-Data[:,i].mean())/(Data[:,i].max()-Data[:,i].min())
theta = np.zeros((1,Data.shape[1]),dtype= "float64") def CostFunction(Data,Y,theta):
h = np.dot(Data,theta.T)
cost = 1/float((2*Data.shape[0]))*(np.sum((h-Y)**2) + np.sum(theta[0,1:]**2) )
return cost
def GradientDescent(Data,Y,theta,alpha):
costList = []
for i in range(100000):
temp = theta[0,0] - (alpha/Data.shape[0]*np.dot(Data[:,:1].T,(np.dot(Data,theta.T)-Y))).T
theta[0,1:] = (1-alpha/Data.shape[0])*theta[0,1:]- (alpha/Data.shape[0]*np.dot(Data[:,1:].T,(np.dot(Data,theta.T)-Y))).T
theta[0,0] = temp
cost = CostFunction(Data, Y, theta)
costList.append(cost)
plt.figure(1, figsize=(12,10), dpi=80, facecolor="green", edgecolor="black", frameon=True)
plt.subplot(111) plt.plot(range(100000),costList)
plt.xlabel("the no. of iterations")
plt.ylabel("cost Error")
plt.title("LinearRegression") plt.savefig("LinearRegressionRegularized.png")
return theta
if __name__ == "__main__":
weight = GradientDescent(Data,Y,theta,alpha)
print weight
cost = CostFunction(Data, Y, weight)
print cost 运行得出损失函数随迭代次数的变化曲线如下图:

可以看出加入正则项并没有优化我们的模型,反而产生了不好的
影响,所以我们在解决问题时,不要盲目使用正则化项。
LinearRegressionWithRegularization的更多相关文章
随机推荐
- Redis集群创建报错
Redis集群环境:och163/och164/och165 在执行如下脚本时报错: ./src/redis-trib.rb create 10.1.253.163: 10.1.253.164: 10 ...
- 中南大学第一届长沙地区程序设计邀请赛 To Add Which?
1350: To Add Which? Time Limit: 1 Sec Memory Limit: 128 MB Description There is an integer sequence ...
- selenium借助AutoIt识别上传文件Java篇
官方网站:https://www.autoitscript.com/site/ 从网站上下载AutoIt并安装,安装完成在菜单中会看到图4.13的目录: 图4.13 AutoIt菜单 1.首先打开A ...
- WIFI知识累计之802.11协议radiotap头解析方法
radiotap官方网站:http://www.radiotap.net/Radiotap 该网站详细介绍了radiotap的各个字段的长度和介绍,并包含解析代码项目地址,该文就在此网站的基础编写一些 ...
- Begin using git (Part1) - Git的安装与配置
Git提供了适用于Linux, Windows, OSX的客户端, 本节以Windows为例介绍基本安装与配置. 所需工具:msysgit, kdiff3. Get windows installer ...
- Win2D 官方文章系列翻译 - 避免内存泄漏
本文为个人博客备份文章,原文地址: http://validvoid.net/win2d-avoiding-memory-leaks/ 在托管 XAML 应用中使用 Win2D 控件时,必须谨慎处理对 ...
- 利用Meida Service的Java SDK来调用Azure Media Services的Index V2实现视频字幕自动识别
Azure Media Services新的Index V2 支持自动将视频文件中的语音自动识别成字幕文件WebVtt,非常方便的就可以跟Azure Media Player集成,将一个原来没字幕的视 ...
- 在java 中,数组与 List<T> 类型的相互转换
在java中,数组与List<T> 之前进行互相转换,转换方法可总结为以下几种: 一. 将 数组转换成List<T> 1. 使用 Collections 的addAll 方法 ...
- AX2012全新的批处理方式
AX2009 的批处理操作我们是通过RunBaseBatch framework,我们所要做的事情就是继承RunBaseBatch class,实现里面该实现的方法来执行批处理. AX2012 的批处 ...
- 2016-03-10:libx265源码解析
单步跟踪执行流程 将cli设定为启动项目,在属性->调试->命令行参数中设置如下参数: --input E:\video\pedestrian_area.yuv --fps 24 --in ...