python一元一次线性回归

本文 给出 一元一次线性回归的代码实现 ,下篇文章会给出机器学习中提到的最小二乘法求线性回归  这个线性回归我是假设楼层与房价是线性回归举得列子,数据是随便写的,


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


# Function to get data
def get_data(file_name):
    data = pd.read_csv(file_name)  #here ,use pandas to read cvs file.
    XParameter = []
    YParameter = []
    for single_square_feet ,single_price_value in zip(data['floor'],data['price']):#遍历数据,
        XParameter.append([float(single_square_feet)])#存储在相应的list列表中
        YParameter.append(float(single_price_value))
    return XParameter,YParameter
#print(get_data("d:/input_data.csv"))

#Function for Fitting our data to Linear model
def linear_model_main(XParameter,YParameter,floorValue):

    # Create linear regression object
    regr = linear_model.LinearRegression()
    regr.fit(XParameter, YParameter)   #train model
    price = regr.predict(floorValue)
    predictions = {}
    predictions['Intercept '] = regr.intercept_
    predictions['coefficient'] = regr.coef_
    predictions['price'] = price
    return predictions

X,Y = get_data('d:/data.csv')
floorValue = 18
result = linear_model_main(X,Y,floorValue)
print ("Intercept  value " , result['Intercept '])
print ("coefficient" , result['coefficient'])
print ("price value: ",result['price'])

# Function to show the resutls of linear fit model
def show_linear_line(X_parameters,Y_parameters):
    # Create linear regression object
    regr = linear_model.LinearRegression()
    regr.fit(X_parameters, Y_parameters)
    plt.scatter(X_parameters,Y_parameters,color='blue')
    plt.plot(X_parameters,regr.predict(X_parameters),color='red',linewidth=4)
    plt.xticks(())
    plt.yticks(())
    plt.show()
    return
show_linear_line(X,Y)

data.csv的数据,  


猜你喜欢

转载自blog.csdn.net/l_mr_l/article/details/79958442
今日推荐