Question

import pandas as pd import numpy as np import matplotlib.pyplot as plt mtcars = pd.read_csv("mtcars.csv", index_col...

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt 
mtcars = pd.read_csv("mtcars.csv", index_col = 0)
mtcars
x = mtcars["hp"]
y = mtcars["mpg"]

plt.plot(x,y,"*")
plt.grid(True)
plt.xlabel("Horse Power")
plt.ylabel("Miles per Gallon")
plt.show()
def standardize(x):
    return (x-x.mean())/x.std(), x.mean(), x.std()

x, muX, stdX = standardize(x)
y, muY, stdY = standardize(y)
if len(x.shape) == 1: 
    num_var = 1
else:
    num_var = x.shape[1]
beta0 = np.random.rand()
beta1 = np.random.rand()


def predict(x, beta0, beta1):
    return beta0 + beta1*x

def loss(y, ypred):
    return np.mean((y-ypred)**2)/2

def gradient(y, ypred,x):
    grad_beta0 = np.mean((ypred-y)*1)
    grad_beta1 = np.mean((ypred-y)*x)
    
    return grad_beta0, grad_beta1

def update_param(beta0, beta1, grad_beta0, grad_beta1, alpha):
    new_beta0 = beta0 - alpha*grad_beta0
    new_beta1 = beta1 - alpha*grad_beta1
    
    return new_beta0, new_beta1
num_iter = 1000
alpha = 0.01

J_list = []

print(beta0)
print(beta1)

for i in range(num_iter):
    ypred = predict(x, beta0, beta1)
    J = loss(y,ypred)
    J_list.append(J)
    
    grad_beta0, grad_beta1 = gradient(y,ypred,x)
    beta0, beta1 = update_param(beta0,beta1,grad_beta0, grad_beta1, alpha)

print(beta0)
print(beta1)
plt.plot(J_list)
plt.show()
plt.plot(x,y,"*")
plt.grid(True)
plt.xlabel("Horse Power")
plt.ylabel("Miles per Gallon")

plt.plot(x,ypred,"-ro")

plt.show()
x = mtcars[["hp","disp"]]
y = mtcars["mpg"]

x.head()
def standardize(x):
    return (x-x.mean())/x.std(), x.mean(), x.std()

x, muX, stdX = standardize(x)
y, muY, stdY = standardize(y)

if len(x.shape) == 1: 
    num_var = 1
else:
    num_var = x.shape[1]
    
beta0 = np.random.rand()
beta = np.random.rand(num_var)


def predict(x, beta0, beta):
    return beta0 + beta[0]*x.iloc[:,0] + beta[1]*x.iloc[:,1] # np.multiply, sum

def loss(y, ypred):
    return np.mean((y-ypred)**2)/2

def gradient(y, ypred,x, num_var):
    grad_beta0 = np.mean((ypred-y)*1)
    
    grad_beta = np.zeros(num_var)
    
    grad_beta[0] = np.mean((ypred-y)*x.iloc[:,0])
    grad_beta[1] = np.mean((ypred-y)*x.iloc[:,1])
    
    return grad_beta0, grad_beta

def update_param(beta0, beta, grad_beta0, grad_beta, alpha):
    new_beta0 = beta0 - alpha*grad_beta0
    
    new_beta = np.zeros(len(beta))
    
    new_beta[0] = beta[0] - alpha*grad_beta[0]
    new_beta[1] = beta[1] - alpha*grad_beta[1]
    
    return new_beta0, new_beta
num_iter = 2000
alpha = 0.01

J_list = []

for i in range(num_iter):
    ypred = predict(x, beta0, beta)
    J = loss(y,ypred)
    J_list.append(J)
    
    grad_beta0, grad_beta = gradient(y,ypred,x,num_var)
    beta0, beta = update_param(beta0,beta,grad_beta0, grad_beta, alpha)

print(beta0)
print(beta)
plt.plot(J_list)
plt.show()

PYTHON-

the  file, it is shown how to find the values of the parameters of Linear Regression for mtcars data in case of "one and two independent variables (input variables)" using the Gradient Descent algorithm. You are asked to make the algorithm work for k arguments here. In other words, instead of using a separate piece of code for a variable and a separate piece of code for 2 variables, the necessary calculations can be made with a single piece of code in both (1 and 2 are given here as examples).
You can prepare by making the necessary changes on the "the code" file.

Homework Answers

Answer #1

Information on Gradient Descent Algorithm can be found here at:

https://machinelearningmastery.com/gradient-descent-for-machine-learning/

Answers below points:

  • What is gradient descent?
  • How can gradient descent be used in algorithms like linear regression?
  • How can gradient descent scale to very large datasets?
  • What are some tips for getting the most from gradient descent?

Below code can be useful, it is in C++. This shall be helpful.

int k = 0;
for (int j = 0; j < 100; j++) { // Added to get the right value.
k = 0;
while (k < 10) {
for (int i = 0; i < 3; i++){
b[i] = b[i] + alpha * (y[k] – prediction) * prediction * (1 – prediction)* x[k][i];
cout << b[i]<<"\n";
}
k++;
output = 0;
for (int i = 0; i < 3; i++)
output += b[i] * x[k][i];

prediction = 1 / (1 + exp(-output));
}

}

Know the answer?
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
Similar Questions
# Parts to be completed are marked with '<<<<< COMPLETE' import random N = 8 MAXSTEPS...
# Parts to be completed are marked with '<<<<< COMPLETE' import random N = 8 MAXSTEPS = 5000 # generates a random n-queens board # representation: a list of length n the value at index i is # row that contains the ith queen; # exampe for 4-queens: [0,2,0,3] means that the queen in column 0 is # sitting in row 0, the queen in colum 1 is in row, the queen in column 2 # is in row 0,...
from typing import List def longest_chain(submatrix: List[int]) -> int: """ Given a list of integers, return...
from typing import List def longest_chain(submatrix: List[int]) -> int: """ Given a list of integers, return the length of the longest chain of 1's that start from the beginning. You MUST use a while loop for this! We will check. >>> longest_chain([1, 1, 0]) 2 >>> longest_chain([0, 1, 1]) 0 >>> longest_chain([1, 0, 1]) 1 """ i = 0 a = [] while i < len(submatrix) and submatrix[i] != 0: a.append(submatrix[i]) i += 1 return sum(a) def largest_rectangle_at_position(matrix: List[List[int]], x:...
Python Blackjack Game Here are some special cases to consider. If the Dealer goes over 21,...
Python Blackjack Game Here are some special cases to consider. If the Dealer goes over 21, all players who are still standing win. But the players that are not standing have already lost. If the Dealer does not go over 21 but stands on say 19 points then all players having points greater than 19 win. All players having points less than 19 lose. All players having points equal to 19 tie. The program should stop asking to hit if...
convert this code to accept int value instead of float values using python. Make sure to...
convert this code to accept int value instead of float values using python. Make sure to follow the same code. do not change the steps and make sure to point to what code you replaced. make sure to have 2 files Method:----------------------- #define a python user difined method def get_float_val (prompt): is_num = False str_val = input (prompt) #prming read for our while #while is_num == False: (ignore this but it works) old school while not is_num: try: value =...
Program will allow anywhere between 1 and 6 players (inclusive). Here is what your output will...
Program will allow anywhere between 1 and 6 players (inclusive). Here is what your output will look like: Enter number of players: 2 Player 1: 7S 5D - 12 points Player 2: 4H JC - 14 points Dealer: 10D Player 1, do you want to hit? [y / n]: y Player 1: 7S 5D 8H - 20 points Player 1, do you want to hit? [y / n]: n Player 2, do you want to hit? [y / n]: y...
So, i have this code in python that i'm running. The input file is named input2.txt...
So, i have this code in python that i'm running. The input file is named input2.txt and looks like 1.8 4.5 1.1 2.1 9.8 7.6 11.32 3.2 0.5 6.5 The output2.txt is what i'm trying to achieve but when the code runs is comes up blank The output doc is created and the code doesn't error out. it should look like this Sample Program Output 70 - 510, [semester] [year] NAME: [put your name here] PROGRAMMING ASSIGN MENT #2 Enter...
write a code in python Write the following functions below based on their comments. Note Pass...
write a code in python Write the following functions below based on their comments. Note Pass is a key word you can use to have a function the does not do anything. You are only allowed to use what was discussed in the lectures, labs and assignments, and there is no need to import any libraries. #!/usr/bin/python3 #(1 Mark) This function will take in a string of digits and check to see if all the digits in the string are...
convert to python 3 from python 2 from Tkinter import * # the blueprint for a...
convert to python 3 from python 2 from Tkinter import * # the blueprint for a room class Room(object): # the constructor def __init__(self,name,image): # rooms have a name, exits (e.g., south), exit locations (e.g., to the south is room n), # items (e.g., table), item descriptions (for each item), and grabbables (things that can # be taken and put into the inventory) self.name = name self.image = image self.exits = {} self.items = {} self.grabbables = [] # getters...