python单变量线性回归

https://www.jianshu.com/p/738f6092ef53

信管专业小白一枚,通过知乎来记录自己的学习旅程!

这段时间帮学长做了个东东,大体意思是通过09-13年的数值,估算出14年的数值来。

起初用Excel做成。后来想试试用Python做一下估算,也就趁机记录下用Python进行一元线性回归分析的这个例子。

主要运用sklearn包中的linear_model.LinearRegression方法。


数据内容:
                   时间                 北京
                   2009                1159
                   2010                1298
                   2011                1364
                   2012                1794
                   2013                1896.3

通过5年的数据构造一元线性回归分析模型,估算出2014年的北京数值。

# coding:utf-8
# 一元线性回归分析例子

from sklearn import linear_model
import pandas as pd

#Function to get data
def get_data(file_name):
    data = pd.read_csv(file_name)
    X = []
    Y = []
    for time, city in zip(data['时间'], data['北京']):
        X.append([float(time)])
        Y.append(float(city))
    return X, Y

#Function for linear model
def linear_model_main(X_parameters, Y_parameters, predict_value):
    regr = linear_model.LinearRegression()
    regr.fit(X_parameters, Y_parameters)
    predict = regr.predict(predict_value)
    predictions = {}
    predictions['intercept'] = regr.intercept_   #截距
    predictions['coefficient'] = regr.coef_   #回归系数
    predictions['predicted_value'] = predict
    return predictions

X, Y = get_data(U'D:\\study\\XXX\\北京.csv')
print X
print Y

predict_time = 2014
result = linear_model_main(X, Y, predict_time)
print "Intercept value ", result['intercept']
print "coefficient", result['coefficient']
print "Predicted value: ", result['predicted_value']

猜你喜欢

转载自blog.csdn.net/u014040043/article/details/80022178