Upload 1134_252_159.py
Browse files- 1134_252_159.py +62 -0
1134_252_159.py
ADDED
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
"""1134.252.159
|
3 |
+
|
4 |
+
Automatically generated by Colab.
|
5 |
+
|
6 |
+
Original file is located at
|
7 |
+
https://colab.research.google.com/drive/1Y4HZHRme1jvjdQROi8EQ1S0PdzDBeh9K
|
8 |
+
"""
|
9 |
+
|
10 |
+
!pip install torch torchvision numpy opencv-python
|
11 |
+
|
12 |
+
from torchvision import datasets, transforms
|
13 |
+
|
14 |
+
transform = transforms.Compose([
|
15 |
+
transforms.Resize((128, 128)),
|
16 |
+
transforms.ToTensor(),
|
17 |
+
transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
|
18 |
+
])
|
19 |
+
|
20 |
+
# Insert your 'path_to_train_data'
|
21 |
+
train_dataset = datasets.ImageFolder(root='path_to_train_data', transform=transform)
|
22 |
+
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=32, shuffle=True)
|
23 |
+
|
24 |
+
import torch.nn as nn
|
25 |
+
import torchvision.models as models
|
26 |
+
|
27 |
+
model = models.resnet18(pretrained=True)
|
28 |
+
num_features = model.fc.in_features
|
29 |
+
model.fc = nn.Linear(num_features, num_classes) # num_classes should be the number of individuals in your dataset
|
30 |
+
|
31 |
+
import torch.optim as optim
|
32 |
+
|
33 |
+
criterion = nn.CrossEntropyLoss()
|
34 |
+
optimizer = optim.Adam(model.parameters(), lr=0.001)
|
35 |
+
|
36 |
+
for epoch in range(num_epochs):
|
37 |
+
for inputs, labels in train_loader:
|
38 |
+
optimizer.zero_grad()
|
39 |
+
outputs = model(inputs)
|
40 |
+
loss = criterion(outputs, labels)
|
41 |
+
loss.backward()
|
42 |
+
optimizer.step()
|
43 |
+
|
44 |
+
model.eval()
|
45 |
+
correct = 0
|
46 |
+
total = 0
|
47 |
+
with torch.no_grad():
|
48 |
+
for inputs, labels in test_loader:
|
49 |
+
outputs = model(inputs)
|
50 |
+
_, predicted = torch.max(outputs.data, 1)
|
51 |
+
total += labels.size(0)
|
52 |
+
correct += (predicted == labels).sum().item()
|
53 |
+
|
54 |
+
accuracy = 100 * correct / total
|
55 |
+
print(f'Accuracy: {accuracy}%')
|
56 |
+
|
57 |
+
model.eval()
|
58 |
+
img = Image.open('path_to_image')
|
59 |
+
img = transform(img).unsqueeze(0) # Add batch dimension
|
60 |
+
output = model(img)
|
61 |
+
_, predicted = torch.max(output, 1)
|
62 |
+
print(f'Predicted Class: {predicted.item()}')
|