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
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 __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
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 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 __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 __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 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")
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 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
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]
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')
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
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)))
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)))
def __init__(self): self.net = Net().float().to(device)
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)
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))
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)
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)
def __init__(self): self.model = Net() self.model.load_state_dict( torch.load(f"{MODEL_PATH}/{MODEL_FILE}", map_location=torch.device('cpu')))
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)
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
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')
def __init__(self): from train import Net vals = torch.load("nets/value.pth") self.model = Net() self.model.load_state_dict(vals) self.reset()
trained_model_gestures = "gestures_173_12311-6836.model" 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):
patients = test_ids_patients.drop_duplicates() num_patients = patients.shape[0] row_ids = pd.DataFrame({'ROW_IDX': test_ids_patients.index}, index=test_ids_patients) # Vocabulary sizes num_static = num_static(data) 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)
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} %' )
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()
import os import torch from train import load_inputs 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))