In Lecture 3, we learned about Newton's method and two different perspectives of…
- User
In Lecture 3, we learned about Newton's method and two different perspectives of deriving the Newton's method. For this question, implement Newton's method.
[Tips] If you're unable to invert the Hessian Matrix due to it being singular, consider adding very small constants to the diagonal elements of the Hessian matrix.
import statsmodels.api as sm from sklearn.preprocessing import StandardScaler from sklearn.metrics import accuracy_score import pandas as pd import numpy as np from scipy.stats import logistic # Logistic function import matplotlib.pyplot as plt
load data
caravan = pd.read_csv('data/Caravan.csv', index_col=0) caravan.Purchase = caravan.Purchase.astype('category')
X = caravan.iloc[:, 0:85].values
scaler = StandardScaler() scaler.fit(X) X = scaler.transform(X)
X = sm.add_constant(X) y = caravan.Purchase.factorize()[0]
X_train = X[1001:] y_train = y[1001:] X_test = X[:1000] y_test = y[:1000]
beta = np.random.rand(X.shape[1]) epochs = 200 # The number of iterations to perform gradient descent n = float(len(X_train)) # Number of elements in X
cost = []
Performing Newton's method
######################## Write your answere here ########################
#########################################################################
plt.plot(np.arange(epochs), cost) plt.title("Learning curve") plt.xlabel("Epoch") plt.ylabel(r"J()"); y_test_pred = logistic.cdf(np.dot(X_test, beta)) > 0.5 # 0.5 should be fixed. acc = accuracy_score(y_test, y_test_pred) print("Accuracy of Logistic Regression (Newton's method): {}".format(acc))
- Assistant
- User
Cell In[90], line 60 cost.append(-np.sum(y_train * np.log§ + (1 - y_train) * np.log(1 - p)) / len(X_train)) ^ SyntaxError: invalid character '§' (U+00A7)
- Assistant
It appears there's an invalid character in the line where the cost is calculated. The '§' symbol should not be there. Let's correct this line by removing the invalid character. The line in question should look like this:
pythoncost.append(-np.sum(y_train * np.log(p) + (1 - y_train) * np.log(1 - p)) / len(X_train))Here is the corrected part replaced within the broader context to avoid the syntax error:
pythonfor epoch in range(epochs): gradient = logistic_loss_and_grad(beta, X_train, y_train) H = logistic_hessian(beta, X_train) # Adding a small constant to the diagonal elements of the Hessian matrix if necessary H += np.eye(H.shape[0]) * lambda_ beta -= np.linalg.solve(H, gradient) # Update rule # Corrected cost calculation z = np.dot(X_train, beta) p = logistic.cdf(z) cost.append(-np.sum(y_train * np.log(p) + (1 - y_train) * np.log(1 - p)) / len(X_train)) - User
- Assistant