示例#1
0
    def load(self, **kwargs):
        session = kwargs["session"]
        assert isinstance(session, tf.Session)

        x_input = tf.placeholder(tf.float32, shape=(None,) + self.x_shape)
        logits = self.inference(
            x_input, 
            reuse=False)
        model_path = get_model_path('pgd_at')
        url = 'https://www.dropbox.com/s/g4b6ntrp8zrudbz/adv_trained.zip?dl=1'
        fname = os.path.join(model_path, url.split('/')[-1])
        if not os.path.exists(fname):
            if not os.path.exists(model_path):
                os.makedirs(model_path)
            
            from six.moves import urllib
            urllib.request.urlretrieve(url, fname)
            import zipfile
            model_zip = zipfile.ZipFile(fname)
                
            model_zip.extractall(model_path)
            print('Extracted model in {}'.format(model_zip.namelist()[1]))
       
        saver = tf.train.Saver()
        checkpoint = tf.train.latest_checkpoint(model_path+'/adv_trained')
        saver.restore(session, checkpoint)
    def load(self, **kwargs):
        session = kwargs["session"]
        assert isinstance(session, tf.Session)

        x_input = tf.placeholder(self.x_dtype, shape=(None, ) + self.x_shape)
        with slim.arg_scope(resnet_v2.resnet_arg_scope()):
            resnet_v2.resnet_v2_152(x_input,
                                    num_classes=self.n_class,
                                    is_training=False,
                                    reuse=tf.AUTO_REUSE)

        model_path = get_model_path('resnet_v2_152')
        if not os.path.exists(model_path):
            os.makedirs(model_path)
            urllib.request.urlretrieve(
                'http://download.tensorflow.org/models/resnet_v2_152_2017_04_14.tar.gz',
                os.path.join(model_path, 'resnet_v2_152_2017_04_14.tar.gz'),
                show_progress)

            tar = tarfile.open(
                os.path.join(model_path, 'resnet_v2_152_2017_04_14.tar.gz'))
            file_names = tar.getnames()
            for file_name in file_names:
                tar.extract(file_name, model_path)

        saver = tf.train.Saver(slim.get_model_variables(scope='resnet_v2'))
        saver.restore(session, os.path.join(model_path, 'resnet_v2_152.ckpt'))
    def load(self, **kwargs):
        model_path = get_model_path('cifar10-convnet-15742544.mat')

        mcn = sio.loadmat(model_path)
        mcn_weights = dict()
        mcn_weights['conv1.weights'] = mcn['net'][0][0][0][0][0][0][0][1][0][
            0].transpose()
        mcn_weights['conv1.bias'] = mcn['net'][0][0][0][0][0][0][0][1][0][
            1].flatten()
        mcn_weights['conv2.weights'] = mcn['net'][0][0][0][0][3][0][0][1][0][
            0].transpose()
        mcn_weights['conv2.bias'] = mcn['net'][0][0][0][0][3][0][0][1][0][
            1].flatten()
        mcn_weights['conv3.weights'] = mcn['net'][0][0][0][0][6][0][0][1][0][
            0].transpose()
        mcn_weights['conv3.bias'] = mcn['net'][0][0][0][0][6][0][0][1][0][
            1].flatten()
        mcn_weights['conv4.weights'] = mcn['net'][0][0][0][0][9][0][0][1][0][
            0].transpose()
        mcn_weights['conv4.bias'] = mcn['net'][0][0][0][0][9][0][0][1][0][
            1].flatten()
        mcn_weights['conv5.weights'] = mcn['net'][0][0][0][0][11][0][0][1][0][
            0].transpose()
        mcn_weights['conv5.bias'] = mcn['net'][0][0][0][0][11][0][0][1][0][
            1].flatten()

        for k in ['conv1', 'conv2', 'conv3', 'conv4', 'conv5']:
            t = self.model.__getattr__(k)
            assert t.weight.data.size() == mcn_weights['%s.weights' % k].shape
            t.weight.data[:] = torch.from_numpy(mcn_weights['%s.weights' % k])
            assert t.bias.data.size() == mcn_weights['%s.bias' % k].shape
            t.bias.data[:] = torch.from_numpy(mcn_weights['%s.bias' % k])
示例#4
0
    def load(self, **kwargs):
        session = kwargs["session"]
        assert isinstance(session, tf.Session)

        x_input = tf.placeholder(tf.float32, shape=(None, ) + self.x_shape)
        with tf.contrib.framework.arg_scope(resnet_v2.resnet_arg_scope()):
            logits, _ = resnet_v2.resnet_v2_50(x_input,
                                               self.n_class,
                                               is_training=False,
                                               reuse=tf.AUTO_REUSE)

        model_path = get_model_path('alp')
        url = 'http://download.tensorflow.org/models/adversarial_logit_pairing/imagenet64_alp025_2018_06_26.ckpt.tar.gz'
        fname = os.path.join(model_path, url.split('/')[-1])
        if not os.path.exists(fname):
            if not os.path.exists(model_path):
                os.makedirs(model_path)

            from six.moves import urllib
            urllib.request.urlretrieve(url, fname, show_progress)
            import tarfile
            t = tarfile.open(fname)
            t.extractall(model_path)
            print('Extracted model')

        saver = tf.train.Saver()
        saver.restore(session, fname.split('.tar.gz')[0])
    def load(self, **kwargs):
        session = kwargs["session"]
        assert isinstance(session, tf.Session)

        keras.backend.set_session(session)
        model_input = Input(shape=self.x_shape)
        model_dic = {}
        model_out = []
        for i in range(3):
            model_dic[str(i)] = resnet_v2(input=model_input,
                                          depth=110,
                                          num_classes=self.n_class)
            model_out.append(model_dic[str(i)][2])
        model_output = keras.layers.concatenate(model_out)
        model = Model(inputs=model_input, outputs=model_output)
        model_ensemble = keras.layers.Average()(model_out)
        model_ensemble = Model(input=model_input, output=model_ensemble)

        model_path = get_model_path('adp-ensemble')
        fname = os.path.join(model_path, 'cifar10_ResNet110v2_model.200.h5')
        if not os.path.exists(fname):
            if not os.path.exists(model_path):
                os.makedirs(model_path)
            urllib.request.urlretrieve(
                "http://ml.cs.tsinghua.edu.cn/~tianyu/ADP/pretrained_models/ADP_standard_3networks/cifar10_ResNet110v2_model.200.h5",
                fname, show_progress)

        datamean = os.path.join(model_path, 'mean.npy')

        model.load_weights(fname)
        self.model = model_ensemble
        self.mean = np.load(datamean)
 def load(self, **kwargs):
     model_path = get_model_path('cifar_resnet_2px.pth')
     
     try:
         print(model_path)
         checkpoint = torch.load(model_path)
         self.model.load_state_dict(checkpoint['state_dict'][0])
         self.eval()
     except FileNotFoundError:
         raise IOError
    def load(self, session, **kwargs):
        assert isinstance(session, tf.Session)

        x_input = tf.placeholder(tf.float32, shape=(None,) + self.x_shape)
        self.model.inference(x_input, self.num_residual_blocks, reuse=False)

        model_path = get_model_path('resnet56-cifar.ckpt')

        saver = tf.train.Saver(var_list=tf.global_variables())
        saver.restore(session, model_path)
    def load(self, **kwargs):
        model_path = get_model_path('cifar10_vgg_rse.pth')

        try:
            checkpoint = torch.load(model_path)
            from collections import OrderedDict
            state_dict = OrderedDict()
            for k, v in checkpoint.items():
                name = k[7:]
                state_dict[name] = v
            self.model.load_state_dict(state_dict)
            self.eval()
        except FileNotFoundError:
            raise IOError
示例#9
0
    def load(self, **kwargs):
        model_path = get_model_path('model_cifar_wrn.pt')
        if not os.path.exists(model_path):
            if not os.path.exists(os.path.dirname(model_path)):
                os.makedirs(os.path.dirname(model_path))
            urllib.request.urlretrieve(
                'http://people.virginia.edu/~yy8ms/TRADES/model_cifar_wrn.pt',
                model_path, show_progress)

        try:
            checkpoint = torch.load(model_path)
            self.model.load_state_dict(checkpoint)
            self.eval()
        except FileNotFoundError:
            raise IOError
示例#10
0
    def load(self, **kwargs):
        session = kwargs["session"]
        assert isinstance(session, tf.Session)

        x_input = tf.placeholder(tf.float32, shape=(None, ) + self.x_shape)
        x_input = tf.transpose(x_input, [0, 3, 1, 2])
        with TowerContext('', is_training=False):
            with tf.variable_scope('', reuse=tf.AUTO_REUSE):
                logits = self.model.get_logits(x_input)

        model_path = get_model_path('R152-Denoise.npz')
        url = 'https://github.com/facebookresearch/ImageNet-Adversarial-Training/releases/download/v0.1/R152-Denoise.npz'
        if not os.path.exists(model_path):
            if not os.path.exists(os.path.dirname(model_path)):
                os.makedirs(os.path.dirname(model_path))

            from six.moves import urllib
            urllib.request.urlretrieve(url, model_path, show_progress)

        get_model_loader(model_path).init(session)
    def loadMat(self):
        stats_path = get_model_path('stats.mat')

        self.stats = sio.loadmat(stats_path)
        self.mean = torch.from_numpy(self.stats['dataMean'][np.newaxis])
        self.trans = torch.from_numpy(self.stats['Trans'].T)