Ejemplo n.º 1
0
def single_run(size, score_to_win, AgentClass, model, **kwargs):
    game = Game(size, score_to_win)
    agent = AgentClass(game, model, display=Display(), **kwargs)
    agent.play(verbose=True)
    return game.score


if __name__ == '__main__':
    GAME_SIZE = 4
    SCORE_TO_WIN = 2048
    N_TESTS = 10
    '''====================
    Use your own agent here.'''
    PATH = './2048.pth'
    #PATH = './2048_CPU.pth'
    model = Net()
    model.load_state_dict(torch.load(PATH))
    #这行语句在测试的时候一定要加,不然参数可能发生变化
    model.eval()
    TestAgent = MyAgent
    '''===================='''

    scores = []
    for _ in range(N_TESTS):
        score = single_run(GAME_SIZE,
                           SCORE_TO_WIN,
                           AgentClass=TestAgent,
                           model=model.cpu())
        #score = single_run(GAME_SIZE, SCORE_TO_WIN,
        #                   AgentClass=TestAgent, model = model)
        scores.append(score)
Ejemplo n.º 2
0
    from torch.autograd import Variable
    import torch.optim as optim
    from tools_for_model import generateTrainSet
    from my_model import Net, weights_init
    import torch
    import time
    #用于保存生成的数据集
    import pickle

    start_time = time.time()

    PATH = './2048.pth'
    PATH_CPU = './2048_CPU.pth'

    model = Net()
    #加载已经训练的模型
    model.load_state_dict(torch.load(PATH))
    #参数初始化
    #model.apply(weights_init)

    if torch.cuda.is_available():
        print("gpu is available")
        model.cuda()  #将所有的模型参数移动到GPU上

    print("Load Time {} minutes".format(int((time.time() - start_time) / 60)))
    criterion = torch.nn.CrossEntropyLoss()
    optimizer = optim.Adam(model.parameters(), lr=5e-5)

    #最外层循环次数
    EPOCH_1 = 20
Ejemplo n.º 3
0
from torchvision.models.inception import inception_v3
from torchvision import datasets, transforms

from PIL import Image
#from scipy.misc import imsave
import imageio

import matplotlib.pyplot as plt
import os
import numpy as np


reverse_trans = lambda x: np.asarray(T.ToPILImage()(x))

loss = nn.CrossEntropyLoss()
net = Net()
net.load_state_dict(torch.load('./fashion_mnist_cnn.pt'))
net.cuda()
net.eval()

eps = 2 * 8 / 225.
steps = 40
norm = float('inf')
step_alpha = 0.01

classes = {
    0:"T-shirt/top",
    1:"Trouser",
    2:"Pullover",
    3:"Dress",
    4:"Coat",
Ejemplo n.º 4
0
import torch
from white_box_attack import *
import pickle
import os
from torch import nn
from torchvision import transforms
from my_model import Net
from torch.autograd import Variable
from torch.autograd.gradcheck import zero_gradients
import matplotlib.pyplot as plt
import os
import numpy as np
"""------------ load models and data ---------------------"""
device = 'cuda: 0'

with open("./attack_data/correct_1k.pkl", "rb") as f:
    data = pickle.load(f)

black_model = torch.load('./Res18_accuracy_0.9264.pkl').to(device)
black_model.conv5_x = nn.AvgPool2d(7, 7, 0)

white_model = Net().to(device)
white_model.load_state_dict(torch.load('./fashion_mnist_cnn.pt'))

imgs = torch.tensor(data[0]).to(device)

labels = torch.tensor(data[1]).to(device).squeeze(dim=1)
labels = labels.max(1)[1]
"""-------------- white box attack ---------------------"""
Ejemplo n.º 5
0
    agent = AgentClass(game=game, myNet=model, **kwargs)

    trace = []
    for board in board_json:
        game.board = np.array(board)
        direction = agent.step()
        trace.append(direction)
    fingerprint = "".join(str(i) for i in trace)
    return fingerprint


from collections import Counter
'''====================
Use your own agent here.'''
PATH = './2048.pth'
#PATH = './2048_CPU.pth'
model = Net()
model.load_state_dict(torch.load(PATH))
#这行语句在测试的时候一定要加,不然参数可能发生变化
model.eval()
TestAgent = MyAgent
'''===================='''

fingerprint = generate_fingerprint(AgentClass=TestAgent, model=model.cpu())
#fingerprint = generate_fingerprint(AgentClass=TestAgent, model=model)

with open("EE369_fingerprint.json", 'w') as f:
    pack = dict()
    pack['fingerprint'] = fingerprint
    pack['statstics'] = dict(Counter(fingerprint))
    f.write(json.dumps(pack, indent=4))