简单的线性回归,主要是sklearn库的学习以及代码的实现
http://scikit-learn.org/stable/index.html
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 1 16:51:59 2018
@author: wp
"""
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
diabetes = datasets.load_diabetes()
diabetes_X = diabetes.data[:, np.newaxis, 2]
diabetes_X_train = diabetes_X[:-20]
diabetes_X_test = diabetes_X[-20:]
diabetes_y_train = diabetes.target[:-20]
diabetes_y_test = diabetes.target[-20:]
#建立模型
regr = linear_model.LinearRegression()
regr.fit(diabetes_X_train, diabetes_y_train)
#预测
diabetes_y_pred = regr.predict(diabetes_X_test)
#输出结果
print('Coefficients: \n', regr.coef_)
#误差平方和
print("Mean squared error: %.2f"
% mean_squared_error(diabetes_y_test, diabetes_y_pred))
#R^2
print('Variance score: %.2f' % r2_score(diabetes_y_test, diabetes_y_pred))
# Plot outputs
plt.scatter(diabetes_X_test, diabetes_y_test, color='black')
plt.plot(diabetes_X_test, diabetes_y_pred, color='blue', linewidth=3)
plt.xticks(()) #去除坐标轴显示
plt.yticks(())
plt.show()