def parse_invocations(): out = [] optfeats = get_data('optionalfeatures.json')['optionalfeature'] invocs = [i for i in optfeats if i['featureType'] == 'EI'] for invoc in invocs: log.info(f"Parsing invocation {invoc['name']}") text = render(invoc['entries']) if 'prerequisite' in invoc: prereqs = [] for prereq in invoc['prerequisite']: if prereq['type'] == 'prereqPact': prereqs.append(f"Pact of the {prereq['entry']}") elif prereq['type'] == 'prereqPatron': prereqs.append(f"Patron: {prereq['entry']}") elif prereq['type'] == 'prereqLevel': prereqs.append(f"Level {prereq['level']}") elif prereq['type'] == 'prereqSpell': prereqs.append(f"*{', '.join(prereq['entries'])}* spell") else: log.warning(f"Unknown prereq type: {prereq['type']}") text = f"*Prerequisite: {', '.join(prereqs)}*\n{text}" inv = { 'name': f"Warlock: Eldritch Invocation: {invoc['name']}", 'text': text, 'srd': invoc['source'] == 'PHB' } out.append(inv) return out
def main(args): # get utils datas, changes, code_table, indices_mv = get_data(args.data_path) num_company, period, num_feature = datas.shape # parameter state_shape = (num_company, args.window_size, num_feature) action_shape = num_company agent = PGAgent(state_shape, action_shape, load_path=None) # env env = Kospi200_Env(datas, changes, code_table, indices_mv, window_size=args.window_size) # log total_reward_log = [] # train for e in tqdm(range(args.num_episode), total=args.num_episode): state = env.reset() total_reward = 0 while True: action = agent.get_action(state) next_state, rewards, done = env.step(action) agent.memorize(state, action, rewards) total_reward += rewards if done: agent.learn() break env.render(mode='print') state = next_state total_reward_log.append(total_reward) print(f"\n + EPISODE: [{args.num_episode} / {e}] \n" f" + TOTAL REWARD : {total_reward}") save_pkl(total_reward_log, os.path.join(args.log_path, f"{num_feature}f" f"_{args.window_size}w" f"_reward.pkl")) agent.model.save_weights(os.path.join(args.checkpoint, f"{num_feature}f" f"_{args.window_size}w.h5"))
def face_experiment(): ''' applies NMF to the faces dataset and generates an image ''' config = yaml.safe_load(open('./config/dev.yml')) experiment_config = yaml.safe_load(open('./experiments/face.yml')) solvers = experiment_config['solver_list'] config['dataset'] = 'face' r = experiment_config['r'] config['r'] = r name = 'face' X, ground_truth = get_data(config) #if ground_truth is not -1: # W = ground_truth[0] # H = ground_truth[1] print('Data loaded, rank of X: ', np.linalg.matrix_rank(X)) experiment = Experiment(config, X, experiment_config) experiment() images = np.zeros((r, 19, 19)) for solver in experiment.solvers: W = solver.solution[0] W /= np.max(W, axis=0) W = 1 - W for i in range(r): images[i, :, :] = np.reshape(W[:, i], (19, 19)) d = 0.05 plt.subplots_adjust(wspace=d, hspace=d) fig, ax = plt.subplots(4, 4) fig.set_figheight(8) fig.set_figwidth(8) for m in range(4): for n in range(4): ax[m, n].imshow(images[4 * m + n, :, :], cmap='gray', vmin=0, vmax=1) ax[m, n].set_xticks([]) ax[m, n].set_yticks([]) fig.savefig('./experiments/' + name + '/' + solver.name + '.pgf', bbox_inches='tight') fig.savefig('./experiments/' + name + '/' + solver.name + '.pdf', bbox_inches='tight') return 0
def main(args): # get utils datas, changes, code_table, indices_mv = get_data(args.data_path) num_company, period, num_feature = datas.shape # parameter state_shape = (num_company, args.window_size, num_feature) action_shape = num_company code_table = list(code_table.items()) agent = PGAgent(state_shape, action_shape, load_path=args.load_path) total_reward = 0 pos_count = 0 neg_count = 0 for p in range(period - args.window_size + 1): obs = datas[:, p:p + args.window_size] obs = np.expand_dims(obs, axis=0) action = agent.get_action(obs) one_hot_action = np.zeros_like(action) prop_action = np.random.choice(range(num_company), 1, p=action, replace=False) for p in prop_action: one_hot_action[p] = 1 dict_actions = {i: r for i, r in enumerate(action)} sorted_dict_actions = sorted(dict_actions.items(), reverse=True, key=lambda item: item[1]) for i, a in enumerate(sorted_dict_actions[:1]): print(f"TOP {i + 1} [{code_table[a[0]]}]") print(f"TOTAL REWARD : {total_reward}") print(f"POS : {pos_count}") print(f"NEG : {neg_count}")
def get_names(): return get_data("names.json")['name']
def get_latest_feats(): return get_data("feats.json")['feat']
def get_latest_backgrounds(): return get_data("backgrounds.json")['background']
def get_latest_items(): return get_data("items.json")['item'] + \ get_data("basicitems.json")['basicitem'] + \ get_data("magicvariants.json")['variant']
def get_objects(): return get_data("objects.json")['object']
def get_races_from_web(): return get_data('races.json')['race']
def classic_experiment(): ''' ''' config = yaml.safe_load(open('./config/dev.yml')) config['dataset'] = 'face' experiment_config = yaml.safe_load(open('./experiments/classic.yml')) name = 'classic' solvers = experiment_config['solver_list'] X, _ = get_data(config) experiment = Experiment(config, X, experiment_config) experiment() fig = plt.figure(figsize=(6, 6)) ax0 = fig.add_subplot(111) ax0.set_xlabel('iteration') ax0.set_ylabel('Relative error') for i, solver in enumerate(experiment.solvers): x_axis = np.array(solver.output['iteration']) y_axis = np.array(solver.output['rel_error']) ax0.plot(x_axis, y_axis, color=COLORS[i], label=solvers[i], linestyle='--', markersize=8, marker='.') ax0.yaxis.set_major_formatter(FormatStrFormatter('%g')) ax0.xaxis.set_major_formatter(FormatStrFormatter('%g')) ax0.get_yaxis().set_tick_params(which='both', direction='in') ax0.get_xaxis().set_tick_params(which='both', direction='in') ax0.grid() ax0.set_ylim([0.1, 0.3]) ax0.legend() #ax0.set_ylabel(Y_LABELS[feature]) #ax0.set_xscale('log') #ax0.set_yscale('log') #s = '_' + str(n) + '_' + str(m) + '_' + str(r) fig.savefig('./experiments/' + name + '/' + 'graph_iter.pgf', bbox_inches='tight') fig.savefig('./experiments/' + name + '/' + 'graph_iter.pdf', bbox_inches='tight') fig = plt.figure(figsize=(6, 6)) ax0 = fig.add_subplot(111) ax0.set_xlabel('time [s]') ax0.set_ylabel('Relative error') for i, solver in enumerate(experiment.solvers): x_axis = np.array(solver.output['time']) y_axis = np.array(solver.output['rel_error']) ax0.plot(x_axis, y_axis, color=COLORS[i], label=solvers[i], linestyle='--', markersize=8, marker='.') ax0.yaxis.set_major_formatter(FormatStrFormatter('%g')) ax0.xaxis.set_major_formatter(FormatStrFormatter('%g')) ax0.get_yaxis().set_tick_params(which='both', direction='in') ax0.get_xaxis().set_tick_params(which='both', direction='in') ax0.grid() ax0.set_ylim([0.1, 0.3]) ax0.legend() #ax0.set_ylabel(Y_LABELS[feature]) #ax0.set_xscale('log') #ax0.set_yscale('log') #s = '_' + str(n) + '_' + str(m) + '_' + str(r) fig.savefig('./experiments/' + name + '/' + 'graph_time.pgf', bbox_inches='tight') fig.savefig('./experiments/' + name + '/' + 'graph_time.pdf', bbox_inches='tight')