Esempio n. 1
0
def MainFunction():
    #CRIEA Start!
    if os.path.exists("Output/"):
        if Init.SystemJudge() == 0:
            os.system("rm -r Output")
        else:
            os.system("rmdir /s /q directory")

    NameArr = Pretreatment.FigureInput(1)
    try:
        if NameArr == -1:
            return
    except:
        pass

    #Figure traversal
    for kase in range(0, len(NameArr)):
        img = np.array(Image.open(NameArr[kase]).convert("L"))
        img = Pretreatment.BFSmooth(img)

        [Tobimg, NodeInfo] = Algorithm.Toboggan(img)
        [Upground, Background] = Algorithm.HandSeed(Tobimg, img, Surround)
        Seeds = Upground | Background
        ProbBlock = []
        VarL = 0

        if Method == "Lap":
            NodeInfo, VarL = Functions.SeedFirst(NodeInfo, Seeds)
            LapEqu = Algorithm.Laplacian(NodeInfo, VarL)
            ProbBlock = Functions.LinearEquation(LapEqu,
                                                 len(NodeInfo) - VarL, VarL)
        """
def main_run():
    arguments = [x.lower() for x in sys.argv[1::]]
    if len(arguments) == 0:
        letter = "c"
    else:
        letter = arguments[0]

    print("\nSTARTED...")
    folder = ("E:/out")
    if not os.path.exists(folder):
        os.makedirs(folder)
    inputName = inputFileNames[letter]
    try:
        with open("input/{}.txt".format(inputName), "r") as inputFile:
            photos = Algorithm.generatePhotoList(inputFile)
    except IOError:
        print("!!! {}.txt NOT FOUND IN INPUT FOLDER !!!".format(inputName))
        exit()

    slideshow = Algorithm.generateSlideshow(photos)
    score = sum(x.points for x in slideshow[:-2])
    print("Found solution with score {}.".format(score))
    outputFileName = "{}/{}_out_{}.txt".format(folder, inputName, score)
    with open(outputFileName, "w") as out:
        out.write(str(len(slideshow)) + "\n")
        for slide in slideshow:
            out.write(str(slide) + "\n")
Esempio n. 3
0
    def run(self):
        self.workStatus.emit('正在进行')
        self.workItem.emit('代码相似度检测')
        self.progressBarValue.emit(0)
        self.buttonStop.emit()

        self.result = {}

        if self.choice:
            self.database = ag.get_databasebylist(in_filename_dc)

        if 'a' in self.choice:
            dict_a = ag.get_simhash_similarity(self.database)
            print(dict_a)
            self.result['a'] = dict_a
        self.progressBarValue.emit(25)
        if 'b' in self.choice:
            dict_b = ag.get_TFIDF_cosine(self.database)
            print(dict_b)
            self.result['b'] = dict_b
        self.progressBarValue.emit(50)
        if 'c' in self.choice:
            dict_c = ag.get_SparseMS(self.database)
            print(dict_c)
            self.result['c'] = dict_c
        self.progressBarValue.emit(75)
        if 'd' in self.choice:
            dict_d = ag.get_KgramHashim(5, 4, 3, self.database)
            print(dict_d)
            self.result['d'] = dict_d
        self.progressBarValue.emit(100)
        self.resultDict.emit(self.result)
        self.buttonStart.emit()
        self.workStatus.emit('已完成')
        self.quit()
Esempio n. 4
0
def dataSendLoop(addData_callbackFunc):
    # Setup the signal-slot mechanism.
    mySrc = Communicate()
    mySrc.data_signal.connect(addData_callbackFunc)
    pos = 0
    vel = 0
    TTC = 10
    while (True):
        try:
            pos, vel = bs.get_pos_vel(pos)
            print("D")
            filtered = Kalman.Kalman(pos, vel)
            #pos, vel = filtered[0][0], filtered[1][0]
            vel = -vel

        except:
            print("?")
            continue

        if (vel == 0):
            pass
        else:
            if vel < 0:
                pass
            else:
                TTC = pos / vel
        Algorithm.algo(TTC, myGUI.myFig.Criteria_TTC)
        mySrc.data_signal.emit(pos)  # <- Here you emit a signal!
Esempio n. 5
0
def main():
    tamanhos = [50, 100, 250]
    n_labirintos = 10
    space_result = dict()
    path_result = dict()

    algorithms = [
        "depth first search", "breadth first search", "best first search",
        "a* search", "hill climbing search"
    ]

    for t in tamanhos:
        temp = np.zeros((5 * 2, n_labirintos))
        print("Dimensões:", t)
        for i in range(n_labirintos):
            print("Criando Labirinto...")
            maze = Maze(random=True, height=t, width=t)

            print("Gerando caminhos...")
            path, min_ = Algorithm.depth_first_search(maze)
            temp[0][i] = len(path)
            temp[1][i] = len(min_)

            path, min_ = Algorithm.breadth_first_search(maze)
            temp[2][i] = len(path)
            temp[3][i] = len(min_)

            path, min_ = Algorithm.best_first_search(maze)
            temp[4][i] = len(path)
            temp[5][i] = len(min_)

            path, min_ = Algorithm.a_star_search(maze)
            temp[6][i] = len(path)
            temp[7][i] = len(min_)

            path, min_ = Algorithm.hill_climbing_search(maze)
            temp[8][i] = len(path)
            temp[9][i] = len(min_)

        print("Calculando Médias...")

        i = 0
        for alg in algorithms:
            if alg in space_result:
                space_result[alg].append(np.mean(temp[2 * i]))
                path_result[alg].append(np.mean(temp[2 * i + 1]))
            else:
                space_result[alg] = [np.mean(temp[2 * i])]
                path_result[alg] = [np.mean(temp[2 * i + 1])]

            i += 1

        print()

    plot_result(tamanhos, space_result, 'Comparação por Número de Iterações')
    plot_result(tamanhos, path_result, 'Comparação por Caminho Mínimo')
    print("Numero de Iterações:", space_result)
    print("Caminho Mínimo:", path_result)
    plt.show()
Esempio n. 6
0
 def test_run(self):
     self.instance.run()
     self.instance = Algorithm.UseThread(0)
     self.instance.run()
     self.instance = Algorithm.UseThread(30)
     self.instance.run()
     self.instance = Algorithm.UseThread(1000000)
     self.instance.run()
Esempio n. 7
0
def sum_all(a1,a560,n):
s560 = n/2 # ตัวแปร s560 นำ n/2 คือ 560/2
a = a1+a560 # ตัวแปร a นำ a1+a560 คือ 42 + 42
return {'sum': s560*a} # คืนค่าผลลัพธ์ sum โดยนำ s560 มาคูณกับ a

blah = Algorithm(a1, a560, n, sum_all)
#print(blah.functions) ถ้าต้องการแสดงฟังก์ชันทั้งหมดที่มี
getsum = blah.run()
print(getsum['sum'])
[/python]
Esempio n. 8
0
def find_route(city, state, start, end, percentage, max_min):
    G, G_projected = MakeMapsOpen.get_map(city, state)

    if Algorithm.is_gps_in_map(G, start) and Algorithm.is_gps_in_map(G, end):
        startN = Algorithm.get_closest_node(G, start)
        endN = Algorithm.get_closest_node(G, end)

        return Algorithm.get_from_djikstra(G, startN, endN, percentage,
                                           max_min)
    else:
        print("not in map")
Esempio n. 9
0
def main(gameMap = None): #Done And Commented
	'''THE function that initializes the entire game and runs the game.'''

	########################################### Create Game Map ##############################################
	if gameMap == None:
		iterable = ["y","n"]
		demand = "Do you want to generate the map yourself? (y/n):"
		err = "Your answer was incorectly formated, try again."
		inp = getInput(demand, err, 0, iterable)
		
		if inp == "y":
			demand = "Input map width and length as two integers seperated by a space:"
			err = "Your input will not create a board larger than a single tile."
			width, length = getInput(demand, err, 1)
			gameMap = Map(True, width, length)
			win_exp = Algorithm.howWinnable(gameMap)
			while win_exp[0] is False:
				gameMap = Map(True, width, length)
				win_exp = Algorithm.howWinnable(gameMap)

			
		else:
			demand = "Input map width and length as two integers seperated by a space:"
			err = "Your input will not create a board larger than a single tile."
			width, length = getInput(demand, err, 1)
			gameMap = Map(False, width, length)
			win_exp = Algorithm.howWinnable(gameMap)
			while win_exp[0] is False:
				gameMap = Map(False, width, length)
				win_exp = Algorithm.howWinnable(gameMap)


	########################################## Create Character ##############################################
	char = Character(gameMap)
	if char.tileOn.requirement == "hill":
		print("You start with Climbing Gear.")
		char.gear[0] = "Climbing Gear"
	elif char.tileOn.requirement == "gate":
		print("You start with a Gate Key.")
		char.gear[1] = "Gate Key"

	############################################# Play Game ##################################################
	play(char, gameMap)

	############################################## End Game ##################################################
	if char.tileOn.idx != gameMap.end:
		print("You ran out of turns. You lose.")
	else:
		dump = char.updateChar(math.ceil(1000/(char.charAtk+char.weaponAtk)), Gen.getWeapAsLoot(char), Gen.getReqAsLoot(char))
		print("You find, battle, and destroy the boss!")
		print("You win! You finished with your chararacter being")
		print("level ", char.level, " and ", char.exp, " experience points in.")
		print("The computers best was: level", win_exp[1][0], ", experience", win_exp[1][1])
Esempio n. 10
0
def main():
    file = input("Select the number of factories: 12, 14, 16, 18 or 20")
    file_name = '{0}.txt'.format(file)
    size, distance, flow = read_data(file_name)
    ga = Algorithm.GeneticAlgorithm(size,
                                    distance,
                                    flow,
                                    200,
                                    0.5,
                                    0.2,
                                    50,
                                    selection='tournament',
                                    tour_size=5,
                                    caching=False)

    test_size = 1
    results_array = np.zeros(shape=(test_size, 2), dtype=int)
    for i in range(test_size):
        results = ga.run()
        results_array[i, 0] = results[0][:, 1][-1]
        results_array[i, 1] = results[0][:, 2][-1]

    ga = Algorithm.GeneticAlgorithm(size,
                                    distance,
                                    flow,
                                    50,
                                    0.5,
                                    0.2,
                                    200,
                                    selection='tournament',
                                    tour_size=5,
                                    caching=False)
    results_array1 = np.zeros(shape=(test_size, 2), dtype=int)
    for i in range(test_size):
        results = ga.run()
        results_array1[i, 0] = results[0][:, 1][-1]
        results_array1[i, 1] = results[0][:, 2][-1]

    print(results_array)
    print("average of the best fitness found in 10 runs: ")
    print(np.average(results_array[:, 0], axis=0))
    print("the best fitness found in 10 runs: ")
    print(np.amin(results_array[:, 0], axis=0))
    print("average of the average fitness found in 10 runs: ")
    print(np.average(results_array[:, 1], axis=0))
    print("\n\n")
    print(results_array1)
    print("average of the best fitness found in 10 runs: ")
    print(np.average(results_array1[:, 0], axis=0))
    print("the best fitness found in 10 runs: ")
    print(np.amin(results_array1[:, 0], axis=0))
    print("average of the average fitness found in 10 runs: ")
    print(np.average(results_array1[:, 1], axis=0))
Esempio n. 11
0
def main1():

    #random.seed(datetime.now())
    prob = Problem()
    pop = Population()
    alg = Algorithm(prob, pop)
    alg.run()
    res = alg.population.v[0]

    fitnessOptim = res.fittness(prob)
    individualOptim = res.x
    print('Result: The detectet minimum point is (%3.2f %3.2f) \n with function\'s value %3.2f'% \
          (individualOptim[0],individualOptim[1], fitnessOptim) )
Esempio n. 12
0
File: App.py Progetto: pamhrituc/AI
def main():
    while True:
        prob = Problem()  #create problem
        size = prob.loadData(
            "data01.in")  #load data of problem, return board size
        x = Individ([0] * size)
        pop = Population(x)
        alg = Algorithm(pop)
        alg.readParameters("param.in")
        printMainMenu()
        x = input()
        if x == "1":
            bestX, sample = alg.run()
            print(bestX)
            print(bestX.fitness())
            plt.plot(sample)
            # function to show the plot
            plt.show()
        if x == "2":
            alg.run()
            sd, m = alg.statistics()
            print("Standard deviation " + str(sd))
            print("Mean " + str(m))
        if x == "0":
            return
Esempio n. 13
0
def ThirdTimeIsTheCharm(user_name, measureAccuracy):
    if measureAccuracy == 'True':
        rmse, mae = Algorithm.GetAccuracy()
        res = json.dumps({'rmse': rmse, 'mae': mae})
        print(res)
    else:
        d = Data()
        recs = Algorithm.GetRecommendations(user_name)

        res = []
        for j, k in recs:
            res.append((d.getBusinessName(j), k))

        print(json.dumps(res))
Esempio n. 14
0
def main():
	if len(argv) != 2:
		print("Usage:")
		print("\tpython3 {} (filename)".format(argv[0]))
		exit(0)

	filename = argv[1]

	if not file_exists(filename):
		print("Invalid filename")
		exit(0)

	maze = Maze(filename)

	# DFS
	print("Building DFS...")
	path, min_path = Algorithm.depth_first_search(maze)
	print("DFS solution:", min_path)
	print("DFS travelled space:", path)
	print()
	
	# BFS
	print("Building Breadth First Search...")
	path, min_path = Algorithm.breadth_first_search(maze)
	print("BFS solution:", min_path)
	print("BFS travelled space:", path)
	print()


	# Best Search First
	print("Building Best First Search...")
	path, min_path = Algorithm.best_first_search(maze)
	print("Best-search solution:", min_path)
	print("Best-search travelled space:", path)
	print()
	
	# A*
	print("Building A* Search...")
	path, min_path = Algorithm.a_star_search(maze)
	print("A* solution:", min_path)
	print("A* travelled space:", path)
	print()

	# Hill Climbing*
	print("Building Hill Climbing Search...")
	path, min_path = Algorithm.hill_climbing_search(maze)
	print("Hill Climbing solution:", min_path)
	print("Hill travelled space:", path)
	print()
Esempio n. 15
0
def algorithm_tfidf():
    print "Running TFIDF"
    # Google data
    # parser = GoogleNewsParser.NewsParsers()
    # parser.parse_data_from_tok()

    # Json Google
    tfidf = ExTFIDF.TfIdf()
    # tfidf.fit_data(parser.get_texts())
    tfidf.fit_data(JsonParser.get_texts(os.getcwd() + "\\" + "clusters"))

    print "lennth of tfidf : " + str(len(tfidf.get_data_as_vector()))

    print "Running algorithm with TFIDF"
    Algorithm.algorithm_Kmean(tfidf.get_data_as_vector())
Esempio n. 16
0
def main(): #main function for display and various values of s
    k,m,p = parseone()
    rawdata,rawwholedata = parsetwo()
    
    f = open('sxv146930.txt' ,'w')
    f.write('\n')
    
    for s in range(1,6):
        finaldata, E, sigma = computepermutation(k, m, p, s, rawdata)
        outdata = deconvertdata(finaldata)
        wholedata = Algorithm.dots(rawwholedata,s)
        wholedata.update(outdata)
        f.write('K-NN = ' + str(s))
        f.write(' E = ' + str(E))
        f.write(' SIGMA = ' + str(sigma))
        f.write('\n')
        
        print_matrix = {}
        for thing in wholedata:
            x2, x1, pred = wholedata[thing][0], wholedata[thing][1], wholedata[thing][2]
            if x1 not in print_matrix:
                print_matrix[x1] = {}
            print_matrix[x1][x2] = pred

        for key in sorted(print_matrix.keys()):
            f.write (' '.join([print_matrix[key][i] for i in sorted(print_matrix[key].keys())])+'\n')
        
        f.write('\n')
Esempio n. 17
0
def go_go_excel(path, number_of_runs):
    if number_of_runs < 1:
        print("Bledna liczba uruchomiec algorytmu")
        return
    workbook = xlsxwriter.Workbook(path)
    worksheet = workbook.add_worksheet()
    worksheet.write(0, 0, 'X')
    worksheet.write(0, 1, 'Y')
    worksheet.write(0, 2, 'Odleglosc')
    worksheet.write(0, 3, 'Czas')
    worksheet.write(0, 4, 'N')
    random.seed(None)
    algorithm = Algorithm.Algorithm()
    
    my_data = Data.Data()
    
    for i in range(number_of_runs):
        Generator.generate_for_excel(my_data.list_of_cards, random.randint(1, 200000))
        algorithm.run(my_data.list_of_cards)
        final_x, final_y, final_trip, time = algorithm.return_results()
        worksheet.write(i+1, 0, final_x)
        worksheet.write(i+1, 1, final_y)
        worksheet.write(i+1, 2, final_trip)
        worksheet.write(i+1, 3, time)
        worksheet.write(i+1, 4, len(my_data.list_of_cards))
        
    workbook.close()
    return
Esempio n. 18
0
 def insertAlgorithmData(self, cur):
     try:
         # TODO: should think about separating out sequence accessors
         alDataSeq = AlgorithmDataSequence()
         next_id = alDataSeq.getNextVal(cur)
         
         algorithm = Algorithm.Algorithm()
         algorithmIndex = algorithm.getAlgorithmIndex(cur, self._algorithm_reff)
         
         # get the current timestamp
         timestamp = getTime(cur)
         
         cur.execute("INSERT INTO " + self._table_name + " " +
                     self._insert_order + " " +
                     "VALUES(%s, %s, %s)",
                     (
                         str(next_id),
                         str(timestamp),
                         str(algorithmIndex)
                     )
                     )
         return next_id
         
     except psycopg2.DatabaseError, e:
         print 'Error AlgorithmData: %s' % e    
Esempio n. 19
0
    def realLogin(self, u_id, pwd):
        """
            真实登录

            successful: ptuiCB('0','0','loginUrl','0','登录成功!', 'nickName');
            failed:     
                ptuiCB('3','0','','0','用户名密码不正确', '');
                ptuiCB('4','0','','0','用户名密码不正确', ''); 
                3 不需要验证码登录  用户名或密码不正确
                4 需要验证码登录    验证码正确,用户名或密码不正确
                3,4后续就是校验是否需要验证码 然后重复流程
        """
        print 'STEP 2: Start login'
        encodePwd = Algorithm.encodePwd(u_id, pwd, self.verifyCode)

        x = SESSION.get(Constants.REAL_LOGIN.replace('{u_id}', u_id).replace(
            '{encode_pwd}',
            encodePwd).replace('{app_id}', Constants.APP_ID).replace(
                '{verifycode}',
                self.verifyCode).replace('{pt_verifysession_v1}',
                                         self.pt_verifysession_v1),
                        headers=Constants.REQUEST_HEADER).content

        print x
        # 截取登录成功返回的重定向地址
        x = x[x.find('(') + 1:x.find(')')].replace('\'', '').split(',')
        if x[0] == '0':
            # 此处请求返回登录成功的url会自动重定向到loginsucc.html 会设置cookies[p_skey, p_uin, pt4_token]
            SESSION.get(x[2], headers=Constants.REQUEST_HEADER)
        else:
            self.tryLoginProcess(u_id, pwd)
def evaluate_best_model():
    scores = []

    # Go through all possible parameters and run the algorithm in order to evaluate the best model
    for reduced_categories in reduced_categories_possibilities:
        for text_mode in text_modes:
            for n in possible_n_grams:
                documents = CSVHandler.get_document(text_mode, n, reduced_categories)
                identifier_addition = "text-mode: '{}', {}-grams, reduced-categories: {}".format(text_mode, n, reduced_categories)

                for feature_model in feature_models:
                    for algorithm in algorithms_list:
                        model = algorithm["algorithm"]
                        tfidf_max_features = algorithm["tfidf_max_features"]
                        tfidf_min_df = algorithm["tfidf_min_df"]
                        tfidf_max_df = algorithm["tfidf_max_df"]
                        bow_max_features = algorithm["bow_max_features"]
                        bow_min_df = algorithm["bow_min_df"]
                        bow_max_df = algorithm["bow_max_df"]
                        scores.append(Algorithm.run(documents, model, feature_model, identifier_addition, True, False, tfidf_max_features, tfidf_min_df, tfidf_max_df, bow_max_features, bow_min_df, bow_max_df))

    # Print models sorted by accuracy
    print("\n\n\n\nOverview:")
    scores = sorted(scores, key=lambda s: (-s[1], s[0]))
    for s in scores:
        print(s)

    # Only the best model when considering accuracy, which is not the case for this project!
    print("\nBest model:")
    print(max(scores, key=itemgetter(1)))
Esempio n. 21
0
    def qrLogin(self):
        """
            二维码登录流程
        """
        ptqrtoken = self.getQRCode()
        while True:
            time.sleep(3)

            resp = SESSION.get(Constants.PT_QR_LOGIN.replace(
                '{app_id}', Constants.APP_ID).replace('{ptqrtoken}',
                                                      str(ptqrtoken)),
                               headers=Constants.REQUEST_HEADER).content

            res = re.search(r'ptuiCB(\(.*\))\;', resp).group(1)
            res = eval(res)
            print res

            code = res[0]
            if code == '0':
                # 扫码成功请求回传重定向地址
                url = res[2]
                print url
                os.remove(QR_CODE_IMG_PATH)
                SESSION.get(url, headers=Constants.REQUEST_HEADER)
                g_tk = Algorithm.g_tk(SESSION.cookies['p_skey'])

                AlbumHandler(SESSION,
                             g_tk).start(SESSION.cookies['uin'].lstrip('o'))
            elif code == '65':
                print 'refresh QR-Code'
                os.remove(QR_CODE_IMG_PATH)
                ptqrtoken = self.getQRCode()
            elif code == '67':
                print 'confirm login in mobile!'
 def __init__(self):
     super(self.__class__, self).__init__()
     self.name = "Algorithm selection window:"
     self.if_setprn = 0
     self.if_setdate = 0
     self.progresscomplete = 0
     self.setdefaultpara()
     self.algo1para = {}
     self.algo2para = {}
     self.algo3para = {}
     self.algo4para = {}
     self.algo1para = dict(self.algo1paradefault.items() +
                           self.algo1para.items())
     self.algo2para = dict(self.algo2paradefault.items() +
                           self.algo2para.items())
     self.algo3para = dict(self.algo3paradefault.items() +
                           self.algo3para.items())
     self.algo4para = dict(self.algo4paradefault.items() +
                           self.algo4para.items())
     self.setStyleSheet(
         "QLabel{color:rgb(96,96,96,255);font-size:15px;font-weight:bold;font-family:Microsoft YaHei;}"
         "QMessageBox{background-color:#DEB887;}")
     self.algoSet = Ag.Algorithm('decision tree', self.algo1para)
     self.prnSet = 0
     self.dateSet = 0
     self.initUI()
Esempio n. 23
0
    def handleSigAndCdata(self, u_id):
        """
            处理vsig参数用于获取验证码 返回cdata用于验证码验证
            >>> 
            {
                "vsig":{vsig},
                "ques":"",
                "chlg":{
                    "randstr":{randstr},
                    "M":{M},
                    "ans":{ans}
                }
            }
        """
        print 'STEP 3: Handle sig arg and (randstr, M, ans) for encode cdata arg'
        sigContent = SESSION.get(Constants.GET_CAPTCHA_SIG.replace(
            '{u_id}', u_id).replace('{sess}', self.sess).replace(
                '{cap_cd}', self.cap_cd).replace('{app_id}', Constants.APP_ID),
                                 headers=Constants.REQUEST_HEADER).json()
        print sigContent
        self.vsig = sigContent['vsig']
        randstr = sigContent['chlg']['randstr']
        M = sigContent['chlg']['M']
        ans = sigContent['chlg']['ans']

        return Algorithm.cdata(randstr, ans, M)
def evaluate_best_TFIDF_parameters():
    documents = CSVHandler.get_document("normal", 2, True)
    best_scores = []
    scores = []
    feature_model = "TF IDF"

    tfidf_max_features = [1500, 1000, 700, 2000]
    tfidf_min_df = [5, 2, 6, 9]
    tfidf_max_df = [0.5, 0.6, 0.7, 0.8, 0.9]

    for algo in algorithms_list:
        for mf in tfidf_max_features:
            for min_df in tfidf_min_df:
                for max_df in tfidf_max_df:
                    identifier_addition = "text-mode: 'normal', 2-grams, reduced-categories: True, max_features: {}, min_df: {}, max_df: {}".format(mf, min_df, max_df)
                    algorithm = algo["algorithm"]
                    scores.append(Algorithm.run(documents, algorithm, feature_model, identifier_addition, True, False, mf, min_df, max_df, 0, 0, 0))

        # Print models sorted by accuracy
        print("\n\n\n\nOverview:")
        scores = sorted(scores, key=lambda s: (-s[1], s[0]))
        for s in scores:
            print(s)

        print("\nBest model:")
        print(max(scores, key=itemgetter(1)))
        best_scores.append(max(scores, key=itemgetter(1)))

    print("Best scores:")
    print(best_scores)
 def buttonsetclicked(self):
     self.buttonset.setDisabled(True)
     c = self.Algochooselist.currentItem()
     if c.text() == ("   " + self.algoSet.algorithm):
         print "algorithm not changed"
     else:
         print "algorithm changed"
         self.buttonplot.setDisabled(True)
     if c.text() == "   " + "decision tree":
         print self.algo1para
         self.infoconsole.clear()
         self.algo1 = Ag.Algorithm('decision tree', self.algo1para)
         self.algoSet = self.algo1
         self.infoconsole.addItem("Decision tree algorithm set" + "      " +
                                  str(datetime.datetime.now()))
         self.infoconsole.addItem(str(self.algo1para))
         self.infoconsole.repaint()
     elif c.text() == "   " + "support vector machine":
         print self.algo2para
         self.infoconsole.clear()
         self.algo2 = Ag.Algorithm('support vector machine', self.algo2para)
         self.algoSet = self.algo2
         self.infoconsole.addItem("support vector machine set" + "      " +
                                  str(datetime.datetime.now()))
         self.infoconsole.addItem(str(self.algo2para))
         self.infoconsole.repaint()
     elif c.text() == "   " + "random forest":
         print self.algo3para
         self.infoconsole.clear()
         self.algo3 = Ag.Algorithm('random forest', self.algo3para)
         self.algoSet = self.algo3
         self.infoconsole.addItem("random forest set" + "      " +
                                  str(datetime.datetime.now()))
         self.infoconsole.addItem(str(self.algo3para))
         self.infoconsole.repaint()
     elif c.text() == "   " + "adaboost":
         print self.algo4para
         self.infoconsole.clear()
         self.algo4 = Ag.Algorithm('adaboost', self.algo4para)
         self.algoSet = self.algo4
         self.infoconsole.addItem("adaboost set" + "      " +
                                  str(datetime.datetime.now()))
         self.infoconsole.addItem(str(self.algo4para))
         self.infoconsole.repaint()
     self.infoconsole.addItem("Selected Satellite No = " + str(self.prnSet))
     self.infoconsole.addItem("Selected date = " + str(self.dateSet))
     self.buttonevaluate.setDisabled(False)
Esempio n. 26
0
def main():
    print("GA started!")
    year = "1"
    fitnessCalc = FitnessCalculator()
    algo = Algorithm()
    fitnessCalc.setsolution("1111")
    myPop = Population(3, True, year)
    generation_count = 0
    #myPop.generate_Fitness()
    val = myPop.get_Fittest()
    print("Fittest : ", val)
    generation_count += 1
    print("Generation: ", generation_count, " Fittest: ",
          fitnessCalc.get_fitness(val))
    print("-------Starting generations : ", generation_count,
          " ------------------")
    myPop = algo.evolve_Population(myPop)
Esempio n. 27
0
def prune_lse_states_at_depth(depth):
    pruned_data = []
    if depth == 1:
        for move in move_set_list:
            for move_type in move_type_list:
                current_state = LSE_State(prune_table[0][0][1])
                current_state.apply_move(move, move_type)
                pruned_data.append([Algorithm(convert_move_to_string(move, move_type)), current_state])
    else:
        for pruned_state in prune_table[depth - 1]:
            for move_type in move_type_list:
                move = MoveSet.U if LSE_Solver.get_last_move(pruned_state[0].algorithm)[0] == MoveSet.M else MoveSet.M
                current_state = LSE_State(pruned_state[1])
                current_state.apply_move(move, move_type)
                pruned_data.append(
                    [Algorithm(pruned_state[0].algorithm + " " + convert_move_to_string(move, move_type)), current_state])
    prune_table.append(pruned_data)
Esempio n. 28
0
def computepermutation(k, m, p, s, rawdata, E=0, V=0): #permutation juggling
    newdata = Algorithm.convertdata(rawdata) 
    v = []
    for permutation in p:
        currdata = newdata
        data = order(permutation)
        sets = divide(data, k, m)
        tempdata, error = Algorithm.algorithm(sets, data, s, m, newdata)
        E = E + error 
        v.append(error)
        for entry in newdata:
            currdata[entry][2] = currdata[entry][2] + tempdata[entry][2]
    
    E = E/len(p)
    for errors in v:
        V = V + (E-errors)**2
    V = V/(len(p)-1)
    return currdata, E, V**0.5
Esempio n. 29
0
def run_algorithm(data):
    algorithm = Algorithm.Algorithm()
    algorithm.run(data.list_of_cards)
    final_x, final_y, final_trip, time = algorithm.return_results()
    print(f'Punkt, do ktorego udalo sie zajsc: X = {final_x}, Y = {final_y}.')
    print(f'przebyta odleglosc: {final_trip}.')
    print(f'Czas wykonywania algorytmu: {time}.')
    temp = input("Wcisnij enter, aby wrocic/zakonczyc.")
    return
def decryption():
    global plain_text, error_text, key, key_match  # update globally

    s = MaxIterations.get('1.0',END).strip()
    if not s.isdigit():
        return False
    print('max iterations: ', s)
    plain_text, key, key_match = CB.Start_Algorithm(cipher_text, int(s), normalized_orig_key())
    return True
Esempio n. 31
0
def bootstrap(data):
    num = 500
    for i in range(num):
        index = int(np.random.rand(1) * 178)
        data = np.vstack((data, data[index]))
    y = data[:, 0].reshape((num + 178, 1))
    x = data[:, 1:14]
    aver_array = np.mean(x, axis=0)
    x = x / aver_array
    accuracy = Algorithm.Without_folds(MaxK, x, y)
    accuracy_ = Algorithm.Without_folds(MaxK, datas, labels)
    plt.figure()
    plt.plot(accuracy[1:MaxK + 2], color='r', label='bootstap')
    plt.plot(accuracy_[1:MaxK + 2], color='b', label='original')
    plt.title("Accuracy of bootstrap and original ")
    plt.xlabel("k-value")
    plt.ylabel("accuracy")
    plt.legend(loc='upper right')
Esempio n. 32
0
def Impfolds():
    accuracy = Algorithm.With_folds(MaxK, datas, labels)
    plt.figure()
    plt.plot(accuracy[1:MaxK + 2])
    Str = "Accuracy With 5-fold"
    plt.title(Str)
    plt.xlabel("k-value")
    plt.ylabel("accuracy")
    return accuracy
Esempio n. 33
0
def main():

    data_in = []
    feed_id = []
    print('start reading data')
    #read_json.read_json(config.path_in,data_in,config.stop_word_path,feed_id,config.data_lines)

    #read_json.test_alignment_py('../data/cpp/small.txt','../data/cpp/python_alignment_extraction1.txt','stop_words.utf8',True,True,5,data_in)
    #print('finish reading data')

    #term_id = []
    id_url = []
    #read_liulanqi_data.read_data(config.path_in, data_in, id_url,50)

    read_weishi_data.read_json(config.path_in, data_in, None, feed_id,
                               config.data_lines, None, config.topk)

    if config.mode == 'Training':
        if config.model_name == 'Counter':
            model = Vectorizer.CounterVector(config.model_name)
        elif config.model_name == 'TfIdf':
            model = Vectorizer.TfIdfVector(config.model_name)
            print('finish initilizing model')
        elif config.model_name == 'FeatureHasher':
            model = Vectorizer.FeatureHasherVector(config.model_name,
                                                   config.n_features)

        model.feature_transform(data_in)
        print(len(model.vectorizer.vocabulary_))

        model.serilize_model()

        if config.algo_name == 'KMeans':
            algo_instance = KMeans.KMeansClustering(config.algo_name)
            print('start training model')
            algo_instance.fit(model.feature)
            algo_instance.serilize_model()
            algo_instance.output_cluster_info(data_in, model, feed_id)

    else:
        print('loading vectorizer')
        model = BaseModel.BaseModel(config.model_name)
        model.de_serilize_model()
        print('finish loading vector')

        if config.algo_name == 'KMeans':
            algo_instance = Algorithm.Base_Algorithm(config.algo_name)
            algo_instance.de_serilize_model()
            print('finish desirialization')
            features = model.transform(data_in)

            labels = algo_instance.predict(features)
            print(labels)
            #algo_instance.get_centroids()
            #algo_instance.output_cluster_info(data_in, model, feed_id)
            print('finish all')