资源简介
L2正则化python实现案例(附代码),含图形展示,对于正则化理解又直观帮助

代码片段和文件信息
import numpy as np
from numpy import *
import matplotlib.pylab as plt
from pylab import * #显示中文
mpl.rcParams[‘font.sans-serif‘] = [‘SimHei‘] #显示中文
#画图中正确显示负数
import matplotlib
matplotlib.rcParams[‘axes.unicode_minus‘]=False
#加载数据
train_data=np.loadtxt(‘ex1data1.txt‘delimiter=‘‘);# train data
test_data=np.loadtxt(‘test1.txt‘delimiter=‘‘)
# new_test=test_data.copy();
# for i in range(new_test.shape[0]):
# new_test[i-1]=new_test[i-1]*(1.0+(0.4*np.random.random()-0.2))
# np.savetxt(‘test1.txt‘new_testdelimiter=‘‘)
#提取数据,x和y
train_X=train_data[:0];
train_y=train_data[:-1]
test_X=test_data[:0];
test_y=test_data[:-1]
#数据标准化
m1=train_X.shape[0]; # m=len(X)
train_X=np.c_[np.ones(m1)train_X]
train_y=np.c_[train_y]
m2=test_X.shape[0]; # m=len(X)
test_X=np.c_[np.ones(m2)test_X]
test_y=np.c_[test_y]
#定义代价函数
def costFunction(Xythetalamda):
m=X.shape[0]
h=np.dot(Xtheta)
theta_r = theta.copy() # theta_r和theta指向不同的地址,若theta_r=theta指向同一个地址
theta_r[0 0] = 0.0 # theta0不参加正则化,所以,设置为0.0
R=lamda/(2.0*m)*np.dot(theta_r.Ttheta_r) #正则化项
J=1.0/(2.0*m)*np.dot((h-y).T(h-y)) +R #带正则化的代价函数
return J
#定义梯度下降
def gradDesc(Xyalpha=0.001lamda=0.0iter_num=15000):
mn=X.shape #样本数m,特征数n
theta=np.zeros((n1)) #初始化theta
J_history=np.zeros(iter_num) #初始化代价函数值
#开始梯度下降
for i in range(iter_num):
J_history[i]=costFunction(Xythetalamda) #计算代价值
h=np.dot(Xtheta) #预测值
theta_r=theta.copy() #theta_r和theta指向不同的地址,若theta_r=theta指向同一个地址
theta_r[00]=0.0 #theta0不参加正则化,所以,设置为0.0
deltatheta=1.0/m*np.dot(X.T(h-y))+lamda/m*theta_r #计算带正则化的deltatheta
theta-=alpha*deltatheta #更新theta
return J_historytheta
#执行梯度下降(带正则化项和不带正则化项)
J_historytheta=gradDesc(train_Xtrain_y) #无正则化项
print(‘无正则化时theta=‘theta)
plt.plot(J_history‘r‘label=‘无正则化‘)
J_history_rtheta_r=gradDesc(test_Xtest_ylamda=200) #有正则化项
print(‘有正则化时theta=‘theta_r)
plt.plot(J_history_r‘g‘label=‘有正则化‘)
plt.legend(loc=‘best‘)
plt.title(‘正则化前后的代价曲线‘)
plt.show()
# #调用ridge岭回归
# from sklearn.linear_model import Ridge
# ridge_reg = Ridge(alpha=200solver=“cholesky“) #solver=‘sag‘
# ridge_reg.fit(train_X train_y)
#画数据图比较正则化前后的变化
plt.figure(figsize=(2525))
plt.subplot(211)
plt.title(‘训练集及回归曲线‘)
plt.scatter(train_X[:1]train_y[:0])
plt.plot(train_X[:1]np.dot(train_Xtheta)c=‘r‘label=‘回归曲线‘)
plt.legend(loc=‘lower right‘shadow=Truefacecolor=‘0.9‘)
plt.subplot(212)
plt.title(‘测试集正则化前后的变化‘)
plt.scatter(test_X[:1]test_y[:0])
plt.plot(test_X[:1]np.dot(test_Xtheta)c=‘r‘label=‘lamda=0‘)
plt.plot(test_X[:1]np.dot(test_Xtheta_r)c=‘g‘label=‘lamda=200‘)
# plt.plot(test_X[:1]ridge_reg.predict(test_X)c=‘k‘label=‘ridge=200‘)
plt.legend(loc=‘lower right‘shadow=Truefacecolor=‘0.9‘)
plt.show()
属性 大小 日期 时间 名称
----------- --------- ---------- ----- ----
文件 3478 2019-02-03 19:21 LR_regular.py
文件 1359 2017-10-21 10:37 ex1data1.txt
文件 5155 2019-01-26 11:01 test1.txt
----------- --------- ---------- ----- ----
9992 3
相关资源
- 机器学习(周志华)配套代码
- 机器学习-岭回归实现
- 012345手势识别神经网络代码
- 猫-非猫图二分类识别
- 机器学习k means算法实现图像分割
- kmeans聚类算法的python实现程序
- Python100经典练习题
- 南瓜书(PumpkinBook)
- 机器学习numpy和pandas基础
- python机器学习Sebastian Raschka中文最新完
- Python-DeepMoji模型的pyTorch实现
- 《机器学习实战》源代码Python3
- Python-使用DeepFakes实现YouTube视频自动换
- Introduction to machine learning with python (
- python新浪微博爬虫,爬取微博和用户
- Python-一系列高品质的动漫人脸数据集
- Python-Insightface人脸检测识别的最小化
- 非线性回归Python代码
- 093 2018北风网人工智能视频(完结)转
- python的色情图片识别
- 贝叶斯网络程序
- 吴恩达深度学习超参数调制完整程序
- 《机器学习实战》Python3代码
- Python-自然场景文本检测PSENet的一个
- Python-在特征金字塔网络FPN的Pytorch实现
- Python-PyTorch实时多人姿态估计项目的实
- Python-用PyTorch10实现FasterRCNN和MaskRCNN比
- Python-心脏核磁共振MRI图像分割
- Python-基于YOLOv3的行人检测
- Python-RLSeq2Seq用于SequencetoSequence模型的
评论
共有 条评论