示例#1
0
def predict(X):
    nn = NN([6, 8, 4, 1])
    nn.load_state_dict(torch.load('model_state/state'))
    nn.eval()
    result = nn.forward(X).detach().numpy().reshape(-1, 1)
    result_transformed = scaler.inverse_transform(result)
    return result_transformed
示例#2
0
 def net_loader(self, path = None):
     testm = NN(self.Layer_s).to(device)
     if path is None:
       model_name = self.part_number + '_model_lr_' + str(self.Learning_r) + '_layer_size_' + str(self.Layer_s) + '.pt'
       path = os.path.join(self.checkpoint_dir, model_name)
       testm.load_state_dict(torch.load(path))
       print(model_name,' Was loaded successfully loaded.\t\t\t [loaded]')
     else:
       testm.load_state_dict(torch.load(path))
       print(model_name,' Was loaded successfully loaded from the path.\t\t\t [loaded from Path]')
     return testm  
示例#3
0
import cv2
from model import NN
import numpy as np
import torch

cap = cv2.VideoCapture(0)
i = 0 
classify = 1 
labels =[] 
Model = NN(batch_size = 1)
Model.load_state_dict(torch.load("1"))
Model.eval()
tardict = {1 : 'Face Detected' , 0 : 'Undetected'  }

while True:
    i += 1
    ret  , frame = cap.read()
    gray = cv2.cvtColor(frame , cv2.COLOR_RGB2GRAY)
    gray = cv2.GaussianBlur(gray, (15,15), 0)
    cv2.imshow('feed' , frame)
    gray = torch.from_numpy(gray).view(1 , 1, 480 , 640).float()
    output = torch.round(Model.forward(gray))
    output = output.item()
    print (tardict[output])
    if output != 0:
        input()
    if cv2.waitKey(1) & 0xFF == ord('q') :
        break 
   
import torch as tc
from model import NN
from champion_dictionary import *

net = NN()
net.load_state_dict(tc.load("model.wab"))

input_data = tc.rand((10), dtype=tc.float)
out = net(input_data)
print(input_data)

if out < 0.5:
    print("Blue team")
    print(out)

else:
    print("Red team")
    print(out)
示例#5
0
文件: test.py 项目: AxelBremer/DL4NLP
def test(config):
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

    # Initialize the device which to run the model on
    device = torch.device(device)

    with open(f'runs/{config.name}/args.txt', 'r') as f:
        config.__dict__ = json.load(f)

    # Initialize the dataset and data loader (note the +1)
    test_dataset = IMDBDataset(train_or_test='test',
                               seq_length=config.seq_length)
    test_data_loader = DataLoader(test_dataset,
                                  batch_size=config.batch_size,
                                  shuffle=True,
                                  num_workers=4)

    # Initialize the model that we are going to use
    if not (config.recurrent_dropout_model):
        model = NN(test_dataset.vocab_size, config.embed_dim,
                   config.hidden_dim, config.output_dim, config.n_layers,
                   config.bidirectional, config.dropout, 0).to(device)
        model.load_state_dict(torch.load(f'runs/{config.name}/model.pt'))
    else:
        model = Model(test_dataset.vocab_size,
                      output_dim=config.output_dim).to(device)
        model.load_state_dict(torch.load(f'runs/{config.name}/model.pt'))

    # Setup the loss and optimizer
    criterion = torch.nn.MSELoss().to(device)
    lowest = 100
    save = []
    epochs = 0
    num_steps = math.floor(25000 / config.batch_size)

    d = {'target': [], 'mean0': [], 'std0': [], 'mean1': [], 'std1': []}

    with torch.no_grad():
        for step, (batch_inputs, batch_targets) in enumerate(test_data_loader):

            x = batch_inputs.long().to(device)
            y_target = batch_targets.long().to(device)

            # print('\n*************************************************\n')
            # print(test_dataset.convert_to_string(x[0].tolist()))

            preds = torch.zeros((100, x.shape[0], config.output_dim))

            for i in range(config.B):
                preds[i, :, :] = model(x)

            # print('\n')

            if step % 1 == 0:
                print(step, '/', num_steps)

            mean = preds.mean(dim=0)
            std = preds.std(dim=0)

            d['target'].extend(batch_targets.tolist())
            d['mean0'].extend(mean[:, 0].tolist())
            d['std0'].extend(std[:, 0].tolist())
            d['mean1'].extend(mean[:, 1].tolist())
            d['std1'].extend(std[:, 1].tolist())

    pd.DataFrame(d).to_csv(f'runs/{config.name}/results.csv')
    return 'joe'
示例#6
0
    #
    if use_pretrained_resnet:
        nn_model = models.resnet50(pretrained=True)
        num_ftr = nn_model.fc.in_features
        nn_model.fc = nn.Linear(num_ftr, 2)
        nn_model.to(device)

    else:
        nn_model = NN()

        if load_weights:
            print("Found State Dict. Loading...")
            with open(r'state/state_dict.pickle', 'rb') as file:
                state_dict = torch.load(r'state/state_dict.pickle')
            nn_model.load_state_dict(state_dict)
        nn_model.to(device)

        learning_rate = 0.0001
        f1_scores = []
        epochs = 1
        for epoch in range(epochs):
            predicted_cumulated, labels_cumulated = np.array([]), np.array([])
            running_loss = 0
            counter = 0
            # optimizer = torch.optim.Adam(conv_nn.parameters(), lr=learning_rate)
            optimizer = torch.optim.Adam(nn_model.parameters(),
                                         lr=learning_rate)
            loss_function = nn.CrossEntropyLoss()

            for i, data in tqdm.tqdm(enumerate(train_loader, 0)):