Question

def gradient_descent(feature_matrix, label, learning_rate = 0.05, epoch = 1000):
"""
Implement gradient descent algorithm for regression.
  
Args:
feature_matrix - A numpy matrix describing the given data, with ones added as the first column. Each row
represents a single data point.
  
label - The correct value of response variable, corresponding to feature_matrix.
  
learning_rate - the learning rate with default value 0.5
  
epoch - the number of iterations with default value 1000

Returns: A numpy array for the final value of theta
"""
n = len(label)
theta = np.zeros(feature_matrix.shape[1]) # initialize theta to be zero vector
for i in range(epoch):
# your code below
# compute (average) gradient below

# update theta below
  
# compute the value of cost function
# It is not necessary to comput cost here. But it is common to use cost
# in the termination condition of the loop

  
# your code above
# test
# print(i, theta, cost)
  
return theta
raise NotImplementedError= 0.05, epoch = 1000): def gradient_descent (feature_matrix, label, learning_rate Implement gradient descent algorithm for re

0 0
Add a comment Improve this question Transcribed image text
Answer #1

import numpy as np

x=np.array([2104,1600,2400,1416,3000,1985,1534])          #feature matrix

mean=x.mean()

std=x.std()

x=(x-mean)/std

x=np.c_[np.ones(np.size(x)),x]                          #adding 1 in the first column

y=np.array([400,330,369,232,540,300,315])

alpha=0.01                                              #learning rate

m=len(y)

theta=np.random.rand(2)

def Grad_dec(x,y,m,alpha,theta):

    for i in range(1000):

        p=np.dot(x,theta)

        error=p-y

        cost=sum(error**2)/(2*m)

        

        theta=theta-(alpha/m)*np.dot(x.T,error)

    return cost,theta

cost,theta=Grad_dec(x,y,m,alpha,theta)

print(theta)

test_data=int(input('Enter test value:'))

test_data=(test_data-mean)/std

test_data=np.array([1,test_data])

print(round(np.dot(test_data.T,theta),4))

File Edit Selection View Go Run Terminal Help .p4.py - HTML1 - Visual Studio Code х EXPLORER e amir5.py e p1.py p4.py sales.t

Add a comment
Know the answer?
Add Answer to:
def gradient_descent(feature_matrix, label, learning_rate = 0.05, epoch = 1000): """ Implement gradient descent algorithm for regression....
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT