Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Question: Implement Linear regression using NumPy. You should implement your code in the provided linear _ regression.py file. This python file takes a csv file
Question:
Implement Linear regression using NumPy. You should implement your code in the provided linearregression.py file. This python file takes a csv file and a list of features as input. From these list of features, the last feature will be the target label and the remaining ones will be your training inputs. For example, in the following usage scenario, linearcsv is the csv file and Writing is the target label, while Math and Reading are training inputs.
$python linearregression.py linear.csv Math Reading Writing
Output the RMSE score of prediction.
provided linearregression.py file,is as follow:
import numpy as np
import pandas as pd
import math
import sys
import os
#Todo : define necessary functions
def computeweightsX y:
Compute linear regression weights using the normal equation.
X: input features with a column of ones bias term
y: target variable.
# Normal equation: XT X XT y
weights nplinalg.invXTdotXdotXTdoty
return weights
def predictX weights:
Predict the target variable using the linear model.
X: input features with a column of ones bias term
weights: weights of the linear model.
predictions Xdotweights
return predictions
def rmsepredictions targets:
Calculate the root mean squared error.
predictions: predicted values.
targets: actual values.
return npsqrtpredictions targetsmean
def linearregressiondata:
data: input data matrix
return: rmse value
#Todo : fill code here
# Extract the features and target variable
features data.iloc: :
target data.iloc:
# Add a column of ones to the features for the intercept term
features nphstacknponesfeaturesshape features
# Compute weights
weights computeweightsfeatures target
# Predict the target variable
predictions predictfeatures weights
# Calculate and return RMSE
return rmsepredictions target
# do not modify this function
def loaddata:
filename sysargv
featurematrix pdreadcsvfilename
featurematrix featurematrix.dropna
features sysargv:
#printfeaturematrixfeatures
return featurematrix
if namemain:
data loaddata
RMSESCORE linearregressiondata
printRMSE score is : RMSESCORE
linearcsvcontains in the following format: Math, Reading, Writing. There are lines of data structured in this way.Math, Reading, Writing. There are lines of data structured in this way.im attaching the image of csv file
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started