






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







[1]: _# classify.py
""" This is the main entry point for MP5. You should only modify code within this file -- the unrevised staff files will be used for all other files and classes when code is run, so be careful to not modify anything else.
train_set - A Numpy array of 32x32x3 images of shape [7500, 3072]. This can be thought of as a list of 7500 vectors that are each 3072 dimensional. We have 3072 dimensions because there are each image is 32x32 and we have 3 color channels. So 32323 = 3072. RGB values have been scaled to range 0-1.
train_labels - List of labels corresponding with images in train_set example: Suppose I had two images [X1,X2] where X1 and X2 are 3072 dimensional ␣ ↪ vectors and X1 is a picture of a dog and X2 is a picture of an airplane. Then train_labels := [1,0] because X1 contains a picture of an animal and X2 contains no animals in the picture.
dev_set - A Numpy array of 32x32x3 images of shape [2500, 3072]. It is the same format as train_set
return - a list containing predicted labels for dev_set """
import numpy as np from sklearn.linear_model import Perceptron
def trainPerceptron(train_set, train_labels, learning_rate, max_iter): # TODO: Write your code here num_features = train_set.shape[1] # 3072 dimensions W = np.zeros(num_features) b = 0 for _ in range(max_iter): for i in range(len(train_set)): # Predict the label (y_hat = 1 if Wx + b >= 0 else -1) if (np.dot(train_set[i], W) + b) > 0: y_pred = 1 else : y_pred = 0 # Binary classification (animal vs non-animal)
# Update rule for perceptron if the prediction is wrong if y_pred != train_labels[i]: if train_labels[i] == 1: W += learning_rate * train_set[i] b += learning_rate else : W -= learning_rate * train_set[i] b -= learning_rate
return W, b # return the trained weight and bias parameters
def classifyPerceptron(train_set, train_labels, dev_set, learning_rate,␣ ↪max_iter): # TODO: Write your code here W, b = trainPerceptron(train_set, train_labels, learning_rate, max_iter) dev_pred_labels = [] # Train perceptron model and return predicted labels of development set for i in range(len(dev_set)): # Predict the label based on the learned weights and bias if (np.dot(dev_set[i], W) + b) > 0: dev_pred_labels.append(1) else : dev_pred_labels.append(0)
return dev_pred_labels
_Parameters: X_train: a numpy array of shape (N, D) containing training data; N examples with D dimensions y_train: a numpy array of shape (N,) containing training labels """
N, D = X_train.shape # Initialize the weights as zeros and the bias term as zero self.w = np.zeros(D) self.b = 0 # Gradient descent for the number of epochs for epoch in range(self.epochs): # Compute the linear combination of inputs and weights linear_model = np.dot(X_train, self.w) + self.b
# Apply the sigmoid function to get probabilities y_pred = self.sigmoid(linear_model) # Calculate the gradient of loss w.r.t weights and bias dw = (1 / N) * np.dot(X_train.T, (y_pred - y_train)) db = (1 / N) * np.sum(y_pred - y_train)
# Update weights and bias using the calculated gradients self.w -= self.lr * dw self.b -= self.lr * db
def predict(self, X_test: np.ndarray) -> np.ndarray: """Use the trained weights to predict labels for test data points.
Parameters: X_test: a numpy array of shape (N, D) containing testing data; N examples with D dimensions
_Returns: predicted labels for the data in X_test; a 1-dimensional array of length N, where each element is an integer giving the predicted class. """
linear_model = np.dot(X_test, self.w) + self.b
# Apply sigmoid to get probabilities y_pred_prob = self.sigmoid(linear_model)
# Convert probabilities to class labels (0 or 1) using the threshold y_pred = (y_pred_prob >= self.threshold).astype(int)
return y_pred
print(f"Optimal Hyperparameters: \n - Learning Rate: { optimal_lr }\n - Epochs:␣ ↪ { optimal_epochs } ") print(f"Training Accuracy: { optimal_train_acc : .2f } %") print(f"Validation Accuracy: { optimal_val_acc : .2f } %") print(f"Test Accuracy: { optimal_test_acc : .2f } %")
[ ]: # Plot 1: Accuracy vs. Number of Epochs (Fixed Learning Rate) train_acc_list = [] val_acc_list = [] test_acc_list = []
for epochs in param_grid['epochs']: train_acc_list.append(results[(optimal_lr, epochs)][0]) val_acc_list.append(results[(optimal_lr, epochs)][1]) test_acc_list.append(results[(optimal_lr, epochs)][2])
plt.figure(figsize=(10, 6)) plt.plot(param_grid['epochs'], train_acc_list, label='Training Accuracy',␣ ↪marker='o') plt.plot(param_grid['epochs'], val_acc_list, label='Validation Accuracy',␣ ↪marker='o') plt.plot(param_grid['epochs'], test_acc_list, label='Test Accuracy', marker='o') plt.xlabel('Number of Epochs') plt.ylabel('Accuracy (%)') plt.title(f'Accuracy vs. Number of Epochs (Learning Rate = { optimal_lr } )') plt.legend() plt.grid() plt.savefig("acc vs no of eopch") plt.show()
[ ]: # Plot 2: Accuracy vs. Learning Rate (Fixed Number of Epochs) train_acc_list_lr = [] val_acc_list_lr = [] test_acc_list_lr = []
for lr in param_grid['learning_rate']: train_acc_list_lr.append(results[(lr, optimal_epochs)][0]) val_acc_list_lr.append(results[(lr, optimal_epochs)][1]) test_acc_list_lr.append(results[(lr, optimal_epochs)][2])
plt.figure(figsize=(10, 6)) plt.plot(param_grid['learning_rate'], train_acc_list_lr, label='Training␣ ↪Accuracy', marker='o') plt.plot(param_grid['learning_rate'], val_acc_list_lr, label='Validation␣ ↪Accuracy', marker='o')
plt.plot(param_grid['learning_rate'], test_acc_list_lr, label='Test Accuracy',␣ ↪marker='o') plt.xlabel('Learning Rate') plt.ylabel('Accuracy (%)') plt.xscale('log') # Use logarithmic scale for learning rate plt.title(f'Accuracy vs. Learning Rate (Epochs = { optimal_epochs } )') plt.legend() plt.grid() plt.savefig("acc vs learnig rate") plt.show()
# Update parameters m_new = m_current - (step_size * m_gradient) b_new = b_current - (step_size * b_gradient)
return m_new, b_new
m, b = 0, 0 L = 0.001 # initial learning rate, can be adjusted later epochs = 100 # we iterate over the same dataset 100 times
for epoch in range(1, epochs+1): m, b = gradient_descent(m, b, data, L) loss = MSE(data, m, b) print(f"Epoch { epoch } , m: { m } , b: { b } , Loss: { loss } ") print(m, b, loss)
fig, ax = plt.subplots(1,1)
ax.scatter(data.Features, data.Targets, color="red", linewidths=0.5, label="Points") ax.plot(data.Features, [m * x + b for x in data.Features], linewidth=3, linestyle="dashed", label="$ f(x) = mx+c $")
ax.legend(loc="lower right", bbox_to_anchor=(.96, 0.0)) ax.set_xlabel("Features") ax.set_ylabel("Targets")
plt.savefig('LinearRegression001.png')
plt.close()
m, b = 0, 0 L = 0.01 # new learning rate epochs = 100
for epoch in range(1, epochs+1): m, b = gradient_descent(m, b, data, L) loss = MSE(data, m, b)
print(f"Epoch { epoch } , m: { m } , b: { b } , Loss: { loss } ") print(m, b, loss)
fig, ax = plt.subplots(1,1)
ax.scatter(data.Features, data.Targets, color="red", linewidths=0.5, label="Points") ax.plot(data.Features, [m * x + b for x in data.Features], linewidth=3, linestyle="dashed", label="$ f(x) = mx+c $")
ax.legend(loc="lower right", bbox_to_anchor=(.96, 0.0)) ax.set_xlabel("Features") ax.set_ylabel("Targets")
plt.savefig('LinearRegression01.png') plt.close()