Introduction
We define a model class to create a reusable and clear structure for our machine learning model. This helps us organize layers and how data flows through them.
import torch.nn as nn class ModelName(nn.Module): def __init__(self): super(ModelName, self).__init__() # Define layers here def forward(self, x): # Define data flow here return x
import torch.nn as nn class SimpleNN(nn.Module): def __init__(self): super(SimpleNN, self).__init__() self.linear = nn.Linear(10, 5) def forward(self, x): return self.linear(x)
import torch.nn as nn import torch.nn.functional as F class TwoLayerNN(nn.Module): def __init__(self): super(TwoLayerNN, self).__init__() self.layer1 = nn.Linear(8, 4) self.layer2 = nn.Linear(4, 2) def forward(self, x): x = self.layer1(x) x = F.relu(x) x = self.layer2(x) return x
import torch import torch.nn as nn import torch.nn.functional as F class SimpleModel(nn.Module): def __init__(self): super(SimpleModel, self).__init__() self.fc1 = nn.Linear(3, 2) def forward(self, x): x = self.fc1(x) return F.softmax(x, dim=1) # Create model instance model = SimpleModel() # Sample input tensor with batch size 2 and 3 features input_tensor = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) # Get model output output = model(input_tensor) print(output)
class MyModel(nn.Module):.print(model(torch.tensor([[1.0, 2.0]]))) output?
import torch
import torch.nn as nn
class SimpleModel(nn.Module):
def __init__(self):
super().__init__()
self.linear = nn.Linear(2, 1)
def forward(self, x):
return self.linear(x)
model = SimpleModel()
with torch.no_grad():
model.linear.weight.fill_(1.0)
model.linear.bias.fill_(0.0)import torch.nn as nn
class BadModel(nn.Module):
def __init__(self):
self.linear = nn.Linear(3, 1)
def forward(self, x):
return self.linear(x)super().__init__() to initialize the base nn.Module class.Pass the test and this pattern moves unknown