예제 #1
0
    def __init__(self, opt):
        BaseModel.__init__(self, opt)
        self.loss_names = ['correctness','regularization']
        self.visual_names = ['input_P1','input_P2', 'warp', 'flow_fields',
                            'masks']
        self.model_names = ['G']

        self.FloatTensor = torch.cuda.FloatTensor if len(self.gpu_ids)>0 \
            else torch.FloatTensor
        self.ByteTensor = torch.cuda.ByteTensor if len(self.gpu_ids)>0 \
            else torch.ByteTensor
        self.net_G = network.define_g(opt, structure_nc=opt.structure_nc, ngf=32, img_f=256, 
                                       encoder_layer=5, norm='instance', activation='LeakyReLU', 
                                       attn_layer=self.opt.attn_layer, use_spect=opt.use_spect_g,
                                       )
        self.L1loss = torch.nn.L1Loss()
        self.flow2color = util.flow2color()

        if self.isTrain:
            self.Correctness = external_function.PerceptualCorrectness().to(opt.device)
            self.Regularization = external_function.MultiAffineRegularizationLoss(kz_dic=opt.kernel_size).to(opt.device)
            self.optimizer_G = torch.optim.Adam(itertools.chain(filter(lambda p: p.requires_grad, self.net_G.parameters())),
                                                lr=opt.lr, betas=(0.0, 0.999))
            self.optimizers.append(self.optimizer_G)
        self.setup(opt)
예제 #2
0
    def __init__(self, input_shape, output_shape, learning_rate):
        BaseModel.__init__(self, input_shape, output_shape)
        self.learning_rate = learning_rate

        obs_input = Input(input_shape, name='observations')

        conv_1 = Convolution2D(filters=32,
                               kernel_size=(8, 8),
                               strides=(4, 4),
                               padding='valid',
                               activation='relu')(obs_input)
        conv_2 = Convolution2D(filters=64,
                               kernel_size=(4, 4),
                               strides=(2, 2),
                               padding='valid',
                               activation='relu')(conv_1)
        conv_3 = Convolution2D(filters=64,
                               kernel_size=(3, 3),
                               strides=(1, 1),
                               padding='valid',
                               activation='relu')(conv_2)
        conv_flattened = Flatten()(conv_3)
        hidden = Dense(512, activation='linear')(conv_flattened)
        output = Dense(output_shape)(hidden)
        self.model = Model(input=obs_input, output=output)
        # Compile model
        optimizer = Adam(lr=self.learning_rate)
        self.model.compile(optimizer=optimizer,
                           loss=tf.losses.huber_loss,
                           metrics=['acc'])
        print(self.model.summary())
예제 #3
0
def train_model(
        model: BaseModel,
        dataset: Dict[str, np.ndarray],
        test_split: Optional[float] = 0.1,
        **kwargs
):
    n = next(iter(dataset.values())).shape[0]

    # shuffle dataset
    shuffle_perm = np.random.permutation(n)
    dataset = {k: v[shuffle_perm] for k, v in dataset.items()}

    # train test split
    if test_split is not None:
        n_test = int(test_split * n)

        dataset_test = {k: v[:n_test] for k, v in dataset.items()}
        dataset_train = {k: v[n_test:] for k, v in dataset.items()}
    else:
        dataset_train = dataset_test = dataset

    # train model
    model.fit(dataset_train, **kwargs)

    # test model
    model.test(dataset_test)
예제 #4
0
    def __init__(self, opt):
        BaseModel.__init__(self, opt)
        self.loss_names = ['mpjpe']
        self.model_names = ['G']
        self.FloatTensor = torch.cuda.FloatTensor if len(self.gpu_ids)>0 \
            else torch.FloatTensor
        self.ByteTensor = torch.cuda.ByteTensor if len(self.gpu_ids)>0 \
            else torch.ByteTensor

        self.net_G = network.define_g(opt, filename='generator', structure_nc=opt.structure_nc, channels=256, layers=4)
        if len(opt.gpu_ids) > 1:
            self.net_G = torch.nn.DataParallel(self.net_G, device_ids=self.gpu_ids)

        self.convert2skeleton = openpose_utils.tensor2skeleton()

        if self.isTrain:
            self.L2loss = torch.nn.MSELoss()
            self.optimizer_G = torch.optim.Adam(itertools.chain(
                                               filter(lambda p: p.requires_grad, self.net_G.parameters())),
                                               lr=opt.lr, betas=(0.0, 0.999))
            self.optimizers.append(self.optimizer_G)
        else:
            self.L2loss = torch.nn.MSELoss()
            util.mkdir(os.path.join(self.opt.results_dir))

        self.setup(opt)
예제 #5
0
 def __init__(self, feature_builder, num_clusters, n_init):
     BaseModel.__init__(self, feature_builder)
     self.le = LabelEncoder()
     self.model = MiniBatchKMeans(n_clusters=num_clusters,
                                  init='k-means++',
                                  n_init=n_init,
                                  init_size=1000,
                                  batch_size=1000)
 def __init__(self, env):
     BaseModel.__init__(self, env)
     nn.Module.__init__(self)
     self.trainable = True
     self.nn_model = True
     self.fc1 = nn.Linear(self.n*3, self.n)
     self.fc_pi = nn.Linear(self.n, self.n)
     self.fc_v = nn.Linear(self.n, 1)
예제 #7
0
    def __init__(self, opt):
        """Initialize the pix2pix class.

        Parameters:
            opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions
        """
        BaseModel.__init__(self, opt)
        # specify the training losses you want to print out. The training/test scripts will call <BaseModel.get_current_losses>
        self.loss_names = ['G_GAN', 'G_L1', 'D_real', 'D_fake']
        # specify the images you want to save/display. The training/test scripts will call <BaseModel.get_current_visuals>
        self.visual_names = ['real_A', 'fake_B', 'real_B']
        # specify the models you want to save to the disk. The training/test scripts will call <BaseModel.save_networks> and <BaseModel.load_networks>
        if self.isTrain:
            self.model_names = ['G', 'D']
        else:  # during test time, only load G
            self.model_names = ['G']
        # define networks (both generator and discriminator)

        # LGQ here I change the generator to my line encoding
        #self.netG = networks.define_G(opt.input_nc, opt.output_nc, opt.ngf, opt.netG, opt.norm,
        #                              not opt.no_dropout, opt.init_type, opt.init_gain, self.gpu_ids)
        self.netG = fusion_nets3._2layerFusionNets_()

        if self.isTrain:
            # define loss functions
            self.criterionGAN = networks.GANLoss(opt.gan_mode).to(self.device)
            self.criterionL1 = torch.nn.L1Loss()
            # LGQ add another loss for G
            self.criterionMTL = MTL_loss()
            # initialize optimizers; schedulers will be automatically created by function <BaseModel.setup>.
            self.optimizer_G = torch.optim.Adam(self.netG.parameters(),
                                                lr=opt.lr,
                                                betas=(opt.beta1, 0.999))
            self.optimizer_G_f = torch.optim.Adam(
                self.netG.fusion_layer.parameters(),
                lr=opt.lr,
                betas=(opt.beta1, 0.999))

            self.optimizer_G_1 = torch.optim.Adam(
                self.netG.side_branch1.parameters(),
                lr=opt.lr,
                betas=(opt.beta1, 0.999))
            self.optimizer_G_2 = torch.optim.Adam(
                self.netG.side_branch2.parameters(),
                lr=opt.lr,
                betas=(opt.beta1, 0.999))
            self.optimizer_G_3 = torch.optim.Adam(
                self.netG.side_branch3.parameters(),
                lr=opt.lr,
                betas=(opt.beta1, 0.999))

            self.optimizers.append(self.optimizer_G)

        self.validation_init()
        self.bw_cnt = 0
        self.displayloss1 = 0
        self.displayloss2 = 0
        self.displayloss3 = 0
    def __init__(self, opt):
        """Initial the pluralistic model"""
        BaseModel.__init__(self, opt)
        self.loss_names = ['app_gen','correctness_p', 'correctness_r','content_gen','style_gen',
                            'regularization_p', 'regularization_r',
                            'ad_gen','dis_img_gen',
                            'ad_gen_v', 'dis_img_gen_v']

        self.visual_names = ['P_reference','BP_reference', 'P_frame_step','BP_frame_step','img_gen', 'flow_fields', 'masks']        
        self.model_names = ['G','D','D_V']

        self.FloatTensor = torch.cuda.FloatTensor if len(self.gpu_ids)>0 \
            else torch.FloatTensor
        self.ByteTensor = torch.cuda.ByteTensor if len(self.gpu_ids)>0 \
            else torch.ByteTensor

        # define the Animation model
        self.net_G = network.define_g(opt, image_nc=opt.image_nc, structure_nc=opt.structure_nc, ngf=64, img_f=512,
                                      layers=opt.layers, num_blocks=2, use_spect=opt.use_spect_g, attn_layer=opt.attn_layer, 
                                      norm='instance', activation='LeakyReLU', extractor_kz=opt.kernel_size)
        if len(opt.gpu_ids) > 1:
            self.net_G = torch.nn.DataParallel(self.net_G, device_ids=self.gpu_ids)

        self.flow2color = util.flow2color()

        self.net_D = network.define_d(opt, ndf=32, img_f=128, layers=4, use_spect=opt.use_spect_d)
        if len(opt.gpu_ids) > 1:
            self.net_D = torch.nn.DataParallel(self.net_D, device_ids=self.gpu_ids)

        input_nc = (opt.frames_D_V-1) * opt.image_nc
        self.net_D_V = network.define_d(opt, input_nc=input_nc, ndf=32, img_f=128, layers=4, use_spect=opt.use_spect_d)
        if len(opt.gpu_ids) > 1:
            self.net_D_V = torch.nn.DataParallel(self.net_D_V, device_ids=self.gpu_ids)                

        if self.isTrain:
            # define the loss functions
            self.GANloss = external_function.AdversarialLoss(opt.gan_mode).to(opt.device)
            self.L1loss = torch.nn.L1Loss()
            self.L2loss = torch.nn.MSELoss()
            self.Correctness = external_function.PerceptualCorrectness().to(opt.device)
            self.Regularization = external_function.MultiAffineRegularizationLoss(kz_dic=opt.kernel_size).to(opt.device)
            self.Vggloss = external_function.VGGLoss().to(opt.device)

            # define the optimizer
            self.optimizer_G = torch.optim.Adam(itertools.chain(
                                               filter(lambda p: p.requires_grad, self.net_G.parameters())),
                                               lr=opt.lr, betas=(0.0, 0.999))
            self.optimizers.append(self.optimizer_G)

            self.optimizer_D = torch.optim.Adam(itertools.chain(
                                filter(lambda p: p.requires_grad, self.net_D.parameters()),
                                filter(lambda p: p.requires_grad, self.net_D_V.parameters())),
                                lr=opt.lr*opt.ratio_g2d, betas=(0.0, 0.999))
            self.optimizers.append(self.optimizer_D)
        else:
            self.results_dir_base = self.opt.results_dir
        self.setup(opt)
예제 #9
0
    def train(self):
        # call parent function.
        BaseModel.train(self)

        #trains the k-nearest-neighbor model
        self.model.fit(self.train_x, self.train_y)

        # update the is_trained variable.
        self.is_trained = True
예제 #10
0
    def train(self):
        # call parent function.
        BaseModel.train(self)

        #trains the support-vector-machine model
        self.model.fit(self.train_x, self.train_y)

        # update the is_trained variable.
        self.is_trained = True
예제 #11
0
    def __init__(self, data, normalize=False):
        # call parent function.
        BaseModel.__init__(self, data, normalize=normalize, **kwargs)

        # placeholders specific to this class.
        self.model = None

        # Reference to the library used: https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html#sklearn.neighbors.KNeighborsClassifier
        # Initlising the class
        self.model = KNeighborsClassifier()
예제 #12
0
    def __init__(self, data, normalize=False, **kwargs):
        # call parent function.
        BaseModel.__init__(self, data, normalize=normalize, **kwargs)

        # placeholders specific to this class.
        self.model = None

        # Reference to the library used: https://scikit-learn.org/stable/modules/svm.html
        # Initlising the class
        self.model = svm.SVC()
예제 #13
0
    def test(self):
        # call parent function.
        BaseModel.test(self)

        # Using model built with training data, to predict the test data - using the predict method in
        # sklearn.neighbors.KNeighborsClassifier
        y_pred = self.model.predict(self.test_x)
        self.test_predictions = pd.Series(data=y_pred, dtype="int64")

        # assess the performance of the predictions.
        self.assess_performance()
예제 #14
0
 def __init__(self, tweet_id=None, author=None, text=None, timestamp=None):
     """
     :type tweet_id: string
     :type author: string
     :type text: string
     :type timestamp: string
     """
     BaseModel.__init__(self, tweet_id)
     self.author = author
     self.text = text
     self.timestamp = timestamp
예제 #15
0
    def hyperparameter_tuning(self):

        # Defines the parameter search space
        param_space = {
            'n_neighbors': (1, 100),  # integer valued parameter
            'weights': ['uniform', 'distance'],  # categorical parameter
            'metric': ['euclidean', 'manhattan',
                       'minkowski']  # categorical parameter
        }

        # Calls the parent function - finds the combination of parameters from the given param_space that
        # yields the highest score - set to accuracy currently
        BaseModel.hyperparameter_tuning(self, 'Grid', param_space)
예제 #16
0
    def __init__(self, input_shape, output_shape, learning_rate):
        BaseModel.__init__(self, input_shape, output_shape)
        self.learning_rate = learning_rate
        # input(f'Input shape: {input_shape}')
        # obs_input = Input(input_shape, name='observations')
        # normalized = Lambda(lambda x: x / 255.0)(obs_input)

        # conv_1 = Convolution2D(16, 8, 8,
        #                        subsample=(4, 4),
        #                        activation='relu')(normalized)
        # conv_2 = Convolution2D(32, 4, 4,
        #                        subsample=(2, 2),
        #                        activation='relu')(conv_1)
        # conv_flattened = Flatten()(conv_2)
        # hidden = Dense(256, activation='linear')(conv_flattened)
        # output = Dense(output_shape)(hidden)
        # # filtered_output = keras.layers.merge.Multiply()([output, actions_mask])

        # self.model = Model(input=obs_input,
        #                    output=output)

        # # Compile model
        # optimizer = RMSprop(learning_rate=self.learning_rate, epsilon=0.01)
        # self.model.compile(optimizer=optimizer,
        #                    loss='mse',
        #                    metrics=['acc'])
        # print(self.model.summary())
        
        
        # self.model = Sequential()
        # self.model.add(Dense(24, input_shape=input_shape, activation="relu"))
        # self.model.add(Dense(24, activation="relu"))
        # self.model.add(Dense(output_shape, activation="linear"))
        # self.model.compile(loss="mse", optimizer=Adam(lr=self.learning_rate))
        # print(self.model.summary())

        # self.model = Sequential()
        # self.model.add(Dense(24, input_shape=input_shape, activation="tanh"))
        # self.model.add(Dense(48, activation="tanh"))
        # self.model.add(Dense(output_shape, activation="linear"))
        # self.model.compile(loss="mse", optimizer=Adam(
        #     learning_rate=self.learning_rate, decay=0.01))
        # print(self.model.summary())

        self.model = Sequential()
        self.model.add(Dense(24, input_shape=input_shape, activation="relu"))
        self.model.add(Dense(24, activation="relu"))
        self.model.add(Dense(output_shape, activation="linear"))
        self.model.compile(loss="mse", optimizer=Adam(lr=self.learning_rate))
        print(self.model.summary())
예제 #17
0
    def __init__(self, opt):
        BaseModel.__init__(self, opt)
        self.opt = opt
        self.keys = ['head', 'body', 'leg']
        self.mask_id = {
            'head': [1, 2, 4, 13],
            'body': [3, 5, 6, 7, 10, 11, 14, 15],
            'leg': [8, 9, 12, 16, 17, 18, 19]
        }
        self.GPU = torch.device('cuda:0')

        self.loss_names = ['correctness', 'regularization']
        self.visual_names = [
            'input_P1', 'input_P2', 'warp', 'flow_fields', 'masks',
            'input_BP1', 'input_BP2'
        ]
        self.model_names = ['G']

        self.FloatTensor = torch.cuda.FloatTensor if len(self.gpu_ids)>0 \
            else torch.FloatTensor
        self.ByteTensor = torch.cuda.ByteTensor if len(self.gpu_ids)>0 \
            else torch.ByteTensor

        self.net_G = network.define_g(
            opt,
            structure_nc=opt.structure_nc,
            ngf=32,
            img_f=256,
            layers=5,
            norm='instance',
            activation='LeakyReLU',
            attn_layer=self.opt.attn_layer,
            use_spect=opt.use_spect_g,
        )
        self.flow2color = util.flow2color()

        if self.isTrain:
            # define the loss functions
            self.Correctness = external_function.PerceptualCorrectness().to(
                opt.device)
            self.Regularization = external_function.MultiAffineRegularizationLoss(
                kz_dic=opt.kernel_size).to(opt.device)
            # define the optimizer
            self.optimizer_G = torch.optim.Adam(itertools.chain(
                filter(lambda p: p.requires_grad, self.net_G.parameters())),
                                                lr=opt.lr,
                                                betas=(0.0, 0.999))
            self.optimizers.append(self.optimizer_G)
        # load the pretrained model and schedulers
        self.setup(opt)
예제 #18
0
 def __init__(self, sess, args):
     BaseModel.__init__(self, sess, args)
     self.args = args
     if self.args.phase.find('train') >= 0:
         self.is_train = True
     else:
         self.is_train = False
     self.image_size = [
         self.args.image_size, self.args.image_size, self.args.image_size
     ]
     self.train_sampler = IntIntSimNetSampler(self.args, True)
     self.validate_sampler = IntIntSimNetSampler(self.args, False)
     self.build_network()
     self.summary()
예제 #19
0
 def __init__(self, comment_id=None, title=None, comment=None, status=None, likes=None, date=None):
     """
     :type comment_id: string
     :type title: string
     :type comment: string
     :type status: string
     :type likes: int
     :type date: string
     """
     BaseModel.__init__(self, comment_id)
     self.title = title
     self.comment = comment
     self.status = status
     self.likes = likes
     self.date = date
예제 #20
0
 def __init__(self, sess, args):
     BaseModel.__init__(self, sess, args)
     # self.sess=sess
     self.args = args
     if args.phase == 'train':
         self.is_train = True
     else:
         self.is_train = False
     self.image_size = [
         self.args.image_size, self.args.image_size, self.args.image_size
     ]
     self.train_sampler = LabIntSimNetSampler(self.args, 'train')
     self.validate_sampler = LabIntSimNetSampler(self.args, 'validate')
     self.build_network()
     self.summary()
예제 #21
0
    def __init__(self, opt):
        BaseModel.__init__(self, opt)
        self.loss_names = ['app_gen', 'correctness_gen', 'content_gen', 'style_gen', 'regularization',
                           'ad_gen', 'dis_img_gen']

        self.visual_names = ['input_P1','input_P2', 'img_gen', 'flow_fields', 'masks']
        self.model_names = ['G','D']

        self.keys = ['head','body','leg']
        self.mask_id = {'head':[1,2,4,13],'body':[3,5,6,7,10,11,14,15],'leg':[8,9,12,16,17,18,19]}
        self.GPU = torch.device('cuda:0')

        self.FloatTensor = torch.cuda.FloatTensor if len(self.gpu_ids)>0 \
            else torch.FloatTensor

        # define the generator
        self.net_G = network.define_g(opt, image_nc=opt.image_nc, structure_nc=opt.structure_nc, ngf=64, img_f=512,
                                      layers=opt.layers, num_blocks=2, use_spect=opt.use_spect_g, attn_layer=opt.attn_layer, 
                                      norm='instance', activation='LeakyReLU', extractor_kz=opt.kernel_size)

        # define the discriminator 
        if self.opt.dataset_mode == 'fashion':
            self.net_D = network.define_d(opt, ndf=32, img_f=128, layers=4, use_spect=opt.use_spect_d)
        elif self.opt.dataset_mode== 'market':
            self.net_D = network.define_d(opt, ndf=32, img_f=128, layers=3, use_spect=opt.use_spect_d)
        self.flow2color = util.flow2color()

        if self.isTrain:
            # define the loss functions
            self.GANloss = external_function.AdversarialLoss(opt.gan_mode).to(opt.device)
            self.L1loss = torch.nn.L1Loss()
            self.Correctness = external_function.PerceptualCorrectness().to(opt.device)
            self.Regularization = external_function.MultiAffineRegularizationLoss(kz_dic=opt.kernel_size).to(opt.device)
            self.Vggloss = external_function.VGGLoss().to(opt.device)

            # define the optimizer
            self.optimizer_G = torch.optim.Adam(itertools.chain(
                                               filter(lambda p: p.requires_grad, self.net_G.parameters())),
                                               lr=opt.lr, betas=(0.0, 0.999))
            self.optimizers.append(self.optimizer_G)

            self.optimizer_D = torch.optim.Adam(itertools.chain(
                                filter(lambda p: p.requires_grad, self.net_D.parameters())),
                                lr=opt.lr*opt.ratio_g2d, betas=(0.0, 0.999))
            self.optimizers.append(self.optimizer_D)

        # load the pre-trained model and schedulers
        self.setup(opt)
예제 #22
0
 def get_a_page_of_link(cls, page, count_of_page):
     """
     获取一页链接
     :param page: 第几页
     :param count_of_page: 每页记录数
     :return:
     """
     return BaseModel.get_one_page_of_table(cls.table_name, " group_status = 0 or group_status = 1", page, count_of_page)
예제 #23
0
 def __init__(self,
              depth=6,
              n_device=1,
              n_parallel_trees=1,
              verbose=0,
              column_sampling_rate=1.0,
              bagging=0,
              tree_method='auto'):
     BaseModel.__init__(self)
     self.verbose = verbose
     self.n_device = n_device
     self.column_sampling_rate = column_sampling_rate
     self.bagging = bagging
     self.n_parallel_trees = n_parallel_trees
     self.tree_method = tree_method
     self.objective = ""
     self.num_class = 1
예제 #24
0
 def __init__(self, sess, args):
     BaseModel.__init__(self, sess, args)
     # self.sess=sess
     # self.args=args
     self.minibatch_size = self.args.batch_size
     self.image_size = [
         self.args.image_size, self.args.image_size, self.args.image_size
     ]
     if args.phase == 'train':
         self.is_train = True
     else:
         self.is_train = False
     self.train_sampler = Sampler(self.args, 'train')
     self.validate_sampler = Sampler(self.args, 'validate')
     self.logger = getLoggerV3('learn2reg', self.args.log_dir)
     self.build_network()
     self.summary()
예제 #25
0
 def __init__(self, params):
     BaseModel.__init__(self, params)
     self.loss_names = [
         'loss_identity', 'loss_cycle', 'loss_gan', 'loss_G', 'loss_D',
         'loss_D_A', 'loss_D_B'
     ]
     self.losses = self.make_loss_dict()
     if self.params.isTrain:
         self.model_names = ['G_A2B', 'G_B2A', 'D_A', 'D_B']
     else:
         self.model_names = ['G_A2B', 'G_B2A']
     # define image pool
     self.fake_pool_A = set_buffer_pool(self.params.pool_size)
     self.fake_pool_B = set_buffer_pool(self.params.pool_size)
     # define the nets
     self.netG_A2B = G(self.params.input_nc,
                       self.params.output_nc).to(self.device)
     self.netG_B2A = G(self.params.input_nc,
                       self.params.output_nc).to(self.device)
     self.netD_A = D(self.params.input_nc).to(self.device)
     self.netD_B = D(self.params.input_nc).to(self.device)
     # define optimizer
     self.optimizer_G = torch.optim.Adam(itertools.chain(self.netG_A2B.parameters(),\
          self.netG_B2A.parameters()),lr=params.lr,betas=(params.beta1,0.999))
     self.optimizer_D = torch.optim.Adam(itertools.chain(self.netD_A.parameters(),\
          self.netD_B.parameters()),lr=params.lr, betas=(params.beta1,0.999))
     self.optimizers = [self.optimizer_G, self.optimizer_D]
     if self.params.isTrain:
         self.schedulers = [
             get_scheduler(optim, self.params) for optim in self.optimizers
         ]
     # define loss function
     self.criterion_identity = torch.nn.L1Loss()
     self.criterion_cycle = torch.nn.L1Loss()
     self.criterion_GAN = torch.nn.MSELoss()
     #create target real and fake
     self.target_real = torch.ones(self.params.batch_size,
                                   requires_grad=False).to(
                                       self.params.device)
     self.target_fake = torch.zeros(self.params.batch_size,
                                    requires_grad=False).to(
                                        self.params.device)
     #init net
     self.init_weight_normal()
예제 #26
0
 def get_a_page_of_link(cls, page, count_of_page):
     """
     获取一页链接
     :param page: 第几页
     :param count_of_page: 每页记录数
     :return:
     """
     return BaseModel.get_one_page_of_table(
         cls.table_name, " group_status = 0 or group_status = 1", page,
         count_of_page)
예제 #27
0
def get_model_api():
    model = BaseModel()

    def model_api(image_storage):
        image = image_to_np_array(image_storage)
        output = model.predict(image)
        image = draw_boxes(image, output, 0.8)
        return image

    return model_api
예제 #28
0
class WechatReplyModel(BaseModel):
    table_name = "topic_wechat_reply"
    db = BaseModel.get_db_lib()

    @classmethod
    def add_setting(cls, wechat_group_name, reply_content, status, reply_key):
        """
        添加机器人绑定
        :param wechat_group_name: 微信群昵称
        :param reply_content: 自动回复内容
        :param status: 回复状态
        :param reply_key: 回复关键字
        :return:
        """
        sql = "insert into " + cls.table_name + "(wechat_group_name, reply_content, status, create_time, reply_key) values(%s, %s, %s, now(), %s);"
        return cls.db.insert(
            sql, [wechat_group_name, reply_content,
                  str(status), reply_key])

    @classmethod
    def update_setting(cls, wechat_group_name, reply_content, status, reply_id,
                       reply_key):
        """
        修改自动回复配置
        :param wechat_group_name: 微信群昵称
        :param reply_content: 自动回复内容
        :param reply_id: 主键id
        :param status: 回复状态
        :param reply_key: 回复关键字
        :return:
        """
        sql = "update " + cls.table_name + " set wechat_group_name = %s, reply_content = %s, status = %s, reply_key = %s where id = %s;"
        return cls.db.update(sql, [
            wechat_group_name, reply_content,
            str(status), reply_key, reply_id
        ])

    @classmethod
    def remove_setting(cls, reply_id):
        """
        删除配置
        :param reply_id: 主键id
        :return:
        """
        sql = "update " + cls.table_name + " set status = 2 where id = %s;"
        return cls.db.update(sql, [reply_id])

    @classmethod
    def get_replys(cls):
        """
        获取自动回复配置
        :return:
        """
        sql = "select * from " + cls.table_name + " where status < 2 order by create_time;"
        return cls.db.query_for_list(sql)
예제 #29
0
    def __init__(self, opt):
        """Initialize the pix2pix class.

        Parameters:
            opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions
        """
        BaseModel.__init__(self, opt)
        # specify the training losses you want to print out. The training/test scripts will call <BaseModel.get_current_losses>
        self.loss_names = ['G_GAN', 'G_L1', 'D_real', 'D_fake']
        # specify the images you want to save/display. The training/test scripts will call <BaseModel.get_current_visuals>
        self.visual_names = ['real_A', 'fake_B', 'real_B']
        # specify the models you want to save to the disk. The training/test scripts will call <BaseModel.save_networks> and <BaseModel.load_networks>
        if self.isTrain:
            self.model_names = ['G', 'D']
        else:  # during test time, only load G
            self.model_names = ['G']
        # define networks (both generator and discriminator)
        self.netG = networks.define_G(opt.input_nc, opt.output_nc, opt.ngf,
                                      opt.netG, opt.norm, not opt.no_dropout,
                                      opt.init_type, opt.init_gain,
                                      self.gpu_ids)

        if self.isTrain:  # define a discriminator; conditional GANs need to take both input and output images; Therefore, #channels for D is input_nc + output_nc
            self.netD = networks.define_D(opt.input_nc + opt.output_nc,
                                          opt.ndf, opt.netD, opt.n_layers_D,
                                          opt.norm, opt.init_type,
                                          opt.init_gain, self.gpu_ids)

        if self.isTrain:
            # define loss functions
            self.criterionGAN = networks.GANLoss(opt.gan_mode).to(self.device)
            self.criterionL1 = torch.nn.L1Loss()
            # initialize optimizers; schedulers will be automatically created by function <BaseModel.setup>.
            self.optimizer_G = torch.optim.Adam(self.netG.parameters(),
                                                lr=opt.lr,
                                                betas=(opt.beta1, 0.999))
            self.optimizer_D = torch.optim.Adam(self.netD.parameters(),
                                                lr=opt.lr,
                                                betas=(opt.beta1, 0.999))
            self.optimizers.append(self.optimizer_G)
            self.optimizers.append(self.optimizer_D)
예제 #30
0
def run_model_inference(image_list):
    images_count = 0
    prediction_dict = dict()

    model = BaseModel()
    session, image_string_input, model_input_image, model_output = model.create_session(
    )

    for image in tqdm(image_list):
        image_id = os.path.basename(image)[:-4]
        img_byte = image_feeder(image, new_width=1280, new_height=856)

        with tf.Graph().as_default():
            prediction = session.run([model_output],
                                     feed_dict={image_string_input: img_byte})

        pred_string = convert_predictions(prediction)
        prediction_dict[image_id] = pred_string
        images_count += 1

    return prediction_dict
예제 #31
0
class ApplyFriendsModel(BaseModel):
    table_name = 'card_apply_friends'
    db = BaseModel.get_db_lib()

    @classmethod
    def apply_friend(cls, source_open_id, target_open_id, remarks):
        """
        申请添加好友
        :param source_open_id: 源用户openid
        :param target_open_id: 目标用户openid
        :param remarks: 备注信息
        :return:
        """
        create_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        sql = "insert into " + cls.table_name + "(source_open_id, target_open_id, create_time, remarks) values(%s, %s, %s, %s);"
        try:
            apply_id = cls.db.insert(
                sql, [source_open_id, target_open_id, create_time, remarks])
            # 通知对方和自己(小助手)
            resource_message_dao.commit_apply.delay(source_open_id,
                                                    target_open_id, apply_id)
            return apply_id
        except IntegrityError:
            return 0

    @classmethod
    def handle_apply(cls, apply_id, handle_status, target_open_id):
        """
        标志申请已经处理
        :param apply_id: 申请id
        :param handle_status: 处理状态
        :return:
        """
        sql = "update " + cls.table_name + " set status = %s, handle_sign = null where id = %s AND target_open_id = %s;"
        nums = cls.db.update(
            sql, [str(handle_status),
                  str(apply_id), target_open_id])
        # 通知对方已经处理
        resource_message_dao.handle_apply.delay(apply_id, handle_status)
        return nums