def main(): MONTHS = [8, 9, 10] X = pd.DataFrame() Y = pd.DataFrame() for month in MONTHS: x = Load.load_data_csv("../train/feature_{}.csv".format(month)) y = Load.load_data_csv("../train/loan_next_month_{}.csv".format(month)) X = pd.concat([X, x]) Y = pd.concat([Y, y]) Test = Load.load_data_csv("../test/feature_{}.csv".format(11)) Test.pop("uid") Test.pop("month") X.pop("uid") X.pop("month") Y.pop("uid") clf = LinearRegression() clf.fit(X, Y) predict = clf.predict(Test) for i in range(len(predict)): if predict[i][0] < 0: predict[i][0] = 0 sample = pd.read_csv("../result_sample/Loan_Forecasting_Upload_Sample.csv", header=None) sample[1] = predict sample.to_csv("../result/Loan_Forecasting_Upload.csv", header=None, index=False, encoding="utf-8", sep=",")
def main(runIndex=None): print("Starting Main.main()") # if the required directory structure doesn't exist, create it makeDirectoryStructure(address) # now start the GMM process Load.main(address, filename_raw_data, runIndex, subsample_uniform,\ subsample_random, subsample_inTime, grid, conc, \ fraction_train, inTime_start, inTime_finish,\ fraction_nan_samples, fraction_nan_depths, cov_type,\ run_bic=False) # loads data, selects train, cleans, centres/standardises, prints PCA.create(address, runIndex, n_dimen, use_fPCA) GMM.create(address, runIndex, n_comp, cov_type) PCA.apply(address, runIndex) GMM.apply(address, runIndex, n_comp) # reconstruction (back into depth space) Reconstruct.gmm_reconstruct(address, runIndex, n_comp) Reconstruct.full_reconstruct(address, runIndex) Reconstruct.train_reconstruct(address, runIndex) # calculate properties mainProperties(address, runIndex, n_comp)
def __init__(self, filename): self.id_room = 1 self.print_fast_id = 0 Load.FILE_NAME = filename Load.load() os.system('cls') Load.room.start()
def gird_model(name, day, timeDs, engine, priceRatio=0.2, geneRatio=0.2, loadRatio=0.1): #pd.set_option('display.max_columns', None) #pd.set_option('display.max_rows', None) res = [] generator = Generator(name, day, engine, frash_ratio=geneRatio) load = Load(name, day, engine, frash_ratio=loadRatio) storage = Storage(name, engine) pricetable = Para_PriceTable(day, engine, frash_ratio=priceRatio) dayplan = Para_DayAheadPlan(day, engine) timenow = datetime(int(day[0:4]), int(day[5:7]), int(day[8:10])) timeD = timedelta(minutes=timeDs) while timenow < datetime(int(day[0:4]), int(day[5:7]), int( day[8:10])) + timedelta(days=1): print('Do:', timenow, '-------------------------------------------') policy = gird_model_dynamic(timenow, storage, load, generator, pricetable, dayplan) log = Do_policy(timenow, timeD, policy, pricetable.get_PP_bytime_buy(timenow).price, pricetable.get_PP_bytime_sale(timenow).price, storage, load, generator, dayplan) res.append(log.tolist()) timenow += timeD generator.refrash(timenow) load.refrash(timenow) pricetable.refrash(timenow) return pd.DataFrame(res, columns=Para_DoLog.get_names())
def all_distance(SavedList): for s_path in SavedList: path = upper_path + '/DataBase/' + s_path [stj, fname0, fname1] = s_path.split('/') acts = Load.fname2act(fname0) hou_dict = Load.load_se_map(stj, fname0, fname1) rooms, T_Bs, furnitures, doors, walls, lims = Load.dic2house(hou_dict) T_B_in, T_B_walls = Dis.T_B2obj_W(T_Bs, rooms) Dis.mod_walls(walls, T_B_walls) discom = Dis.cal_dis_val(rooms, furnitures, walls, lims, t_b_in=T_B_in) X0, Y0 = lims[0][0] - edge, lims[1][0] - edge destinations = Dest.cal_destinations(rooms, furnitures, doors, discom, X0, Y0) max_diss_d = {} connectflag = 0 for act in acts: s_nodes = destinations[act] topo = Dist.topology(discom) distance, max_dis = Dist.weighted_dijistra(s_nodes, topo, discom) if connectflag == 0: che_con, e_act = Dist.connect_check(distance, max_dis, destinations) if che_con: connectflag = 1 else: return False, e_act, s_path max_diss_d[act] = max_dis f_name = act + '_distance' HSa.save_filed(f_name, path, '%7.2f', distance) HSa.save_filed('Discomfortable_value', path, '%5.2f', discom) HSa.save_normaljson(path, destinations, 'Destinations') HSa.save_normaljson(path, max_diss_d, 'Max_Distances') return True, None, None
def main(): eSweep = ['0.0', '0.1', '0.2', '0.3', '0.4', '0.5', '0.6'] tSweep = ['0.0', '0.1', '0.2', '0.3', '0.4', '0.5', '0.6'] bResults = Load.loadFloatMatrix('MCTS_sweepET_b', len(tSweep), len(eSweep)) wResults = Load.loadFloatMatrix('MCTS_sweepET_w', len(tSweep), len(eSweep)) plt.figure() plot = plt.imshow(bResults, cmap=mpl.cm.Greys, norm=mpl.colors.Normalize(vmin=0, vmax=1), origin='lower') cbar = plt.colorbar(plot) cbar.ax.set_ylabel('Probability') plt.title('B Probability of using optimal strategy') plt.xlabel('Temperature') plt.xticks(list(range(len(tSweep))), tSweep) plt.ylabel('Epsilon') plt.yticks(list(range(len(eSweep))), eSweep) plt.figure() plot = plt.imshow(wResults, cmap=mpl.cm.Greys, norm=mpl.colors.Normalize(vmin=0, vmax=1), origin='lower') cbar = plt.colorbar(plot) cbar.ax.set_ylabel('Probability') plt.title('W Probability of using optimal strategy') plt.xlabel('Temperature') plt.xticks(list(range(len(tSweep))), tSweep) plt.ylabel('Epsilon') plt.yticks(list(range(len(eSweep))), eSweep) plt.show()
def handle_events(): global MouseX, MouseY, ChangeCity, ChangeScene events = get_events() for event in events: if event.type == SDL_QUIT: Framework.quit() elif event.type == SDL_KEYDOWN and event.key == SDLK_ESCAPE: Framework.quit() elif event.type == SDL_MOUSEMOTION: MouseX, MouseY = event.x, (get_canvas_height() - 1) - event.y elif event.type == SDL_MOUSEBUTTONDOWN: MouseX, MouseY = event.x, (get_canvas_height() - 1) - event.y width, height = image["MainButton_Green"].w, image[ "MainButton_Green"].h CenterPointX, CenterPointY = get_canvas_width() / 2, 565 x1, y1, x2, y2 = Load.GetCorners(CenterPointX, CenterPointY, width, height) if Load.PointInRect(x1, y1, x2, y2, MouseX, MouseY): ChangeScene = SimpleWeatherScene.name w, h = image["Background_RegionLayout"].w, image[ "Background_RegionLayout"].h for weather_info in Load.WeatherSub.values(): x11, y11, x22, y22 = Load.GetCorners(weather_info.x, weather_info.y, w, h) if Load.PointInRect(x11, y11, x22, y22, MouseX, MouseY): ChangeCity = weather_info.city ChangeScene = SimpleWeatherScene.name pass
def main(): sample = pd.read_csv("../result_sample/Loan_Forecasting_Upload_Sample.csv", header=None) uid = pd.DataFrame({"uid":sample[0]}) # 提取用户信息 user = Load.load_data_csv("../data/t_user.csv") # 用户特征 user["sex"] = user["sex"].apply(lambda x: 1 if x == 1 else 0) user.pop("active_date") MONTHES = [11] for MONTH in MONTHES: #提取历史贷款信息 loan = Load.load_data_csv("../data/t_loan.csv") loan["month"] = loan["loan_time"].apply(split_by_month) #特征 loan["pay_per_month"] = loan.apply(get_pay_per_month, axis=1) loan["remain_loan"] = loan.loc[loan["month"]<=MONTH].apply(get_remain_loan, axis=1, args=(MONTH,)) loan["remain_loan"] = loan["remain_loan"] .fillna(0) loan["remain_pay"] = loan.loc[loan["month"] <= MONTH].apply(get_remain_pay, axis=1, args=(MONTH,)) loan["remain_pay"] = loan["remain_pay"].fillna(0) #当月贷款 loan_per_month = pd.DataFrame( loan.loc[loan["month"]==MONTH]["loan_amount"].groupby([loan["uid"]]).sum()).reset_index() #当月月供 pay_per_month = pd.DataFrame(loan.loc[loan["month"]==MONTH]["pay_per_month"].groupby([loan["uid"]]).sum()).reset_index() #历史贷款总额 remain_loan = pd.DataFrame(loan.loc[loan["month"]<=MONTH]["remain_loan"].groupby([loan["uid"]]).sum()).reset_index() #累计月供 remain_pay = pd.DataFrame(loan.loc[loan["month"]<=MONTH]["remain_pay"].groupby([loan["uid"]]).sum()).reset_index() feature_loan = pd.merge(uid, loan_per_month, on=["uid"], how="left") feature_loan = pd.merge(feature_loan, pay_per_month, on=["uid"], how="left") feature_loan = pd.merge(feature_loan, remain_loan, on=["uid"], how="left") feature_loan = pd.merge(feature_loan, remain_pay, on=["uid"], how="left") #提取购物特征 order = Load.load_data_csv("../data/t_order.csv") order["price"] = order["price"].fillna(0) #为消费记录,按照时间分割 order["month"] = order["buy_time"].apply(split_by_month) #获取用户在每笔费用的实际消费(金钱*数量-折扣) order["real_price"] = order.apply(count_price_per_order, axis=1) #获取每个用户当月的总消费额 feature_order = pd.DataFrame({"total_price":order.loc[order["month"]==MONTH]["real_price"].groupby([order["uid"]]).sum()}).reset_index() #合并数据集,将User和特种一一对应 feature = pd.merge(uid,user,on=["uid"],how="left") feature = pd.merge(feature, feature_order, on=["uid"], how="left") feature = pd.merge(feature,feature_loan,on=["uid"],how="left") #处理异常值 feature["month"] = MONTH feature["total_price"] = feature["total_price"].fillna(0.0) feature["loan_amount"] = feature["loan_amount"].fillna(0.0) feature["pay_per_month"] = feature["pay_per_month"].fillna(0.0) feature["remain_loan"] = feature["remain_loan"].fillna(0.0) feature["remain_pay"] = feature["remain_pay"].fillna(0.0) #保存特征数据 feature.to_csv("../test/feature_{}.csv".format(MONTH),index=False)
def main(): user = pd.read_csv("../processed_data/processed_user.csv") feature = capture_user_information(user) uid = user["uid"] MONTHs = [11] NUMs = [4.0] for NUM, MONTH in zip(NUMs, MONTHs): #提取 print("正在提取7/30天各个表格的详细信息") loan = pd.read_csv("../processed_data/processed_loan.csv") order = pd.read_csv("../processed_data/processed_order.csv") for gap in [7, 15]: order_features = capture_order_information(order, gap, MONTH + 1) for sub_feature in order_features: feature = pd.merge(feature, sub_feature, on=["uid"], how="left") loan_features = capture_loan_information(loan, gap, MONTH + 1) for sub_feature in loan_features: feature = pd.merge(feature, sub_feature, on=["uid"], how="left") order_loan_features = capture_order_loan_cross_information( order, loan, gap, MONTH + 1) for sub_feature in order_loan_features: feature = pd.merge(feature, sub_feature, on=["uid"], how="left") # 提取历史贷款信息 print("正在提取贷款历史统计信息...") loan = Load.load_data_csv("../data/processed_loan.csv") loan_features = get_loan_feature(loan, MONTH, NUM, uid) for sub_feature in loan_features: feature = pd.merge(feature, sub_feature, on=["uid"], how="left") # 提取购物特征 print("正在提取购物史统计信息...") order = Load.load_data_csv("../data/processed_order.csv") order_features = get_order_feature(order, MONTH, NUM, uid) for sub_feature in order_features: feature = pd.merge(feature, sub_feature, on=["uid"], how="left") # 提取点击特征 print("正在提取点击信息...") click = pd.read_csv("../data/click_{}_sum.csv".format(MONTH)) feature = pd.merge(feature, click, on=["uid"], how="left") loan = Load.load_data_csv("../data/processed_loan.csv") user = pd.read_csv("../data/t_user.csv") new_feature = get_loan_limit_ratio(user, loan, MONTH) feature = pd.merge(feature, new_feature, on=["uid"], how="left") #处理异常值 feature = feature.fillna(0.0) # 保存特征数据 feature.to_csv("../test/test_x_online.csv", index=False)
def loadData(): global name, queryData Load.copyFileFromS3() Load.parseFileToDB() queryData = "" name = "Data Loaded" return redirect('/index')
def main(): # Parameters nGames = 1000 learningRate = 0 temperature = 0 # Initialize bias = Load.loadFloatArray('SL_bias_smooth', 2) weights = Load.loadFloatMatrix('SL_weights_smooth', 2, 2) SLAI = SoftmaxLinearAI.AI(learningRate, temperature, bias, weights) HCAI = [] HC_string = '' game = Game.Game() for i in range(game.n - 1): HCAI.append(0) HC_string += '0' for i in range(game.n): HCAI.append(1) HC_string += '1' print('Start SL benchmark!') print('[Total games: %d]' % (nGames)) strategies = {} SLvHC = 0 # Run the benchmark for iGame in range(nGames): if iGame % int(nGames / 10) == 0: print('Completed ' + str(int(100 * iGame / nGames)) + '%') game = Game.Game() SL_string = '' while game.running: SL_action = SLAI.getAction(game.getFeatures(True)) SL_string += str(SL_action) game.progress([SL_action, HCAI[game.round]]) if game.win[0]: SLvHC += 1 if SL_string in strategies: strategies[SL_string] += 1 else: strategies[SL_string] = 1 print('Completed 100%') # Write the results resultsFile = open('SL_benchmark_results.txt', 'w') resultsFile.write('## Softmax Linear\n') resultsFile.write('Games: ' + str(nGames) + '\n' + 'Temperature: ' + str(temperature) + '\n\n') resultsFile.write('# Optimal strategy usage: \n') if HC_string in strategies: resultsFile.write(str(100 * strategies[HC_string] / nGames) + '%\n\n') else: resultsFile.write('Did not use the optimal strategy at all\n\n') resultsFile.write('# Win percentage: \n') resultsFile.write(str(100 * SLvHC / nGames) + '%\n') resultsFile.close()
def load(): """ Load necessarry shared data """ global tetrominos, keymap, options, _loaded if not _loaded: Log.log("Loading shared data") tetrominos = Load.loadTetrominos() keymap = Load.loadKeymaps() options = Load.loadOptions() _loaded = True
def figure(self, root, path): self.Canvas = tk.Canvas(root, bg='white', height=370, width=640) path_l = path.split('/') house_js = Load.load_se_map(path_l[0], path_l[1], path_l[2]) self.rooms, self.T_Bs, self.furnitures, self.doors, self.walls, self.lims = Load.dic2house(house_js) self.Fur_set, self.scale, self.IsROT, self.Fur_indexs = \ SP.layoutplot(self.Canvas, [640, 370], self.rooms, self.T_Bs, self.furnitures, self.doors, self.walls, self.lims) self.Canvas.pack(side='left') self.Canvas.bind('<Button-1>', self.mousepick) self.Canvas.bind('<B1-Motion>', self.mousedrag)
def edit_image(self, length, splicing = True): #YOUR CODE HERE imgs = [0,0] if self.bird_type == "BIRDIE": img = self.make_long_img(Load.load_image("new_birdie.png", -1, self.bird_size)[0], length)[0] return img, img.get_rect() imgs[self.on_right] = Load.load_image(self.image_dict[self.bird_type], -1,self.bird_size)[0] #imgs[not self.on_right] = Load.load_image('new_birdie.png', -1, (length - self.bird_size[0] * (not self.need_append[self.bird_type]),self.bird_size[1]))[0] imgs[not self.on_right] = self.make_long_img(Load.load_image("new_birdie.png", -1, self.bird_size)[0], (length - self.bird_size[0] * (not self.need_append[self.bird_type])))[0] return self.splice_image(imgs)
def layout(self, root): Canvas = tk.Canvas(root, bg='white', height=370, width=640) path = self.savelist[self.pindex] path_l = path.split('/') house_js = Load.load_se_map(path_l[0], path_l[1], path_l[2]) rooms, T_Bs, furnitures, doors, walls, self.lims = Load.dic2house(house_js) Fur_set, self.scale, self.IsROT, Fur_indexs = SP.layoutplot(Canvas, [640, 370], rooms, T_Bs, furnitures, doors, walls, self.lims, showbg=False) self.key, self.key_ = self.deterkey(self.TPindex, self.saindex) [self.body_c, self.left_f, self.right_f] = self.TPs[self.pindex][self.key] return Canvas
def main(): # Parameters nGames = 1000000 learningRate = 0 temperature = 0 # Initialize print('Start benchmark!') print('[Total games: %d]' % ((2 * nGames))) bBias = Load.loadFloatArray('SL_bBias_smooth', c.nOutputs) bWeights = Load.loadFloatMatrix('SL_bWeights_smooth', c.nOutputs, c.nInputs) bSLAI = SoftmaxLinearAI.AI(learningRate, temperature, bBias, bWeights) wBias = Load.loadFloatArray('SL_wBias_smooth', c.nOutputs) wWeights = Load.loadFloatMatrix('SL_wWeights_smooth', c.nOutputs, c.nInputs) wSLAI = SoftmaxLinearAI.AI(learningRate, temperature, wBias, wWeights) HCAI = [] for i in range(1): HCAI.append(2) for i in range(35): HCAI.append(1) bSLvHC = 0 wSLvHC = 0 # Run the benchmark for iGame in range(nGames): game = Game.Game(c.team2, c.team3) while game.running: game.trainers[0].setNextAction(bSLAI.getAction(game.getFeatures(c.amBlack))) game.trainers[1].setNextAction(HCAI[game.round]) game.progress() if game.win[0]: bSLvHC += 1 game = Game.Game(c.team2, c.team3) while game.running: game.trainers[0].setNextAction(HCAI[game.round]) game.trainers[1].setNextAction(wSLAI.getAction(game.getFeatures(c.amWhite))) game.progress() if game.win[1]: wSLvHC += 1 # Write the results resultsFile = open('SL_benchmark_results.txt', 'w') resultsFile.write('### Softmax Linear\n') resultsFile.write('Games: ' + str(nGames) + '\n\n') resultsFile.write('## Black \n\n') resultsFile.write('# Win percentage: \n') resultsFile.write(str(100 * bSLvHC / nGames) + '%\n\n') resultsFile.write('## White \n\n') resultsFile.write('# Win percentage: \n') resultsFile.write(str(100 * wSLvHC / nGames) + '%\n\n') resultsFile.close()
def handle_events(): global MouseX, MouseY, city, ChangeScene, EnterScene events = get_events() for event in events: if event.type == SDL_QUIT: Framework.quit() elif event.type == SDL_KEYDOWN and event.key == SDLK_ESCAPE: Framework.quit() elif event.type == SDL_MOUSEMOTION: MouseX, MouseY = event.x, (get_canvas_height() - 1) - event.y elif event.type == SDL_MOUSEBUTTONDOWN: MouseX, MouseY = event.x, (get_canvas_height() - 1) - event.y if not EnterScene: info_tmp = weather[city].getTemperature() if not info_tmp: info_tmp = '측정정보없음' else: info_tmp = str(info_tmp) + '˚' w, h = font[62].getpixelSize_unicode(info_tmp) x2, y2 = get_canvas_width() / 2 + w / 2, get_canvas_height() / 1.3 + h / 2 info_PM10 = ' 미세먼지: ' if weather[city].getPM10State() == '측정정보없음': info_PM10 = '측정정보없음' else: info_PM10 = info_PM10 + weather[city].getPM10State() + ' ' w, h = font[26].getpixelSize_unicode(info_PM10) x1, y1 = get_canvas_width() / 2 - w / 2, get_canvas_height() / 2.7 - h / 2 if Load.PointInRect(x1, y1, x2, y2, MouseX, MouseY): ChangeScene = DetailWeatherScene.name info_Address = weather[city].getAdress() if not info_Address: info_Address = '측정정보없음' else: info_Address = ' ' + info_Address + '시 ' width, height = font[36].getpixelSize_unicode(info_Address) CenterPointX, CenterPointY = get_canvas_width() / 2 - width / 2, get_canvas_height() / 4 + height / 2 x1, y1, x2, y2 = Load.GetCorners(CenterPointX, CenterPointY, width, height) if Load.PointInRect(x1, y1, x2, y2, MouseX, MouseY): ChangeScene = MapWeatherScene.name buttonW, buttonH = image['RefreshButton'].w, image['RefreshButton'].h buttonX, buttonY = get_canvas_width() / 2, get_canvas_height() / 10.5 Buttonx1, Buttony1, Buttonx2, Buttony2 = Load.GetCorners(buttonX, buttonY, buttonW, buttonH) if Load.PointInRect(Buttonx1, Buttony1, Buttonx2, Buttony2, MouseX, MouseY): weather[city].Update(city) pass
def bic_oneRun(address, filename_raw_data, subsample_bic, fraction_train, repeat_bic, max_groups, grid_bic,\ conc_bic, size_bic, n_dimen, fraction_nan_samples, fraction_nan_depths, dtype): # Load the training data #lon_train, lat_train, Tint_train, varTrain_centre, Sint_train, varTime_train \ # = None, None, None, None, None, None lon_train, lat_train, Tint_train, varTrain_centre = None, None, None, None # DD found bug... below to fix always running 'uniform' subsampling for bic if subsample_bic == "uniform": subs_u, subs_r, subs_it = True, False, False if subsample_bic == "random": subs_u, subs_r, subs_it = False, True, False if subsample_bic == "intime": subs_u, subs_r, subs_it = False, False, True #lon_train, lat_train, Tint_train, varTrain_centre \ # = Load.main(address, filename_raw_data, None, subsample_bic, False,\ lon_train, lat_train, Tint_train, varTrain_centre \ = Load.main(address, filename_raw_data, None, subs_u, subs_r,\ subs_it, grid_bic, conc_bic, fraction_train, None, None,\ fraction_nan_samples, fraction_nan_depths, dtype, run_Bic=True) # Calculate PCA pca, X_pca_train = None, None pca = decomposition.PCA(n_components=n_dimen) # Initialise PCA object pca.fit(varTrain_centre) # Fit the PCA to the training data X_pca_train = pca.transform(varTrain_centre) del pca # Run BIC for GMM with different number of components # bic_values contains the array of scores for the different n_comp # n_lowest is the lowest n for each repeat # n_comp_array is from 0 to max_groups in integers bic_values, n_lowest, n_comp_array = None, None, None bic_values, n_lowest, n_comp_array = bic_calculate(X_pca_train, max_groups) return bic_values, n_lowest, n_comp_array
def bic_oneRun(address, filename_raw_data, subsample_bic, repeat_bic, max_groups, grid_bic,\ conc_bic, size_bic, n_dimen, fraction_nan_samples, fraction_nan_depths, cov_type): # load the training data lon_train, lat_train, dynHeight_train, Tint_train, varTrain_centre, Sint_train, varTime_train \ = None, None, None, None, None, None, None lon_train, lat_train, dynHeight_train, Tint_train, varTrain_centre, Sint_train, varTime_train \ = Load.main(address, filename_raw_data, None, subsample_bic, False,\ False, grid_bic, conc_bic, None, None, None,\ fraction_nan_samples, fraction_nan_depths, cov_type, run_bic=True) # calculate PCA pca, X_pca_train = None, None pca = decomposition.PCA(n_components=n_dimen) # Initialise PCA object pca.fit(varTrain_centre) # Fit the PCA to the training data X_pca_train = pca.transform(varTrain_centre) del pca # run BIC for GMM with different number of components # bic_values contains the array of scores for the different n_comp # n_lowest is the lowest n for each repeat # n_comp_array is from 0 to max_groups in integers bic_values, n_lowest, n_comp_array = None, None, None bic_values, n_lowest, n_comp_array = bic_calculate(X_pca_train, max_groups, cov_type) return bic_values, n_lowest, n_comp_array
def main(): # 提取用户信息 user = Load.load_data_csv("../data/t_user.csv") user.pop("active_date") uid = pd.DataFrame(user["uid"]) MONTH = 11 # 提取历史贷款信息 loan = Load.load_data_csv("../data/processed_loan.csv") loan_features = get_loan_feature(loan, MONTH) feature = pd.merge(uid, loan_features, on=["uid"], how="left") # 处理异常值 feature = feature.fillna(0.0) # 保存特征数据 feature.to_csv("../train/train_y_offline_11.csv", index=False)
def Encontro(Eu): Falagg("""Você escuta um barulho estranho. o som das rapidas passadas aumentam, algo está correndo em sua direção Se prepare essa será sua primeira batalha Você está de frente com um ghuul, um ser místico que habita corpos mortos Boa sorte!!""") L.Batalha(Load.enemy("Ghuul"), Eu) return [Eu, 3]
def __init__(self, game, size): pygame.sprite.Sprite.__init__(self) self.image, self.rect = Load.load_image("denero.jpg", -1, size) self.game = game game.allsprites.add(self) self.rect.bottom = self.game.bigSurface.get_rect().bottom self.rect.left = 0 self.onScreen = True
def __init__(self, top=HIGHSCORES, header_font=MENU_HEADER_FONT, *args, **kwargs): super(HighscoreList, self).__init__("HighscoreList", *args, **kwargs) self.running = self.mainLoop self.scores = Load.loadScores() sorted_score_table = [(("Name", "Score", "Lines"), None)] sorted_score_table.extend([ ((score["name"], score["score"], score["lines"]), score) for score in sorted(self.scores, key=lambda d: d["score"], reverse=True) ]) self.header_font = {} self.header_font.update(header_font) self.addJob("header", Jobs.TextBox( self, "Scores", y=20, xcenter=True, textfit=True, underline=False, colors={"background":(0x22,0x22,0x22), "font":(0xaa,0xaa,0xaa)}, font=self.header_font, onmouseclick=self.onHeaderClick, queue=JobQueue.HEADER, fill=TETRIS_BACKGROUND, ) ) self.addJob( "table", Jobs.Table( self, SPACER, self.jobs.header.y+self.jobs.header.height + 1, TETRIS_STATUSBOX_FONT, sorted_score_table, colors=TETRIS_STATUSBOX_COLORSCHEME, onmouseclick=self.previewScore, xcenter=True,# queue=JobQueue.TEXTBOX, ) ) self.addJob( "exit_button", Jobs.TextBox( self, "Exit", x=SPACER, y=self.height - SPACER, textfit=True, underline=True, colors={"background":(0x22,0x22,0x22), "font":(0xaa,0xaa,0xaa)}, font=TETRIS_STATUSBOX_FONT, onmouseclick=self.quitGame, queue=JobQueue.SCROLL_FILLER + 1, fill=TETRIS_BACKGROUND, ) ) self.jobs.exit_button.y -= self.jobs.exit_button.height ## Keeps the exit_button from being overwritten by the table self.addJob( "bottom_filler", Jobs.Filler( self, 0, self.jobs.exit_button.y - SPACER, self.width, self.jobs.exit_button.height + (self.height - self.jobs.exit_button.y) + SPACER, queue=JobQueue.SCROLL_FILLER, ) ) ## Keeps the table from being visible above the header self.addJob( "top_filler", Jobs.Filler( self, 0, 0, self.width, self.jobs.header.y, queue=JobQueue.SCROLL_FILLER, ) )
def __init__(self, *args, **kwargs): self.id = "TetrisGame" super(TetrisGame, self).__init__( self.id, *args, fill=True, soundtrack=os.path.join(Load.MUSICDIR, "uprising.ogg"), sound_enabled=SOUND_ENABLED, **kwargs ) self.running = self.mainGame self.highscores = Load.loadHighscores(top=HIGHSCORES) self.addJob("interface", TetrisInterface(self, SPACER, SPACER))
def __init__(self, *args, **kwargs): self.id = "Credits" super(Credits, self).__init__( self.id, soundtrack=os.path.join(Load.MUSICDIR, "elevator_cat.ogg"), sound_enabled=SOUND_ENABLED, ticktime=CREDITS_FRAMERATE, **kwargs ) # self.text = "Loltris v{}\n\n".format(VERSION) self.text = Load.loadCredits() self.running = self.mainLoop ## Jobs title_font = {} title_font.update(CREDITS_FONT) title_font["size"] += 20 title_font["bold"] = True self.addJob("title", Jobs.ScrollingText( self, "Loltris v{}\n".format(VERSION), speed=-1, font=title_font, colors=CREDITS_COLORSCHEME, fill=MENU_BACKGROUND, queue=1, ) ) self.addJob("text", Jobs.ScrollingText( self, self.text, speed=-1, font=CREDITS_FONT, colors=CREDITS_COLORSCHEME, fill=MENU_BACKGROUND, y=SCREEN_HEIGHT + self.jobs.title.height, queue=0, ) ) ## TODO: For this to be possible, Jobs.ScrollingText needs to stop drawing itself when it reaches a certain point, ## it needs a y-coordinate where the text starts to disappear. # blockwidth = (self.width) // len(TITLE_BLOCKS[0]) # self.addJob("title_board", # Jobs.Board( # self, # y=SPACER, # height=len(TITLE_BLOCKS), # width=len(TITLE_BLOCKS[0]), # blockwidth=blockwidth, # bgcolor=self.bgcolor, # queue=100, # draw_grid=False, # draw_border=False, # ) # ) # self.jobs.title_board.x = (self.width // 2) - (self.jobs.title_board.width // 2) # for x, y in Matrix.matrixToSet(TITLE_BLOCKS): # self.jobs.title_board.blocks[(x, y)] = (0xaa,0xaa,0xaa) self.addJob("endtimer", Jobs.TimedExecution(self, self.quitGame, timed=False, anykey=True))
def main(run=None): print("Starting Main.main()") # Now start the GMM process Load.main(address, dir_raw_data, run, subsample_uniform, subsample_random,\ subsample_inTime, grid, conc, fraction_train, inTime_start,\ inTime_finish, fraction_nan_samples, fraction_nan_depths, dtype) #Load.main(address, filename_raw_data, run, subsample_uniform, subsample_random,\ # Loads data, selects Train, cleans, centres/standardises, prints PCA.create(address, run, n_dimen) # Uses Train to create PCA, prints results, stores object GMM.create(address, run, n_comp) # Uses Train to create GMM, prints results, stores object PCA.apply(address, run) # Applies PCA to test dataset GMM.apply(address, run, n_comp) # Applies GMM to test dataset # Reconstruction Reconstruct.gmm_reconstruct(address, run, n_comp) # Reconstructs the results in original space Reconstruct.full_reconstruct(address, run) Reconstruct.train_reconstruct(address, run) # new stuff DD 27/08/18, after seeing updates on DJ github #mainProperties(address, runIndex, n_comp) # Plotting -- first commented out DD #Plot.plotMapCircular(address, address_fronts, run, n_comp) #Plot.plotPosterior(address, address_fronts, run, n_comp, plotFronts=True) Plot.plotPostZonal(address, run, n_comp, dtype, plotFronts=False) ## zonal frequencies #Plot.plotPosterior(address, run, n_comp, dtype, plotFronts=False) ## works but data overlaps spatially... Plot.plotProfileClass(address, run, n_comp, dtype, 'uncentred') Plot.plotProfileClass(address, run, n_comp, dtype, 'depth') Plot.plotGaussiansIndividual(address, run, n_comp, dtype, 'reduced')#uncentred')#'depth')#reduced') # Plot.plotGaussiansIndividual(address, run, n_comp, 'depth') # ERROR NOT WOKRING PROPERLY # Plot.plotGaussiansIndividual(address, run, n_comp, 'uncentred') # ERROR NOT WOKRING PROPERLY #Plot.plotProfile(address, run, dtype, 'original') # these run just fine but are huge and unhelpful Plot.plotProfile(address, run, dtype, 'uncentred') Plot.plotWeights(address, run, dtype)
def plot(title, yName, yLabel): #dSweep = [1, 10, 20, 30, 40] dSweep = [1, 5, 10, 15, 20] y = Load.loadFloatArray('MCTS_sweepD_results/MCTS_sweepD_' + yName, len(dSweep)) plt.figure() plt.plot(dSweep, y, 'x') plt.title(title) plt.xlabel('Depth') plt.ylabel(yLabel)
def search(self): for i in range(len(self.map_Che_val)): self.varvals[self.map_Che_val[i]] = 2*self.vars[i].get() for i in range(len(self.map_Com_val)): if self.strs[i].get() == 'Must be in': self.varvals[self.map_Com_val[i]] = 2 elif self.strs[i].get() == 'May be in': self.varvals[self.map_Com_val[i]] = 1 Ranges = [self.ranges[i].get() for i in range(10)] N, self.Pathlist = Load.search(self.varvals, Ranges) Info = 'There are %d houses which satisfy your requirement' % (N) tkinter.messagebox.showinfo(title='Info', message=Info)
def main(): import sys sys.path.append('../Utils') sys.path.append('../Utils/Evaluation') sys.path.append('../Utils/Tuning') import Matrix as matrix import Load as load import numpy,learningCurves import measures import SVM_Tuning trainPath = '/home/leonidas/Downloads/Clef2013/train_2x2_CIELab_256.txt' testPath = '/home/leonidas/Downloads/Clef2013/test_2x2_CIELab_256.txt' trainLabelPath = '/home/leonidas/Downloads/Clef2013/train_2x2_CIELab_256_labels.txt' testLabelPath = '/home/leonidas/Downloads/Clef2013/test_2x2_CIELab_256_labels.txt' trainPath = '/home/leovala/databases/Clef2013/GBoCFeatures/train_2x2_CIELab_256.txt' testPath = '/home/leovala/databases/Clef2013/GBoCFeatures/test_2x2_CIELab_256.txt' trainLabelPath = '/home/leovala/databases/Clef2013/GBoCFeatures/train_2x2_CIELab_256_labels.txt' testLabelPath = '/home/leovala/databases/Clef2013/GBoCFeatures/test_2x2_CIELab_256_labels.txt' [trainArray, train_labels, testArray, test_labels,ouClasses] = load.loadFeatures(trainPath=trainPath, trainLabels=trainLabelPath, testPath=testPath, testLabels=testLabelPath); # resize to 2D array trainArray=numpy.reshape(trainArray,(trainArray.shape[0], -1)) testArray=numpy.reshape(testArray,(testArray.shape[0], -1 )) print "training" # Random SEARCH ( 0 , 50 ): # Best parameters set found on development set: # {'C': 21, 'gamma': 46} # print 'tuning now...' [bestC , bestGamma]= SVM_Tuning.svm_tuning(trainArray,train_labels,testArray,test_labels,randomized=False) print bestC print bestGamma model = train(trainArray,train_labels,c=bestC,g=bestGamma,k='rbf') # model = train(trainArray,train_labels) print "testing" predictions = predict(testArray,model) accuracy = measures.accuracy(test_labels,predictions) print accuracy # Learning Curves learningCurves.plot_learning_curve(features_train=trainArray, labels_train=train_labels, features_test=testArray, labels_test=test_labels ,K='rbf',C=bestC,G=bestGamma)
def NewGame(graph, clock): par = party() par.mems[1] = character() par.mems[1].mage() saveF = shelve.open('saveFile') saveF.clear() saveF['mcImage'] = 'tokenFilled.png' saveF['mapN'] = 'LavTest' saveF['party'] = par Load(graph, clock)
def main(): # Parameters nGames = 1000000 nStrategies = 7 # Initialize infoFile = open('HC_sweepW_info.txt', 'w') infoFile.write('Games = ' + str(nGames) + '\n' + 'Strategies = ' + str(nStrategies) + '\n') infoFile.close() print('Start HC weakening sweep!') print('[Total games: %d]' % (nGames * nStrategies**2)) strategy = [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ] strategies = [strategy.copy()] for i in range(nStrategies - 1): strategy.insert(0, 2) strategies.append(strategy.copy()) resultsFile = open('HC_sweepW.txt', 'w') # Run the sweep for iStrategy in range(nStrategies): for jStrategy in range(nStrategies): print('Completed %1.1f' % (100 * (iStrategy * nStrategies + jStrategy) / (nStrategies**2)) + '%') bWin = 0 for iGame in range(nGames): game = Game.Game(c.team2, c.team3) while game.running: game.trainers[0].setNextAction( strategies[iStrategy][game.round]) game.trainers[1].setNextAction( strategies[jStrategy][game.round]) game.progress() if game.win[0]: bWin += 1 resultsFile.write(str(bWin / nGames) + '\n') resultsFile.close() # Calculate optimal number of weakening moves sweepResults = Load.loadFloatMatrix('HC_sweepW', nStrategies, nStrategies) optimalFile = open('HC_optimal.txt', 'w') optimalFile.write('### Hard Coded\n') optimalFile.write('## Optimal number of weakening moves\n\n') bOptimal = np.sum(sweepResults, axis=0) / nStrategies optimalFile.write('# Charmander: ' + str(bOptimal.tolist().index(min(bOptimal))) + '\n\n') wOptimal = np.sum(sweepResults, axis=1) / nStrategies optimalFile.write('# Squirtle: ' + str(wOptimal.tolist().index(max(wOptimal))) + '\n\n')
def handle_events(): global MouseX, MouseY, ChangeScene events = get_events() for event in events: if event.type == SDL_QUIT: Framework.quit() elif event.type == SDL_KEYDOWN and event.key == SDLK_ESCAPE: Framework.quit() elif event.type == SDL_MOUSEMOTION: MouseX, MouseY = event.x, (get_canvas_height() - 1) - event.y elif event.type == SDL_MOUSEBUTTONDOWN: MouseX, MouseY = event.x, (get_canvas_height() - 1) - event.y width, height = image["MainButton_Green"].w, image["MainButton_Green"].h a = " 간편대기 " w, h = Load.font[18].getpixelSize_unicode(a) CenterPointX, CenterPointY = get_canvas_width() / 2, 550 + h / 2 x1, y1, x2, y2 = Load.GetCorners(CenterPointX, CenterPointY, width, height) if Load.PointInRect(x1, y1, x2, y2, MouseX, MouseY): ChangeScene = SimpleWeatherScene.name pass
def main(): nBattles = 1000 nPlotPoints = 1001 x = np.linspace(0, nBattles, nPlotPoints) xLine = np.linspace(0, nBattles, 2) bias = Load.loadFloatMatrix('SL_bias_plot', nPlotPoints, 2) weights = Load.loadFloatMatrix('SL_weights_plot', nPlotPoints, 2 * 2) biasSmooth = Load.loadFloatArray('SL_bias_smooth', 2) weightsSmooth = Load.loadFloatArray('SL_weights_smooth', 2 * 2) plt.figure() plt.plot(x, bias, linewidth=0.5) plt.plot(x, weights, linewidth=0.5) plt.plot(xLine, [biasSmooth, biasSmooth], ':') plt.plot(xLine, [weightsSmooth, weightsSmooth], ':') plt.title('Biases and weights') plt.xlabel('Number of trained games') plt.ylabel('Weight values') plt.show()
def __init__(self, game, rounds, startPos=(250, 250)): pygame.sprite.Sprite.__init__(self) self.game = game self.image, self.rect = Load.load_image("ink.png", None, (468, 468)) self.initial_round = self.game.turns self.rounds = rounds game.allsprites.add(self) game.gui.add(self) screen = pygame.display.get_surface() self.startPos = startPos self.rect.center = self.game.translatePoint(startPos) self.onScreen = True
def __init__(self, **kwargs): super(MainMenu, self).__init__( "MainMenu", onHeaderClick=lambda: Webbrowser.open(PROJECT_SITE), header_font=MENU_HEADER_FONT, option_font=MENU_OPTION_FONT, isroot=True, xcenter=True, soundtrack=Path.join(Load.MUSICDIR, "jazz_cat_infinite_loop_cut.ogg"), sound_enabled=SOUND_ENABLED, **kwargs) self.title_blocks = BlockText.render(TITLE_TEXT, font=Load.loadBlockFont("standard")) blockwidth = (self.width) // len(self.title_blocks[0]) Log.debug("title_board.blockwidth = {}".format(blockwidth)) self.addJob("title_board", Jobs.Board( self, y=SPACER, height=len(self.title_blocks), width=len(self.title_blocks[0]), blockwidth=blockwidth, bgcolor=self.bgcolor, queue=100, draw_grid=False, draw_border=False, ) ) self.jobs.title_board.x = (self.width // 2) - (self.jobs.title_board.width // 2) for x, y in Matrix.matrixToSet(self.title_blocks): self.jobs.title_board.blocks[(x, y)] = (0xaa,0xaa,0xaa) self.options_pos[1] = self.jobs.title_board.y + self.jobs.title_board.height + SPACER*2 self.menu = Factory.textBoxes([ ("Single Player", lambda: self.call(TetrisGame.TetrisGame, caption="Loltris")), ("Two Player", lambda: self.call(TwoPlayerTetrisGame.TwoPlayerTetris, caption="Loltris - Two Player")), ("LAN Play", lambda: self.call(LANTetrisGame.LANMenu, caption="Loltris - LAN play")), ("Options", lambda: self.call(OptionsMenu, caption="Loltris - Options")), ("Creative", lambda: self.call(MakeTetromino.MakeTetromino, caption="Loltris - Creator")), ("Scores", lambda: self.call(HighscoreExplorer.HighscoreList, caption="Loltris - Highscores")), ("Credits", lambda: self.call(Credits.Credits, caption="Loltris - Credits")), ("Homepage", lambda: Webbrowser.open(PROJECT_SITE)), ("SandBox", lambda: self.call(SandBox.SandBox, caption="Loltris - SandBox")), ("Exit", self.quit), ], self, font=MENU_OPTION_FONT, fill=MENU_3DBORDER_BACKGROUND, xcenter=True, colors={ "background":self.colorscheme["background"], "font":self.colorscheme["option"], }, ) self.setupObjects() #self.loadHighscores() ## XXX: Temporary bugfix, scroll_filler is drawn on every frame while the board is not. del self.jobs.scroll_filler
def loadProject(self, fileName="", confirmReset=True): """ Load a project from a file which will be selected by the user. """ Util.debug(2, "App.loadProject", "Loading project from file " + str(fileName)) # Reset app to a clean slate self.resetToDefaults(confirmReset) # Now load the project if fileName == "": fileDialog = QFileDialog(self.ui.workspace, "Load Project") fileDialog.setNameFilter("PySciPlot Project (*.psp);;All Files (*)") fileDialog.setDefaultSuffix("psp") fileDialog.setConfirmOverwrite(False) fileDialog.setDirectory(self.projectDirectory()) fileDialog.setAcceptMode(QFileDialog.AcceptOpen) fileDialog.exec_() fileName = str(fileDialog.selectedFiles()[0]) Load.loadProjectFromFile(self, fileName)
def save(self, name): xlow = min(x for x, y in self.jobs.board.blocks) xhigh = max(x for x, y in self.jobs.board.blocks) ylow = min(y for x, y in self.jobs.board.blocks) yhigh = max(y for x, y in self.jobs.board.blocks) matrix = [ [(x, y) in self.jobs.board.blocks for x in xrange(xlow, xhigh+1)] for y in xrange(ylow, yhigh+1) ] Log.log("Created new tetromino, displaying below") Matrix.put(matrix) Save.saveTetromino(self.color, name, matrix) Shared.tetrominos = Load.loadTetrominos() return True
def __init__(self, **kwargs): super(OptionsMenu, self).__init__("OptionsMenu", header_font=MENU_HEADER_FONT, option_font=MENU_OPTION_FONT, xcenter=True, **kwargs) self.header = "Options" self.options = Load.loadOptions() self.menu = Factory.textBoxes([ ("Keymaps", lambda: self.call(KeymapMenu, caption=self.caption)), ], self, font=MENU_OPTION_FONT, colors={"background":self.colorscheme["background"], "font":self.colorscheme["option"], }, fill=MENU_3DBORDER_BACKGROUND, xcenter=True, ) ## >inb4 immature jokes def turnOn(option, options): Log.debug(option) if options.get(option) != None: Log.warning("Turning on non-existent option: {}".format(repr(option))) options[option] = True Save.saveOptions() def turnOff(option, options): Log.debug(option) if options.get(option) != None: Log.warning("Turning off non-existent option: {}".format(repr(option))) options[option] = False Save.saveOptions() self.menu.extend( Factory.basicSwitches([ ("Uber-Tetromino", "uber_tetromino"), ("Flip tetromino", "flip_tetromino"), ], self, turnOn, turnOff, Shared.options["gameplay"], font=MENU_OPTION_FONT, colors=SWITCH_OPTION_COLORS, boxwidth=8, box_center=True, fill=MENU_3DBORDER_BACKGROUND, ) ) self.setupObjects()
def main(): import sys sys.path.append('../Utils') sys.path.append('../Utils/Evaluation') import numpy from Evaluation import measures import Load as load from Tuning import Log_Regression_Tuning import learningCurves trainPath = '/home/leonidas/Downloads/Clef2013/train_2x2_CIELab_256.txt' testPath = '/home/leonidas/Downloads/Clef2013/test_2x2_CIELab_256.txt' trainLabelPath = '/home/leonidas/Downloads/Clef2013/train_2x2_CIELab_256_labels.txt' testLabelPath = '/home/leonidas/Downloads/Clef2013/test_2x2_CIELab_256_labels.txt' [trainArray, train_labels, testArray, test_labels,outputClasses] = load.loadFeatures(trainPath=trainPath, trainLabels=trainLabelPath, testPath=testPath, testLabels=testLabelPath); # resize to 2D array trainArray=numpy.reshape(trainArray,(trainArray.shape[0], -1 )) testArray=numpy.reshape(testArray,(testArray.shape[0], -1 )) [bestC , bestAccuracy] = Log_Regression_Tuning.findBestCost(features_train=trainArray, labels_train=train_labels, features_test=testArray, labels_test=test_labels) print 'best accuracy : {0} , best cost : {1}'.format(bestAccuracy,bestC) model = train(trainArray,train_labels,c=bestC) predictions = predict(testArray,model) print predictions accuracy = measures.accuracy(test_labels,predictions) print ' acc : {0}'.format(accuracy) learningCurves.plot_learning_curve(features_train=trainArray, labels_train=train_labels, features_test=testArray, labels_test=test_labels,classifier="LR",C=bestC)
def setup(self): Log.debug("Running setup for {}".format(self.id)) Pygame.init() Pygame.mouse.set_visible(int(self.mouse_visible)) Pygame.display.set_icon(Load.loadImage(WM_ICON)) if not Pygame.mixer.get_init() and self.sound_enabled: Log.log("Initializing mixer") Pygame.mixer.init() if self.soundtrack and self.sound_enabled and not self.playing: Log.debug("Playing music: {}".format((self.soundtrack, self.sound_enabled, self.playing))) self.playMusic(self.soundtrack, loops=-1) if not self.screen or self.screen.get_width() != self.width or self.screen.get_height() != self.height: Log.notice("Setting display mode {}".format((self.width, self.height))) self.screen = Pygame.display.set_mode((self.width, self.height), DISPLAY_OPTIONS) self.screen.fill(self.bgcolor) Pygame.display.flip() self.clock = Pygame.time.Clock() Pygame.display.set_caption(self.caption)
def loadHighscores(self): """ Load scores from disk, then add the highscorelist job to see them """ self.highscores = Load.loadHighscores(top=HIGHSCORES) Log.debug("Loaded new highscores from disk, displaying below") Log.dump("".join(["{}: {}\n".format(d["name"], d["score"]) for d in self.highscores])) if self.highscores: self.addJob( "highscorelist", Jobs.TextBox( self, ( "Top {} scores\n\n".format(HIGHSCORES) + ## Title "".join(["{}: {}\n".format(x["name"], x["score"]) for x in self.highscores]) + ## The scores ("\n" * (HIGHSCORES - len(self.highscores))) ## Empty lines ), y=self.menu[0].y+1, textfit=True, colors=HIGHSCORELIST_COLORSCHEME, font=HIGHSCORELIST_FONT, border=True, background=True, ) ) ## The highscore-list should be 5 pixels from the right edge self.jobs.highscorelist.x = SCREEN_WIDTH - self.jobs.highscorelist.width - 5
def on_menuGravity_select(self, event): self.GLoad = Load.load(self)
:param officials: list of officials :param role: role to be sorted by :param weight_model: name of the model to sort by :param filter: if the zero weight entries should be removed from the returned list :return: sorted list of officials data (name, cert level (ref or NSO depending on the role), weighted value, raw games in that role) """ # remove the officials with no experience in the role list = officials if filter is True: list = ifilter(lambda x: methodcaller("get_weight", role, weight_model)(x) > 0, officials) # sort the list by weighted value list = sorted(list, key=methodcaller("get_weight", role, weight_model), reverse=True) # return a list of tuples containing just the information needed # return map(lambda z: (z.name, z.refcert if role in config.ref_roles else z.nsocert, z.weighting[weight_model][role], len(z.get_games(role))), list) return map(lambda z: z.get_role_summary(role, weight_model), list) if __name__ == "__main__": # o = filtertest() w = create_weights() import Load mh = Load.load_file("../sample/MikeHammer_GameHistoryNew.xlsx") mh.apply_weight_models(w) print mh.weighting["wstrict"] # print mh.weighting['std'] # print mh.weighting['aged']
def ManyClassifiers(): import sys sys.path.append('../Utils') sys.path.append('../Utils/Evaluation') import Load as load from Evaluation import measures from Utils.Tuning import SVM_Tuning # trainFolder = '/home/leonidas/Desktop/images/TrainSet' # testFolder = '/home/leonidas/Desktop/images/TestSet' # # trainFolder = '/home/leonidas/Desktop/images/SampleImages - Copy - Copy' # testFolder = '/home/leonidas/Desktop/images/SampleImages - Copy' # # # [trainArray, train_labels, testArray, test_labels,outputClasses] = matrix.load_dataset(trainFolder=trainFolder,testFolder=testFolder # ,imageSize=(250,250)) # print (trainArray.shape) # print (testArray.shape) trainPath = '/home/leonidas/Downloads/Clef2013/train_2x2_CIELab_256.txt' testPath = '/home/leonidas/Downloads/Clef2013/test_2x2_CIELab_256.txt' trainLabelPath = '/home/leonidas/Downloads/Clef2013/train_2x2_CIELab_256_labels.txt' testLabelPath = '/home/leonidas/Downloads/Clef2013/test_2x2_CIELab_256_labels.txt' [trainArray, train_labels, testArray, test_labels,outputClasses] = load.loadFeatures(trainPath=trainPath, trainLabels=trainLabelPath, testPath=testPath, testLabels=testLabelPath); import numpy # resize to 2D array trainArray=numpy.reshape(trainArray,(trainArray.shape[0], -1)) testArray=numpy.reshape(testArray,(testArray.shape[0], -1)) print (trainArray.shape) print (testArray.shape) print outputClasses print ("Training") # train classifiers classifiers = [] for i in range(0,outputClasses): temp_labels = [1 if x == i else 0 for x in train_labels] # print ('mpika tuning for classifier : {0}'.format(i)) # [bestC , bestGamma]= SVM_Tuning.svm_tuning(trainArray,temp_labels,testArray,test_labels,randomized=False,kernel='linear') model = train(trainArray,temp_labels,g=16,c=16,k='linear') classifiers.append(model) print ("Testing") classifiers_predictions = [] for model in classifiers: predictions = predictProba(testArray,model) classifiers_predictions.append(predictions) # classifiers_predictions = numpy.asarray(classifiers_predictions) # take maximum class probability from classifiers # predicted_labels = numpy.argmax(classifiers_predictions,axis=0) # print predicted_labels accuracy = measures.accuracy(test_labels,numpy.argmax(classifiers_predictions,axis=0) ) print 'Accuracy with many classifiers : {0} '.format(accuracy)
self.setupObjects() class MainMenu(Menu): def __init__(self, **kwargs): super(MainMenu, self).__init__("MainMenu", header_font=MENU_HEADER_FONT, option_font=MENU_OPTION_FONT, **kwargs) self.header = "Molltris" self.menu = { "Start Game": lambda: self.call(TetrisGame, caption="Mølltris"), "Options": lambda: self.call(OptionsMenu, caption="Mølltris - options"), "Quit": self.quit, } self.setupObjects() class PauseMenu(Menu): def __init__(self, **kwargs): super(PauseMenu, self).__init__("PauseMenu", header_font=MENU_HEADER_FONT, option_font=MENU_OPTION_FONT, **kwargs) self.header = "Pause" self.menu = { "Quit Game": self.quit, "Quit to main menu": lambda: self.quitGame("MainMenu"), "Continue": self.quitGame, } self.setupObjects() if __name__ == '__main__': import doctest tetrominos = Load.loadTetrominos() keymap = Load.loadKeymaps() doctest.testmod() MainMenu(caption="Mølltris").run()
def previewScore(self, seq, row, reference): ## Don't do anything if the user clicks on the header. if not seq: return blocks = Load.loadSnapshot(reference["seq"]) self.call(Preview, blocks, **reference)