コード例 #1
0
def main():
    args = parse_args()
    env = Game(args.max_steps, [args.board_height, args.board_width],
               args.food_period, args.max_food, args.food_life)
    if args.action == "train":
        train(args, env)
    if args.action == "test":
        test(args, env)
コード例 #2
0
ファイル: cli.py プロジェクト: shdubsh/statsd-exporter-tools
def main(args):
    if args.tool == 'test':
        test(args)
        exit(0)
    if args.tool == 'validate':
        validate(args)
        exit(0)
    if args.tool == 'convert':
        convert(args)
        exit(0)
    print('No such tool \'{}\''.format(args.tool))
    exit(1)
コード例 #3
0
ファイル: run.py プロジェクト: SallyPoon/DSC180Q2
def main(targets):
    data_cfg = json.load(open('config/conversion.json'))
    viz_cfg = json.load(open('config/viz-params.json'))
    test_cfg = json.load(open('config/test.json'))

    if 'test' in targets:
        test(**test_cfg)
        print('Successfully Completed. Plots are saved.')
    if 'conversion' in targets:
        convert(**data_cfg)
        print('Raw Data Bags Extracted and Converted to csv')
    if 'viz_analysis' in targets:
        plot_all(**viz_cfg)
        print('Data plotted')
    return
コード例 #4
0
    def parseXML( self, node ):
        self.name = node.getAttribute( src.xmlDefs.ATTR_NAME )
        self.ignore = node.getAttribute( src.xmlDefs.ATTR_IGNORE ) == src.xmlDefs.ATTR_VALUE_YES

        test_nodes = node.getElementsByTagName( src.xmlDefs.ELEMENT_TEST )
        for child in test_nodes:
            t = test(self.manager)
            t.parseXML( child )
            self.tests.append( t )
コード例 #5
0
def run_test(p):
    # Evaluate classifiers
    classifiers = load_imports(p['classifiers'])

    # Evaluate metrics
    scorers = load_scorers(p['metrics'])

    # Evaluate aggregator
    voter = Voter(list(p['voter'].values()))
    combiner = Combiner(load_imports(p['combiner']))
    mathematician = Mathematician(p['mathematician'])
    arbiters = load_arbiters(p['arbiter'])

    # Get names
    mathematician_names = list()
    for names in p['mathematician'].values():
        mathematician_names += [name for name in names]

    arbiter_names = []
    arb_methods = list(p['arbiter']['methods'].keys())
    for arb in arbiters:
        for name in arb_methods:
            arbiter_names.append(str(arb) + '_' + name)

    classif_names = list(p['classifiers'].keys())
    combiner_names = list(p['combiner'].keys())
    voter_names = list(p['voter'].keys())

    names = classif_names + voter_names + combiner_names + arbiter_names + mathematician_names

    # Run test
    test(overlap=p['overlap'],
         filepath=p['dataset'],
         iterations=p['iterations'],
         class_column=p['class_column'],
         random_state=p['random_state'],
         scorers=scorers,
         classifiers=classifiers,
         voter=voter,
         arbiters=arbiters,
         combiner=combiner,
         mathematician=mathematician,
         names=names,
         results_path=p['result_path'])
コード例 #6
0
def run_test(task, dataset_name, models, labels, save_filename,
             embedding_test_dir):
    sys.path.append(embedding_test_dir)
    from src.test import test
    args = {}
    if task == 'classification':
        args['radio'] = [0.8]
        args['label_name'] = labels
        evalution = None
    elif task == 'link_predict':
        evalution = 'AUC'
        args['data_dir'] = labels

    with cd(embedding_test_dir):
        test(task,
             evalution,
             dataset_name,
             models,
             save_filename=save_filename,
             **args)
コード例 #7
0
def test(args: List[str]):
    from src.test import test
    from src.utils.template import load_old_config, print_config
    # initializing a config from a previous run:
    # - load from directory
    # - delete unwanted (and non-resolvable) nodes, such as loggers
    path = Path(args[2]).absolute()
    config = load_old_config(path=path, delete_fields=["logger"])
    # Pretty printing same as train
    print_config(config)
    # Test model
    return test(config, path)
コード例 #8
0
ファイル: utils.py プロジェクト: MitchellTesla/AutoGL
def run_test(task, dataset_name, models, labels, save_filename,
             embedding_test_dir):
    sys.path.append(embedding_test_dir)
    from src.test import test

    args = {}
    if task == "classification":
        args["radio"] = [0.8]
        args["label_name"] = labels
        evalution = None
    elif task == "link_predict":
        evalution = "AUC"
        args["data_dir"] = labels
    args["sampling_mapping"] = {"Flickr": 100000, "wiki": 1000000}

    with cd(embedding_test_dir):
        test(task,
             evalution,
             dataset_name,
             models,
             save_filename=save_filename,
             **args)
コード例 #9
0
    def parseXML( self, node ):
        self.name = node.get(src.xmlDefs.ATTR_NAME, "")
        self.ignore = getYesNoAttributeValue(node, src.xmlDefs.ATTR_IGNORE)

        for child in node.getchildren():
            if child.tag == src.xmlDefs.ELEMENT_REQUIRE_FEATURE:
                self.parseFeatures( child, require=True )
            elif child.tag == src.xmlDefs.ELEMENT_EXCLUDE_FEATURE:
                self.parseFeatures( child, require=False )
            elif child.tag == src.xmlDefs.ELEMENT_TEST:
                t = test(self.manager)
                t.parseXML( child )
                self.tests.append( t )
コード例 #10
0
    def parseXML(self, node):
        self.name = node.get(src.xmlDefs.ATTR_NAME, "")
        self.ignore = getYesNoAttributeValue(node, src.xmlDefs.ATTR_IGNORE)
        self.only = getYesNoAttributeValue(node, src.xmlDefs.ATTR_ONLY)
        self.changeuid = getYesNoAttributeValue(node,
                                                src.xmlDefs.ATTR_CHANGE_UID)

        for child in node.getchildren():
            if child.tag == src.xmlDefs.ELEMENT_REQUIRE_FEATURE:
                self.parseFeatures(child, require=True)
            elif child.tag == src.xmlDefs.ELEMENT_EXCLUDE_FEATURE:
                self.parseFeatures(child, require=False)
            elif child.tag == src.xmlDefs.ELEMENT_TEST:
                t = test(self.manager)
                t.parseXML(child)
                self.tests.append(t)
コード例 #11
0
    def try_params(self, n_iterations, params):
        # Number of iterations or epoch for the model to train on
        n_iterations = int(round(n_iterations))
        print(params)
        sys.stderr.write(TextColor.BLUE + ' Loss: ' + str(n_iterations) + "\n" + TextColor.END)
        sys.stderr.write(TextColor.BLUE + str(params) + "\n" + TextColor.END)

        depth = params['depth']
        widen_factor = params['widen_factor']
        drop_rate = params['dropout_rate']
        batch_size = params['batch_size']
        epoch_limit = n_iterations
        learning_rate = params['learning_rate']
        l2 = params['l2']

        model = train(self.train_file, depth, widen_factor, drop_rate, batch_size, epoch_limit, learning_rate, l2,
                      self.debug_mode, self.gpu_mode, self.seq_len, self.iteration_jump, self.num_classes)
        stats_dictionary = test(model, self.test_file, batch_size, self.num_classes,
                                self.gpu_mode, self.seq_len, self.debug_mode)
        return stats_dictionary
コード例 #12
0
    source = csv.reader(y, delimiter=',')
    for row in source:
        data_y.append(row[0])

data = [data_x, data_y]
encodeData = encodeData(DIGITS, data, CHARS)

diff_training_size = [10000, 20000, 30000, 40000]

# Iterate Different Training Size
with open('./log/test_acc.csv', 'w') as output:
    output.write('model,test_acc\n')
    for training_size in diff_training_size:
        DATA_SIZE['TRAINING_SIZE'] = training_size
        TRAINING_SIZE = DATA_SIZE['TRAINING_SIZE']
        # Training data - validating data
        REAL_TRAINING_SIZE = int((TRAINING_SIZE - TRAINING_SIZE / 10) / 1000)

        # set training & testing data
        trainingOutputPath = './log/d' + str(DIGITS) + '/s' + str(
            REAL_TRAINING_SIZE) + '.csv'
        dataSet = splitData(DATA_SIZE, encodeData)

        # build model & training
        model = buildModel(DIGITS, CHARS)
        training_model = train(dataSet, BATCH_SIZE, trainingOutputPath, model)
        test_acc = test(dataSet, model, CHARS)

        output.write(trainingOutputPath + ',')
        output.write(str(test_acc) + '\n')
コード例 #13
0
device = train.get_device()
model.to(device)
dog_human_labeller = learn_dict['dog_human_labeller']
breed_labeller = learn_dict['breed_labeller']
imagenet_stats = learn_dict['model_normalization_stats']
criterion = loss_func.CustomLoss(dog_human_labeller)
train_ds = Dataset(path_dogs,
                   human_test,
                   'train',
                   breed_labeller=breed_labeller,
                   dog_human_labeller=dog_human_labeller,
                   stats=imagenet_stats,
                   size=args.img_size)
valid_ds = Dataset(path_dogs,
                   human_train,
                   'valid',
                   breed_labeller=breed_labeller,
                   dog_human_labeller=dog_human_labeller,
                   stats=imagenet_stats,
                   size=args.img_size)
test_ds = Dataset(path_dogs,
                  human_valid,
                  'test',
                  breed_labeller=breed_labeller,
                  dog_human_labeller=dog_human_labeller,
                  stats=imagenet_stats,
                  size=args.img_size)
test.test(model, train_ds, criterion, device, dataset_type='train')
test.test(model, valid_ds, criterion, device, dataset_type='valid')
test.test(model, test_ds, criterion, device, dataset_type='test')
コード例 #14
0
from src.test import test
import numpy as np

def get_pins(observed):
    keypad = np.stack([[str(num) for num in range(x, x + 3)] for x in range(1, 9, 3)] + [[None, '0', None]])

    possible = []
    rotated = np.rot90(keypad)
    for num in iter(observed):
        row, col = np.where(keypad == str(num))
        row, col = row[0], col[0]
        pr = [keypad[i][col] for i in range(row - 1, row + 2) if any(keypad[i])]
        pc = [rotated[i][row] for i in range(col - 1, col + 2) if any(rotated[i])]
        possible = possible + list(dict.fromkeys((pr + pc)))

    res = np.asarray(possible)
    res = [i for i in res if i is not None]
    return np.asarray(possible)

test(get_pins('8'), ['5','7','8','9','0'])
# test(get_pins('11'),["11", "22", "44", "12", "21", "14", "41", "24", "42"])
# test(get_pins('369'), ["339","366","399","658","636","258","268","669","668","266","369","398","256","296","259","368","638","396","238","356","659","639","666","359","336","299","338","696","269","358","656","698","699","298","236","239"])
コード例 #15
0
from src.test import test

def pig_it(text):
    text = [[letter for letter in word] for word in text.split()]
    for index, word in enumerate(text):
        tail = word[0] + 'ay' if word[0].isalpha() else word[0]
        base = word[1:]
        text[index] = ''.join(base) + tail
    return ' '.join(text)

test(pig_it('Pig latin is cool'),'igPay atinlay siay oolcay')
test(pig_it('This is my string'),'hisTay siay ymay tringsay')
コード例 #16
0
ファイル: trailing_zeros.py プロジェクト: jakbellamy/codewars
from src.test import test
import math
import re


def zeros(n):
    fs = str(math.factorial(n))
    return len(re.split(r"[123456789]+", fs)[-1])


test(zeros(0), 0)
test(zeros(6), 1)
test(zeros(30), 7)
コード例 #17
0
ファイル: sort.py プロジェクト: jakbellamy/codewars
from src.test import test


def sort_array(arr):
    odds = [num for num in arr if not num % 2 == 0]
    odds.sort()
    for i, num in enumerate(arr):
        if not num % 2 == 0:
            arr[i] = odds.pop(0)
    return arr


test(sort_array([5, 3, 2, 8, 1, 4]), [1, 3, 2, 8, 5, 4])
コード例 #18
0
ファイル: outlier.py プロジェクト: jakbellamy/codewars
from src.test import test


def find_outlier(integers):
    even = [i for i in integers if i % 2 == 0]
    return [i for i in integers
            if not i % 2 == 0][0] if len(even) > 1 else even[0]


test(find_outlier([2, 4, 6, 8, 10, 3]), 3)
test(find_outlier([2, 4, 0, 100, 4, 11, 2602, 36]), 11)
test(find_outlier([160, 3, 1719, 19, 11, 13, -21]), 160)
コード例 #19
0
ファイル: run.py プロジェクト: nbir/544nlp
if __name__ == '__main__':
	parser = argparse.ArgumentParser()
	parser.add_argument('-t', '--test', nargs='*')
	parser.add_argument('-r', '--run', nargs='*', help='\
		[all - Run entire process]')
	parser.add_argument('-p', '--prep', nargs='*')
	parser.add_argument('-f', '--feat', nargs='?')
	parser.add_argument('-c', '--classi', nargs='?')
	args = parser.parse_args()

	if args.test:
		import src.test as do
		if 'test' in args.test:
			print '\n*** Test, test, test! ***\n'
			do.test()
	if args.prep:
		if 'ami' in args.prep or 'amida' in args.prep:
			import src.prep_amida as prep
			#prep.build_word_dict()
			#prep.build_subj_list()
			#prep.make_data_info()
			#prep.balance_classes()
		if 'yt' in args.prep or 'youtube' in args.prep:
			import src.prep_youtube as prep
			#prep.remane_files('audio', 'wav')
			#prep.remane_files('transcriptions', 'trs')
			#prep.remane_files('_praat', 'csv')
			#prep.build_word_dict()
			#prep.build_utterence_list()
			#prep.make_data_info()
コード例 #20
0
ファイル: is_p.py プロジェクト: jakbellamy/codewars
from src.test import test


def is_pangram(s):
    s = [l.lower() for l in s if l.isalnum() and not l.isdigit()]
    return True if len(list(dict.fromkeys(s))) == 26 else False


test(is_pangram('sdfaf'), False)
test(is_pangram('qwertyuiopasdfghjklzxcvbnm'), True)
コード例 #21
0
def testFun(status_var, t):
    text = '测试样本'
    status_var.set(text)
    test(END, t)
コード例 #22
0
    while i <= len(brd) - 1:
        quads[sq] += brd[i][set:set + 3]
        if (i + 1) % 3 == 0: sq = sq + 1
        if i == len(brd) - 1:
            set += 3
            i = 0 if set < len(brd[0]) else i + 1
        else:
            i += 1
    return quads


def done_or_not(board):
    if not line_test(board): return 'Try again!'
    if not line_test(np.rot90(board)): return 'Try again!'
    if not line_test(to_quad(board)): return 'Try again!'
    return 'Finished!'


test(
    done_or_not([[1, 3, 2, 5, 7, 9, 4, 6, 8], [4, 9, 8, 2, 6, 1, 3, 7, 5],
                 [7, 5, 6, 3, 8, 4, 2, 1, 9], [6, 4, 3, 1, 5, 8, 7, 9, 2],
                 [5, 2, 1, 7, 9, 3, 8, 4, 6], [9, 8, 7, 4, 2, 6, 5, 3, 1],
                 [2, 1, 4, 9, 3, 5, 6, 8, 7], [3, 6, 5, 8, 1, 7, 9, 2, 4],
                 [8, 7, 9, 6, 4, 2, 1, 5, 3]]), 'Finished!')

test(
    done_or_not([[1, 3, 2, 5, 7, 9, 4, 6, 8], [4, 9, 8, 2, 6, 1, 3, 7, 5],
                 [7, 5, 6, 3, 8, 4, 2, 1, 9], [6, 4, 3, 1, 5, 8, 7, 9, 2],
                 [5, 2, 1, 7, 9, 3, 8, 4, 6], [9, 8, 7, 4, 2, 6, 5, 3, 1],
                 [2, 1, 4, 9, 3, 5, 6, 8, 7], [3, 6, 5, 8, 1, 7, 9, 2, 4],
                 [8, 7, 9, 6, 4, 2, 1, 3, 5]]), 'Try again!')
コード例 #23
0
    # about path
    tf.flags.DEFINE_string("data_name", "Fairchild_HDR",
                           "data_name is Fairchild_HDR or Funt_HDR")
    tf.flags.DEFINE_string(
        "train_dir", "./dataset/training_samples",
        "Path to training image directory or an individual image")
    tf.flags.DEFINE_string(
        "valid_dir", "./dataset/valid_samples",
        "Path to valid image directory or an individual image")
    tf.flags.DEFINE_string(
        "test_dir", "./dataset/testing_samples",
        "Path to testing image directory or an individual image")
    tf.flags.DEFINE_string("out_dir", "results", "Path to output directory")
    tf.flags.DEFINE_string("summary_dir", "summary",
                           "Path to output directory")
    tf.flags.DEFINE_string("dm", "./models_dm",
                           "Path to trained CNN dm_weights")
    tf.flags.DEFINE_string("um", "./models_um",
                           "Path to trained CNN um_weights")

    if FLAGS.model_type == 0:
        train(FLAGS)
    elif FLAGS.model_type == 1:
        test(FLAGS)
    else:
        predict(FLAGS)

    # Program over
    print('success! u are a smart boy!')
コード例 #24
0
def main(opt):
    start_epoch = 0
    err_best = 1000
    glob_step = 0
    lr_now = opt.lr

    # save options
    log.save_options(opt, opt.out_dir)

    # create and initialise model
    # parents = [1, 2, 7, 7, 5, 7, 5, -1, 8, 7, 7, 10, 7]
    # assert len(parents) == 13
    # adj = adj_mx_from_skeleton(13, parents)

    model = LinearModel(
        input_size=26,
        output_size=39,
        linear_size=opt.linear_size,
        num_stage=opt.num_stage,
        p_dropout=opt.dropout,
    )
    # groups = [[2, 3], [5, 6], [1, 4], [0, 7], [8, 9], [14, 15], [11, 12], [10, 13]]
    # model = SemGCN(adj, 128, num_layers=4, p_dropout=0.0, nodes_group=None)

    # model = SemGCN()
    model = model.cuda()
    model.apply(weight_init)
    criterion = nn.MSELoss(size_average=True).cuda()
    optimizer = torch.optim.Adam(model.parameters(), lr=opt.lr)

    print(">>> total params: {:.2f}M".format(
        sum(p.numel() for p in model.parameters()) / 1000000.0))

    # load pretrained ckpt
    if opt.load:
        print(">>> loading ckpt from '{}'".format(opt.load))
        ckpt = torch.load(opt.load)
        start_epoch = ckpt["epoch"]
        err_best = ckpt["err"]
        glob_step = ckpt["step"]
        lr_now = ckpt["lr"]
        model.load_state_dict(ckpt["state_dict"])
        optimizer.load_state_dict(ckpt["optimizer"])
        print(">>> ckpt loaded (epoch: {} | err: {})".format(
            start_epoch, err_best))

    if opt.test:
        log_file = "log_test.txt"
    else:
        log_file = "log_train.txt"
    if opt.resume:
        logger = log.Logger(os.path.join(opt.out_dir, log_file), resume=True)
    else:
        logger = log.Logger(os.path.join(opt.out_dir, log_file))
        logger.set_names(
            ["epoch", "lr", "loss_train", "loss_test", "err_test"])

    # data loading
    print("\n>>> loading data")
    stat_3d = torch.load(os.path.join(opt.data_dir, "stat_3d.pth.tar"))

    # test
    if opt.test:
        test_loader = DataLoader(
            dataset=data_loader(data_path=opt.data_dir, is_train=False),
            batch_size=opt.batch_size,
            shuffle=False,
            num_workers=opt.job,
            pin_memory=True,
        )

        loss_test, err_test, joint_err, all_err, outputs, targets, inputs = test(
            test_loader, model, criterion, stat_3d)

        print(os.path.join(opt.out_dir, "test_results.pth.tar"))
        torch.save(
            {
                "loss": loss_test,
                "all_err": all_err,
                "test_err": err_test,
                "joint_err": joint_err,
                "output": outputs,
                "target": targets,
                "input": inputs,
            },
            open(os.path.join(opt.out_dir, "test_results.pth.tar"), "wb"),
        )

        # print("train {:.4f}".format(err_train), end="\t")
        print("test {:.4f}".format(err_test), end="\t")
        sys.exit()

    # load datasets for training
    test_loader = DataLoader(
        dataset=data_loader(data_path=opt.data_dir, is_train=False),
        batch_size=opt.batch_size,
        shuffle=False,
        num_workers=opt.job,
        pin_memory=True,
    )

    train_loader = DataLoader(
        dataset=data_loader(data_path=opt.data_dir,
                            is_train=True,
                            noise=opt.noise),
        batch_size=opt.batch_size,
        shuffle=True,
        num_workers=opt.job,
        pin_memory=True,
        drop_last=False,
    )

    # loop through epochs
    cudnn.benchmark = True
    for epoch in range(start_epoch, opt.epochs):
        print("==========================")
        print(">>> epoch: {} | lr: {:.10f}".format(epoch + 1, lr_now))

        # train
        glob_step, lr_now, loss_train = train(
            train_loader,
            model,
            criterion,
            optimizer,
            lr_init=opt.lr,
            lr_now=lr_now,
            glob_step=glob_step,
            lr_decay=opt.lr_decay,
            gamma=opt.lr_gamma,
            max_norm=opt.max_norm,
        )

        loss_test, err_test, _, _, _, _, _ = test(train_loader, model,
                                                  criterion, stat_3d)

        # test
        loss_test, err_test, _, _, _, _, _ = test(test_loader, model,
                                                  criterion, stat_3d)

        # update log file
        logger.append(
            [epoch + 1, lr_now, loss_train, loss_test, err_test],
            ["int", "float", "float", "float", "float"],
        )

        # save ckpt
        is_best = err_test < err_best
        err_best = min(err_test, err_best)
        log.save_ckpt(
            {
                "epoch": epoch + 1,
                "lr": lr_now,
                "step": glob_step,
                "err": err_best,
                "state_dict": model.state_dict(),
                "optimizer": optimizer.state_dict(),
            },
            ckpt_path=opt.out_dir,
            is_best=is_best,
        )

    logger.close()
コード例 #25
0
):  # technically only passes online if i try after the while else return res
    res, i = snail_map.pop(0), 0
    while snail_map:
        if not i == len(snail_map):
            res.append(snail_map[i].pop())
            i += 1
        else:
            if snail_map:
                [res.append(n) for n in reversed(snail_map.pop())]
                [res.append(n.pop(0)) for n in reversed(snail_map)]
                [res.append(n) for n in snail_map.pop(0)]
            i = 0
    return res


test(snail([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), [1, 2, 3, 6, 9, 8, 7, 4, 5])

test(snail([[1, 2, 3], [8, 9, 4], [7, 6, 5]]), [1, 2, 3, 4, 5, 6, 7, 8, 9])

test(
    snail([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15],
           [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]]), [
               1, 2, 3, 4, 5, 10, 15, 20, 25, 24, 23, 22, 21, 16, 11, 6, 7, 8,
               9, 14, 19, 18, 17, 12, 13
           ])

## Cool way i saw after ##


def _snail(array):
    array, product = np.array(array), []
コード例 #26
0
    if not sl[-1].isdigit() or sl[-1] == '0':
        return ''.join(sl) + '1' if not sl[-1] == '0' else ''.join(
            sl[:-1]) + '1'

    if sl[-1] == '9':
        counter = 1
        while sl[-counter] == '9':
            counter += 1
        product = ''.join(sl[:-counter]) + str(10**(counter - 1))
    else:
        product = ''.join(sl[:-1]) + str(int(sl[-1]) + 1)

    return product


test(increment_string("foo"), "foo1")
test(increment_string("foobar001"), "foobar002")
test(increment_string("foobar1"), "foobar2")
test(increment_string("foobar00"), "foobar01")
test(increment_string("foobar99"), "foobar100")
test(increment_string("foobar099"), "foobar100")
test(increment_string(""), "1")


def _increment_string(strng):
    head = strng.rstrip('0123456789')
    tail = strng[len(head):]
    if tail == "": return strng + "1"
    return head + str(int(tail) + 1).zfill(len(tail))

コード例 #27
0
            val_loss, val_acc, val_correct, val_total = valid(
                val_dataloader, net)  #追記
            val_acc_end = val_acc  #追記

            print(
                'epoch %d, train_loss: %.4f validation_loss: %.4f min_loss: %.4f train_accuracy: %.4f(%d/%d) val_accuracy: %.4f(%d/%d)'
                % (epoch, train_loss, val_loss, early_stopping.loss, train_acc,
                   train_correct, train_total, val_acc_end, val_correct,
                   val_total))

            if early_stopping.validate(val_loss):
                break
            # print('epoch %d, train_loss: %.4f train_accuracy: %.4f(%d/%d)'
            #     % (epoch, train_loss, train_acc, train_correct, train_total))

            #logging
            loss_list.append(train_loss)
            val_loss_list.append(val_loss)
            val_acc_list.append(val_acc)

        print('validation_accuracy: %.4f' % val_acc_end)
        print('Finished training')

    # Test
    test_loss, test_acc, test_correct, test_total = test(test_dataloader, net)
    print('test_loss: %.4f test_accuracy: %.4f(%d/%d)' %
          (test_loss, test_acc, test_correct, test_total))

#入力例
#python main.py --use_data Sample --window_size 2 --vocab_size 50 --emb_dim 15 --batch_size 10 --max_epoch 100
コード例 #28
0
from src.test import test


def create_phone_number(n):
    n = [str(x) for x in n]
    return f"({''.join(n[:3])}) {''.join(n[3:6])}-{''.join(n[6:])}"


test(create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]), "(123) 456-7890")
test(create_phone_number([1, 1, 1, 1, 1, 1, 1, 1, 1, 1]), "(111) 111-1111")
test(create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]), "(123) 456-7890")
test(create_phone_number([0, 2, 3, 0, 5, 6, 0, 8, 9, 0]), "(023) 056-0890")
test(create_phone_number([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), "(000) 000-0000")
コード例 #29
0
from src.test import test


def is_valid_IP(str):
    x = [
        True for x in str.split('.')
        if x.isdigit() and 0 <= int(x) <= 255 and f'{int(x)}' == x
    ]
    return len(x) == 4


test(is_valid_IP('12.255.56.1'), True)
test(is_valid_IP(''), False)
test(is_valid_IP('abc.def.ghi.jkl'), False)
test(is_valid_IP('123.456.789.0'), False)
test(is_valid_IP('12.34.56'), False)
test(is_valid_IP('12.34.56 .1'), False)
test(is_valid_IP('12.34.56.-1'), False)
test(is_valid_IP('123.045.067.089'), False)
test(is_valid_IP('127.1.1.0'), True)
test(is_valid_IP('0.0.0.0'), True)
test(is_valid_IP('0.34.82.53'), True)
test(is_valid_IP('192.168.1.300'), False)
コード例 #30
0
        puts(colored.green("Successfully logged in"))
    elif 'init-session' in args:
        init_session()
        puts(colored.green("Successfully logged in"))

    validate_cookies()

    # recover previous session
    session = requests.session()
    with open(COOKIES_PATH, 'rb') as cookiesfile:
        session.cookies.update(pickle.load(cookiesfile))

    validate_session(session)

    flags = args.flags
    if 'status' in args:
        summary(session, '--solved' in flags or '-s' in flags)
    elif 'sync' in args:
        sync_samples = '--sync-samples' in flags or '-ssa' in flags or '--sync-all' in flags or '-sa' in flags
        sync_statements = '--sync-statements' in flags or '-sst' in flags or '--sync-all' in flags or '-sa' in flags
        sync(session, sync_samples, sync_statements)
    elif 'standings' in args:
        standings(session)
    elif 'test' in args:
        test(args)
    elif 'style' in args:
        style(args)

    # menu = login(session)
    # print(menu)
コード例 #31
0
from src.test import test
import re

def domain_name(url):
    surl = re.split(r"[./]+", url)
    i = 0
    while not surl[i].find('http') == -1 or surl[i] == 'www': 
        i += 1
    return surl[i]

test(domain_name("http://google.com"), "google")
test(domain_name("http://google.co.jp"), "google")
test(domain_name("www.xakep.ru"), "xakep")
test(domain_name("https://youtube.com"), "youtube")

def _domain_name(url):
    return url.split("//")[-1].split("www.")[-1].split(".")[0]
コード例 #32
0
from src.test import test


def dirReduc(arr):
    opposites = {
        'NORTH': 'SOUTH',
        'SOUTH': 'NORTH',
        'EAST': 'WEST',
        'WEST': 'EAST'
    }
    i = 0
    while i < len(arr):
        print(arr, i)
        if not i + 1 == len(arr) and (opposites[arr[i]] == arr[i + 1]
                                      or arr[i] == arr[i + 1]):
            arr.pop(i)
            i = 0
        else:
            i += 1

    return arr


test(dirReduc(["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]),
     ['WEST'])
test(dirReduc(["NORTH", "WEST", "SOUTH", "EAST"]),
     ["NORTH", "WEST", "SOUTH", "EAST"])
コード例 #33
0
ファイル: like_this.py プロジェクト: jakbellamy/codewars
from src.test import test


def likes(names):
    shown, extra = [], []
    for name in names:
        if len(shown) < 2: shown.append(name)
        else: extra.append(name)
    if not shown: return 'no one likes this'
    if len(shown) == 1: return f"{shown[0]} likes this"
    if not extra: return shown[0] + ' and ' + shown[1] + ' like this'
    tail = extra[0] if len(extra) == 1 else f"{str(len(extra))} others"
    return shown[0] + ', ' + shown[1] + ' and ' + tail + ' like this'


test(likes([]), 'no one likes this')
test(likes(['Peter']), 'Peter likes this')
test(likes(['Jacob', 'Alex']), 'Jacob and Alex like this')
test(likes(['Max', 'John', 'Mark']), 'Max, John and Mark like this')
test(likes(['Alex', 'Jacob', 'Mark', 'Max']),
     'Alex, Jacob and 2 others like this')


def _likes(names):
    n = len(names)
    return {
        0: 'no one likes this',
        1: '{} likes this',
        2: '{} and {} like this',
        3: '{}, {} and {} like this',
        4: '{}, {} and {others} others like this'
コード例 #34
0
ファイル: run.py プロジェクト: nbir/gambit-scripts
		pass

	if args.out:
	# python run.py -o region nhood-pts
		import src.out as out
		if 'region' in args.out:
			print '\n*** Output: JSON of all homes and latlng in region ***\n'
			out.out_homes_and_points_json()
		if 'region-csv' in args.out:
			print '\n*** Output: CSV files of all homes and latlng in region ***\n'
			out.out_homes_and_points_csv()
		if 'nhood-pts' in args.out:
			print '\n*** Output: JSON of latlng by users of each nhood in region ***\n'
			out.out_hoodwise_latlng_json()	

		if 'test' in args.out:
			out.test()

	if args.test:
		import src.test as test
		if 'test' in args.test:
			print '\n*** Test; Test, test! ***\n'
			test.test()
		if 'home' in args.test:
			print '\n*** Test: home. ***\n'
			test.test_home()