Skip to content

Instantly share code, notes, and snippets.

@mamigot
Last active December 2, 2022 22:47
Show Gist options
  • Save mamigot/0bde9b22f01768a2f3eb3d282286bff9 to your computer and use it in GitHub Desktop.
Save mamigot/0bde9b22f01768a2f3eb3d282286bff9 to your computer and use it in GitHub Desktop.
Linear regression function in Python that you could use to predict your final grade in a course based on the grades you have received on various assessments:
import numpy as np
def linear_regression(X, y):
# Add a column of ones to X to represent the bias term
X = np.concatenate([np.ones((X.shape[0], 1)), X], axis=1)
# Compute the transpose of X
X_t = np.transpose(X)
# Compute the dot product of X_t and X
X_t_X = np.dot(X_t, X)
# Compute the inverse of X_t_X
X_t_X_inv = np.linalg.inv(X_t_X)
# Compute the dot product of X_t and y
X_t_y = np.dot(X_t, y)
# Compute the weights of the linear regression model
weights = np.dot(X_t_X_inv, X_t_y)
return weights
# Define the input data
X = np.array([
[10], # grade on first assessment
[20], # grade on second assessment
[30] # grade on third assessment
])
# Define the target variable
y = np.array([
[80] # final grade in the course
])
# Compute the weights of the linear regression model
weights = linear_regression(X, y)
# Define the input data for which we want to make a prediction
X_test = np.array([
[15], # grade on fourth assessment
[25], # grade on fifth assessment
[35] # grade on sixth assessment
])
# Add a column of ones to X_test to represent the bias term
X_test = np.concatenate([np.ones((X_test.shape[0], 1)), X_test], axis=1)
# Compute the dot product of X_test and weights
predictions = np.dot(X_test, weights)
# Print the predictions
print(predictions)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment