forked from dingo-actual/dropgrad
-
Notifications
You must be signed in to change notification settings - Fork 0
/
basic_usage.py
51 lines (41 loc) · 1.28 KB
/
basic_usage.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import torch
import torch.nn as nn
import torch.optim as optim
from dropgrad import DropGrad
# Define a simple neural network
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(10, 20)
self.fc2 = nn.Linear(20, 5)
self.relu = nn.ReLU()
def forward(self, x):
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
return x
# Create an instance of the network
net = Net()
# Define the loss function and optimizer
criterion = nn.MSELoss()
optimizer = optim.Adam(net.parameters(), lr=0.001)
# Wrap the optimizer with DropGrad
drop_rate = 0.1
dropgrad_optimizer = DropGrad(optimizer, drop_rate=drop_rate)
# Training loop
num_epochs = 10
batch_size = 32
for epoch in range(num_epochs):
for i in range(100):
# Generate random input and target data
inputs = torch.randn(batch_size, 10)
targets = torch.randn(batch_size, 5)
# Forward pass
outputs = net(inputs)
loss = criterion(outputs, targets)
# Backward pass and optimization
dropgrad_optimizer.zero_grad()
loss.backward()
dropgrad_optimizer.step()
# Print the average loss for every epoch
print(f"Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}")