Implement Linear Regression Gradient Descent
DatabricksMachine Learning Engineer · OnsiteLast updated
This question tests the ability to implement batch gradient descent for simple linear regression from scratch, requiring the derivation of gradients for weights and bias, and understanding how to optimize convergence.
Linear Regression Gradient Descent Implementation
Implement a function gradient_descent(X, y, learning_rate, iterations) to perform batch gradient descent for a linear regression model. Assume the model follows the form y_pred = w * X + b.
Requirements:
- Input
Xis a list/array of feature values, andyis a list/array of target values. - Initialize
w(weight) andb(bias) to zero. - Use the Mean Squared Error (MSE) as the loss function:
Loss = (1/n) * sum((y_pred - y)^2). - Perform the update steps for
wandbsimultaneously for the specified number of iterations. - Return the final
wandbas a tuple.
Example:
# Input
X = [1, 2, 3]
y = [2, 4, 6]
learning_rate = 0.01
iterations = 1000
# Output
# Final w, b (e.g., approximately 1.99, 0.03)
Constraints:
- Assume
Xandyare of equal lengthn. n>= 1.- Learning rate is a positive float.
- Iterations is a positive integer.
Edge Cases to Consider:
- What happens if the learning rate is too large?
- How does the scale of input features affect convergence speed?
- How would the implementation change if we switched from Batch Gradient Descent to Stochastic Gradient Descent (SGD)?
Hints
Hint 1
The gradient of the MSE loss with respect to weight `w` is `(2/n) * sum(X * (y_pred - y))`.
Hint 2
The gradient of the MSE loss with respect to bias `b` is `(2/n) * sum(y_pred - y)`.
Hint 3
Remember to update `w` and `b` using the calculated gradients multiplied by the negative learning rate at every iteration.
Follow-up questions
- How would you modify this code to include L2 regularization (Ridge regression)?
- What are the trade-offs between choosing a very small versus a very large learning rate in this implementation?
- If the input features have vastly different scales (e.g., one feature ranges from 0-1 and another from 0-1000), how would that impact your gradient descent and how would you fix it?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.