Last active
June 16, 2022 14:35
-
-
Save twobob/4be2d380bc98b5828f48e3d7540c1a75 to your computer and use it in GitHub Desktop.
GPT-3 Code modification: plot w1_vals, w2_vals using plt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#write the code for an efficient and modular, reentrant, Stochastic gradient descent in python for any set of two unknown float inputs. output the results in matlab graph format and as an Open Office Spreadsheet. | |
import numpy as np | |
import matplotlib.pyplot as plt | |
%matplotlib inline | |
def sgd(w1, w2, eta, n_iter): | |
""" | |
Performs stochastic gradient descent (SGD) using two unknown float inputs. | |
Parameters | |
---------- | |
w1 : float | |
First weight. | |
w2 : float | |
Second weight. | |
eta : float | |
Learning rate. | |
n_iter : int | |
Number of iterations. | |
Returns | |
------- | |
w1_vals : list | |
Values of w1 across iterations. | |
w2_vals : list | |
Values of w2 across iterations. | |
""" | |
# Initialize lists to store weights | |
w1_vals = [] | |
w2_vals = [] | |
# Iterate for n_iter | |
for i in range(n_iter): | |
# Calculate current prediction | |
pred = w1 * x1 + w2 * x2 | |
# Calculate current error | |
error = pred - y | |
# Update weights | |
w1 = w1 - eta * error * x1 | |
w2 = w2 - eta * error * x2 | |
# Store weights | |
w1_vals.append(w1) | |
w2_vals.append(w2) | |
return w1_vals, w2_vals | |
# Instantiate inputs x1 and x2 | |
x1 = 0.5 | |
x2 = 0.5 | |
# Instantiate output y | |
y = 1.0 | |
# Set learning rate and number of iterations | |
eta = 0.05 | |
n_iter = 1000 | |
# Calculate w1_vals and w2_vals using sgd | |
w1_vals, w2_vals = sgd(x1, x2, eta, n_iter) | |
# Extract each element of w1_vals as a separate list | |
w1_vals = [val[0] for val in w1_vals] | |
# Extract each element of w2_vals as a separate list | |
w2_vals = [val[1] for val in w2_vals] | |
# Create shapefile of closed curves from the list of lists of point x and y coordinates | |
plt.plot(w1_vals, w2_vals) | |
# Show plot | |
plt.show() | |
# END CODE | |
end = time() | |
print ("------------------------", (end-start)/60, " minutes-----------------------------", (end-start)/60/60, " hours") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment