Exemple #1
0
def draw_kernels(start, end, ns, kernel_size):
    global image
    global tkImage
    global labels
    labels = [tk.Label(top) for _ in range(ns)]
    global images
    images = []

    Label_visker = tk.Label(top, text="Used Gaussian Kernels:")
    Label_visker.place(x=10, y=130)
    for s in range(ns):
        temp = template(kernel_size, start + s * (end - start) / ns)
        temp = temp / temp.max() * 255
        image = Image.fromarray(temp).resize((90, 90))
        tkImage = ImageTk.PhotoImage(image=image)
        images.append(tkImage)
        # image.show()
    for s in range(ns):
        labels[s].config(image=images[s])
        labels[s].place(x=10 + s * 90, y=160)
def run(data_source):
    total_num = 100
    run_once_button.config(state='disabled')
    run_all_button.config(state='disabled')

    start = float(s1.get())
    end = float(s2.get())
    ns = int(s3.get())
    kernel_size = int(s4.get())

    draw_kernels(start, end, ns, kernel_size)

    ckpt = checkpoint.get()
    if net_comboxlist.get() == 'LeNet':
        net = Net()
        params = torch.load(ckpt)
        net.load_state_dict(params)
        trans = transforms.Compose([transforms.ToTensor()])
    if net_comboxlist.get() == 'ResNet32':
        checkp = torch.load(ckpt, map_location='cpu')
        net = checkp['net']
        trans = transforms.Compose([
            transforms.ToTensor(),
            transforms.Normalize(mean=[0.4914, 0.4822, 0.4465],
                                 std=[0.2023, 0.1994, 0.2010])
        ])

    if use_cuda.get():
        net.cuda()
    net.eval()

    Acc = 0

    Count = 0

    global line_label
    line_label = tk.Label(top)

    image_labels = [tk.Label(top) for _ in range(ns)]

    pathdir = imagedir.get() + data_source
    for name in os.listdir(pathdir):
        filename = os.path.join(pathdir, name)
        img = np.load(filename)
        Count += 1
        C = np.zeros((ns, 10))

        global exam_images
        exam_images = []

        for i in range(ns):
            #  do gaussian blur
            temp = template(2, i * (2 / ns))
            input_image = img_conv2d(img, temp)

            if i < 5:
                image = Image.fromarray(np.uint8(input_image)).resize((90, 90))
                exam_images.append(ImageTk.PhotoImage(image=image))
                image_labels[i].config(image=exam_images[i])
                image_labels[i].place(x=10 + i * 90, y=360)

            if len(input_image.shape) == 2:
                input_image = np.expand_dims(input_image, 2)
            input_image = trans(input_image / 255)
            input_image = input_image.view(-1, input_image.shape[0],
                                           input_image.shape[1],
                                           input_image.shape[2])
            input_image = input_image.float()

            if use_cuda.get():
                input_image = input_image.cuda()

            preds = F.softmax(net(input_image), dim=1)
            C[i, :] = preds.cpu().detach().numpy()

            draw_preds_lines(C)

        draw_roc_curves(C, name, Image.fromarray(np.uint8(img)))

        c = np.zeros(10)

        for i in range(10):
            c[i] = max(C[:, i]) - min(C[:, i])

        fluc = max(c)

        t = 0.5
        if fluc > t:
            Acc += 1

        if Count >= total_num:
            acc = Acc / total_num
            log_text = "Done! The attack detection accuracy is {.2f}!".format(
                acc)
            send_information(Receive_window, log_text)
            break
        time.sleep(2)

    run_once_button.config(state='normal')
    run_all_button.config(state='normal')
Exemple #3
0
def run():
    run_button.config('disabled')
    start = int(s1.get())
    end = int(s2.get())
    ns = int(s3.get())
    kernel_size = int(s4.get())

    draw_kernels(start, end, ns, kernel_size)

    Progress = tk.Label(top, text="Running Progress", font=ft)
    Progress.place(x=10, y=260)

    global canvas
    canvas = tk.Canvas(top, width=465, height=22)
    canvas.place(x=10, y=280)

    global out_rec
    global fill_rec
    out_rec = canvas.create_rectangle(2, 2, 440, 20, outline="blue", width=1)
    fill_rec = canvas.create_rectangle(2,
                                       2,
                                       0,
                                       20,
                                       outline="",
                                       width=0,
                                       fill="green")

    datasetname = comboxlist.get()

    for idx, (data, target) in enumerate(train_loader):
        if datasetname == 'MNIST':
            data = data.numpy()[0][0] * 255
        if datasetname == 'CIFAR10':
            data = data.numpy()[0] * 255
            data = data.transpose((1, 2, 0))
        target = target.numpy()[0]

        root = 'data/augemented_data/{}/{}'.format(datasetname, target)
        if os.path.exists(root) is False:
            os.makedirs(root)

        for s in range(ns):
            temp = template(kernel_size, start + s * (end - start) / ns)
            img = img_conv2d(data, temp)
            file_name = 'data/augemented_data/{}/{}/{}-{}.bmp'.format(
                datasetname, target, idx, s)
            if datasetname == 'MNIST':
                im = Image.fromarray(np.uint8(img)).convert('L')
            else:
                im = Image.fromarray(np.uint8(img))
            im.save(file_name)

        if idx % int(len(train_loader) / 600) == 0:
            change_schedule(idx, len(train_loader))
        if idx > 10:
            break

    Finish_label = tk.Label(
        top,
        wraplength=520,
        justify='left',
        text=
        "Done! The augmentated images are stored in \"data/augmente\nd_data/{}\" for next use in step2!"
        .format(datasetname),
        font=ft)
    Finish_label.place(x=10, y=310)

    draw_eample_results(ns)
    run_button.config(state='normal')
    load_button.config(state='normal')
Exemple #4
0
def run(run_num):

    run_once_button.config(state='disabled')
    run_all_button.config(state='disabled')

    start = int(s1.get())
    end = int(s2.get())
    ns = int(s3.get())
    kernel_size = int(s4.get())

    draw_kernels(start, end, ns, kernel_size)

    # load model
    ckpt = checkpoint.get()
    if net_comboxlist.get() == 'LeNet':
        net = Net()
        params = torch.load(ckpt)
        net.load_state_dict(params)
        trans = transforms.Compose([transforms.ToTensor()])
    if net_comboxlist.get() == 'ResNet32':
        checkp = torch.load(ckpt, map_location='cpu')
        net = checkp['net']
        trans = transforms.Compose([
            transforms.ToTensor(),
            transforms.Normalize(mean=[0.4914, 0.4822, 0.4465],
                                 std=[0.2023, 0.1994, 0.2010])
        ])

    if use_cuda.get():
        net.cuda()
    net.eval()

    C = 0
    ns = 5
    count_succ = np.zeros(ns + 1)

    Label_visexa = tk.Label(top, text="Evolved images:")
    Label_visexa.place(x=10, y=340)
    image_labels = [tk.Label(top) for _ in range(ns)]

    pathdir = imagedir.get()

    Label_vispic = tk.Label(top, text="Histogram of Evolved Predictions:")
    Label_vispic.place(x=480, y=10)

    global bar_labels
    bar_labels = [tk.Label(top) for _ in range(ns + 1)]

    for name in os.listdir(pathdir):
        filename = os.path.join(pathdir, name)
        true_label = int(filename[-7])
        wrong_label = int(filename[-5])
        img = np.load(filename)
        C += 1
        scale_preds = np.zeros([1, 10])
        global exam_images
        exam_images = []

        global bar_images
        bar_images = []
        for i in range(ns):
            #  do gaussian blur
            temp = template(2, i * 0.4)
            input_image = img_conv2d(img, temp)
            # for visualization
            image = Image.fromarray(np.uint8(input_image)).resize((90, 90))

            exam_images.append(ImageTk.PhotoImage(image=image))
            image_labels[i].config(image=exam_images[i])
            image_labels[i].place(x=10 + i * 90, y=360)

            if net_comboxlist.get() == 'LeNet':
                input_image = np.expand_dims(input_image, 2)

            input_image = trans(input_image / 255)
            input_image = input_image.view(-1, input_image.shape[0],
                                           input_image.shape[1],
                                           input_image.shape[2])
            input_image = input_image.float()

            if use_cuda.get():
                input_image = input_image.cuda()
            preds = F.softmax(net(input_image), dim=1)

            preds = preds.cpu().detach().numpy()
            scale_preds += preds

            draw_preds(preds, i)

            pred_label = np.argmax(preds)
            if pred_label == int(true_label):
                count_succ[i] += 1

        scale_preds = scale_preds / ns

        Label_viscon = tk.Label(top, text="Multiscale confidences:")
        Label_viscon.place(x=480, y=150)
        draw_preds(scale_preds, ns)
        scale_label = np.argmax(scale_preds)

        logtext = "Classification result:\n"
        send_information(Receive_window, logtext)
        logtext = "True label: {}\n".format(true_label)
        send_information(Receive_window, logtext)
        if scale_label == int(true_label):
            count_succ[ns] += 1
            logtext = "Before multiscale defense {}, after multiscale defense {}, defense successes!\n".format(
                wrong_label, scale_label)
            send_information(Receive_window, logtext)
        else:
            logtext = "Before multiscale defense {}, after multiscale defense {}, defense fails!\n".format(
                wrong_label, scale_label)
            send_information(Receive_window, logtext)

        if C % 50 == 0:
            log_text = "processing: {} / {}\n".format(C, run_num)
            send_information(Receive_window, log_text)
        if C >= run_num:
            break
        time.sleep(1)

    log_text = "Before defense: {} / {} \t  Classification accuracy:{:.2f} \n".format(
        0, run_num, 0)
    send_information(Receive_window, log_text)
    log_text = "After defense:  {} / {} \t Classification accuracy:{:.2f} \n".format(
        int(count_succ[ns]), run_num, count_succ[ns] / run_num)
    send_information(Receive_window, log_text)

    run_once_button.config(state='normal')
    run_all_button.config(state='normal')