def buildModels(t: str): global AnkiModels y = json.loads(t) templates = [] flds = [] with IncrementalBar("\tBuilding Models", max=len(y.keys())) as bar: for k in y.keys(): AnkiModels[str( y[k]["id"])] = Model(str(y[k]["id"]), y[k]["type"], cssutils.parseString(y[k]["css"]), y[k]["latexPre"], y[k]["latexPost"]) for fld in y[k]["flds"]: flds.append((fld["name"], fld["ord"])) flds.sort(key=lambda x: int(x[1])) AnkiModels[str(y[k]["id"])].flds = tuple([f[0] for f in flds]) for tmpl in y[k]["tmpls"]: templates.append( Template(tmpl["name"], tmpl["qfmt"], tmpl["did"], tmpl["bafmt"], tmpl["afmt"], tmpl["ord"], tmpl["bqfmt"])) AnkiModels[str(y[k]["id"])].tmpls = tuple(templates) templates = [] flds = [] bar.next() bar.finish()
def Main(): parser = argparse.ArgumentParser( description= 'A battleship game built with Python. You can play versus the ' 'computer or against someone else. Call the program with the ' 'arguments described below to enable those features. The colors ' 'of shots while playing represents the answer of the enemy. ' 'Once the game has ended, the console will output the result.') parser.add_argument( '-n', dest='network_player_name', action='store', default=False, help='Play against someone specific on the network "-n friendName", ' 'versus someone random on the server "-n None", ' 'or play against your computer without adding "-n". ' 'If you play on the network and does not find someone to play ' 'against within about 3 seconds, the game might freeze, ' 'then just restart it to try again.') parser.add_argument( '-c', dest='is_local_player_comp', action='store_true', default=False, help='Add this argument to play as the computer against your opponent.' ) parser.add_argument( '-s', dest='is_display_disabled', action='store_true', default=False, help='Add this argument to disable display. Can only be set if ' 'you play automatically as the computer. ') requiredNamed = parser.add_argument_group('required named arguments') requiredNamed.add_argument('-u', dest='username', help='Set your username: "******".', required=True) args = parser.parse_args() if args.is_display_disabled and not args.is_local_player_comp: # Do not raise as we do not want a stack trace. print( 'ERROR: Must play as computer to disable display. Add the "-c" argument.' ) return m = Model(args.username, not args.is_display_disabled, args.is_local_player_comp, args.network_player_name) v = Viewer(m) c = Controller(m, v.view)
def main(): # changeable print("Initialize") pathData = "data/Porter.txt" pathID = "data/ID/ID_Porter.txt" pathQuery = "data/Query/query.txt" uniqueTerm = 1341890 # 不在檔案中 isStemming = True # declare model MD = Model(pathData=pathData, pathID=pathID, pathQuery=pathQuery, uniqueT=uniqueTerm, isStemming=isStemming) print("VectorSpace Start") VSFile = open("output/Porter/Porter_VSFile.txt", "wt") MD.printVectorSpace(VSFile, k1=2, b=0.75) VSFile.close() print("VectorSpace End") print("") print("Laplace Start") LaplaceFile = open("output/Porter/Porter_LaplaceFile.txt", "wt") MD.printLanguageModelLaplace(LaplaceFile) LaplaceFile.close() print("Laplace End") print("") print("JM Start") JMFile = open("output/Porter/Porter_JMFile.txt", "wt") MD.printLanguageModelJM(JMFile, 0.2) JMFile.close() print("JM End")
def main_loop(path): env = gym.make('SpaceInvaders-v0') model = Model() model.load_variables(path) print(model.weights[0], "Loaded Weights") with tf.Session() as session: session.run(tf.global_variables_initializer()) max_episodes = 100000 env.reset() Q = None prev_obs = None curr_obs, curr_reward, done, info = env.step(0) curr_obs = process_observations(curr_obs, prev_obs) for eps in range(max_episodes): prob = model.forward_pass(session, curr_obs.reshape([1, 185, 120, 1])) action = choose_action(prob) curr_obs, curr_reward, done, info = env.step(action) curr_obs = process_observations(curr_obs, prev_obs) prev_obs = curr_obs env.render() if done is True: done = False env.reset()
# -------------------------------------------------- imcropsize = 128 # should be the same as in train.py nchannels = 1 # should be the same as in train.py modelpath = '/home/mc457/Workspace/TFModel/SiamRelease.ckpt' impath = '/home/mc457/Images/ImageForensics/RealExamplesNoPlots' outfigpath = '/home/mc457/Workspace/AcrcTest.png' nruns = 10 imtestoutpath = '/home/mc457/Workspace/Scratch' # images saved only when nruns == 1 # -------------------------------------------------- print('load model and parameters') # -------------------------------------------------- from Models import Model model = Model(nchannels, imcropsize) saver = tf.train.Saver() sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) # config parameter needed to save variables when using GPU saver.restore(sess, modelpath) print("Model restored.") # -------------------------------------------------- print('test') # -------------------------------------------------- classes = os.listdir(impath) impaths = [] for c in classes:
h = 0.5 eps_0 = 5e-4 T_inf = 25 z = np.linspace(0, 1, N + 1) # parameters for GenData M = 32 # parameters for Prior beta_prior = np.ones((N - 1, )) sigma_prior = 1 C_beta = np.diag(sigma_prior**2 * np.ones((N - 1, ))) # start model = Model(N, eps_0, h, T_inf) prior = Prior(beta_prior, C_beta) data = GenData(M, h, T_inf) R = np.linalg.cholesky(C_beta) N_samples = int(1e3) beta_samp_lst = [] T_samp_lst = [] for i in range(N_samples): s = np.random.randn(N - 1) beta_sample = beta_prior + R.dot(s) T_sample, _ = model.get_T_mult(beta_sample)
def main_loop(): env = gym.make('SpaceInvaders-v0') with tf.Session() as session: model = Model() done = False alpha = 1e-3 gamma = 0.99 target = None episode = 0 curr_obs = env.reset() prev_obs = None net_reward = 0 curr_reward = 0 memory = [] death_count = 0 action_to_prob = [3, 2, 1, 1, 0] num_actions = 4 max_episodes = 50000 threshhold = 100 Q = None for eps in range(max_episodes): if Q is None: epsilon_prob = [ random.uniform(0, 1) for _ in range(num_actions) ] action = choose_action(epsilon_prob) elif eps % 57 == 0: # random asss number epsilon_prob = [ random.uniform(0, 1) for _ in range(num_actions) ] action = choose_action(epsilon_prob) else: prob = model.forward_pass(session, curr_obs.reshape([1, 185, 120, 1])) action = choose_action(prob) curr_obs, curr_reward, done, info = env.step(action) curr_obs = process_observations(curr_obs, prev_obs) memory.append((prev_obs, action, curr_reward, curr_obs, eps)) while len(memory) > 100: rand_death_i = random.randint(0, len(memory) - 1) del memory[rand_death_i] if eps % threshhold == 0: print("Episode", eps) rand_i = random.randint(0, len(memory) - 1) mem_sample = memory[rand_i] if Q is None: target = mem_sample[2] Q = np.random.random_sample((max_episodes, num_actions)) else: target = mem_sample[2] + gamma * Q[ mem_sample[-1], max_Q(Q, mem_sample[-1])] #print(target, "TARGET") model.train(session, training_data=mem_sample[-2], labels=Q[eps], target=target) Q[eps, action_to_prob[action]] += alpha * ( target - Q[eps, action_to_prob[action]]) env.render() prev_obs = curr_obs if info['ale.lives'] == 0: death_count = death_count + 1 done = False env.reset() print("Death count", death_count) print(model.save_variables(session))
iterator = tf.data.Iterator.from_structure(tr_data.output_types, tr_data.output_shapes) next_element = iterator.get_next() tr_init_op = iterator.make_initializer(tr_data) im1, im2, im3 = tf.split(next_element, 3, 3) triplet_batch = tf.tuple((im1, im2, im3)) # -------------------------------------------------- print('model') # -------------------------------------------------- from Models import Model model = Model(nchannels, imcropsize, testIdx) print('reslearn: ', model.residualLearning) # -------------------------------------------------- print('train') # -------------------------------------------------- saver = tf.train.Saver() sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True) ) # config parameter needed to save variables when using GPU if os.path.exists(trainlogpath): shutil.rmtree(trainlogpath) if os.path.exists(validlogpath): shutil.rmtree(validlogpath) train_writer = tf.summary.FileWriter(trainlogpath, sess.graph)
data['Open'].isnull().sum() data['Volume_(BTC)'].fillna(value=0, inplace=True) data['Volume_(Currency)'].fillna(value=0, inplace=True) data['Weighted_Price'].fillna(value=0, inplace=True) data['Open'].fillna(method='ffill', inplace=True) data['High'].fillna(method='ffill', inplace=True) data['Low'].fillna(method='ffill', inplace=True) data['Close'].fillna(method='ffill', inplace=True) # standardize the data df = (data - data.mean())/ data.std() # lr = Model(df, 0.025).linear_regression() nn1 = Model(df, 0.025).nn_1_keras() print('hi') print('hi') print('hi') print('hi')
print(' h1:') scores, evaluated_params = evaluate_params( model_type, h1_train_x, h1_train_y, tuning_x, tuning_y, metrics[0], params, get_autc=autotune_autc, verbose=verbose) # scores_h1.append(scores) if params_list is None: params_list = evaluated_params h1 = Model(model_type, 'h1', params=params_list[np.argmax(scores)]) else: h1 = Model(model_type, 'h1', params=chosen_params) h1.fit(h1_train_x, h1_train_y) user_count = 0 # todo: USER LOOP for user_id, item in hists_inner_seed_by_user.items(): hist_train, hist_valid, hist_test_x, hist_test_y = item if chrono_split: hist_train_range = np.zeros(len(h2_train)) start_idx, end_idx = hist_train_ranges[user_id][0] hist_train_range[start_idx:end_idx] = 1 else:
def setUp(self): self.model = Model()