Python AI Assignment1
In this assignment, you will implement linear regression with one variable.¶
100 points total¶
# clear all variables
%reset_selective -f a
import numpy as np
import matplotlib.pyplot as plt
from numpy import loadtxt
Load data from data.csv file (5 Points)¶
# Complete the function below to load the data from data.csv.
# Return [X,y] where X is the input and y is the target
def load_data(file_name):
# write your code here
return X,y
[X,y] = load_data(“data.csv”)
Visualise the data (5 Points)¶
def vis_data(X,y):
# write your code here
vis_data(X,y)
Implement a loss function (10 Points)¶
# y_true –> the target values.
# y_pred –> the predicted values
def loss(y_true, y_pred):
#Calculating loss.
return loss
Test loss function¶
loss(np.array([5,2]),np.array([10,3]))
Implement a function to calculate gradients (20 Points)¶
# X –> Input.
# y_true –> target values.
# y_pred –> predictions.
# dw –> the gradient with respect to the weights
# db –> the gradient with respect to the bias.
def gradients(X, y_true, y_pred):
# write your code here
return dw, db
Test gradients¶
dw,db = gradients(np.array([5]),np.array([1.5]),np.array([1.1]))
print(f’dw = {dw} , db = {db}’)
Write a function that uses your loss and gradients to train a LR model (25 Points)¶
# X –> Input.
# y –> true/target value.
# add more arguments as you need
def train(X, y,…):
# write your code here
# returning weights, bias and losses(List).
return w, b
w, b = train(X, y,…)
Write a function to use your model to predict (15 Points)¶
def predict(X, w, b,…):
# write your code here
# Returning predictions.
Visualise your predictions¶
fig = plt.figure(figsize=(8,6))
plt.plot(X, y, ‘y.’)
plt.plot(X, predict(X, w, b,…), ‘r.’)
plt.legend([“Data”, “Predictions”])
plt.xlabel(‘X – Input’)
plt.ylabel(‘y – target / true’)
plt.title(‘Regression’)
Calculate the fit score¶
from sklearn.metrics import r2_score
y_true = y
y_pred = predict(X, w, b, [2])
r2_score(y_true, y_pred)
Use scikit-learn to fit a linear regression model using the data from data,csv (20 points)¶
# write your code here