Example #1
0
 def __init__(self, config, vocab):
     super().__init__()
     self.config = config
     self.vocab = vocab
     self.model = PointerGenerator(config, vocab)
     self.criterion = Loss(args=config.loss.args)
     self.num_step = 0
     self.cov_weight = config.loss.args.cov_weight
     self.rouge = Rouge()
Example #2
0
 def __init__(self, embedding_matrix, config, vocab):
     super().__init__()
     self.config = config
     self.vocab = vocab
     self.model = PointerGenerator(embedding_matrix, config, vocab)
     self.criterion = Loss(args=config)
     self.num_step = 0
     self.cov_weight = config.cov_loss_wt
     self.rouge = Rouge()
def active_losses():
    losses = []

    sql = "SELECT * FROM losses where recovered = False"
    results = run_sql(sql)

    for row in results:
        wizard = wiz_repo.select(row['wizard_id'])
        item = item_repo.select(row['item_id'])
        loss = Loss(row['day'], row['month'], row['year'], row['details'],
                    wizard, item, row['recovered'], row['id'])
        losses.append(loss)
    return losses
def select(id):
    loss = None
    sql = "SELECT * FROM losses WHERE id = %s"
    values = [id]
    result = run_sql(sql, values)[0]

    if result is not None:
        wizard = wiz_repo.select(result['wizard_id'])
        item = item_repo.select(result['spell_id'])
        loss = Loss(result['day'], result['month'], result['year'],
                    result['details'], wizard, item, result['recovered'],
                    result['id'])
    return loss
def loss_history(wizard):
    losses = []

    sql = "SELECT * FROM losses where wizard_id = %s AND recovered = False"
    values = [wizard.id]
    results = run_sql(sql, values)

    for row in results:
        wizard = wiz_repo.select(row['wizard_id'])
        item = item_repo.select(row['item_id'])
        loss = Loss(row['day'], row['month'], row['year'], row['details'],
                    wizard, item, row['recovered'], row['id'])
        losses.append(loss)
    return losses
Example #6
0
def main(config, resume):
    train_logger = Logger()

    # load data
    train_dataloader = ICDARDataLoader(config).train()

    # initial model
    os.environ['CUDA_VISIBLE_DEVICES'] = ','.join([str(i) for i in config['gpus']])
    model = Model(config)
    model.summary()

    loss = Loss()
    trainer = Trainer(model, loss, resume, config, train_dataloader, train_logger)
    trainer.train()
Example #7
0
 def __init__(self, args):
     super(NNUnet, self).__init__()
     self.args = args
     self.save_hyperparameters()
     self.build_nnunet()
     self.loss = Loss(self.args.focal)
     self.dice = Dice(self.n_class)
     self.best_sum = 0
     self.best_sum_epoch = 0
     self.best_dice = self.n_class * [0]
     self.best_epoch = self.n_class * [0]
     self.best_sum_dice = self.n_class * [0]
     self.learning_rate = args.learning_rate
     self.tta_flips = get_tta_flips(args.dim)
     self.test_idx = 0
     self.test_imgs = []
     if self.args.exec_mode in ["train", "evaluate"]:
         self.dllogger = get_dllogger(args.results)
Example #8
0
 def setUp(self):
     wizard = Wizard("Norman", "Stargazer", 1000)
     item = Item("Hat", "Pink", "Glittery", wizard)
     self.loss = Loss("02", "02", "2000",
                      "Lost at event at Gimli's Nightclub", wizard, item)
Example #9
0
 def loss(self, predictions, labels):
     user_feat, pos_item_feat, neg_item_feat = predictions
     loss_func = Loss.factory(self.hparam)
     loss = loss_func(user_feat, pos_item_feat, neg_item_feat)
     return loss
def test_test():
    img_path_list, target_list = \
        make_dataset(r"D:\datasets\VOCdevkit\VOC0712\JPEGImages",
                     r"D:\datasets\VOCdevkit\VOC0712\Annotations",
                     r"D:\datasets\VOCdevkit\VOC0712\pkl\voc_0712_test.pkl",
                     r"D:\datasets\VOCdevkit\VOC0712\ImageSets\Main\test.txt", "voc", False)

    dataset = LoadImagesAndLabels(img_path_list, target_list, 640, 32, 0.5,
                                  False, {"batch_size": 1})

    # x: Tensor[C, H, W], target_out: Tensor[X, 6], path: str. [idx, cls, *xywh]
    # test show
    def test1():
        for x, target, img_path in dataset:
            print(x.shape, target, img_path)
            x = x.numpy()
            x = x.transpose(1, 2, 0)[:, :, ::-1]  # to (H, W, C), RGB to BGR,
            x = np.ascontiguousarray(x)
            h, w = x.shape[:2]
            boxes = target[:, 2:].numpy()
            labels = target[:, 1].numpy()
            boxes = cxcywh2ltrb(boxes)
            boxes[:, 0::2] *= w  # lr
            boxes[:, 1::2] *= h  # tb
            draw_target_in_image(x, boxes, labels, None, "voc")
            cv.imshow("1", x)
            cv.waitKey(0)

    # test1()
    if torch.cuda.is_available():
        device = torch.device('cuda')
    else:
        device = torch.device('cpu')
    model = YOLOv5(20).to(device)
    print(load_params(model, "weights/yolov5s_voc.pth", strict=False))
    model.float().fuse().eval().requires_grad_(False)
    half = (device.type != 'cpu')
    model.half() if half else None
    hyp = {
        "obj_pw": 0.911,
        "cls_pw": 0.631,
        "anchor_t": 2.91,
        "box_lw": 0.0296,
        "obj_lw": 0.301,
        "cls_lw": 0.06075
    }
    loss_func = Loss(model, hyp)
    loss = torch.zeros((4, ), device=device)
    for x, target0, img_path in reversed(dataset):
        img0 = x.numpy()
        img0 = img0.transpose(1, 2, 0)[:, :, ::-1]  # to (H, W, C), RGB to BGR,
        img0 = np.ascontiguousarray(img0)
        img = img0.copy()
        # 预处理
        x, target0 = x.to(device), target0.to(device)
        x = x.half() if half else x.float()
        x /= 255
        if x.dim() == 3:
            x = x[None]
        # 预测
        target, loss_target = model(x)
        loss += loss_func([loss_t.float() for loss_t in loss_target],
                          target0)[1]
        target = nms(target, 0.001, 0.6)

        # 后处理
        # 1
        target = target[0]
        boxes = target[:, :4].cpu().numpy()
        scores = target[:, 4].cpu().numpy()
        labels = target[:, 5].cpu().numpy()
        draw_target_in_image(img, boxes, labels, scores, "voc")
        cv.imshow("pred", img)
        # 2
        img2 = img0.copy()
        h, w = img2.shape[:2]
        boxes = target0[:, 2:].cpu().numpy()
        labels = target0[:, 1].cpu().numpy()
        boxes = cxcywh2ltrb(boxes)
        boxes[:, 0::2] *= w  # lr
        boxes[:, 1::2] *= h  # tb
        draw_target_in_image(img2, boxes, labels, None, "voc")
        cv.imshow("target", img2)
        cv.waitKey(0)
Example #11
0
item_repo.save(hat3)
shoes1 = Item("Shoes", "Red and Black", "Jordan Air's", wizard1)
item_repo.save(shoes1)
shoes2 = Item("Shoes", "Blue", "Curly Pointed Slippers", wizard2)
item_repo.save(shoes1)
shoes3 = Item("Shoes", "Black", "90s Platform Trainers", wizard3)
item_repo.save(shoes1)
wand1 = Item("Wand", "Light brown", "Knobbly", wizard1)
item_repo.save(wand1)
wand2 = Item("Wand", "Black", "Straight, smooth", wizard2)
item_repo.save(wand2)
wand3 = Item("Wand", "Brown", "Zig-zagged", wizard3)
item_repo.save(wand3)

# day, month, year, details, wizard_id, item_id, recovered
loss1 = Loss("01","01","2020", "Lost at event at Gimli's Nightclub", wizard1, hat1)
loss_repo.save(loss1)
loss2 = Loss("04","03","2019", "Lost in forest (forest name unknown)", wizard2, hat2)
loss_repo.save(loss2)
loss3 = Loss("07","07","2019", "Woke up without it on the bus this morning", wizard3, wand3)
loss_repo.save(loss3)
loss4 = Loss("03", "07", "2019", "No memory of loss", wizard1, shoes1)
loss_repo.save(loss4)

# wizards = wiz_repo.select_all()
# items = item_repo.select_all()
# losses = loss_repo.select_all()

# Test Update Wizard Here (Change Age)
wizard1.age = 50000
wiz_repo.update(wizard1)