Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torchvision
|
3 |
+
import torchvision.transforms as transforms
|
4 |
+
import torch.nn as nn
|
5 |
+
import torch.optim as optim
|
6 |
+
|
7 |
+
# κΈ°λ³Έ λͺ¨λΈ λ‘λ
|
8 |
+
base_model = torchvision.models.vqa_resnet_finetune(pretrained=True)
|
9 |
+
|
10 |
+
# OK-VQA λ°μ΄ν°μ
λ‘λ λ° μ μ²λ¦¬
|
11 |
+
# (μ¬κΈ°μμλ λ°μ΄ν°λ₯Ό λ‘λνλ μ½λμ μ μ²λ¦¬ κ³Όμ μ κ°λ΅νκ² ννν©λλ€)
|
12 |
+
|
13 |
+
train_dataset = OKVQADataset('train_data.json', transform=transforms.Compose([transforms.Resize((224, 224)), transforms.ToTensor()]))
|
14 |
+
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=32, shuffle=True)
|
15 |
+
|
16 |
+
# μλ‘μ΄ λ μ΄μ΄ μΆκ°
|
17 |
+
num_classes = len(train_dataset.classes) # μμμμλ λ°μ΄ν°μ
μ ν΄λμ€ μλ₯Ό μ¬μ©
|
18 |
+
base_model.fc = nn.Linear(base_model.fc.in_features, num_classes)
|
19 |
+
|
20 |
+
# GPU μ¬μ© κ°λ₯ μ GPUλ‘ λͺ¨λΈ μ΄λ
|
21 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
22 |
+
base_model = base_model.to(device)
|
23 |
+
|
24 |
+
# Loss λ° Optimizer μ μ
|
25 |
+
criterion = nn.CrossEntropyLoss()
|
26 |
+
optimizer = optim.Adam(base_model.parameters(), lr=0.001)
|
27 |
+
|
28 |
+
# Fine-tuning
|
29 |
+
num_epochs = 10
|
30 |
+
for epoch in range(num_epochs):
|
31 |
+
for inputs, labels in train_loader:
|
32 |
+
inputs, labels = inputs.to(device), labels.to(device)
|
33 |
+
|
34 |
+
optimizer.zero_grad()
|
35 |
+
outputs = base_model(inputs)
|
36 |
+
loss = criterion(outputs, labels)
|
37 |
+
loss.backward()
|
38 |
+
optimizer.step()
|
39 |
+
|
40 |
+
print(f'Epoch {epoch+1}/{num_epochs}, Loss: {loss.item()}')
|
41 |
+
torch.save(base_model.state_dict(), 'git-vqa-finetuned-on-ok-vqa.pth')
|