# Design model using Class classLinearModel(torch.nn.Module): def__init__(self): super(LinearModel,self).__init__() self.linear = torch.nn.Linear(1,1) # Class nn.Linear contains two members Tensors: Weight and Bias
defforward(self,x): y_pred = self.linear(x) return y_pred model = LinearModel()
# Construct loss and optimizer criterion = torch.nn.MSELoss(size_average=False,reduce=True) optimizer = torch.optim.SGD(model.parameters(),lr=0.01)
# Training cycle for epoch inrange(1000): y_pred = model(x_data) loss = criterion(y_pred,y_data) # forward print(epoch,loss.item())
# Design model using Class classLogisticRegressionModel(torch.nn.Module): def__init__(self): super(LogisticRegressionModel,self).__init__() self.linear = torch.nn.Linear(1,1)
defforward(self,x): y_pred = F.sigmoid(self.linear(x)) return y_pred model = LogisticRegressionModel()
# Construct loss and optimizer criterion = torch.nn.BCELoss(size_average=False,reduce=True) optimizer = torch.optim.SGD(model.parameters(),lr=0.01)
# Training cycle for epoch inrange(1000): y_pred = model(x_data) loss = criterion(y_pred,y_data) # forward print(epoch,loss.item())
x = np.linspace(0,10,200) x_t = torch.Tensor(x).view((200,1)) y_t = model(x_t) y = y_t.data.numpy() plt.plot(x,y) plt.plot([0,10],[0.5,0.5],c='r') plt.xlabel('Hours') plt.ylabel('Probability of Pass') plt.grid() plt.show()
Multiple Dimension
A variable is called a Feature.
8-tensor as an example.
change dimension:
1 2 3 4 5 6 7 8 9 10 11 12
classModel(torch.nn.Module): def__init__(self): super(Model.self).__init__() self.linear1 = torch.nn.Linear(8,6) self.linear2 = torch.nn.Linear(6,2) self.linear3 = torch.nn.Linear(2,1) self.sigmoid= torch.nn.Sigmoid() defforward(self,x): x = self.sigmoid(self.linear1(x)) x = self.sigmoid(self.linear2(x)) x = self.sigmoid(self.linear3(x))
Dataset and DataLoader
1 2 3 4
# Training cycle for epoch inrange(training_epochs):\ # Loop over all batches for i inrange(total_batch):
Epoch: One forward pass and one backward pas of all the training examples.
Batch-Size: The number of training examples in one forward backward pass.
Iteration: Number of passes, each pass using [batch-size] number of examples.
import torch from torchvision import transforms from torchvision import datasets from torch.utils.data import DataLoader import torch.nn.functional as F import torch.optim as optim
batch_size = 64 transform = transforms.Compose([ transforms.ToTensor(), # Convert the Pillow Image to Tensor transforms.Normalize((0.1307,),(0.3081,)) # mean and std:to N(0,1) ])
defforward(self,x): # use ReLU x = x.view(-1,784) # change shape x = F.relu(self.l1(x)) x = F.relu(self.l2(x)) x = F.relu(self.l3(x)) x = F.relu(self.l4(x)) returnself.l5(x)
deftest(): correct = 0 total = 0 with torch.no_grad(): for data in test_loader: images,labels = data outputs = model(images) _,predicted = torch.max(outputs.data,dim=1) total += labels.size(0) correct += (predicted == labels).sum().item() print('Accuracy on test set: %d %%' %(100*correct/total))
if __name__ == '__main__': for epoch inrange(10): train(epoch) test()
Convert the Pillow Image to Tensor:Z28×28,pixel∈0,...,255→R1×28×28,pixle∈[0,1]