In skearn, you can use sklearn.linear_model to create a linear model
Then use the fit function to train
Then use predict to predict
You can also use the score function to predict and calculate the accuracy of the prediction
Code
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn import linear_model
#获取数据 X,Y,并画图
X, Y = datasets.make_regression(n_samples=100, n_features=1, n_targets=1, noise=1)
plt.scatter(X, Y)
plt.show()
#区分训练集和测试集
X_train = X[:-20]
X_test = X[-20:]
Y_train = Y[:-20]
Y_test = Y[-20:]
#选择模型
lm = linear_model.LinearRegression()
#训练,获得模型
lm.fit(X_train, Y_train)
#查看模型的参数,也就是系数
print('模型参数:', lm.coef_)
#训练集和测试集的预测值
train_pred = lm.predict(X_train)
test_pred = lm.predict(X_test)
#输出预测的误差
print("训练集的预测均方误差:%.2f" % np.mean((train_pred-Y_train)**2))
print("测试集的预测均方误差:%.2f" % np.mean((test_pred-Y_test)**2))
print("预测score:%.2f" % lm.score(X_test, Y_test))