Question: update this code like own work not copied from online tool import numpy as np import matplotlib.pyplot as plt # Load the data from CSV
update this code like own work not copied from online tool
import numpy as np
import matplotlib.pyplot as plt
# Load the data from CSV
data npgenfromtxtAdvertisingNpcsv delimiter skipheader
# Separate the features and the target variable
X data: : # TV Radio, Newspaper
y data: # Sales
# Add a column of ones for the intercept term
X npcolumnstacknponesXshape X # N x p design matrix
nprandom.seed # For reproducibility
beta nprandom.uniform Xshape # p parameters
def minibatchgradientdescentX y beta, batchsize learningratee iterations:
N Xshape # Number of observations
B N batchsize # Number of batches per iteration
costhistory
betahistory
for itr in rangeiterations:
# Shuffle data
permutation nprandom.permutationN
Xshuffled Xpermutation
yshuffled ypermutation
for b in rangeB:
# Create minibatch
start b batchsize
end start batchsize
Xb Xshuffledstart:end
yb yshuffledstart:end
# Compute the prediction
ypred npdotXb beta
# Compute the gradient
gradient npdotXbTyb ypred batchsize
# Update the parameters
beta learningrate gradient
# Record cost and beta at each iteration
cost npsumy npdotX beta
costhistory.appendcost
betahistory.appendbetacopy
return beta, costhistory, betahistory
finalbeta, costhistory, betahistory minibatchgradientdescentX y beta
betahistory nparraybetahistory
pltfigurefigsize
for i in rangebetahistory.shape:
pltplotbetahistory: i labelf'Beta i
pltxlabelIteration
pltylabelBeta Coefficients'
plttitleEffect of Iterations on Beta Coefficients'
pltlegend
pltshow
pltfigurefigsize
pltplotcosthistory
pltxlabelIteration
pltylabelCost
plttitleEffect of Iterations on Cost'
pltshow
printBestfit model parameters:", finalbeta
mse npmeany npdotX finalbeta
printMean Squared Error on training set:", mse
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
