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

 # -*-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. Prim算法POJ1258

    http://poj.org/problem?id=1258 这道题是最简单的一个啦,,,, #include<stdio.h> #include<iostream> #inc ...

  2. SQL SERVER树型数据处理时,函数递归调用问题,查询根节点,子节点函数

    /* 标题:查询指定节点及其所有子节点的函数 作者:爱新觉罗.毓华(十八年风雨,守得冰山雪莲花开) 时间:2008-05-12 地点:广东深圳 */ ) , pid ) , name )) ' , n ...

  3. LeetCode:237

    题目:Delete Node in a Linked List(从列表中删除指定结点) 描述:Write a function to delete a node (except the tail) i ...

  4. Android 中获取 debug 测试 SHA1 和 release SHA1 证书指纹数据的方法

    百度地图开发的时候要申请KEY,需要提供SHA1证书指纹数据 Eclipse eclipse中直接查看:windows -> preferance -> android -> bui ...

  5. xml是什么?

    xml Extensible Markup Language 可扩展标记语言 它被设计用来传输和存储数据. 它的内容都是由标签组成,非常有规律.

  6. Android的消息处理机制,handler,message,looper(一)

    当应用程序启动时,Android首先会开启一个主线程(也就是UI线程),主线程为管理界面中的UI控件.在程序开发时,对于比较耗时的操作,通常会为其开辟一个单独的线程来执行,以尽可能减少用户的等待时间. ...

  7. Unity3d - RPG项目学习笔记(一)

    通过NGUI和工程素材,学习泰课项目——黑暗之光. 现阶段心得整理: 一.开始界面 开始界面显示顺序为:①白幕渐隐:②镜头拉近:③标题渐显:④按键响应. 1.1 白幕渐隐 NGUI是一个非常强大的插件 ...

  8. excel中单元格计算

    首先,得明确excel中相对引用和绝对引用的概念,这里$符号起着关键作用,当在一个行或列的指示符前面加$则表示绝对引用,否则相对引用,具体: 1.相对引用,复制公式时地址跟着发生变化,如C1单元格有公 ...

  9. UVa10603 倒水 Fill-状态空间搜索

    https://vjudge.net/problem/UVA-10603 There are three jugs with a volume of a, b and c liters. (a, b, ...

  10. 学习总结 java线程

    package com.hanqi.xc; public class Test1 { public static void main(String[] args) { // 线程测试 for (int ...