东方耀AI技术分享

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
热搜: 活动 交友 discuz
123
返回列表 发新帖
楼主: 东方耀
打印 上一主题 下一主题

[课堂笔记] 11、机器学习实战案例:普通最小二乘法求线性回归_笔记

[复制链接]

0

主题

96

帖子

202

积分

中级会员

Rank: 3Rank: 3

积分
202
地板
发表于 2019-12-22 20:50:34 | 只看该作者
this is good idea
回复

使用道具 举报

0

主题

96

帖子

202

积分

中级会员

Rank: 3Rank: 3

积分
202
板凳
发表于 2019-12-22 20:48:07 | 只看该作者
this is good idea
回复

使用道具 举报

1366

主题

1857

帖子

1万

积分

管理员

Rank: 10Rank: 10Rank: 10

积分
14459
QQ
沙发
 楼主| 发表于 2019-9-12 09:31:26 | 只看该作者
  1. import numpy as np
  2. from .metrics import r2_score

  3. class LinearRegression:

  4.     def __init__(self):
  5.         """初始化Linear Regression模型"""
  6.         self.coef_ = None
  7.         self.intercept_ = None
  8.         self._theta = None

  9.     def fit_normal(self, X_train, y_train):
  10.         """根据训练数据集X_train, y_train训练Linear Regression模型"""
  11.         assert X_train.shape[0] == y_train.shape[0], \
  12.             "the size of X_train must be equal to the size of y_train"

  13.         X_b = np.hstack([np.ones((len(X_train), 1)), X_train])
  14.         self._theta = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y_train)

  15.         self.intercept_ = self._theta[0]
  16.         self.coef_ = self._theta[1:]

  17.         return self

  18.     def fit_gd(self, X_train, y_train, eta=0.01, n_iters=1e4):
  19.         """根据训练数据集X_train, y_train, 使用梯度下降法训练Linear Regression模型"""
  20.         assert X_train.shape[0] == y_train.shape[0], \
  21.             "the size of X_train must be equal to the size of y_train"

  22.         def J(theta, X_b, y):
  23.             try:
  24.                 return np.sum((y - X_b.dot(theta)) ** 2) / len(y)
  25.             except:
  26.                 return float('inf')

  27.         def dJ(theta, X_b, y):
  28.             # res = np.empty(len(theta))
  29.             # res[0] = np.sum(X_b.dot(theta) - y)
  30.             # for i in range(1, len(theta)):
  31.             #     res[i] = (X_b.dot(theta) - y).dot(X_b[:, i])
  32.             # return res * 2 / len(X_b)
  33.             return X_b.T.dot(X_b.dot(theta) - y) * 2. / len(X_b)

  34.         def gradient_descent(X_b, y, initial_theta, eta, n_iters=1e4, epsilon=1e-8):

  35.             theta = initial_theta
  36.             cur_iter = 0

  37.             while cur_iter < n_iters:
  38.                 gradient = dJ(theta, X_b, y)
  39.                 last_theta = theta
  40.                 theta = theta - eta * gradient
  41.                 if (abs(J(theta, X_b, y) - J(last_theta, X_b, y)) < epsilon):
  42.                     break

  43.                 cur_iter += 1

  44.             return theta

  45.         X_b = np.hstack([np.ones((len(X_train), 1)), X_train])
  46.         initial_theta = np.zeros(X_b.shape[1])
  47.         self._theta = gradient_descent(X_b, y_train, initial_theta, eta, n_iters)

  48.         self.intercept_ = self._theta[0]
  49.         self.coef_ = self._theta[1:]

  50.         return self

  51.     def fit_sgd(self, X_train, y_train, n_iters=5, t0=5, t1=50):
  52.         """根据训练数据集X_train, y_train, 使用梯度下降法训练Linear Regression模型"""
  53.         assert X_train.shape[0] == y_train.shape[0], \
  54.             "the size of X_train must be equal to the size of y_train"
  55.         assert n_iters >= 1

  56.         def dJ_sgd(theta, X_b_i, y_i):
  57.             return X_b_i * (X_b_i.dot(theta) - y_i) * 2.

  58.         def sgd(X_b, y, initial_theta, n_iters, t0=5, t1=50):

  59.             def learning_rate(t):
  60.                 return t0 / (t + t1)

  61.             theta = initial_theta
  62.             m = len(X_b)

  63.             for cur_iter in range(n_iters):
  64.                 indexes = np.random.permutation(m)
  65.                 X_b_new = X_b[indexes]
  66.                 y_new = y[indexes]
  67.                 for i in range(m):
  68.                     gradient = dJ_sgd(theta, X_b_new[i], y_new[i])
  69.                     theta = theta - learning_rate(cur_iter * m + i) * gradient

  70.             return theta

  71.         X_b = np.hstack([np.ones((len(X_train), 1)), X_train])
  72.         initial_theta = np.random.randn(X_b.shape[1])
  73.         self._theta = sgd(X_b, y_train, initial_theta, n_iters, t0, t1)

  74.         self.intercept_ = self._theta[0]
  75.         self.coef_ = self._theta[1:]

  76.         return self

  77.     def predict(self, X_predict):
  78.         """给定待预测数据集X_predict,返回表示X_predict的结果向量"""
  79.         assert self.intercept_ is not None and self.coef_ is not None, \
  80.             "must fit before predict!"
  81.         assert X_predict.shape[1] == len(self.coef_), \
  82.             "the feature number of X_predict must be equal to X_train"

  83.         X_b = np.hstack([np.ones((len(X_predict), 1)), X_predict])
  84.         return X_b.dot(self._theta)

  85.     def score(self, X_test, y_test):
  86.         """根据测试数据集 X_test 和 y_test 确定当前模型的准确度"""

  87.         y_predict = self.predict(X_test)
  88.         return r2_score(y_test, y_predict)

  89.     def __repr__(self):
  90.         return "LinearRegression()"
复制代码
让天下人人学会人工智能!人工智能的前景一片大好!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|人工智能工程师的摇篮 ( 湘ICP备2020019608号-1 )

GMT+8, 2024-6-26 18:55 , Processed in 0.175076 second(s), 18 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表