Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Machine learning question, use jupyter lab, no AI plz: Import this: import sys from packaging import version import sklearn import matplotlib.pyplot as plt import numpy

Machine learning question, use jupyter lab, no AI plz:
Import this:
import sys
from packaging import version
import sklearn
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from sklearn.preprocessing import add_dummy_feature
from sklearn.datasets import make_blobs
from sklearn import metrics #Import scikit-learn metrics module for accuracy calculation
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
print("Sklearn package",sys.version_info)
print("Sklearn package",sklearn.__version__)
print("TensorFlow version:", tf.__version__)
assert sys.version_info >=(3,7)
assert version.parse(sklearn.__version__)>= version.parse("1.0.1")
plt.rc('font', size=12)
plt.rc('axes', labelsize=14, titlesize=14)
plt.rc('legend', fontsize=14)
plt.rc('xtick', labelsize=10)
plt.rc('ytick', labelsize=10)
----
Questions:
7. Q5- Constructing three layer neural network for binary classification.
7.0.1. Modify the two layer network for binary classification from the tutorial. The new code should have two hidden layers.
def sigmoid(x):
return 1/(1+ np.exp(-x))
#Calculating the loss function.
def cross_entropy(preds, labels):
return -np.sum(labels * np.log(preds)+(1- labels)* np.log(1- preds))
#return -np.mean(labels * np.log(preds)+(1- labels)* np.log(1- preds))
#Write your code here
class ThreeLayersBinaryClassifier():
def __init__(self, input_size, hidden1_size, hidden2_size, output_size, lr=1e-4):
"""
Initialize the model. Weights are initialized to random values.
w1: First layer weights; has shape (input_size, hidden_size)
w2: Second layer weights; has shape (hidden_size, output_size)
Inputs:
- input_size: The dimension D of the input data.
- hidden2_size: The number of neurons in the first hidden layer.
- hidden2_size: The number of neurons in the second hidden layer.
- output_size: The number of classes C.
"""
# reset seed before start
np.random.seed(1)
#initialize self.w1, self.w2, selfw3
#Give X, a matrix with N by D dimensions
#Calculate y_pred, N by 1
def predict(self, X):
#calculate z1 from X and W1 and calculate h1 from sigmoid(z1)
#calculate z2 from h1 and W2 and calculate h2 from sigmoid(z2)
#calculate z3 from h2 and W3 and calculate y_pred from sigmoid(z3)
y_pred = None
return(y_pred)
def forward_backward(self, X, y):
loss =0
grad_w1= None
grad_w2= None
grad_w3= None
#
return(loss, grad_w1, grad_w2, grad_w3)
def train(self, X_train, y_train, learning_rate=1e-4, epochs=1000):
loss_history =[]
for iter in range(epochs):
print(iter)
#get loss and grad_1,grad_2, grad_3 from the forward_backward method
#update self.w1,self.w2,self.w3
#loss_history.append(loss)
return (loss_history)
#Testing the three layers network
N, D_in, H1, H2, D_out =200,2,100,50,1
np.random.seed(42) # to make this code example reproducible
class_centers = np.array([[1.8,3.5],[4.2,6]])
X, y = make_blobs(n_samples = N, centers = class_centers, n_features = D_in,random_state=42)
y = y.reshape((N,1))
print("X.shape=", X.shape, "y.shape=",y.shape)
plt.scatter(X[:,0], X[:,1], c=y)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle=False)
epochs =1000
learning_rate =0.01
print(D_in, H1, H2, D_out, learning_rate)
clf = ThreeLayersBinaryClassifier(D_in, H1, H2, D_out, learning_rate)
loss_path = clf.train(X_train,y_train, learning_rate, epochs)
print("Three Layers Binary Classification")
print("Final Loss",loss_path[-1])
#Print Final Prediction
y_pred = clf.predict(X_test) #It has the updated W1, W2, and W3
y_pred[y_pred>=.5]=1
y_pred[y_pred<.5]=0
print("Testing Accuracy:", metrics.accuracy_score(y_test[:,0], y_pred[:,0]))

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Murach's SQL Server 2012 For Developers

Authors: Bryan Syverson, Joel Murach, Mike Murach

1st Edition

1890774693, 9781890774691

More Books

Students also viewed these Databases questions