import torch

from model import MyNet

# Create the model and load the weights
model = MyNet()
model.load_state_dict(torch.load('my_network.pth'))

# Create dummy input
dummy_input = torch.rand(1, 3, 32, 32)

# Define input / output names
input_names = ["my_input"]
output_names = ["my_output"]

# Convert the PyTorch model to ONNX
torch.onnx.export(model,
                  dummy_input,
                  "my_network.onnx",
                  verbose=True,
                  input_names=input_names,
                  output_names=output_names)
def save(output, fname, out_dir=args.out_dir):
    out_path = os.path.join(dir, fname)


# define model
loadedparams = torch.load(args.model_dir, map_location=args.device)
model = MyNet(3)
if use_cuda:
    model.cuda()
loss_fn = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=args.lr, momentum=0.9)
label_colours = np.random.randint(255, size=(100, 3))
model.eval()

if args.model_dir != '':
    model.load_state_dict(loadedparams['model'], strict=True)
else:
    print('PLEASE LOAD A MODEL_DIR AS AN OPTION')

# main function for testing
if __name__ == '__main__':

    # process a single image
    if args.input != '':
        data = readfile(args.input)
        with torch.no_grad():
            output = model(data)[0]

        print(output)
        quit()
        # visualize predicted output
Beispiel #3
0
    'Over_ink': 'over_ink',
    'Set_off': 'set_off',
    'Under_ink': 'under_ink',
    'Wiping': 'wiping',
}

class_names = ['dot', 'miss_print', 'over_ink', 'set_off', 'under_ink', 'wiping']

# instantiate the CNN
use_cuda = torch.cuda.is_available()
layer_sizes = [512, 256, 128]
model = MyNet(output_size=6, layer_sizes=layer_sizes)
if use_cuda:
    model = model.cuda()

model.load_state_dict(torch.load('model/model_resnet101_512_256_128_back.pt', map_location=torch.device('cpu')))


# ### Get the directory path from the argument

if __name__ == "__main__":
    dir_path = sys.argv[1].strip()
#in put the directory path
#dir_path = input('Enter the images directory path: ').strip()

#print(dir_path)
#delete the output folder if exists
for files in os.listdir(dir_path):
    if files == 'output':
        shutil.rmtree(os.path.join(dir_path, files))
        #shutil.rmtree(os.path.join(os.getcwd()+'/' + dir_path, files))
Beispiel #4
0
def main(args):
    #hyper parameter
    end_epoch = 200
    lr = 0.001
    beta1 = 0.5
    beta2 = 0.99
    gpu = 0

    #set model
    model = MyNet()

    #set GPU or CPU
    if gpu >= 0 and torch.cuda.is_available():
        device = 'cuda:{}'.format(gpu)
    else:
        device = 'cpu'
    model.to(device)
    model.load_state_dict(
        torch.load("models/" + args.model + "/" + str(args.epoch - 1) +
                   ".pth"))
    model.eval()

    criteria = nn.CrossEntropyLoss()

    dataset = MyDataset("data/", is_train=False)
    test_loader = torch.utils.data.DataLoader(dataset,
                                              batch_size=1,
                                              shuffle=True)

    with torch.no_grad():
        epoch_loss = 0
        epoch_acc = 0
        if not os.path.exists("result/" + args.model + "/true_favo/"):
            os.makedirs("result/" + args.model + "/true_favo/")
            os.makedirs("result/" + args.model + "/true_no_favo/")
            os.makedirs("result/" + args.model + "/false_favo/")
            os.makedirs("result/" + args.model + "/false_no_favo/")
        for i, data in enumerate(test_loader):
            print("\riteration: {}".format(i), end="")
            inputs, labels = data
            outputs = model(inputs.to(device))
            _, preds = torch.max(outputs.data, 1)
            loss = criteria(outputs, labels.to(device))

            favo_preds = preds.to('cpu')
            if favo_preds == labels:
                if favo_preds == 1:
                    save_image(
                        inputs, "result/" + args.model + "/true_favo/" +
                        str(i) + ".jpg")
                elif favo_preds == 0:
                    save_image(
                        inputs, "result/" + args.model + "/true_no_favo/" +
                        str(i) + ".jpg")
            else:
                if favo_preds == 1:
                    save_image(
                        inputs, "result/" + args.model + "/false_favo/" +
                        str(i) + ".jpg")
                elif favo_preds == 0:
                    save_image(
                        inputs, "result/" + args.model + "/false_no_favo/" +
                        str(i) + ".jpg")

            epoch_loss += loss.data.to('cpu') * inputs.size(0)
            epoch_acc += torch.sum(favo_preds == labels.data)

        epoch_loss /= len(test_loader)
        epoch_acc = epoch_acc / float(len(test_loader))
        print("[Loss: {}] [Acc: {}]".format(epoch_loss, epoch_acc))
Beispiel #5
0
import torch
from model import MyNet
from dataLoader import DataGetter, Euler2Rot
import numpy as np
from plotting import plotXYZ
from tkinter import filedialog as fd

# data_dir = 'D:/data_odometry_gray/dataset'
data_dir = 'D:/data_odometry_color/dataset'
folder_num = 6
batch_size = 1

model_name = fd.askopenfilename()
model = MyNet()
model.load_state_dict(torch.load(model_name))

getter = DataGetter(data_dir,
                    batch_size,
                    folder_num,
                    folder_num,
                    randomize_data=False)

if torch.cuda.is_available():
    device = 'cuda'
    model.cuda()
else:
    device = 'cpu'
model.eval()

running_R = torch.eye(3, dtype=torch.float)
running_t = torch.zeros((1, 3), dtype=torch.float)