Esempio n. 1
0
    def __init__(self, img_ch=3, output_ch=1):
        super(SRF_UNet, self).__init__()
        filters = [64, 128, 256, 512]
        resnet = resnest.resnest50(pretrained=True)
        self.firstconv = resnet.conv1
        self.firstbn = resnet.bn1
        self.firstrelu = resnet.relu
        self.firstmaxpool = resnet.maxpool
        self.encoder1 = resnet.layer1
        self.encoder2 = resnet.layer2
        self.encoder3 = resnet.layer3
        self.encoder4 = resnet.layer4

        #self.dab1 = DAB()
        #self.dab2 = DAB()
        #self.dab3 = DAB()
        #self.dab4 = DAB()
        #self.Up5_thick = up_conv(ch_in=2048, ch_out=1024)
        #self.Up_conv5_thick = res_conv_block(ch_in=2048, ch_out=1024)

        self.Up4_thick = up_conv(ch_in=1024, ch_out=512)
        self.Up_conv4_thick = res_conv_block(ch_in=1024, ch_out=512)

        self.Up3_thick = up_conv(ch_in=512, ch_out=256)
        self.Up_conv3_thick = res_conv_block(ch_in=512, ch_out=256)

        self.Up2_thick = up_conv(ch_in=256, ch_out=64)
        self.Up_conv2_thick = res_conv_block(ch_in=128, ch_out=64)

        self.Up1_thick = up_conv(ch_in=64, ch_out=64)
        self.Up_conv1_thick = res_conv_block(ch_in=64, ch_out=32)
        self.Conv_1x1_thick = nn.Conv2d(32, output_ch, kernel_size=1)
        """
Esempio n. 2
0
    def __init__(self):
        super(ModelResnest50,self).__init__()
        base_model = resnest50(pretrained=True)
        self.conv = nn.Sequential(*list(base_model.children())[:-2])
        self.avg_pool = nn.AdaptiveAvgPool2d((1, 1))
        feature = 2048

        self.classifier = nn.Linear(in_features=feature,out_features=5,bias=True)
Esempio n. 3
0
# load image
#image_path = os.path.join("X:/model", "test.jpg")
img = Image.open("X:/dataset/公安部大楼/00000.jpg")
plt.imshow(img)
# [N, C, H, W]
img = data_transform(img)
# expand batch dimension
img = torch.unsqueeze(img, dim=0)

# read class_indict
try:
    json_file = open('./class_indices.json', 'r')
    class_indict = json.load(json_file)
except Exception as e:
    print(e)
    exit(-1)

# create model
model = resnest50(num_classes=5)
# load model weights
model_weight_path = "./resNest50.pth"
model.load_state_dict(torch.load(model_weight_path, map_location=device))
model.eval()
with torch.no_grad():
    # predict class
    output = torch.squeeze(model(img))
    predict = torch.softmax(output, dim=0)
    predict_cla = torch.argmax(predict).numpy()
print(class_indict[str(predict_cla)], predict[predict_cla].numpy())
plt.show()
Esempio n. 4
0
def main():
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    print("using {} device.".format(device))

    data_transform = {
        "train":
        transforms.Compose([
            transforms.RandomResizedCrop(224),
            transforms.RandomHorizontalFlip(),
            transforms.ToTensor(),
            transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
        ]),
        "val":
        transforms.Compose([
            transforms.Resize(256),
            transforms.CenterCrop(224),
            transforms.ToTensor(),
            transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
        ])
    }

    data_root = os.path.abspath(os.path.join(os.getcwd(),
                                             "../.."))  # get data root path
    image_path = os.path.join("D:", "imagenet")  # flower data set path
    assert os.path.exists(image_path), "{} path does not exist.".format(
        image_path)
    train_dataset = datasets.ImageFolder(root=os.path.join(
        image_path, "train"),
                                         transform=data_transform["train"])
    train_num = len(train_dataset)

    # {'daisy':0, 'dandelion':1, 'roses':2, 'sunflower':3, 'tulips':4}
    flower_list = train_dataset.class_to_idx
    cla_dict = dict((val, key) for key, val in flower_list.items())
    # write dict into json file
    json_str = json.dumps(cla_dict, indent=4)
    with open('class_indices.json', 'w') as json_file:
        json_file.write(json_str)

    nw = min([os.cpu_count(), batch_size if batch_size > 1 else 0,
              8])  # number of workers
    print('Using {} dataloader workers every process'.format(nw))

    train_loader = torch.utils.data.DataLoader(
        train_dataset,
        batch_size=batch_size,
        shuffle=True,
    )
    validate_dataset = datasets.ImageFolder(root=os.path.join(
        image_path, "val"),
                                            transform=data_transform["val"])
    val_num = len(validate_dataset)
    validate_loader = torch.utils.data.DataLoader(
        validate_dataset,
        batch_size=batch_size,
        shuffle=False,
    )

    print("using {} images for training, {} images for validation.".format(
        train_num, val_num))

    net = resnest50(num_classes=10)
    net_input = torch.randn(batch_size, 3, 224, 224)
    flops, params = profile(net, inputs=(net_input, ))
    print("网络计算量GFlops:{},网络参数量#P:{}".format(flops, params))
    '''
    # load pretrain weights
    # download url: https://download.pytorch.org/models/resnet34-333f7ec4.pth
    
    #assert os.path.exists(model_weight_path), "file {} does not exist.".format(model_weight_path)
    #####读取训练好的参数###############
    
    model_weight_path = "./ResNeSkt.pth"
    missing_keys, unexpected_keys = net.load_state_dict(torch.load(model_weight_path), strict=False)
    for param in net.parameters():
        param.requires_grad = False
    '''
    # change fc layer structure
    in_channel = net.fc.in_features
    net.fc = nn.Linear(in_channel, 10)
    net.to(device)

    loss_function = nn.CrossEntropyLoss()
    optimizer = optim.Adam(net.parameters(), lr=lr)

    best_acc = 0.0
    save_path = './ResNeSkt.pth'
    list_loss = list()
    list_acc = list()
    for epoch in range(epoch_all):
        # train
        net.train()
        running_loss = 0.0
        for step, data in enumerate(train_loader, start=0):
            images, labels = data
            optimizer.zero_grad()
            logits = net(images.to(device))
            loss = loss_function(logits, labels.to(device))
            loss.backward()
            optimizer.step()
            # print statistics
            running_loss += loss.item()
            # print train process
            rate = (step + 1) / len(train_loader)
            a = "*" * int(rate * 50)
            b = "." * int((1 - rate) * 50)
            print("\rtrain loss: {:^3.0f}%[{}->{}]{:.4f}".format(
                int(rate * 100), a, b, loss),
                  end="")

        # validate
        net.eval()
        acc = 0.0  # accumulate accurate number / epoch
        with torch.no_grad():
            for val_data in validate_loader:
                val_images, val_labels = val_data
                outputs = net(val_images.to(
                    device))  # eval model only have last output layer
                # loss = loss_function(outputs, test_labels)
                predict_y = torch.max(outputs, dim=1)[1]
                acc += (predict_y == val_labels.to(device)).sum().item()
            val_accurate = acc / val_num
            if val_accurate > best_acc:
                best_acc = val_accurate
                torch.save(net.state_dict(), save_path)
            print('[epoch %d] train_loss: %.3f  test_accuracy: %.3f' %
                  (epoch + 1, running_loss / step, val_accurate))
            list_loss.append(running_loss / step)
            list_acc.append(val_accurate)
        if epoch % 20 == 0:
            #保存loss and acc
            file_loss_path = "./ResNeSkt_loss.txt"
            with open(file_loss_path, "w") as file_object:
                json.dump(list_loss, file_object)

            file_acc_path = "./ResNeSkt_acc.txt"
            with open(file_acc_path, "w") as file_object:
                json.dump(list_acc, file_object)
    print('Finished Training')
Esempio n. 5
0
    plt.plot(new_est[:, 0],
             new_est[:, 1],
             color='blue',
             linewidth=1,
             label='EST')
    plt.show()
    return


if __name__ == '__main__':
    path = 'data/test/EvaluationFramework_ISMIR2014/DATASET'
    f_path = 'data/test/Process_data/FEAT'

    onset = [0.1, 0.256, 0.279, 0.336, 0.469, 0.53]
    offset = [0.01, 0.23, 0.266, 0.267, 0.39, 0.4]

    # model = get_Resnet(channel=hparam.FEAT_channel).to(device)
    # model.load_state_dict(torch.load("checkpoint/1227_748HP.pth"))
    from resnest import resnest50

    model = resnest50(channel=9, num_classes=6).to(device)
    model.load_state_dict(torch.load("checkpoint/3690.pth"))
    model.eval()
    print("load OK")

    testset_evaluation(path,
                       f_path,
                       model=model,
                       timestep=0,
                       channel=hparam.FEAT_channel)