线性回归随手笔记

来源:互联网 发布:海康算法研究院怎么样 编辑:程序博客网 时间:2024/05/29 13:31

线性回归

import numpy as npimport pandas as pdfrom sklearn.linear_model import LinearRegressionfrom 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)
原创粉丝点击