defmain(train_path, eval_path, pred_path): """Problem 1(b): Logistic regression with Newton's Method.
Args: train_path: Path to CSV file containing dataset for training. eval_path: Path to CSV file containing dataset for evaluation. pred_path: Path to save predictions. """ x_train, y_train = util.load_dataset(train_path, add_intercept=True)
deffit(self, x, y): """Run Newton's Method to minimize J(theta) for logistic regression.
Args: x: Training example inputs. Shape (m, n). y: Training example labels. Shape (m,). """ # *** START CODE HERE *** m, n = x.shape self.theta = np.zeros(n) while1: theta_old = np.copy(self.theta)
h_x = 1 / (1 + np.exp(np.dot(-x, self.theta))) # print(h_x.shape) g = np.dot(x.T, (h_x - y)) / m # H = x.T*h_x*(1-h_x)*x/m H = (x.T * h_x * (1 - h_x)).dot(x) / m self.theta = theta_old - np.linalg.inv(H).dot(g)
if np.linalg.norm(self.theta - theta_old, ord=1) < self.eps: break
# *** END CODE HERE ***
predict
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
defpredict(self, x): """Make a prediction given new inputs x.
Args: x: Inputs of shape (m, n).
Returns: Outputs of shape (m,). """ # *** START CODE HERE *** m, n = x.shape y = np.zeros(m) h_x = 1 / (1 + np.exp(np.dot(-x, self.theta))) y[h_x >= 0.5] = 1 y[h_x < 0.5] = 0 return y # *** END CODE HERE ***
defmain(train_path, eval_path, pred_path): """Problem 1(b): Logistic regression with Newton's Method.
Args: train_path: Path to CSV file containing dataset for training. eval_path: Path to CSV file containing dataset for evaluation. pred_path: Path to save predictions. """ x_train, y_train = util.load_dataset(train_path, add_intercept=True)
deffit(self, x, y): """Run Newton's Method to minimize J(theta) for logistic regression.
Args: x: Training example inputs. Shape (m, n). y: Training example labels. Shape (m,). """ # *** START CODE HERE *** m, n = x.shape self.theta = np.zeros(n) while1: theta_old = np.copy(self.theta)
h_x = 1 / (1 + np.exp(np.dot(-x, self.theta))) # print(h_x.shape) g = np.dot(x.T, (h_x - y)) / m # H = x.T*h_x*(1-h_x)*x/m H = (x.T * h_x * (1 - h_x)).dot(x) / m self.theta = theta_old - np.linalg.inv(H).dot(g)
if np.linalg.norm(self.theta - theta_old, ord=1) < self.eps: break
# *** END CODE HERE ***
defpredict(self, x): """Make a prediction given new inputs x.
Args: x: Inputs of shape (m, n).
Returns: Outputs of shape (m,). """ # *** START CODE HERE *** m, n = x.shape y = np.zeros(m) h_x = 1 / (1 + np.exp(np.dot(-x, self.theta))) y[h_x >= 0.5] = 1 y[h_x < 0.5] = 0 return y # *** END CODE HERE ***