机器学习-sklearn-一元线性回归

首先导入要用到的包

from sklearn.linear_model import LinearRegression
import numpy as np
import matplotlib.pyplot as plt

载入数据

data = np.genfromtxt(r"G:\work\python\jupyter_notebook_work\机器学习\回归\data.csv",delimiter = “,”)
x_data = data[:,0]
y_data = data[:,1]
plt.scatter(x_data, y_data)
plt.show()
print(x_data.shape)

此处截取局部

[[ 32.50234527 31.70700585]
[ 56.86890066 83.14274979]
[ 34.3331247 55.72348926]
[ 59.04974121 77.63418251]
[ 57.78822399 99.05141484]
[ 54.28232871 79.12064627]
[ 68.31936082 97.91982104]
[ 50.03017434 81.53699078]
[ 49.23976534 72.11183247]
[ 50.03957594 85.23200734]
[ 48.14985889 66.22495789]
[ 25.12848465 53.45439421]]
机器学习-sklearn-一元线性回归_第1张图片
(100, )

数据切分

x_data = data[:, 0, np.newaxis]
print(x_data.shape)

(100, 1)

x_data = data[:, 0, np.newaxis]
y_data = data[:, 1, np.newaxis]

创建并拟合模型

model = LinearRegression()
model.fit(x_data, y_data)

LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)

画图

plt.plot(x_data, y_data, ‘b.’)
plt.plot(x_data, model.predict(x_data), ‘r’)
plt.show()

机器学习-sklearn-一元线性回归_第2张图片

你可能感兴趣的:(机器学习第一部分,python)