예제 #1
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
예제 #2
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)
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
예제 #4
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])
예제 #5
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()
예제 #6
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 
예제 #7
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
예제 #8
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)
예제 #9
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])
예제 #10
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])
예제 #11
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
예제 #12
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')
예제 #13
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))
예제 #14
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
예제 #15
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)))
예제 #16
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)))
예제 #17
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)

예제 #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)

        # Window 
        while cv2.getWindowProperty('Camera',0) >= 0:
            ret_val, img = cap.read()

            # Convert to grayscale and apply Gaussian filtering
            im_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            im_gray = cv2.GaussianBlur(im_gray, (5, 5), 0)

            # Threshold the image
            ret, im_th = cv2.threshold(im_gray, 90, 255, cv2.THRESH_BINARY_INV)

            # Find contours in the image
            im2, ctrs, hier = cv2.findContours(im_th, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

            # Get rectangles contains each contour
            rects = [cv2.boundingRect(ctr) for ctr in ctrs]

            # For each rectangular region, calculate HOG features and predict
            # the digit using Linear SVM.
            for rect in rects:
                # Draw the rectangles
                cv2.rectangle(img, (rect[0], rect[1]), (rect[0] + rect[2], rect[1] + rect[3]), (0, 255, 0), 3) 
                # Make the rectangular region around the digit
                leng = int(rect[3] * 1.6)
                pt1 = int(rect[1] + rect[3] // 2 - leng // 2)
                pt2 = int(rect[0] + rect[2] // 2 - leng // 2)
                roi = im_gray[pt1:pt1+leng, pt2:pt2+leng]
                # Resize the image
                h, w = roi.shape
                if h > 10 and w > 10:
                    # Transform inputs
                    inputs = transform_inputs(roi, device)
                    # Run Model Evaluation
                    output = model(inputs)
                    result = output.data.cpu().numpy().argmax()
                    cv2.putText(img, str(result), (rect[0], rect[1]),cv2.FONT_HERSHEY_DUPLEX, 2, (0, 255, 255), 3)
            
            cv2.imshow("Camera", img)

	    # 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')
예제 #19
0
    num_dp_codes, num_cp_codes = vocab_sizes(data)

    # CUDA for PyTorch
    use_cuda = torch.cuda.is_available()
    device = torch.device('cuda:0' if use_cuda else 'cpu')
    torch.backends.cudnn.benchmark = True

    # Network
    net = Net(num_static, num_dp_codes, num_cp_codes).to(device)

    print('Evaluate...')
    # Set log dir to read trained model from
    logdir = hp.logdir + hp.net_variant + '/'

    # Restore variables from disk
    net.load_state_dict(
        torch.load(logdir + 'final_model.pt', map_location=device))

    # Bootstrapping
    np.random.seed(hp.np_seed)
    avpre_vec = np.zeros(hp.bootstrap_samples)
    auroc_vec = np.zeros(hp.bootstrap_samples)
    f1_vec = np.zeros(hp.bootstrap_samples)
    sensitivity_vec = np.zeros(hp.bootstrap_samples)
    specificity_vec = np.zeros(hp.bootstrap_samples)
    ppv_vec = np.zeros(hp.bootstrap_samples)
    npv_vec = np.zeros(hp.bootstrap_samples)

    for sample in range(hp.bootstrap_samples):
        print('Bootstrap sample {}'.format(sample))

        # Test data
예제 #20
0
num_classes_objects = 3
num_classes_gestures = 2

objs = []
objs.append("Google")
objs.append("Lamp")
objs.append("Nothing")

gestures = []
gestures.append("Wave")
gestures.append("Nothing")

# Load the saved models.
checkpoint_objects = torch.load(trained_model_objects)
model_objects = Net(num_classes=num_classes_objects)
model_objects.load_state_dict(checkpoint_objects)
model_objects.eval()

checkpoint_gestures = torch.load(trained_model_gestures)
model_gestures = Net(num_classes=num_classes_gestures)
model_gestures.load_state_dict(checkpoint_gestures)
model_gestures.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, classifier_type):
    # Preprocess the image.
예제 #21
0
class MainWindow(QMainWindow):
    def __init__(self, path="mnist_cnn.pt"):
        super(MainWindow, self).__init__()

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

        self.initUI()

    def onMyToolBarButtonClick(self, s):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getOpenFileName(
            self,
            "QFileDialog.getOpenFileName()",
            "",
            "All Files (*);;PNG (*.png)",
            options=options)

        if fileName:
            try:
                self.img = mpimg.imread(fileName)
                self.img = torch.from_numpy(
                    self.img[:, :, 0]).unsqueeze(0).unsqueeze(0)

                pixmap = QPixmap(fileName)
                pixmap = pixmap.scaled(self.img_label.width(),
                                       self.img_label.height())

                self.img_label.setPixmap(pixmap)

                prediction_digit = self.model(self.img).argmax()
                output_str = "Prediction of {}: {}".format(
                    os.path.basename(fileName), prediction_digit)
                print(output_str)
                self.digit_label.setText(output_str)

            except Exception as e:
                print("Error uploading the file: {}".format(e))

    def initUI(self):
        """initialize UI settings"""

        self.H, self.W = 800, 600
        self.setWindowTitle("Simple Digit Recognition")
        self.setWindowIcon(QIcon("icons/trial.ico"))
        self.resize(self.W, self.H)
        self.moveCenter()

        layout = QVBoxLayout()

        self.upload_btn = QPushButton(QIcon("icons/filesave.png"),
                                      "Upload Image")
        self.upload_btn.clicked.connect(self.onMyToolBarButtonClick)
        self.upload_btn.setFixedHeight(50)

        layout.addWidget(self.upload_btn)

        self.img_label = QLabel(self)
        self.img_label.setFixedHeight(600)
        self.img_label.setFixedHeight(600)
        layout.addWidget(self.img_label)

        self.digit_label = QLabel(self)
        self.digit_label.setFont(QFont('Arial', 32))

        layout.addWidget(self.digit_label)

        widget = QWidget()
        widget.setLayout(layout)
        self.setCentralWidget(widget)

    def moveCenter(self):
        """make the window to be located at the center of desktop"""
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
예제 #22
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))
예제 #23
0
def main():
    transform = transforms.Compose([
        transforms.ToTensor(),
        transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
    ])  # Normalize(平均, 偏差)

    trainset = torchvision.datasets.CIFAR10(root='./data',
                                            train=True,
                                            download=True,
                                            transform=transform)
    trainloader = torch.utils.data.DataLoader(trainset,
                                              batch_size=4,
                                              shuffle=True,
                                              num_workers=2)

    testset = torchvision.datasets.CIFAR10(root='./data',
                                           train=False,
                                           download=True,
                                           transform=transform)
    testloader = torch.utils.data.DataLoader(testset,
                                             batch_size=4,
                                             shuffle=False,
                                             num_workers=2)
    classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse',
               'ship', 'truck')

    # テストデータデータをランダムに取得
    dataiter = iter(testloader)
    images, labels = dataiter.next()

    last_saved_model = train(trainloader, SAVE_DIR)
    last_saved_model = SAVE_DIR / "epochs_2_iter_12000.pth"
    model = Net()
    model.load_state_dict(torch.load(last_saved_model))
    model.eval()

    correct = 0
    total = 0
    with torch.no_grad():
        for data in testloader:
            images, labels = data
            outputs = model(images)
            _, predicted = torch.max(outputs.data, 1)
            total += labels.size(0)
            correct += (predicted == labels).sum().item()

    print(
        f'Accuracy of the network on the 10000 test images: {100 * correct / total} %'
    )

    class_correct = list(0. for i in range(10))
    class_total = list(0. for i in range(10))
    with torch.no_grad():
        for data in testloader:
            images, labels = data
            outputs = model(images)
            _, predicted = torch.max(outputs, 1)
            c = (predicted == labels).squeeze()
            for i in range(4):
                label = labels[i]
                class_correct[label] += c[i].item()
                class_total[label] += 1

    for i in range(10):
        print(
            f'Accuracy of {classes[i]:.5s} : {100 * class_correct[i] / class_total[i]:.2f} %'
        )
예제 #24
0
from train import Net

WORKING_DIR = os.getcwd()
DATA_DIR = os.path.join(WORKING_DIR, "data")
TEST_DATA_DIR = os.path.join(DATA_DIR, "test")
MODELS_PATH = "S:\\models"
MODEL_FILE = "model286_tloss359.pt"

inputs, idx_to_name = load_inputs(TEST_DATA_DIR, testing=True)

# model = Net(len(inputs[0])).cuda()
model = Net(3, 20).cuda()

checkpoint = torch.load(os.path.join(MODELS_PATH, MODEL_FILE))

model.load_state_dict(checkpoint['model_state_dict'])

f_out = open(os.path.join(MODELS_PATH, MODEL_FILE.split('.')[0] + ".csv"), mode='w')
f_out.write("id,class\n")

model.eval()
with torch.no_grad():
    for idx, input in enumerate(inputs):

        input = input.cuda()

        prediction = model.forward(input.view(1, 3, -1))

        _, top_class = prediction.topk(1)

        f_out.write(f"{idx_to_name[idx]},{top_class.item() + 1}\n")
예제 #25
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)
예제 #26
0
if __name__ == '__main__':
    torch.multiprocessing.freeze_support()

    transform = transforms.Compose(
        [transforms.ToTensor(),
        transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
    testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)
    testloader = torch.utils.data.DataLoader(testset, batch_size=4, shuffle=False, num_workers=2)

    classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
    PATH = './eyelang/cifar_net.pth'
    # test the NN on test data
    # re-load saved model
    net = Net()
    net.load_state_dict(torch.load(PATH))

    dataiter = iter(testloader)
    images, labels = dataiter.next()

    # print images
    # permute to have channels as last dimension
    plt.imshow(torchvision.utils.make_grid(images).permute(1, 2, 0))
    plt.show()
    print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))
    outputs = net(images) # neural net's classifications
    _, predicted = torch.max(outputs, 1) # get highest energy/most likely label
    print('Predicted: ', ' '.join('%5s' % classes[predicted[j]] for j in range(4)))

    correct = 0
    total = 0
예제 #27
0

# 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)
            # print(outputs.shape)
            _, prediction = torch.max(outputs.data, dim=1)
class Inferencing():
    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)

    def get3Dcoordinates(self, skel_2d):
        """Returns Z(3D) coordinates of a 2D pose"""
        skel_2d = skel_2d.to(self.device)
        z_out = self.net(skel_2d)
        z_out = z_out.detach().cpu().numpy()
        z_out = z_out.reshape(-1)
        return z_out

    def testSample(self):
        """Inferences on 5 random samples."""
        val_idx = np.load(self.validation_set)
        val_sampler = SubsetRandomSampler(val_idx)
        pose_dataset = PoseDataset(self.dataset_path)
        val_loader = DataLoader(dataset=pose_dataset, batch_size=1,\
            sampler=val_sampler)
        for i in range(5):
            data_iter = iter(val_loader)
            skel_2d, skel_z = next(data_iter)

            # inference
            skel_2d = skel_2d.to(self.device)
            z_out = self.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)
            self.show_skeletons(skel_2d, z_out, z_gt)

    def show_skeletons(self, skel_2d, z_out, z_gt=None):
        """Show skeleton in 2D and 3D, includes full upper body and headself.

        Keyword Arguments:
        skel_2d - skeleton with x,y coordinates
        z_out - predicted z coordinates (for 3d)
        z_gt - ground truth z coordinates
        """
        fig = plt.figure(figsize=(20, 20))
        ax1 = fig.add_subplot(1, 2, 1)
        ax2 = fig.add_subplot(1, 2, 2, projection='3d')
        edges = np.array([[1, 0], [0, 2], [2, 3], [3, 4], [0, 5], [5, 6],
                          [6, 7]])

        ax_2d = ax1
        ax_3d = ax2

        # draw 3d
        for edge in edges:
            ax_3d.plot(skel_2d[0, edge],
                       z_out[edge],
                       skel_2d[1, edge],
                       color='r')
            if z_gt is not None:
                ax_3d.plot(skel_2d[0, edge],
                           z_gt[edge],
                           skel_2d[1, edge],
                           color='g')

        ax_3d.set_aspect('equal')
        ax_3d.set_xlabel("x"), ax_3d.set_ylabel("z"), ax_3d.set_zlabel("y")
        ax_3d.set_xlim3d([-2,
                          2]), ax_3d.set_ylim3d([2, -2
                                                 ]), ax_3d.set_zlim3d([2, -2])
        ax_3d.view_init(elev=10, azim=-45)

        # draw 2d
        for edge in edges:
            ax_2d.plot(skel_2d[0, edge], skel_2d[1, edge], color='r')

        ax_2d.set_aspect('equal')
        ax_2d.set_xlabel("x"), ax_2d.set_ylabel("y")
        ax_2d.set_xlim([-2, 2]), ax_2d.set_ylim([2, -2])

        plt.show()
예제 #29
0
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)
    image_tensor.cuda()
예제 #30
0
파일: predict.py 프로젝트: giacomov/mnist
from train import Net
from PIL import Image
import numpy as np
import glob
import torch
import torch.nn.functional as F

weights = glob.glob("output/*.pth")
if len(weights) == 0:
    raise IOError("Could not find any model")
print(f"Found {len(weights)} models, using {weights[0]}")

device = torch.device('cpu')
model = Net()
model.load_state_dict(torch.load(weights[0], map_location=device))


def predict(file_path):

    img = np.array(Image.open(file_path).resize(size=(28, 28)))
    img = img.reshape(1, 1, 28, 28)
    img = img.astype('float32')
    img = img / 255.0
    digit = F.softmax(model(torch.from_numpy(img)), dim=1)
    return str(int(digit[0].argmax()))


if __name__ == "__main__":

    print(predict("./301.png"))