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的更多相关文章
随机推荐
- Kindle3与亚马逊
喜欢上亚马逊,偶尔会买些免费或极低价格的书,但始终无法把这些书传到“我的”kindle3上,原因是kindle3无法在中国注册,又绕不开DRM,同时经历了换屏.换主板,早已不是原来的kindle了.今 ...
- OC基础(27)
单例设计模式 *:first-child { margin-top: 0 !important; } body > *:last-child { margin-bottom: 0 !import ...
- Java: 基类、子类、构造函数、程序块的初始化顺序
初始化顺序 基类static block 子类static block 基类non-static block 子类non-static block 基类constructor 子类constructo ...
- Sqoop2常用命令介绍
命令行操作之Create Command 1.Create Connection Function create connection --cid 1 说明:Create new connectio ...
- mysql 存储结构
mysql存储结构:数据库->表->数据 1)管理数据库 增:create database sjk; 删:drop database sjk; 改:alter database sjk; ...
- 【LeetCode】84. Largest Rectangle in Histogram
Largest Rectangle in Histogram Given n non-negative integers representing the histogram's bar height ...
- Java程序员面试宝典1 ---Java基础部分(该博文为原创,转载请注明出处)
(该博文为原创,转载请注明出处 http://www.cnblogs.com/luyijoy/ by白手伊凡) 1. 基本概念 1) Java为解释性语言,运行过程:程序源 ...
- 慕课网-安卓工程师初养成-2-11 Java常量
来源:http://www.imooc.com/code/1256 所谓常量,我们可以理解为是一种特殊的变量,它的值被设定后,在程序运行过程中不允许改变. 语法:final 常量名 = 值; 程序中使 ...
- ubuntu 更新重启后 登录后 无法进入图形界面
切换到控制台然后看看-/.Xauthority的组属性是否正确,如果被改成root组了,就会造成不能登陆,你将其删除就ok了
- 在Windows程序中启用console输出-2016.01.04
在某些时候,我们可能需要在Win32窗口应用程序中打开控制台窗口,打印一些消息,或者作为当前程序的另外一个人机交互界面,或者为了帮助调试程序.为了达到这种效果,需要了解函数AllocConsole和C ...