ML01 LinearRegression

发布时间:2022-07-05 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了ML01 LinearRegression脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

ML实战:线性回归+多项式回归

  • 本次实验采用的数据集是sklearn内置的波斯顿房价数据集

代码实现

From sklearn import datasets
from sklearn.linear_model import LinearRegression
import numpy as np
from sklearn.model_selection import train_test_splIT
from sklearn.PReprocessing import Standardscaler
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
import Sys

np.set_printoptions(supPress=True)#取消科学计数法输出


x=datasets.load_boston().data
y=datasets.load_boston().target
#初始化数据集

x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=0)
#拆分成训练集和测试集,测试集占20%

X = np.arange(1, len(y_test) + 1)
#用于画图使用

def showres(y_predict,name=None):
    #画图打印结果
    plt.figure(figsize=(20,8),dpi=80)
    plt.title(name)
    plt.plot(X,y_test,label='real',color='red')
    plt.scatter(X,y_test,color='blue')
    plt.plot(X,y_predict,label='predict',color='green')
    plt.scatter(X,y_predict,color='blue')
    plt.legend(loc=[1, 0])
    #plt.savefig('E:/Python/ml/pic/LinearRegression_'+name+".png")

def linear_poly():
    #多项式回归
    poly=PolynomialFeatures(degree=2)#设置阶数为2
    x_train_poly=poly.fit_transform(x_train)
    x_test_poly=poly.fit_transform(x_test)
    linear=LinearRegression()
    linear.fit(x_train_poly,y_train)
    showres(linear.predict(x_test_poly),name='PolynomialFeatures')

def linear():
    #线性回归
    transfer=StandardScaler()
    x_train_standard=transfer.fit_transform(x_train)
    x_test_standard=transfer.fit_transform(x_test)
    linear=LinearRegression()
    linear.fit(x_train_standard,y_train)
    showres(linear.predict(x_test_standard),name='LinearRegression')


linear()
linear_poly()

sys.exit(0)

结果

线性回归

ML01 LinearRegression

多项式回归

ML01 LinearRegression

脚本宝典总结

以上是脚本宝典为你收集整理的ML01 LinearRegression全部内容,希望文章能够帮你解决ML01 LinearRegression所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。