线性回归随手笔记

线性回归

import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from matplotlib import pyplot as plt

#生成随机数
def get_data():
    x=np.random.rand(10,1)*100
    z=np.random.randn(10,1)*10
    y=x*2+z
    print(x)
    print(z)
    print(y)
    print(x.shape,y.shape)
    return x,y


# 线性回归分析
def linear_model_main(X_parameter, Y_parameter, predict_square_feet):
    # 1. 构造回归对象
    regr = LinearRegression()
    regr.fit(X_parameter, Y_parameter)
    # 2. 获取预测值
    predict_outcome = regr.predict(predict_square_feet)
    # 3. 构造返回字典
    predictions = {}
    # 3.1 截距值
    predictions['intercept'] = regr.intercept_
    # 3.2 回归系数(斜率值)
    predictions['coefficient'] = regr.coef_
    # 3.3 预测值
    predictions['predict_value'] = predict_outcome
    return predictions

# 绘出图像
def show_linear_line(X_parameter, Y_parameter):
    # 1. 构造回归对象
    regr = LinearRegression()
    regr.fit(X_parameter, Y_parameter)

    # 2. 绘出已知数据散点图
    plt.scatter(X_parameter, Y_parameter, color='blue')
    predicts=regr.predict(X_parameter)
    # 3. 绘出预测直线
    plt.plot(X_parameter,predicts, color='red', linewidth=4)
    print('========================')
    print(predicts)
    plt.title('Predict the house price')
    plt.xlabel('square feet')
    plt.ylabel('price')
    plt.show()

if __name__ == '__main__':
    x,y=get_data()
    r=linear_model_main(x,y, 6)
    show_linear_line(x,y)
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值