在线性回归的基础上加上正则项:

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

随机推荐

  1. Redis集群创建报错

    Redis集群环境:och163/och164/och165 在执行如下脚本时报错: ./src/redis-trib.rb create 10.1.253.163: 10.1.253.164: 10 ...

  2. jmeter做接口测试

    jmeter做接口测试有两种方式: 1. 2.

  3. PagedList.MVC分页

    using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...

  4. oracle 将查询到的数据插入表

    1. 新增一个表,通过另一个表的结构和数据 create table tab1 as select * from tab2 2. 如果表存在: insert into tab1 select * fr ...

  5. 感受机房管理化繁为简-新款KVM使用心得

    感受机房管理化繁为简-新款KVM使用心得 一. 背景 随着网络应用的不断增多,各地机房服务器数量也随之增加,利用多传统主机切换器的方式已经无法满足目前这种区域广.设备多人员紧缺的现状,而且即使是使用了 ...

  6. SVN与TortoiseSVN实战:标签与分支

    最近在写<IOS性能调优系列>,今天偷个懒,写写SVN与TortoiseSVN实战的第二篇,标签与分支. 第一篇详见<SVN与TortoiseSVN实战:从入门到精通> SVN ...

  7. MySQL 按日期分表

    一.表不存在时则创建 之前做项目实在是太赶了,很多东西都没记录.是时候补回来了 MySQL做一个大表,由于要存历史记录,所以数据量很大,查询很慢.恰好查询的时候,又不需要时间太久的冷数据.现在将其实现 ...

  8. PowerDesigner英文字段转换中文字段显示

    get_comments.vbs代码如下点击Run Option Explicit ValidationMode = True InteractiveMode = im_Batch Dim mdl ' ...

  9. Android IOS WebRTC 音视频开发总结(六六)-- 三个角度分析美女视频直播这个行业

    本文主要从用户,公司和技术角度分析美女视频直播这个行业,文章最早发表在我们的微信公众号上,支持原创,详见这里, 欢迎关注微信公众号blackerteam,更多详见www.rtc.help 美女视频直播 ...

  10. ftp自动上传下载文件脚本

    FTP自动登录批量下载文件 从ftp服务器192.168.1.60 上的/home/data 到本地的/home/databackup目录 #!/bin/bash ftp -v -n 192.168. ...