Q1. What Linear Regression training algorithm can you use if you have a training set with millions of features?
A1:Stochastic Gradient Descent or Mini-Batch Gradient Descent.
Q2. Suppose the features in your training set have very different scales. What algorithms might suffer from this, and how? What can you do about it?
A2: The normal Function will work well. We can scale the training set before training the model, use StandardScaler class.
Q3. Can Gradient Descent get stuck in a local minimum when training a Logistic Rregression model?
A3: Logistic Rregression's cost function is convex, so it cannot get stuck in a local minimum.
Q4. Do all Gradient Descent algorithms lead to the same model provided you let them run long enough?
A4: Theoratically, if the optimization problem is convex, all Gradient Descent algorithms will approach the global optimum and end up producing fairly similiar models. But unless you gradually reduce the learning rate, Stochastic GD and Mini-Batch GD will never truly converge, because they will keep jumping back and forth around the global optimum without reaching it, even if you let them run long enough. So they will end up producing slightly different.
Q5. Suppose you use Batch Gradient Descent and you plot the validation error at every epoch. If you notice that the validation error consistently goes up, what is likely going on? How can you fix this?
A5: The learning rate is too high, and the model is diverging. Or you have overfitting the training set. We need to check the training error, if training error continues to go down, it's overfitting, we need to plus regularization or change to a more simple model; if training error also goes up, that means the learning rate is too high, we need to reduce the learninig rate.
Q6. Is it a good idea to stop Mini-Batch Gradient Descent immediately when the validation error goes up?
A6: No, because it's too early, the Mini-Batch GD is not guaranteed to make progress every epoch. We can save the model at regular intervals, and when it has not improved for a really long time, then we can stop it can come back the best saved model.
Q7. Which Gradient Descent algorithm (among those we discussed) will reach the vicinity of the optimal solution the fastest? Which will actually converge? How can you make the others converge as well?
A7: Stochastic GD has the fastest training iteration since it considers only one training instance at a time. Batch GD will actually converge given enough time. To make Stochastic GD and Mini-Batch GD to converge at last we need to gradually reduce the learning rate.
Q8. Suppose you are using Polynomial Regression. You plot the learning curves and you notice that there is a large gap between the training error and the validation error. What is happening? What are three ways to solve this?
A8: It's overfitting the training set. Firstly, We can plus a regularization to solve this problem, such as Ridge Regression and Lasso Regression; Secondly, we can reduce the polynomial degree, because a model with fewer degrees of freedom is less likely to overfit; Thirdly, we can increase the size of the training set.
Q9. Suppose you are using Ridge Regression and you notice that the training error and the validation error are almost equal and farly high. Would you say that the model suffers from high bias or high variance? Should you increase the regularization hyperparameter alpha or reduce it?
A9: It's underfitting the training set, which means it suffers from a high bias. We should reduce the hyperparameter alpha.
Q10. Why would you want to use:
A10: We prefer Ridge Regression to Linear Regression because the former one has a regularization, so it's much less likely to overfitting the training set; we prefer Lasso to Ridge because it can eliminate the weights of the least important features, which means Lasso naturally performs a feature selection; we prefer Elastic Net to Lasso because Lasso may behave erratically when the number of features is greater than the number of training intances or when several features are strongly correlated.
Q11. Suppose you want to classify pictures as outdoor/indoor and daytime/nighttime. Should you implement two Logistic Regression classifier or one Softmax Regression classifier?
A11: Because these are not exclusive classes, all four combinations are possible, so we should implement atwo Logistic Regression classifiers.
Q12.Implemet Batch Gradient Descent with early stopping for Softmax Regression ( without using Scikit-Learn)
A12:
#Load the iris data
X = iris["data"][:, (2, 3)] # petal length, petal width
y = iris["target"]
#Add bias term as x0 = 1
X_with_bias = np.c_[np.ones([len(X), 1]), X]
#Set random seed
np.random.seed(2042)
#Split the data into training set, validation set and test set
test_ratio = 0.2
validation_ratio = 0.2
total_size = len(X_with_bias)
test_size = int(total_size * test_ratio)
validation_size = int(total_size * validation_ratio)
train_size = total_size - test_size - validation_size
rnd_indices = np.random.permutation(total_size)
X_train = X_with_bias[rnd_indices[:train_size]]
y_train = y[rnd_indices[:train_size]]
X_valid = X_with_bias[rnd_indices[train_size:-test_size]]
y_valid = y[rnd_indices[train_size:-test_size]]
X_test = X_with_bias[rnd_indices[-test_size:]]
y_test = y[rnd_indices[-test_size:]]
#One-Hot encoder
def to_one_hot(y):
n_classes = y.max() + 1
m = len(y)
Y_one_hot = np.zeros((m, n_classes))
Y_one_hot[np.arange(m), y] = 1
return Y_one_hot
#Test
y_train[:10]
to_one_hot(y_train[:10])
#Create the target class probabilities matrix
Y_train_one_hot = to_one_hot(y_train)
Y_valid_one_hot = to_one_hot(y_valid)
Y_test_one_hot = to_one_hot(y_test)
#Softmax function
def softmax(logits):
exps = np.exp(logits)
exp_sums = np.sum(exps, axis=1, keepdims=True)
return exps / exp_sums
#Define the input and output
n_inputs = X_train.shape[1] # == 3 (2 features plus the bias term)
n_outputs = len(np.unique(y_train)) # == 3 (3 iris classes)
#Computation
eta = 0.01
n_iterations = 5001
m = len(X_train)
epsilon = 1e-7
Theta = np.random.randn(n_inputs, n_outputs)
for iteration in range(n_iterations):
logits = X_train.dot(Theta)
Y_proba = softmax(logits)
loss = -np.mean(np.sum(Y_train_one_hot * np.log(Y_proba + epsilon), axis=1))
error = Y_proba - Y_train_one_hot
if iteration % 500 == 0:
print(iteration, loss)
gradients = 1/m * X_train.T.dot(error)
Theta = Theta - eta * gradients
#Check the model parameters
Theta
#Validation corss
logits = X_valid.dot(Theta)
Y_proba = softmax(logits)
y_predict = np.argmax(Y_proba, axis=1)
accuracy_score = np.mean(y_predict == y_valid)
accuracy_score
#Add the regularization
eta = 0.1
n_iterations = 5001
m = len(X_train)
epsilon = 1e-7
alpha = 0.1 # regularization hyperparameter
Theta = np.random.randn(n_inputs, n_outputs)
for iteration in range(n_iterations):
logits = X_train.dot(Theta)
Y_proba = softmax(logits)
xentropy_loss = -np.mean(np.sum(Y_train_one_hot * np.log(Y_proba + epsilon), axis=1))
l2_loss = 1/2 * np.sum(np.square(Theta[1:]))
loss = xentropy_loss + alpha * l2_loss
error = Y_proba - Y_train_one_hot
if iteration % 500 == 0:
print(iteration, loss)
gradients = 1/m * X_train.T.dot(error) + np.r_[np.zeros([1, n_outputs]), alpha * Theta[1:]]
Theta = Theta - eta * gradients
#Check
logits = X_valid.dot(Theta)
Y_proba = softmax(logits)
y_predict = np.argmax(Y_proba, axis=1)
accuracy_score = np.mean(y_predict == y_valid)
accuracy_score
#Early stopping
eta = 0.1
n_iterations = 5001
m = len(X_train)
epsilon = 1e-7
alpha = 0.1 # regularization hyperparameter
best_loss = np.infty
Theta = np.random.randn(n_inputs, n_outputs)
for iteration in range(n_iterations):
logits = X_train.dot(Theta)
Y_proba = softmax(logits)
xentropy_loss = -np.mean(np.sum(Y_train_one_hot * np.log(Y_proba + epsilon), axis=1))
l2_loss = 1/2 * np.sum(np.square(Theta[1:]))
loss = xentropy_loss + alpha * l2_loss
error = Y_proba - Y_train_one_hot
gradients = 1/m * X_train.T.dot(error) + np.r_[np.zeros([1, n_outputs]), alpha * Theta[1:]]
Theta = Theta - eta * gradients
logits = X_valid.dot(Theta)
Y_proba = softmax(logits)
xentropy_loss = -np.mean(np.sum(Y_valid_one_hot * np.log(Y_proba + epsilon), axis=1))
l2_loss = 1/2 * np.sum(np.square(Theta[1:]))
loss = xentropy_loss + alpha * l2_loss
if iteration % 500 == 0:
print(iteration, loss)
if loss < best_loss:
best_loss = loss
else:
print(iteration - 1, best_loss)
print(iteration, loss, "early stopping!")
break
#Check
logits = X_valid.dot(Theta)
Y_proba = softmax(logits)
y_predict = np.argmax(Y_proba, axis=1)
accuracy_score = np.mean(y_predict == y_valid)
accuracy_score
#Plot the prediction
x0, x1 = np.meshgrid(
np.linspace(0, 8, 500).reshape(-1, 1),
np.linspace(0, 3.5, 200).reshape(-1, 1),
)
X_new = np.c_[x0.ravel(), x1.ravel()]
X_new_with_bias = np.c_[np.ones([len(X_new), 1]), X_new]
logits = X_new_with_bias.dot(Theta)
Y_proba = softmax(logits)
y_predict = np.argmax(Y_proba, axis=1)
zz1 = Y_proba[:, 1].reshape(x0.shape)
zz = y_predict.reshape(x0.shape)
plt.figure(figsize=(10, 4))
plt.plot(X[y==2, 0], X[y==2, 1], "g^", label="Iris-Virginica")
plt.plot(X[y==1, 0], X[y==1, 1], "bs", label="Iris-Versicolor")
plt.plot(X[y==0, 0], X[y==0, 1], "yo", label="Iris-Setosa")
from matplotlib.colors import ListedColormap
custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
plt.contourf(x0, x1, zz, cmap=custom_cmap)
contour = plt.contour(x0, x1, zz1, cmap=plt.cm.brg)
plt.clabel(contour, inline=1, fontsize=12)
plt.xlabel("Petal length", fontsize=14)
plt.ylabel("Petal width", fontsize=14)
plt.legend(loc="upper left", fontsize=14)
plt.axis([0, 7, 0, 3.5])
plt.show()
#Accuracy
logits = X_test.dot(Theta)
Y_proba = softmax(logits)
y_predict = np.argmax(Y_proba, axis=1)
accuracy_score = np.mean(y_predict == y_test)
accuracy_score