コード例 #1
0
 def __init__(self, manager):
     self.man = manager
     interface.MyFrame.__init__(self, None, -1, "")
     adon_window.AdonWindow.__init__(self, window_id='wnd_localdb', window_caption='')
     self.filename = localdb.db.filename
     self.root_dir = '/db'
     tree.buildTree(self, self.root_dir)
コード例 #2
0
ファイル: kcross.py プロジェクト: keithxm23/kSoccer
def adaboost(train, test, headers, fullTestData):
    ylabels = ['H', 'A', 'D']#Make predictions for each of the possible labels
    results = []
    for y in ylabels:
#        print "Training for", y
        rootNode = Node(train)#Initialize first decision stump
        treeRootNode = buildTree(rootNode, y, headers)
        results.append(predict(test, rootNode.splits, y))
    
    print "Now making predictions"    
    prediction = []
    for r in xrange(0,len(results[0])):
        temp = [zy for zy in column(results, r)]
        #Take the label with corresponding max value of alpha as final prediction
        prediction.append(ylabels[temp.index(max(temp))])
        
    print "Now checking predictions"
    corr = 0
    print "Home\tAway\tPrediction\tActual\tBookie"
    file = open("resultdata.csv", 'a')
    writer = csv.writer(file, quoting=csv.QUOTE_ALL)
    for p in xrange(0,len(prediction)):
        print '\a'
        writer.writerow([column(fullTestData,-2)[p], column(fullTestData,-1)[p], prediction[p], column(test,-2)[p], column(fullTestData,-4)[p]]) 
        print [column(fullTestData,-2)[p], column(fullTestData,-1)[p], prediction[p], column(test,-2)[p], column(fullTestData,-4)[p]]
        if prediction[p] == column(test,-2)[p]:
            corr+=1
    
    file.close()
    try:
        print str(float(corr)*100/len(prediction)), len(prediction)
    except ZeroDivisionError:
        print 0, len(prediction)
    print "done"
コード例 #3
0
def example_theory():
    variables = createVariables(givenBoardCondition, k)

    #overall variables for overall node types and winning condition
    Wh = Var("Wh")
    Wo = Var("Wo")
    Sh = Var("Sh")
    Br = Var("Br")
    W = Var("W")

    #create variable arrays
    wood, wheat, sheep, brick = createVariableLists(variables)
    tree = buildTree(variables, createImplicationList(givenBoardCondition, k))
    rowVariables = variablesToRows(variables)

    E = Encoding()
    #Making Constraints based on board condition
    E = createBoardConstraints(givenBoardCondition, variables, E, k)
    #Adding constraint for winning condition
    E.add_constraint(W.negate() | (Wh & Wo & Sh & Br))
    #Setting W to always true so that the solver tries to find a winning model
    E.add_constraint(W)

    E = setOverallVariablesTrueOrFalse(Wh, Wo, Br, Sh, variables, wood, wheat,
                                       sheep, brick, E, S)
    E = leaf_constraints(
        findLeaves(
            tree,
            findAllParents(tree, createImplicationList(givenBoardCondition,
                                                       k))), E, variables)
    E = implementRequiredNodes(S, E, Wo, Wh, Sh, Br)
    E = rowVariablesToConstraints(rowVariables, E)
    #print(findLeaves(tree,findAllParents(tree,createImplicationList(givenBoardCondition,k))))
    print(E.constraints)
    return E
コード例 #4
0
    def getMove(self):
        assert self.game is not None, "MINIMAX ERROR: No game has been initialized!"
        assert (self.player == "RED") or (self.player == "BLUE"), \
            "MINIMAX ERROR: Player must be 'RED' or 'BLUE'!"

        self.expandedNodes = 0

        # Create a root node and build the search tree to decide the next move
        #root = tree.Node(self.game, self.player, 0, "MAX", None, None)
        # root = tree.Node(self.game, self.player, 0, "MAX", None)
        root = tree.Node(self.game, self.player, 3 - self.treeDepth, "MAX",
                         None)
        tree.buildTree(self, root)
        optimalMove = root.childChoice.prevMove
        assert optimalMove is not None, "MINIMAX ERROR: No move can be made!"

        return optimalMove
コード例 #5
0
def decompress(input_bytes, byte_frequencies):
    _, tree = buildTree(byte_frequencies)
    input_bits = bin(int.from_bytes(input_bytes, sys.byteorder))[3:]
    output_bytes = b''
    current_node = tree
    for bit in input_bits:
        if bit == LEFT:
            current_node = current_node.left
        else:
            current_node = current_node.right

        if type(current_node) is Leaf:
            output_bytes += current_node.data
            current_node = tree

    return output_bytes
コード例 #6
0
def main(argv):
    """
    
    """   
    import os
    import tree
    import ising_io as io
        
    if len(sys.argv) !=2 :
        raise ValueError("The script takes exactly 1 arguments, {} are given. Stopping...".
            format(str(len(argv))+'\n'))
    
    params_fn = sys.argv[1]
    params_fn = '/home/evgeny/Documents/personal/D-Wave/Ising_on_trees_ES/data/test01.txt'
    
    logger.info('Getting model input info... \n')
    dataHandler = io.InputReader(params_fn)
    if not dataHandler.valid():
        logger.error('cannot read data file, exiting...')
        return
    testName, nS, nW = \
        dataHandler.testName, dataHandler.nS,dataHandler.nW
    #model_dict = {0:[(0,-1),(1,1)], 1:[(1,-1),(2,1),(3,1)], 2:[(2,-1)]} 
    model_dict = dataHandler.make_dict()
    
    logger.info('Building the tree... \n')
    T = tree.buildTree(model_dict)
    n=T.length()
    #check consistancy of the tree
    if n!=nS:
        logger.error('wrong number of spins, perhaps wrong data file. Exiting...')
        return
        
    S = map(int,np.ones(T.length()))
    T.setS(S) 
    
    logger.info('Find min energy state... \n')
    E = minimize(T,S,T.getE(),n-1,0)
    
    logger.info('Save the results ... \n')
    import ntpath 
    folder, fn = ntpath.split(params_fn)
    fn = str(testName)+'_OUT.txt'
    io.save2file(folder,fn, E, S)
    logger.info(' Done. \n')
コード例 #7
0
def compress(all_bytes):
    byte_frequencies = getFrequencies(all_bytes)
    leaves, _ = buildTree(byte_frequencies)

    symbol_map = {leaf.data: leaf.code for leaf in leaves}

    output_bits = '1'
    for b in all_bytes:
        output_bits = output_bits + symbol_map[b]
    output_bytes = bitstring_to_bytes(output_bits)

    max_count_bytes = ceil(leaves[-1].freq.bit_length() / 8)
    header_bytes = len(leaves).to_bytes(2, sys.byteorder)
    header_bytes += max_count_bytes.to_bytes(8, sys.byteorder)

    for leaf in leaves:
        header_bytes += leaf.data.to_bytes(1, sys.byteorder)
        header_bytes += leaf.freq.to_bytes(max_count_bytes, sys.byteorder)

    return header_bytes+output_bytes
コード例 #8
0
 def On_refresh_clk(self, event=None):
     self.tree_db.DeleteAllItems()
     tree.buildTree(self, self.root_dir)
コード例 #9
0
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 06 14:21:43 2015

@author: Herbert
"""
import tree
import plotTree
import saveTree

fr = open('lenses.txt')
lensesData = [data.strip().split('\t') for data in fr.readlines()]
lensesLabel = ['age', 'prescript', 'astigmatic', 'tearRate']
lensesTree = tree.buildTree(lensesData, lensesLabel)
#print lensesData
print lensesTree

print plotTree.createPlot(lensesTree)