author: Juma Shafara date: "2024-08-12" title: Softmax Classifer 1D keywords: [Training Two Parameter, Mini-Batch Gradient Decent, Training Two Parameter Mini-Batch Gradient Decent] description: How to create complex Neural Network in pytorch.

Objective
- How to create complex Neural Network in pytorch.
Table of Contents
Estimated Time Needed: 25 min
Preparation
We'll need to import the following libraries for this lab.
Define the plotting functions.
def PlotStuff(X,Y,model=None,leg=False):
plt.plot(X[Y==0].numpy(),Y[Y==0].numpy(),'or',label='training points y=0 ' )
plt.plot(X[Y==1].numpy(),Y[Y==1].numpy(),'ob',label='training points y=1 ' )
if model!=None:
plt.plot(X.numpy(),model(X).detach().numpy(),label='neral network ')
plt.legend()
plt.show()
Get Our Data
Define the class to get our dataset.
class Data(Dataset):
def __init__(self):
self.x=torch.linspace(-20, 20, 100).view(-1,1)
self.y=torch.zeros(self.x.shape[0])
self.y[(self.x[:,0]>-10)& (self.x[:,0]<-5)]=1
self.y[(self.x[:,0]>5)& (self.x[:,0]<10)]=1
self.y=self.y.view(-1,1)
self.len=self.x.shape[0]
def __getitem__(self,index):
return self.x[index],self.y[index]
def __len__(self):
return self.len
Define the Neural Network, Optimizer and Train the Model
Define the class for creating our model.
Create the function to train our model, which accumulate lost for each iteration to obtain the cost.
def train(data_set,model,criterion, train_loader, optimizer, epochs=5,plot_number=10):
cost=[]
for epoch in range(epochs):
total=0
for x,y in train_loader:
optimizer.zero_grad()
yhat=model(x)
loss=criterion(yhat,y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
total+=loss.item()
if epoch%plot_number==0:
PlotStuff(data_set.x,data_set.y,model)
cost.append(total)
plt.figure()
plt.plot(cost)
plt.xlabel('epoch')
plt.ylabel('cost')
plt.show()
return cost
Create our model with 9 neurons in the hidden layer. And then create a BCE loss and an Adam optimizer.
this is for exercises
model= torch.nn.Sequential( torch.nn.Linear(1, 6), torch.nn.Sigmoid(), torch.nn.Linear(6,1), torch.nn.Sigmoid()
)