荣誉版主
- 积分
- 978
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2010-2-23
- 最后登录
- 1970-1-1
|
29. Train Linear Regression and Logistic Regression by using gradient descent
参考
1. 斯坦福 CS229的Lecture Note: https://see.stanford.edu/materials/aimlcs229/cs229-notes1.pdf.
2. Python Machine Learning的ch03 和 ch10的code: https://github.com/rasbt/python-machine-learning-book-3rd-edition
(1). Train Linear Regression
- import numpy as np
- import pandas as pd
- from sklearn.preprocessing import StandardScaler
- import matplotlib.pyplot as plt
复制代码
. ----. .и
- import numpy as np
- class Linear_Regression:.
- . 1point3acres
- # initialize learning_rate and iteration times
- def __init__(self, learning_rate=0.001, n_iter=50):
- self.learning_rate = learning_rate
- self.n_iter = n_iter
-
- # fit the model. .и
- def fit(self, X, y):
. Waral dи, - # initialize w, the linear regression coefficients
- self.w = np.zeros(1 + X.shape[1])
- self.costs = []. .и
-
- for i in range(self.n_iter):
- # calculate h(X)
. ---- - h_X = self.h(X)
- # calculate errors = y - h(X)
- errors = (y - h_X)
-
- # update linear coefficients w[1:]. .и
- self.w[1:] += self.learning_rate*np.dot(X.T, errors). From 1point 3acres bbs
- # update intercept w[0]
- self.w[0] += self.learning_rate*errors.sum()
- # calculate the L2 cost: J
- J = (errors**2).sum()/2.0
- self.costs.append(J)
- -baidu 1point3acres
- return self
-
- # calculate h(x) = x^{T}*w, in matrix form: h(X) = X*w
- def h(self, X):
- return np.dot(X, self.w[1:]) + self.w[0]
-
- # do prediction by using h(X) = X*w
- def predict(self, X):. ----
- return self.h(X)
复制代码
. Waral dи,
- df = pd.read_csv('https://raw.githubusercontent.com/rasbt/'
- 'python-machine-learning-book-3rd-edition/'
- 'master/ch10/housing.data.txt',
- header=None,
- sep='\s+')
- .
- df.columns = ['CRIM', 'ZN', 'INDUS', 'CHAS',
- 'NOX', 'RM', 'AGE', 'DIS', 'RAD',
- 'TAX', 'PTRATIO', 'B', 'LSTAT', 'MEDV']. 1point3acres
- # get X, y
- X = df[['RM']].values
- y = df['MEDV'].values
- # Standardize X, y
- sc_x = StandardScaler()
- sc_y = StandardScaler()
- . check 1point3acres for more.
- X_std = sc_x.fit_transform(X). .и
- y_std = sc_y.fit_transform(y[:, np.newaxis]).flatten()
- # Fit the model by using X_std and y_std
- lr = Linear_Regression()
- lr.fit(X_std, y_std)
- print('Slope: %.3f' % lr.w[1])
- print('Intercept: %.3f' % lr.w[0])
. Waral dи,
- # Slope: 0.695
- # Intercept: -0.000
复制代码
(2). Train Logistic Regression
- class Logistic_Regression:
-
- # initialize learning_rate and iteration times and random seed for initial value of w
- # w is the logistic regression coefficients.--
- def __init__(self, learning_rate=0.05, n_iter=100, random_state=1):
- self.learning_rate = learning_rate
- self.n_iter = n_iter
- self.random_state = random_state
- . Χ
- def fit(self, X, y):-baidu 1point3acres
- # set random seed to a distribution from which an initial value for w is generated
- random_generator = np.random.RandomState(self.random_state).
- # initialize
- self.w = random_generator.normal(loc=0.0, scale=0.01, size=1 + X.shape[1])
- self.cost = []
-
- for i in range(self.n_iter):
- # calculate Z(X)
- Z_X = self.Z(X). Χ
- # calculate h = g(Z)
- h_X = self.g(Z_X)
- # calculate errors = y - h(X)
- errors = (y - h_X)
- # update logistic regression coefficients w[1:]
- self.w[1:] += self.learning_rate*np.dot(X.T, errors)
- # update intercept w[0]
- self.w[0] += self.learning_rate*errors.sum()-baidu 1point3acres
-
- # calculate the cross-entropy cost. 1point3acres
- cost = -y.dot(np.log(h_X)) - ((1 - y).dot(np.log(1 - h_X)))
- self.cost.append(cost).1point3acres
-
- # calculate z = x^{T}*w, in matrix form: Z = X*w
- def Z(self, X):
- return self.w[0] + np.dot(X, self.w[1:])
- . Waral dи,
- # calculate g(z), the sigmoid function. 1point 3acres
- def g(self, z):
- return 1.0/(1 + np.exp(-z))
-
- # make prediction for new X
- def predict(self, X):
- return np.where(self.Z(X) >= 0.0, 1, 0)
-
-
复制代码
.
|
|