• 入门教程
• 分类教程
• 回归教程
• 聚类教程
• KNN教程
• 关注我们

# 回归算法 - 入门教程

## 代码实现

### 第1步 - 导入包

import numpy as np
from sklearn import linear_model
import sklearn.metrics as sm
import matplotlib.pyplot as plt

### 第2步 - 导入数据集

input=r'C:\linear.txt'

input_data=np.loadtxt(input, delimiter=',')
X, y=input_data[:, :-1], input_data[:, -1]

### 第3步 - 数据整理

training_samples = int(0.6 * len(X))
testing_samples = len(X) - num_training
X_train, y_train = X[:training_samples], y[:training_samples]
X_test, y_test = X[training_samples:], y[training_samples:]

### 第4步 - 模型评估和预测

reg_linear=linear_model.LinearRegression()

reg_linear.fit(X_train, y_train)

y_test_pred=reg_linear.predict(X_test)

### 第5步 - 绘图和可视化

plt.scatter(X_test, y_test, color = 'red')
plt.plot(X_test, y_test_pred, color = 'black', linewidth = 2)
plt.xticks(())
plt.yticks(())
plt.show()

### 第6步 - 性能计算

print("Regressor model performance:")
print("Mean absolute error(MAE) =", round(sm.mean_absolute_error(y_test, y_test_pred), 2))
print("Mean squared error(MSE) =", round(sm.mean_squared_error(y_test, y_test_pred), 2))
print("Median absolute error =", round(sm.median_absolute_error(y_test, y_test_pred), 2))
print("Explain variance score =", round(sm.explained_variance_score(y_test, y_test_pred), 2))
print("R2 score =", round(sm.r2_score(y_test, y_test_pred), 2))

Regressor model performance:
Mean absolute error(MAE)=1.78
Mean squared error(MSE)=3.89
Median absolute error=2.01
Explain variance score=-0.09
R2 score=-0.09

Go语言核心36讲 -〔郝林〕

Swift核心技术与实战 -〔张杰〕

MongoDB高手课 -〔唐建法（TJ）〕