You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# single layer NNimporttorchdefactivation(x):
""" Sigmoid activation function Arguments --------- x: torch.Tensor """return1/(1+torch.exp(-x))
### Generate some datatorch.manual_seed(7) # Set the random seed so things are predictable# Features are 3 random normal variablesfeatures=torch.randn((1, 5))
print("features ", features)
# True weights for our data, random normal variables againweights=torch.randn_like(features)
print("weights ", weights)
# and a true bias termbias=torch.randn((1, 1))
## Calculate the output of this network using matrix multiplicationdefoutput(features, weights, bias):
transposedWeight=weights.view(5,1)
mm=torch.mm(features, transposedWeight) # matrix multh=mm+biasreturnactivation(h)
# y = activation(torch.mm(features, weights.view(5,1) + bias))print(output(features, weights, bias))
Defining the Network using class
fromtorchimportnnimporttorch.nn.functionalasFclassNetwork(nn.Module):
def__init__(self):
super().__init__()
# Inputs to hidden layer linear transformationself.hidden=nn.Linear(784, 256)
# Output layer, 10 units - one for each digitself.output=nn.Linear(256, 10)
defforward(self, x):
# Hidden layer with sigmoid activationx=F.sigmoid(self.hidden(x))
# Output layer with softmax activationx=F.softmax(self.output(x), dim=1)
returnx
Training
fromtorchimportoptimmodel=nn.Sequential(nn.Linear(784, 128),
nn.ReLU(),
nn.Linear(128, 64),
nn.ReLU(),
nn.Linear(64, 10),
nn.LogSoftmax(dim=1))
criterion=nn.NLLLoss()
optimizer=optim.SGD(model.parameters(), lr=0.003)
epochs=5foreinrange(epochs):
running_loss=0forimages, labelsintrainloader:
# Flatten MNIST images into a 784 long vectorimages=images.view(images.shape[0], -1)
# TODO: Training passoptimizer.zero_grad()
output=model.forward(images)
loss=criterion(output, labels)
loss.backward()
optimizer.step()
running_loss+=loss.item()
else:
print(f"Training loss: {running_loss/len(trainloader)}")
%matplotlibinlineimporthelperimages, labels=next(iter(trainloader))
img=images[0].view(1, 784)
# Turn off gradients to speed up this partwithtorch.no_grad():
logits=model.forward(img)
# Output of the network are logits, need to take softmax for probabilitiesps=F.softmax(logits, dim=1)
helper.view_classify(img.view(1, 28, 28), ps)