コード例 #1
0
ファイル: camera.py プロジェクト: tomasvdw/thas
    def test_api(self):
        rd.flushall()
        main.test("/signup", {"name": "tomtomtom", "password": "******", "email": "*****@*****.**"})

        main.test(
            "/trip", {"name": "tomtomtom", "password": "******", "loc": "51x4", "cam-num": "2", "cam-direction": "2"}
        )
コード例 #2
0
ファイル: config.py プロジェクト: deepmipt/stand_squad_en
def main(_):
    config = flags.FLAGS
    if config.mode == "train":
        train(config)
    elif config.mode == "prepro":
        copyfile(_[0], dir + 'config.py')
        prepro(config)
    elif config.mode == "debug":
        config.num_steps = 2
        config.val_num_batches = 1
        config.checkpoint = 1
        config.period = 1
        train(config)
    elif config.mode == "test":
        if config.use_cudnn:
            print(
                "Warning: Due to a known bug in Tensorlfow, the parameters of CudnnGRU may not be properly restored."
            )
        test(config)
    elif config.mode == "predict":
        if config.use_cudnn:
            print(
                "Warning: Due to a known bug in Tensorlfow, the parameters of CudnnGRU may not be properly restored."
            )
        predict(config)
    elif config.mode == "test_sber":
        if config.use_cudnn:
            print(
                "Warning: Due to a known bug in Tensorlfow, the parameters of CudnnGRU may not be properly restored."
            )
        test_sber(config)
    else:
        print("Unknown mode")
        exit(0)
コード例 #3
0
def main(_):
    config = flags.FLAGS
    if config.mode == "train":
        while True:
            try:
                train(config)
            except Exception:
                print("exception...")
                print('restart....')
                pass
            else:
                break

    elif config.mode == "prepro":
        prepro(config)
    elif config.mode == "debug":
        config.num_steps = 2
        config.val_num_batches = 1
        config.checkpoint = 1
        config.period = 1
        train(config)
    elif config.mode == "test":
        test(config)
    elif config.mode == "demo":
        demo(config)
    else:
        print("Unknown mode")
        exit(0)
コード例 #4
0
def Problem2D_LeakyRelu():
    x, y = NN.get_component([2, 10, 10, 1], "xavier")
    k = x.copy()
    l = y.copy()
    input = []
    output = []
    for i in range(500):
        a = int(np.random.uniform(-1000, 1000)) / 1000
        b = int(np.random.uniform(-1000, 1000)) / 1000
        input_sub = [a, b]
        r = None
        if ((a < 0 and b < 0) or (a > 0 and b > 0)):
            r = 1
        else:
            r = 0

        output_sub = [r]
        input.append(input_sub)
        output.append(output_sub)

    input = np.array(input)
    output = np.array(output)

    #NN.test(x,y,input[0:100],output[0:100],NN.L_Relu,NN.sig)

    w, b = NN.train(input, output, k, l, NN.L_Relu, NN.L_Relu_D, NN.L_Relu,
                    NN.L_Relu_D, 1, 40000, 0.008)
    NN.test(w, b, input[0:100], output[0:100], NN.L_Relu, NN.sig)
コード例 #5
0
def main(_):
    config = flags.FLAGS
    if config.mode == "prepare":
        prepare(config)
    elif config.mode == "test":
        test(config)
    elif config.mode == "train":
        train(config)
    else:
        print("Unknown mode")
        exit(0)
コード例 #6
0
def main(_):
    config = flags.FLAGS

    if config.mode == 'prepro':
        prepro(config)
    elif config.mode == 'train':
        train(config)
    elif config.mode == 'test':
        test(config)
    else:
        raise ValueError('The mode must choose from [prepro/train/test]!')
コード例 #7
0
ファイル: test_main.py プロジェクト: anianruoss/LDABNN
    def test_test_function(self):
        """Testing function :func:`main.test`."""
        # Ensure reproducibility.
        torch.manual_seed(42)
        torch.cuda.manual_seed_all(42)
        rand = np.random.RandomState(42)

        n_in = 5
        n_out = 5
        n_samples = 2

        x = rand.uniform(low=0, high=1, size=(n_samples, n_in))
        y = rand.uniform(low=0, high=1, size=(n_samples, n_out))

        data = utils.RegressionDataset(x, y)
        data_loader1 = DataLoader(data, batch_size=n_samples)
        assert (len(data_loader1) == 1)
        data_loader2 = DataLoader(data, batch_size=n_samples // 2)
        assert (len(data_loader2) > 1)

        device = torch.device("cpu")

        net = MLP(n_in=n_in, n_out=n_out)
        net.eval()

        with torch.no_grad():
            predictions = net.forward(data.inputs)

        # Avoid any console prints.
        with open(os.devnull, 'w') as devnull:
            with contextlib.redirect_stdout(devnull):
                mse1_test = main.test(device, data_loader1, net)

        # See docstring of method `_pytorch_mse` in
        # `tests.public.lib.test_backprop_functions`.
        mse1 = F.mse_loss(predictions, data.outputs, reduction='none')
        mse1 = 0.5 * mse1.sum(dim=1).mean()

        self.assertAlmostEqual(mse1_test, float(mse1), 5,
                               'Method "main.test" does not work correctly.')

        ### Check if `test` handles multiple batches correctly correctly.

        # Avoid any console prints.
        with open(os.devnull, 'w') as devnull:
            with contextlib.redirect_stdout(devnull):
                mse2_test = main.test(device, data_loader2, net)

        self.assertAlmostEqual(
            mse2_test, float(mse1), 5,
            'Method "main.test" does not work correctly when iterating ' +
            'over multiple mini batches.')
コード例 #8
0
    def test_api(self):
        rd.flushall()
        main.test('/signup', { 
           'name':'Tomtomtom', 
           'password':'******', 
           'email':'*****@*****.**'
           })

        main.test('/trip', {
            'name':'tomtomtom', 
            'password':'******', 
            'loc':'51x4',
            'cam-num':'2',
            'cam-direction':'2'
        })
        main.test('/trip', {
            'name':'tomtomtom', 
            'password':'******', 
            'loc':'51x4.002',
            'cam-num':'2',
            'cam-direction':'2'
        })

        main.test('/get-user', { 
           'name':'tomtomtom', 
           'password':'******'
           })
コード例 #9
0
ファイル: task.py プロジェクト: yq911122/squad-model
def main(_):
    config = flags.FLAGS
    if config.mode == "train":
        train(config)
    elif config.mode == "debug":
        config.num_steps = 2
        config.val_num_batches = 1
        config.checkpoint = 1
        config.period = 1
        train(config)
    elif config.mode == "test":
        test(config)
    else:
        print("Unknown mode")
        exit(0)
コード例 #10
0
ファイル: test.py プロジェクト: h2oboi89/Euler
    def run_problems(self, dir):
        start = datetime.datetime.now()
        print('--------------------------')
        print(start)
        print('--------------------------')
        for sub_dir in os.listdir(dir):
            p = os.path.join(os.getcwd(), dir, sub_dir)

            t = os.getcwd()

            os.chdir(p)
            sys.path.append(p)

            try:
                importlib.reload(main)
            except NameError:
                import main

            importlib.reload(main)

            print(dir + sub_dir, end=': ')

            self.assertTrue(main.test())

            os.chdir(t)
            sys.path.remove(p)
        end = datetime.datetime.now()
        duration = end - start
        print('--------------------------')
        print(end)
        print('--------------------------')
        print(duration)
        print('--------------------------')
コード例 #11
0
ファイル: mainTest.py プロジェクト: andreasbrake/AI-Jam2014
	def testFaces(self):

		numCorrect = 0 
		total = 0 # should be 120 in total
		incorrect = {}
		for imgName in glob.glob("./img/*_*_.bmp"):
			imgName = imgName.replace("\\","/")
			# determine the slicing indices based on file name
			#start = 6
			#end = 8 if self.isNumber(imgName[start:8]) else 7

			#expected = imgName[start:end]
			expected = imgName.split("/")[-1].split("_")[0]
			print("expecting: " + imgName)
			actual = main.test(imgName) # test each face from the data set
			
			print expected, actual
			if (expected == actual[0]):
				print "PASS\n"
				numCorrect += 1
			else:
				print "FAIL\n"
				incorrect[imgName] = actual

			total += 1

		print "Incorrect images and their matches:"
		pprint.pprint(incorrect) 
		print "\nNumber correct: " + str(numCorrect) + " out of " + str(total)
		print "Percentage correct: " + str ( (float(numCorrect)/float(total) ) * 100) + "%\n"
コード例 #12
0
    def testFaces(self):

        numCorrect = 0
        total = 0  # should be 120 in total
        incorrect = {}
        for imgName in glob.glob("./img/*_*_.bmp"):
            imgName = imgName.replace("\\", "/")
            # determine the slicing indices based on file name
            #start = 6
            #end = 8 if self.isNumber(imgName[start:8]) else 7

            #expected = imgName[start:end]
            expected = imgName.split("/")[-1].split("_")[0]
            print("expecting: " + imgName)
            actual = main.test(imgName)  # test each face from the data set

            print expected, actual
            if (expected == actual[0]):
                print "PASS\n"
                numCorrect += 1
            else:
                print "FAIL\n"
                incorrect[imgName] = actual

            total += 1

        print "Incorrect images and their matches:"
        pprint.pprint(incorrect)
        print "\nNumber correct: " + str(numCorrect) + " out of " + str(total)
        print "Percentage correct: " + str(
            (float(numCorrect) / float(total)) * 100) + "%\n"
コード例 #13
0
def food_classify(img_path):
    label, score = main.test(img_path, model, opt)
    ret = []
    for li, si in zip(label, score):
        if si < 1e-4 :
            si = si + 1e-4
        ret.append({"label": int(li), "score": "%.2f" % (float(si)*100)})
    return ret
コード例 #14
0
def main(_):
    config = flags.FLAGS
    if config.mode == "train":
        train(config)
    elif config.mode == "prepro":
        prepro(config)
    elif config.mode == "debug":
        config.num_steps = 2
        config.val_num_batches = 1
        config.checkpoint = 1
        config.period = 1
        train(config)
    elif config.mode == "test":
        test(config)
    else:
        print("Unknown mode, you must choose mode from [train/prepro/debug/test]")
        exit(0)
コード例 #15
0
def main(_):
    config = flags.FLAGS
    if config.mode == 'train':
        train(config)
    elif config.mode == 'prepro':
        prepro(config)
    elif config.mode == 'debug':
        config.num_steps = 2
        config.val_num_batches = 1
        config.checkpoint = 1
        config.period = 1
        train(config)
    elif config.mode == 'test':
        test(config)
    else:
        print('Unknown mode')
        exit(0)
コード例 #16
0
ファイル: master.py プロジェクト: Gpython20/masterMind
def chooseSeq():
	print(test())
	inp=input('choose 4 colors sequece \tEx: [1,2,3,4]')
	a,b,c,d=str(inp)
	lst=[]
	for i in [a,b,c,d]:
		lst+= getColor(int(i)-1)
	lst+='\t'+compare(int(inp),int(table.key))+'\n'
	return lst
コード例 #17
0
def main(_):
    config = flags.FLAGS
    os.environ["CUDA_VISIBLE_DEVICES"] = config.gpu  # 选择一块gpu
    if config.mode == "train":
        train(config)
    elif config.mode == "prepro":
        data_process_addAnswer.prepro(config)
    elif config.mode == "test":
        test(config)
    elif config.mode == "examine":
        examine_dev(config)
    elif config.mode == "save_dev":
        save_dev(config)
    elif config.mode == "save_test":
        save_test(config)
    else:
        print("Unknown mode")
        exit(0)
コード例 #18
0
ファイル: config.py プロジェクト: Mars-Wei/R-Net
def main(_):
    config = flags.FLAGS
    if config.mode == "train":
        train(config)
    elif config.mode == "prepro":
        prepro(config)
    elif config.mode == "debug":
        config.num_steps = 2
        config.val_num_batches = 1
        config.checkpoint = 1
        config.period = 1
        train(config)
    elif config.mode == "test":
        if config.use_cudnn:
            print("Warning: Due to a known bug in Tensorlfow, the parameters of CudnnGRU may not be properly restored.")
        test(config)
    else:
        print("Unknown mode")
        exit(0)
コード例 #19
0
ファイル: config.py プロジェクト: txye/QANet
def main(_):
    config = flags.FLAGS
    if config.mode == "train":
        train(config)
    elif config.mode == "prepro":
        prepro(config)
    elif config.mode == "debug":
        config.num_steps = 2
        config.val_num_batches = 1
        config.checkpoint = 1
        config.period = 1
        train(config)
    elif config.mode == "test":
        test(config)
    elif config.mode == "demo":
        demo(config)
    else:
        print("Unknown mode")
        exit(0)
コード例 #20
0
def run():
    # Training settings
    parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
    parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',
                        help='input batch size for testing (default: 1000)')
    parser.add_argument('--no-cuda', action='store_true', default=True,
                        help='disables CUDA training')
    parser.add_argument('--seed', type=int, default=1, metavar='S',
                        help='random seed (default: 1)')
    parser.add_argument('--log-interval', type=int, default=10, metavar='N',
                        help='how many batches to wait before logging training status')
    parser.add_argument('--test-AWGN', action='store_true', default=False,
                        help='Test AWGN transformation')
    parser.add_argument('--sigma', type=float, default=0.0, metavar='N',
                        help='standard deviation of AWGN')
    args = parser.parse_args()

    use_cuda = not args.no_cuda and torch.cuda.is_available()

    torch.manual_seed(args.seed)

    device = torch.device("cuda" if use_cuda else "cpu")

    test_kwargs = {'batch_size': args.test_batch_size}

    ## import model from main and import weights
    model = main.Net().to(device)
    model.load_state_dict(torch.load("mnist_cnn.pt"))
    # Print model's state_dict
    print("Model's state_dict:")
    for param_tensor in model.state_dict():
        print(param_tensor, "\t", model.state_dict()[param_tensor].size())

    for i, sigma in enumerate([0, 0.3, 0.6, 1.0]):
        transform = transforms.Compose([transforms.ToTensor(), main.AWGN(sigma), transforms.Normalize((0.1307,), (0.3081,))])

        test_dataset = datasets.MNIST('../data', train=False, transform=transform)

        test_loader = torch.utils.data.DataLoader(test_dataset, **test_kwargs)

        print(f"\nAccuracy for AWGN with a standard deviation of {sigma}")
        main.test(model, device, test_loader)
コード例 #21
0
def main(_):
    jieba.re_han_default = re.compile("([\u4E00-\u9FD5a-zA-Z0-9+#&\._%\xd7]+)",
                                      re.U)
    config = flags.FLAGS
    if config.mode == "train":
        train(config)
    elif config.mode == "prepro":
        prepro(config)
    elif config.mode == "debug":
        config.num_steps = 2
        config.val_num_batches = 1
        config.checkpoint = 1
        config.period = 1
        train(config)
    elif config.mode == "test":
        test(config)
    elif config.mode == "demo":
        demo(config)
    else:
        print("Unknown mode")
        exit(0)
コード例 #22
0
ファイル: task.py プロジェクト: yq911122/nn-depency-parser
def main(_):
    config = flags.FLAGS
    if config.mode == "train":
        train(config)
    elif config.mode == "debug":
        config.train_file = os.path.join(data_dir, "debug")
        config.dev_file = os.path.join(data_dir, "debug")
        config.test_file = os.path.join(data_dir, "debug")
        config.batch_size = 2
        config.eval_batch_size = 2
        config.num_steps = 2
        config.checkpoint = 2
        config.period = 1
        config.dev_val_num_sentences = 2
        config.test_val_num_sentences = 2
        train(config)
    elif config.mode == "test":
        test(config)
    else:
        print("Unknown mode")
        exit(0)
コード例 #23
0
ファイル: config.py プロジェクト: wly-thu/QGforQA
def main(_):
    config = flags.FLAGS
    if config.mode == "get_vocab":
        get_vocab(config)
    elif config.mode == "prepare":
        prepare(config)
    elif config.mode == "train":
        train(config)
    elif config.mode == "train_rl":
        train_rl(config)
    elif config.mode == "train_qpp":
        train_qpp(config)
    elif config.mode == "train_qap":
        train_qap(config)
    elif config.mode == "train_qqp_qap":
        train_qqp_qap(config)
    elif config.mode == "test":
        test(config)
    else:
        print("Unknown mode")
        exit(0)
コード例 #24
0
def main(_):
    config = flags.FLAGS
    get_args(config)
    if config.mode == "train":
        train(config)
    elif config.mode == "prepro":
        prepro(config)
    elif config.mode == "debug":
        config.num_steps = 1
        config.val_num_batches = 1
        config.checkpoint = 1
        config.period = 1
        train(config)
    elif config.mode == "test":
        test(config)
    #
    # elif config.mode == "predict":
    #     predict(config)
    else:
        print("Unknown mode")
        exit(0)
コード例 #25
0
def slots():
    sentence = str(request.args.get('sentence'))
    with graph.as_default():
        response_time, slots = test(process, [sentence], read_file=False)

    response = {
        'sentence': sentence,
        'slots': slots,
        'response_time': str(response_time)[:4] + 's',
        'model': str(best_model_filename)
    }
    
    return sendResponse(response)
コード例 #26
0
def execute_command():
    if request.method == 'POST':
        command = request.form['command']
        result = test(command, True)
        if result != None:
            if request.form['is_sql_command'] == 'run':
                op, flash_message = run_command(result, True)
                flash(flash_message)
                return redirect(url_for('index'))
            if request.form['is_sql_command'] == 'evaluate':
                op, flash_message = run_command(result, False)
                flash(flash_message)
                return redirect(url_for('index'))
        return "Sin respuesta"
コード例 #27
0
ファイル: config.py プロジェクト: r06944010/QANet-KGB
def main(_):
    config = flags.FLAGS
    if config.mac == "m40":
        config.ta_w2v = os.path.join(home, "data", "word2vec", "race_word_vector_300.txt")
        config.ta_c2v = os.path.join(home, "data", "word2vec", "single_w2v_300.txt")
    if config.mode == "train":
        train(config)
    elif config.mode == "prepro":
        prepro(config)
    elif config.mode == "debug":
        config.num_steps = 1
        config.val_num_batches = 1
        config.checkpoint = 1
        config.period = 1
        config.batch_size = 2
        train(config)
    elif config.mode == "test":
        test(config)
    elif config.mode == "demo":
        demo(config)
    else:
        print("Unknown mode")
        exit(0)
コード例 #28
0
def main(_):
    config = flags.FLAGS
    os.environ["CUDA_VISIBLE_DEVICES"] = config.gpu  # 选择一块gpu
    if config.mode == "train":
        train(config)
    elif config.mode == "prepro":
        data_process.prepro(config)
    elif config.mode == "debug":
        config.num_steps = 2
        config.val_num_batches = 1
        config.checkpoint = 1
        config.period = 1
        train(config)
    elif config.mode == "test":
        test(config)
    elif config.mode == "examine":
        examine_dev(config)
    elif config.mode == "save_dev":
        save_dev(config)
    elif config.mode == "save_test":
        save_test(config)
    else:
        print("Unknown mode")
        exit(0)
コード例 #29
0
def test_taxi():
    main.test()
コード例 #30
0
ファイル: test.py プロジェクト: adammendoza/loom
def test():
    main.test()
コード例 #31
0
label_dict = reddit.empty_label_dictionary()
label_list = list(label_dict.keys())

for eachpair in pair_labels:
    label0 = eachpair[0]
    label1 = eachpair[1]
    
    index0 = label_list.index(label0)
    index1 = label_list.index(label1)
    
    label_counts[index0, index1] += 1
    
    
# Grab the predicted and test set labels
predicted, groundtruth = main.test(save=False)
# Convert into a row
predicted = predicted.reshape(-1)
test_len = predicted.shape[0]
counter = 0
while counter < test_len:
    test_pair_labels = convert_label_pairs_num2string(predicted[counter])
    label0 = test_pair_labels[0]
    label1 = test_pair_labels[1]
    index0 = label_list.index(label0)
    index1 = label_list.index(label1)
    test_label_counts[index0, index1] += 1
    
    test_pair_truth = convert_label_pairs_num2string(groundtruth[counter])
    label0 = test_pair_truth[0]
    label1 = test_pair_truth[1]
コード例 #32
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec  8 14:15:07 2017

@author: jyao
"""

from regularizer import Regularizer
import main
if __name__ == '__main__':
    print(Regularizer.PARAMETERS)
    p = 3
    Regularizer.register(p)
    print(Regularizer.PARAMETERS)
    main.test(5)
    print(Regularizer.PARAMETERS)
コード例 #33
0
ファイル: test.py プロジェクト: Pulkit-100/VocalForLocal
def test_test():
    assert main.test() == "Works!"
コード例 #34
0
ファイル: base.py プロジェクト: JxSrcInc/python
from main import training
from main import test
from main import load_mnist

img_images, img_labels, tst_images, tst_labels = load_mnist()
print(img_images.shape)
clf = training(img_images, img_labels, 500)
test_size = 100
num_correct = test(clf, tst_images, tst_labels, test_size)
print ("Baseline classifier using an SVM.")
print ("%s of %s values correct." % (num_correct, test_size))

コード例 #35
0
 def test_name(self):
     self.assertEqual(test('11'), 'Пашина Ксения Игоревна')
コード例 #36
0
 def test_surname(self):
     self.assertEqual(test('Павлова'), 10)
コード例 #37
0
    def __init__(self):
        super(HeavyPlayer, self).__init__()
        self.attack = 200
        self.speed = 100
        self.defense = 200


class LightPlayer(Player):
    def __init__(self):
        super(LightPlayer, self).__init__()
        self.attack = 100
        self.speed = 200
        self.defense = 100


if __name__ == "__main__":
    import main
    import weapon
    main.init()
    p = LightPlayer()
    wep1 = weapon.generate_weapon("Machine Gun")
    p.weapons.append(wep1)
    wep2 = weapon.generate_weapon("Missle Launcher")
    p.weapons.append(wep2)
    wep3 = weapon.generate_weapon("Laser Gun")
    p.weapons.append(wep3)
    p.equipped = p.weapons[0]
    print p.equipped
    p.speed = 400
    main.test(p)