1. 程式人生 > >python 線性迴歸 預測資料

python 線性迴歸 預測資料

忙碌的一週將至尾聲

本週嘗試線性迴歸預測房價
假設方程式
y=kx+b
資料集:
這裡寫圖片描述

程式碼如下:

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

def get_data(filename):
    data = pd.read_csv(filename)
    x_parameter=''
    y_parameter=''
    for single_square_feet,single_price_value in
zip(data['square_feet'],data['price']): x_parameter.append([float(single_square_feet)]) y_parameter.append(float(single_sprice_value)) return x_parameter,y_parameter def linear_model_main(x_parameter,y_parameter,predict_value): regr = linear_model.LinearRegression() regr.fit(x_parameter,y_parameter) predict_outcome = regr.predict(predict_value) predicitions={} predictions['intercept'
]=regr.intercept_ predictions['coefficient']=regr.coef_ predictions['predicted_value']=predict_outcome_ return predictions def show_linear_line(x_parameter,y_parameter): regr=linear_model.LinearRegression() regr.fit(x_parameter,y_parameter) plt.scatter(x_parameter,y_parameter,color='blue'
) plt.plot(x_parameterregr.predict(x_parameter),color='red',linewidth=4) plt.xticks() plt.yticks() plt.show() x,y=get_data('house_price.csv') predictvalue=500 result=linear_model_main(x,y,predictvalue) print('intercept value', result['intercept']) print('coefficient value', result['coefficient']) print('predicted value', result['predicted_value']) show_linear_line(x,y)