Python语言与信息数据获取和机器学习机器学习实战人工智能/模式识别/机器学习精华专题

机器学习(3)——回归模型

2018-03-06  本文已影响79人  飘涯

前言:紧接上一篇文章结尾,预测值和真实值存在较大差距,接着介绍用多项式权重来提高拟合度(R2),过拟合解决办法,引出正则项L1和L2,Ridge回归和LASSO回归。

目标函数

机器学习中目标函数是指模型训练的过程中(参数求解的过程中)方向是什么。例如线性回归的方向就是让目标函数的取值越小越好,线性回归用到就是平方和损失函数,感知损失用到SVM,对数损失函数用到逻辑回归等。常见的几种目标函数: image.png

多项式扩展

#-*- conding:utf-8 -*-
#准确率:print("电流预测准确率: ", lr2.score(X2_test,Y2_test))
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import PolynomialFeatures
import numpy as np
import pandas as pd
from pandas import DataFrame
import matplotlib as mpl
import matplotlib.pyplot as plt
import time
#防止中文乱码
mpl.rcParams['font.sans-serif']=[u'simHei']
mpl.rcParams['axes.unicode_minus']=False
#加载数据
path="household_power_consumption_1000.txt"
df = pd.read_csv(path,sep=";")
#数据处理,包括,清除空数据
df1=df.replace("?",np.nan)
data = df1.dropna(axis=0,how="any")
#把数据中的字符串转化为数字
def data_formate(x):
    t = time.strptime(' '.join(x), '%d/%m/%Y %H:%M:%S')
    return (t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec)
X = data.iloc[:,0:2]
x = X.apply(lambda x:pd.Series(data_formate(x)),axis=1)
y = data.iloc[:,4]
#数据分集
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=0)
#标准化
ss = StandardScaler()
x_train=ss.fit_transform(x_train)
x_test=ss.transform(x_test)
#模型训练
pol = PolynomialFeatures(degree = 9)
xtrain_pol = pol.fit_transform(x_train)
xtest_pol = pol.fit_transform(x_test)
lr = LinearRegression()
lr.fit(xtrain_pol,y_train)
y_pridect=lr.predict(xtest_pol)
#输出参数
print("模型的系数(θ):",lr.coef_)
print("模型的截距:",lr.intercept_)
# print("训练集上R2:",lr.score(x_train, y_train))
print("测试集上R2:",lr.score(xtest_pol, y_test))
mse = np.average((y_pridect-y_test)**2)
rmse = np.sqrt(mse)
print("rmse:",rmse)
#画图
t=np.arange(len(y_test))
plt.figure(facecolor='w')#建一个画布,facecolor是背景色
plt.plot(t, y_test, 'r-', linewidth=2, label='真实值')
plt.plot(t, y_pridect, 'g-', linewidth=2, label='预测值')
plt.legend(loc = 'upper left')#显示图例,设置图例的位置
plt.title("线性回归预测时间和电压之间的关系", fontsize=20)
plt.grid(b=True)#加网格
plt.show()

当参数degree = 1,2,3,4时候图像如下:

image.png
准确率提高了不少,当degree = 9时候,会发现参数值会异常大,这就是出现了所谓的过拟合了,模型的系数(θ): [ 1.75147911e+12 4.24195739e+10 -2.94579982e+11 ... 0.00000000e+00
0.00000000e+00 0.00000000e+00]
为了防止模型的过拟合我们引入了正则项norm

正则项

机器学习调参

在实际工作中,对于各种算法模型(以线性模型弹性网络算法为例)来讲,我们需要获取θ、入、p的值的求解其实就是算法模型的求解,一般不需要开发人员参与(算法已经实现),
主要需要求解的是λ和p的值,这个过程就叫做调参(超参)

上一篇 下一篇

猜你喜欢

热点阅读