WMICraft/algorithms/neural_network/neural_network_interface.py

126 lines
4.3 KiB
Python
Raw Normal View History

import torch
2022-05-25 19:47:08 +02:00
import common.helpers
2022-05-26 23:34:46 +02:00
from algorithms.neural_network.neural_network import NeuralNetwork
from algorithms.neural_network.watersandtreegrass import WaterSandTreeGrass
2022-05-25 19:47:08 +02:00
from common.constants import DEVICE, BATCH_SIZE, NUM_EPOCHS, LEARNING_RATE, SETUP_PHOTOS, ID_TO_CLASS
from torch.utils.data import DataLoader
from torchvision.io import read_image, ImageReadMode
import torch.nn as nn
from torch.optim import Adam
2022-05-18 12:18:59 +02:00
import matplotlib.pyplot as plt
2022-05-25 19:47:08 +02:00
import pytorch_lightning as pl
from pytorch_lightning.callbacks import EarlyStopping
def train(model):
2022-05-25 19:47:08 +02:00
model = model.to(DEVICE)
model.train()
2022-05-25 19:47:08 +02:00
trainset = WaterSandTreeGrass('./data/train_csv_file.csv', transform=SETUP_PHOTOS)
testset = WaterSandTreeGrass('./data/test_csv_file.csv', transform=SETUP_PHOTOS)
train_loader = DataLoader(trainset, batch_size=BATCH_SIZE, shuffle=True)
test_loader = DataLoader(testset, batch_size=BATCH_SIZE, shuffle=True)
criterion = nn.CrossEntropyLoss()
2022-05-25 19:47:08 +02:00
optimizer = Adam(model.parameters(), lr=LEARNING_RATE)
2022-05-25 19:47:08 +02:00
for epoch in range(NUM_EPOCHS):
for batch_idx, (data, targets) in enumerate(train_loader):
2022-05-25 19:47:08 +02:00
data = data.to(device=DEVICE)
targets = targets.to(device=DEVICE)
scores = model(data)
loss = criterion(scores, targets)
optimizer.zero_grad()
loss.backward()
optimizer.step()
2022-05-25 19:47:08 +02:00
if batch_idx % 4 == 0:
2022-05-18 15:44:07 +02:00
print("epoch: %d loss: %.4f" % (epoch, loss.item()))
2022-05-18 15:44:07 +02:00
print("FINISHED TRAINING!")
2022-05-25 19:47:08 +02:00
torch.save(model.state_dict(), "./learnednetwork.pth")
2022-05-18 15:44:07 +02:00
print("Checking accuracy for the train set.")
check_accuracy(train_loader)
2022-05-18 15:44:07 +02:00
print("Checking accuracy for the test set.")
check_accuracy(test_loader)
2022-05-25 19:47:08 +02:00
print("Checking accuracy for the tiles.")
check_accuracy_tiles()
def check_accuracy_tiles():
answer = 0
for i in range(100):
if what_is_it('../../resources/textures/grass_with_tree.jpg') == 'tree':
answer = answer + 1
print("Accuracy(%) grass_with_tree.jpg", answer)
answer = 0
for i in range(100):
if what_is_it('../../resources/textures/grass2.png') == 'grass':
answer = answer + 1
print("Accuracy(%) grass2.png", answer)
answer = 0
for i in range(100):
if what_is_it('../../resources/textures/grass3.png') == 'grass':
answer = answer + 1
print("Accuracy(%) grass3.png", answer)
answer = 0
for i in range(100):
if what_is_it('../../resources/textures/grass4.png') == 'grass':
answer = answer + 1
print("Accuracy(%) grass4.png", answer)
answer = 0
for i in range(100):
if what_is_it('../../resources/textures/grass1.png') == 'grass':
answer = answer + 1
print("Accuracy(%) grass1.png", answer)
answer = 0
for i in range(100):
if what_is_it('../../resources/textures/water.png') == 'water':
answer = answer + 1
print("Accuracy(%) water.png", answer)
answer = 0
for i in range(100):
if what_is_it('../../resources/textures/sand.png') == 'sand':
answer = answer + 1
print("Accuracy(%) sand.png", answer)
2022-05-18 12:18:59 +02:00
def what_is_it(img_path, show_img=False):
image = read_image(img_path, mode=ImageReadMode.RGB)
2022-05-18 12:18:59 +02:00
if show_img:
plt.imshow(plt.imread(img_path))
plt.show()
2022-05-25 19:47:08 +02:00
image = SETUP_PHOTOS(image).unsqueeze(0)
2022-05-26 23:34:46 +02:00
model = NeuralNetwork.load_from_checkpoint('./lightning_logs/version_0/checkpoints/epoch=4-step=405.ckpt')
with torch.no_grad():
model.eval()
idx = int(model(image).argmax(dim=1))
2022-05-25 19:47:08 +02:00
return ID_TO_CLASS[idx]
CNN = NeuralNetwork()
2022-05-26 13:19:17 +02:00
common.helpers.createCSV()
2022-05-25 19:47:08 +02:00
2022-05-26 13:19:17 +02:00
#trainer = pl.Trainer(accelerator='gpu', devices=1, callbacks=[EarlyStopping('val_loss')], max_epochs=NUM_EPOCHS)
trainer = pl.Trainer(accelerator='gpu', devices=1, auto_lr_find=True, max_epochs=NUM_EPOCHS)
2022-05-25 19:47:08 +02:00
trainset = WaterSandTreeGrass('./data/train_csv_file.csv', transform=SETUP_PHOTOS)
testset = WaterSandTreeGrass('./data/test_csv_file.csv', transform=SETUP_PHOTOS)
train_loader = DataLoader(trainset, batch_size=BATCH_SIZE, shuffle=True)
test_loader = DataLoader(testset, batch_size=BATCH_SIZE)
2022-05-26 13:19:17 +02:00
trainer.fit(CNN, train_loader, test_loader)
2022-05-25 19:47:08 +02:00
#trainer.tune(CNN, train_loader, test_loader)
2022-05-26 13:19:17 +02:00
#check_accuracy_tiles()
#print(what_is_it('../../resources/textures/sand.png', True))