线性回归初学
导入库
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
开始操作
x = np.array([1,2,3])
y = np.array([4,5,6])
x
array([1, 2, 3])
#later
x = np.array([1,2,3]).reshape(-1,1)
y = np.array([4,5,6]).reshape(-1,1)
x
array([[1],
[2],
[3]])
展示出来
plt.plot(x,y,marker = 'o')
plt.show()
from sklearn import linear_model
model = linear_model.LinearRegression()
#参数fit_intercept截距
#参数normalize回归之前要不要进行类标准化的处理
#参数copy_X表示进行回归时,复制特征矩阵x,不会覆盖原矩阵
#参数n_jobs表示计算的作业数,输入-1则使用全部的CPU来计算
model.fit(x,y)
LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None, normalize=False)
model.predict([[6]])
array([[9.]])
print('系数',model.coef_)
print('常数',model.intercept_)
系数 [[1.]]
常数 [3.]
案例
body = pd.read_excel('./身高体重.xls')
body
身高 体重
0 1.55 50
1 1.60 52
2 1.65 57
3 1.67 56
4 1.70 60
5 1.75 65
6 1.80 62
7 1.82 70
model.fit(body['体重'].values.reshape(-1,1),body['身高'].values.reshape(-1,1))
LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None, normalize=False)
model.predict([[70]])
array([[1.8401129]])