损失函数:(y_preduct - y_true) ** 2,用最小二乘法求解

image.png

  1. import numpy as np
  2. from matplotlib import pyplot as plt
  3. x = np.array([1, 2, 3, 4, 5])
  4. y = np.array([1, 3, 2, 3, 5])
  5. plt.scatter(x, y)

image.png

  1. y_meain = np.mean(y)
  2. x_mean = np.mean(x)
  3. a = np.dot((x - x_mean), (y - y_meain) / np.dot((x-x_mean), x-x_mean))
  4. b = y_meain - a * x_mean
  5. y_preduct = x * a + b
  6. plt.scatter(x, y)
  7. plt.plot(x, y_preduct, color='r')

image.png

回归算法的评价

均方误差 MSE 因为存在量纲的问题 使用均方根误差 RMSE 平均绝对误差 MAE

  1. from sklearn import datasets
  2. boston = datasets.load_boston()
  3. X = boston.data[:, [5]]
  4. plt.scatter(X, y)

image.png

  1. line = LinearRegression()
  2. line.fit(X, y)
  3. y_prdict = line.predict(X)
  4. plt.scatter(X, y)
  5. plt.scatter(X, y_prdict)

image.png

  1. MSE = sum((y_prdict - y) ** 2) / len(y)
  2. MSE
  3. RMSE = np.sqrt(MSE)
  4. RMSE
  5. MAE = sum(np.absolute(y_prdict - y)) / len(y)
  6. MAE

机器学习中的MSE、MAE库

  1. from sklearn.metrics import mean_squared_error, mean_absolute_error
  2. mean_squared_error(y_prdict, y)
  3. mean_absolute_error(y_prdict, y)

R**2

image.png

  1. R = 1 - np.dot((y_prdict - y), (y_prdict - y)) / np.dot((np.mean(y) - y), (np.mean(y) - y))
  2. line.score(X, y)
  3. # sklear中的R**2
  4. from sklearn.metrics import r2_score
  5. r2_score(y, y_prdict)

R 2 <= 1。
R
2 越大越好,当我们训练的模型不犯任何错误的时候是 R2得到最大值。
当我们的模型等于基准模型时 R
2 = 0。
如果R**2 < 0, 说明我们学习的模型还不如基准模型。此时很可能我们的数据不存在任何线性关系。

多项式回归—-损失函数求解方式:正规方程

image.png