Exemplo n.º 1
0
    def __init__(self, path="mnist_cnn.pt"):
        super(MainWindow, self).__init__()

        self.model = Net()
        self.model.load_state_dict(torch.load(path))

        self.initUI()
Exemplo n.º 2
0
 def __init__(self, labels_path):
     image_shape = [32, 32, 3]
     super(CNNWrapper, self).__init__(image_shape=image_shape,
                                              labels_path=labels_path)
     self.model = Net()
     self.model.load_state_dict(torch.load('./checkpoint/cifar_net_best.pth'))  # 获取模型参数
     self.model_name = 'CNN_public'
Exemplo n.º 3
0
 def __init__(self):
     #load saved parameter values
     vals = torch.load("nets/value.pth", map_location=lambda storage, loc: storage)
     
     #Load the model with saved values
     self.model = Net()
     self.model.load_state_dict(vals)
Exemplo n.º 4
0
    def __init__(self):

        vals = torch.load("nets/value_epoch16.pth",
                          map_location=lambda storage, loc: storage)
        self.model = Net()
        self.model.load_state_dict(vals)
        self.count = 0
Exemplo n.º 5
0
class Old_model_Veluator():
    def __init__(self, prams_path):
        self.net = Net()
        self.net.load_state_dict(
            torch.load(prams_path, map_location=lambda x, loc: x))
        self.net.eval()

    def eval(self, board):
        outputs = {}
        for m in board.legal_moves:
            board.push(m)
            input = torch.unsqueeze(
                torch.from_numpy(State(board).serialize()).float(), 0)
            outputs[m] = self.net(input).data.numpy()[0][0]
            board.pop()
        return outputs

    def play_one_step(self, board, verbose=False):
        qa = v.eval(board)
        # if verbose:
        #     print(qa.values())
        best_m = sorted(qa.items(), key=lambda x: x[1],
                        reverse=board.turn)[0][0]
        san_m = board.san(best_m)
        board.push(best_m)
        if verbose:
            return board, san_m, qa.values()
        else:
            return board, san_m
Exemplo n.º 6
0
 def __init__(self):
     import torch
     from train import Net
     vals = torch.load("nets/value.pth",
                       map_location=lambda storage, loc: storage)
     self.model = Net()
     self.model.load_state_dict(vals)
 def model_initialize(self):
     self.Model = Net(vocab_size=len(self.product_field.vocab.stoi), 
                         embedding_dim=256,
                         nb_category=len(self.category_field.vocab.stoi)-1,
                         nb_ingredients=len(self.ingredients_field.vocab.stoi)-1,
                         lstm_nb_layers=3, 
                         lstm_hidden_dim=256, 
                         fc_out=128, 
                         dropout_p=0.5, ).to(DEVICE)
     print("Model Initialized")
Exemplo n.º 8
0
class Valuator(object):
    def __init__(self):
        vals = torch.load("nets/value.pth", map_location=lambda storage, loc: storage)
        self.model = Net()
        self.model.load_state_dict(vals)

    def __call__(self, s):
        brd = s.serialize()[None]
        output = self.model(torch.tensor(brd).float())
        return float(output.data[0][0])
Exemplo n.º 9
0
class Evaluator():
    def __init__(self):
        self.model = Net()
        self.model.load_state_dict(
            torch.load(f"{MODEL_PATH}/{MODEL_FILE}",
                       map_location=torch.device('cpu')))

    def __call__(self, state):
        board = state.serialize()[None]
        output = self.model(torch.tensor(board).float())
        return output.item()
 def __init__(self, network_path, dataset_path, validation_set):
     self.network_path = network_path
     self.dataset_path = dataset_path
     self.validation_set = validation_set
     self.device =\
         torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
     self.net = Net()
     self.net.to(self.device)
     self.net.load_state_dict(
         torch.load(self.network_path, map_location='cpu'))
     self.net.train(False)
Exemplo n.º 11
0
class Veluator():
    def __init__(self):
        self.net = Net()
        self.net.load_state_dict(torch.load('nets/values.pth',map_location = lambda x,loc:x))
        self.net.eval()
    def eval(self,board):
        outputs = {}
        for m in board.legal_moves:
            board.push(m)
            input =torch.unsqueeze( torch.from_numpy(State(board).serialize()).float(),0)
            outputs[m] =  self.net(input).data.numpy()[0][0]
            board.pop()
        return outputs 
Exemplo n.º 12
0
def test():
    # cpu or gpu?
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    print('using device {}'.format(device))

    # load net
    net = Net()
    net.to(device)
    net.load_state_dict(torch.load('trained_net.pt'))
    net.train(False)

    # sample data
    val_idx = np.load('val_idx.npy')
    val_sampler = SubsetRandomSampler(val_idx)
    pose_dataset = PoseDataset('panoptic_dataset.pickle')
    val_loader = DataLoader(dataset=pose_dataset,
                            batch_size=1,
                            sampler=val_sampler)

    while True:
        data_iter = iter(val_loader)
        skel_2d, skel_z = next(data_iter)
        print(skel_2d)

        # inference
        skel_2d = skel_2d.to(device)
        z_out = net(skel_2d)

        # show
        skel_2d = skel_2d.cpu().numpy()
        skel_2d = skel_2d.reshape((2, -1), order='F')  # [(x,y) x n_joint]
        z_out = z_out.detach().cpu().numpy()
        z_out = z_out.reshape(-1)
        z_gt = skel_z.numpy().reshape(-1)
        show_skeletons(skel_2d, z_out, z_gt)
Exemplo n.º 13
0
def test(path_x, model_path):
    model = Net()
    state_dict = torch.load(model_path)
    model.load_state_dict(state_dict)
    tensor_x = process_image(path_x)
    output = model(tensor_x)
    pred_certainty, pred = torch.max(output, 1)

    predictions = pred.numpy()
    for i in range(0, len(predictions)):
        if pred_certainty[i] < certainty_threshold:
            predictions[i] = -1
    np.save('predicted.npy', predictions)
    return predictions
Exemplo n.º 14
0
class CNNWrapper(PublicImageModelWrapper):

    def __init__(self, labels_path):
        image_shape = [32, 32, 3]
        super(CNNWrapper, self).__init__(image_shape=image_shape,
                                                 labels_path=labels_path)
        self.model = Net()
        self.model.load_state_dict(torch.load('./checkpoint/cifar_net_best.pth'))  # 获取模型参数
        self.model_name = 'CNN_public'

    def forward(self, x):
        return self.model.forward(x)

    def get_cutted_model(self, bottleneck):
        return CNN_cutted(self.model, bottleneck)
Exemplo n.º 15
0
class Valuator:

    def __init__(self):
        #load saved parameter values
        vals = torch.load("nets/value.pth", map_location=lambda storage, loc: storage)
        
        #Load the model with saved values
        self.model = Net()
        self.model.load_state_dict(vals)

    def __call__(self, s):
        #board state
        brd = s.serialize()[None]
        #value from net for given board
        output = self.model(torch.tensor(brd).float())
        return float(output.data[0][0])
Exemplo n.º 16
0
class Valuator():
    def __init__(self):
        from train import Net
        vals = torch.load("nets/value.pth")
        self.model = Net()
        self.model.load_state_dict(vals)
        self.reset()

    def __call__(self, s):
        self.count += 1
        b = s.serialize()[None]
        out = self.model(torch.tensor(b).float())
        return float(out.data[0][0])

    def reset(self):
        self.count = 0
Exemplo n.º 17
0
class Valuator(object):
    def __init__(self):
        self.count = 0
        import torch
        from train import Net
        vals = torch.load("nets/value100K.pth",
                          map_location=lambda storage, loc: storage)
        self.model = Net()
        self.model.load_state_dict(vals)

    def __call__(self, s):
        self.count += 1
        brd = s.serialize()[None]
        output = self.model(torch.tensor(brd).float())
        #print(output.data[0][0])
        return float(output.data[0][0])
Exemplo n.º 18
0
def show_camera(args):
    # To flip the image, modify the flip_method parameter (0 and 2 are the most common)
    print(gstreamer_pipeline(flip_method=0))
    use_cuda = torch.cuda.is_available()
    device = torch.device("cuda" if use_cuda else "cpu")
    model = Net()
    model.load_state_dict(torch.load(args.model_path))
    model = model.to(device)

    font = cv2.FONT_HERSHEY_SIMPLEX
    fontScale = 1
    org = (30, 50)
    color = (0, 0, 255)
    thickness = 2

    cap = cv2.VideoCapture(gstreamer_pipeline(flip_method=0),
                           cv2.CAP_GSTREAMER)
    if cap.isOpened():
        window_handle = cv2.namedWindow('Camera', cv2.WINDOW_AUTOSIZE)
        cv2.namedWindow('image', cv2.WINDOW_AUTOSIZE)
        cv2.namedWindow('inputs', cv2.WINDOW_AUTOSIZE)
        # Window
        while cv2.getWindowProperty('Camera', 0) >= 0:
            ret_val, img = cap.read()
            # Transform inputs
            image0, image, inputs = transform_inputs(img, device)
            # Run Model Evaluation
            output = model(inputs)
            index = output.data.cpu().numpy().argmax()
            cv2.putText(img, str(index), org, font, fontScale, color,
                        thickness, cv2.LINE_AA)
            cv2.imshow('Camera', img)
            cv2.imshow("image", cv2.resize(image0, (200, 200)))
            cv2.imshow("inputs", cv2.resize(image, (200, 200)))
            # This also acts as
            keyCode = cv2.waitKey(30) & 0xff
            # Stop the program on the ESC key
            if keyCode == 27:
                break
        cap.release()
        cv2.destroyAllWindows()
    else:
        print('Unable to open camera')
Exemplo n.º 19
0
class Agent():
    """
    Agent for testing
    """
    def __init__(self):
        self.net = Net().float().to(device)

    def select_action(self, state):
        state = torch.from_numpy(state).float().to(device).unsqueeze(0)
        with torch.no_grad():
            alpha, beta = self.net(state)[0]
        action = alpha / (alpha + beta)

        action = action.squeeze().cpu().numpy()
        return action

    def load_param(self):
        #TODO add for vae and InfoMax

        self.net.load_state_dict(torch.load(args.model_path))
Exemplo n.º 20
0
def main():
    net = Net()
    net.load_state_dict(torch.load(PATH))

    g = Game()
    red = True
    moves = 0

    while not g.won():
        board = g.to_tensor(red)

        prediction = request_move(net, board, chance=1 if red else 0.0)
        max_value = torch.max(prediction)
        move = np.zeros((1, 7))

        for i, element in enumerate(prediction):
            if element == max_value:
                move[:, i] = 1
                prediction[i] = 0.

        column = move.tolist()[0].index(1.)

        for iter in range(7):
            try:
                g.insert(column, RED if red else YELLOW)
                moves += 1
                break
            except Exception as e:
                column = (column + 1) % 7
        else:
            return False, moves

        if g.won():
            g.print_board()
            return red, moves

        # switch turn
        if red:
            red = False
        else:
            red = True
Exemplo n.º 21
0
def inference(loader, path='data/Model.pth'):
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    model = Net().to(device)

    model.load_state_dict(torch.load(path))
    model.eval()
    confmatrix = np.zeros((5, 5))
    correct = 0
    predictions = []
    for i in loader:
        if i[0].flag == 1 and i[1].flag == 1:
            if labels[i[0].truelab[0]] == 0:
                confmatrix[0][0] += 1
                correct += 1
            else:
                confmatrix[0][labels[i[0].truelab[0]]] += 1
            predictions.append(0)
        else:
            data16 = i[0].to(device)
            data20 = i[1].to(device)
            dc = i[2].to(device)
            with torch.no_grad():
                out = model(data16, data20, dc)
            yval = labels[data16.truelab[0]]
            pred = out.max(dim=1)[1].cpu().detach().numpy()
            correct += out.max(dim=1)[1].eq(data16.y).sum().item()
            predictions.append(pred)
            confmatrix[pred[0]][yval] += 1
    return correct / len(loader), predictions, confmatrix
Exemplo n.º 22
0
def test_pytorch():
    net = Net()
    checkpoint_path = 'mnist_cnn_3.pt'
    net.load_state_dict(torch.load(checkpoint_path))

    correct = 0
    data, targets = torch.load('data/MNIST/processed/test.pt')
    data, targets = data.numpy(), targets.numpy()
    with torch.no_grad():
        for index in range(len(data)):
            if index % 100 == 0:
                print(index, len(data))
            img, target = data[index], int(targets[index])
            img = normalize(img, mean=(0.1307, ), std=(0.3081, ))
            img = img[np.newaxis, np.newaxis, :, :]
            img = torch.from_numpy(img)
            output = net(img.float())
            pred = np.argmax(output.numpy(), axis=1)
            correct += pred[0] == target

    print('\nAccuracy: {}  ({:.0f}%)\n'.format(correct,
                                               100. * correct / len(targets)))
Exemplo n.º 23
0
def main():
    # lr = 0.01
    batch_size = 32
    # device = "cpu"
    device = "cuda"

    trans = transforms.Compose(
        [transforms.ToTensor(),
         transforms.Normalize((0.5, ), (1.0, ))])
    # if not exist, download mnist dataset
    train_set = CIFAR10(root="data/",
                        train=True,
                        transform=trans,
                        download=True)
    test_set = CIFAR10(root="data/",
                       train=False,
                       transform=trans,
                       download=True)

    train_loader = DataLoader(train_set,
                              batch_size=batch_size,
                              shuffle=True,
                              pin_memory=False,
                              num_workers=4)
    test_loader = DataLoader(test_set,
                             batch_size=batch_size,
                             shuffle=False,
                             pin_memory=False,
                             num_workers=4)

    model = Net()
    model.load_state_dict(torch.load("checkpoints/best.pt"))
    criterion = nn.CrossEntropyLoss()

    metrics = OrderedDict([("loss", criterion),
                           ("acc", torch_fuze.metrics.Accuracy())])
    print(
        metrics_to_nice_string(
            run_supervised_metrics(model, metrics, test_loader, device)))
Exemplo n.º 24
0
def experiment(trial: optuna.Trial, train_dl, valid_dl, *,
               device='cpu', n_classes, n_epochs, input_shape):
    net = Net(input_shape, n_classes, trial).to(device)
    trainer = Trainer(trial, n_epochs=n_epochs, device=device)

    def epoch_end_callback(epoch, _, acc):
        trial.report(acc, epoch)
        if trial.should_prune(epoch):
            raise optuna.exceptions.TrialPruned()

        if acc < 0.05:  # Prune really bad runs
            raise optuna.exceptions.TrialPruned()

    losses, accuracies = trainer.fit(net, train_dl, valid_dl,
                                     epoch_end_callback=epoch_end_callback)
    return accuracies[-1]
Exemplo n.º 25
0
        low = Image.open(low_path).convert('RGB')  # 540 * 960
        name = low_path.split('/')[-1]
        low = self.transform(low)
        return (low, name)


transform = transforms.Compose([
    transforms.ToTensor(),
    #transforms.Normalize((0.5,), (0.5,))
])

test_ds = TestDataset(low_files, transform)
test_dl = DataLoader(test_ds, batch_size=batch_size)

checkpoint = torch.load(checkpoint_dir + "model_epoch%03d.pth" % (epoch))

model = nn.DataParallel(Net()).cuda()
model.load_state_dict(checkpoint['net'])

model.eval()
with torch.no_grad():
    for test_X, name in test_dl:
        test_X = test_X.cuda()
        test_preds = model(test_X)[0].cpu().numpy()
        for i in range(batch_size):
            im = test_preds[i, :, :, :]
            im = np.swapaxes(np.swapaxes(im, 0, 2), 0, 1)  # H * W * C
            im[:, :, [0, 2]] = im[:, :, [2, 0]]  # RGB
            cv2.imwrite('./data/result/' + name[i], im * 255)
        del test_preds
Exemplo n.º 26
0
img_width = 640
img_height = 960
trained_model = "tipper_final.model"
num_classes = 2

solenoid_pin = 23  # Pin #16
green_led_pin = 25  # Pin 22.
red_led_pin = 8  # Pin 24.
GPIO.setmode(GPIO.BCM)
GPIO.setup(solenoid_pin, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(green_led_pin, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(red_led_pin, GPIO.OUT, initial=GPIO.LOW)

# Load the saved model.
checkpoint = torch.load(trained_model)
model = Net(num_classes=num_classes)
model.load_state_dict(checkpoint)
model.eval()

transformation = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])


def predict_image_class(image):
    # Preprocess the image.
    image_tensor = transformation(image).float()

    # Add an extra batch dimension since pytorch treats all images as batches.
    image_tensor = image_tensor.unsqueeze_(0)
Exemplo n.º 27
0
trainingData = np.load("Training_Data.npy", allow_pickle=True)

#Further processing training data
x = torch.Tensor([i[0] for i in trainingData]).view(-1, 50, 50)
x = x / 255.0
y = torch.Tensor([i[1] for i in trainingData])

# Divide dataset into training and testing sets
testFraction = 0.1
size = int(len(x) * testFraction)
print(size)

testX = x[-size:]
testY = y[-size:]

# Load model
net = Net()
net.load_state_dict(torch.load("./DogsVsCats_net.pth"))

# Start testing
with torch.no_grad():
    for i in tqdm(range(len(testX))):
        realClass = torch.argmax(testY[i])
        predictedClass = torch.argmax(net(testX[i].view(-1, 1, 50, 50)))

        if predictedClass == realClass:
            correct += 1
        total += 1

print("Accuracy: ", round(correct / total, 4))
Exemplo n.º 28
0
    def __len__(self) -> int:
        return len(self.path_list)


# test_path = 'D:\\DeapLearn Project\\Face_Recognition\\data\\test\\'
test_path = 'D:\\DeapLearn Project\\ License plate recognition\\single_num\\resize\\'

test_data = MyDataSet(test_path)
new_test_loader = DataLoader(test_data,
                             batch_size=32,
                             shuffle=False,
                             pin_memory=True,
                             num_workers=0)

# 创造一个一模一样的模型
model = Net()
# 加载预训练模型的参数
model.load_state_dict(torch.load('Model.pth'))

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model.to(device)


def test():
    correct = 0
    total = 0
    with torch.no_grad():
        for _, data in enumerate(new_test_loader, 0):
            inputs, _ = data[0], data[1]
            inputs = inputs.to(device)
            outputs = model(inputs)
Exemplo n.º 29
0
        update_model(net_one, good_boards, good_moves, good_preds)
        update_model(net_two, bad_boards, bad_moves, bad_preds)
    else:
        update_model(net_two, good_boards, good_moves, good_preds)
        update_model(net_one, bad_boards, bad_moves, bad_preds)


if __name__ == '__main__':
    games = 1000

    # net = Net()
    games = int(sys.argv[1])
    if len(sys.argv) > 3:
        PATH_ONE = sys.argv[2]
        PATH_TWO = sys.argv[3]

        net_one = Net()
        net_one.load_state_dict(torch.load(PATH_ONE))

        net_two = Net()
        net_two.load_state_dict(torch.load(PATH_TWO))
    else:
        net_one = Net()
        net_two = Net()

    for game_num in range(1, games + 1):
        play(net_one, net_two)

    save_model('one', net_one)
    save_model('two', net_two)
Exemplo n.º 30
0
  game.print_board()
  # if its no longer foos turn, he won
  good_moves = foo_moves if not foos_turn else bar_moves
  good_preds = foo_preds if not foos_turn else bar_preds
  good_boards = foo_boards if not foos_turn else bar_boards

  bad_moves = foo_moves if foos_turn else bar_moves
  bad_moves = [(move - 1) * -1 for move in bad_moves]

  bad_preds = foo_preds if foos_turn else bar_preds
  bad_boards = foo_boards if foos_turn else bar_boards

  update_model(net, good_boards, good_moves, good_preds)
  # update_model(net, bad_boards, bad_moves, bad_preds)


if __name__ == '__main__':
  games = int(sys.argv[1])

  if len(sys.argv) > 2:
    net = Net()
    net.load_state_dict(torch.load(sys.argv[2]))
  else:
    net = Net()

  for game_num in range(1,games+1):
    play(net)

    save_model(net)