KristofGaming39 commited on
Commit
4abf447
1 Parent(s): eebb924

Create codefortraining.py

Browse files
Files changed (1) hide show
  1. codefortraining.py +70 -0
codefortraining.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torchvision
3
+ from torchvision.models import resnet50
4
+ from torchvision.transforms import transforms
5
+ from torch.utils.data import DataLoader, Dataset
6
+
7
+ # Define the dataset class
8
+ class RobloxDataset(Dataset):
9
+ def __init__(self, root_dir, transform=None):
10
+ self.root_dir = root_dir
11
+ self.transform = transform
12
+
13
+ def __len__(self):
14
+ return 200 # Number of images in the dataset, replace with your own to train with your own images.
15
+
16
+ def __getitem__(self, idx):
17
+ img_path = f'{self.root_dir}/human_{str(idx+1).zfill(2)}.png'
18
+ image = Image.open(img_path).convert('RGB')
19
+
20
+ if self.transform:
21
+ image = self.transform(image)
22
+
23
+ return image
24
+
25
+ data_transform = transforms.Compose([
26
+ transforms.Resize((224, 224)),
27
+ transforms.ToTensor(),
28
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
29
+ ])
30
+
31
+ dataset = RobloxDataset('/content/dataset', transform=data_transform)
32
+
33
+ data_loader = DataLoader(dataset, batch_size=1, shuffle=True)
34
+
35
+ model = resnet50(pretrained=True)
36
+ model.fc = torch.nn.Linear(in_features=2048, out_features=1) # Adjust the number of output classes if needed
37
+
38
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
39
+ model.to(device)
40
+
41
+ criterion = torch.nn.BCEWithLogitsLoss()
42
+ optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
43
+
44
+ # Train the model
45
+ num_epochs = 100 # Adjust the number of training epochs (more epochs = more training time but with more accuracy and less loss).
46
+ """ Training the model with more epochs
47
+ Pros:
48
+ - more accuracy
49
+ - less loss (it means the model is improving)
50
+
51
+ Con:
52
+ - more training time
53
+ """
54
+
55
+ for epoch in range(num_epochs):
56
+ for images in data_loader:
57
+ images = images.to(device)
58
+ labels = torch.ones((images.size(0), 1)).to(device) # Assuming all images belong to the same class
59
+
60
+ outputs = model(images)
61
+ loss = criterion(outputs, labels)
62
+
63
+ optimizer.zero_grad()
64
+ loss.backward()
65
+ optimizer.step()
66
+
67
+ print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item()}')
68
+
69
+ # Save the trained model
70
+ torch.save(model.state_dict(), '/content/zero_shot_classification_model.pth')