Gradient Descent Training
Glossary
Batch: a small part of the training set
Class initializer: called when creating an instance of a class.
Neural network: a model that consists of many simple models
Regularization: a method that adds additional limitations to the conditions in order to reduce overfitting
Practice
1# Stochastic gradient descent23class SGDLinearRegression:4 def __init__(self, step_size, epochs, batch_size):5 self.step_size = step_size6 self.epochs = epochs7 self.batch_size = batch_size89 def fit(self, train_features, train_target):10 X = np.concatenate((np.ones((train_features.shape[0], 1)), train_features), axis=1)11 y = train_target12 w = np.zeros(X.shape[1])1314 for _ in range(self.epochs):15 batches_count = X.shape[0] // self.batch_size16 for i in range(batches_count):17 begin = i * self.batch_size18 end = (i + 1) * self.batch_size19 X_batch = X[begin:end, :]20 y_batch = y[begin:end]2122 gradient = 2 * X_batch.T.dot(X_batch.dot(w) - y_batch) / X_batch.shape[0]2324 w -= self.step_size * gradient2526 self.w = w[1:]27 self.w0 = w[0]2829 def predict(self, test_features):30 return test_features.dot(self.w) + self.w0
1# Ridge regression23class RidgeRegression:4 def __init__(self, step_size, epochs, batch_size, reg_weight):5 self.step_size = step_size6 self.epochs = epochs7 self.batch_size = batch_size8 self.reg_weight = reg_weight910 def fit(self, train_features, train_target):11 X = np.concatenate((np.ones((train_features.shape[0], 1)), train_features), axis=1)12 y = train_target13 w = np.zeros(X.shape[1])1415 for _ in range(self.epochs):16 batches_count = X.shape[0] // self.batch_size17 for i in range(batches_count):18 begin = i * self.batch_size19 end = (i + 1) * self.batch_size20 X_batch = X[begin:end, :]21 y_batch = y[begin:end]2223 gradient = 2 * X_batch.T.dot(X_batch.dot(w) - y_batch) / X_batch.shape[0]24 reg = 2 * w.copy()25 reg[0] = 026 gradient += self.reg_weight * reg2728 w -= self.step_size * gradient2930 self.w = w[1:]31 self.w0 = w[0]3233 def predict(self, test_features):34 return test_features.dot(self.w) + self.w0