当前位置: 首页>>代码示例>>Python>>正文


Python Node.value方法代码示例

本文整理汇总了Python中node.Node.value方法的典型用法代码示例。如果您正苦于以下问题:Python Node.value方法的具体用法?Python Node.value怎么用?Python Node.value使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在node.Node的用法示例。


在下文中一共展示了Node.value方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: p_vaciaList

# 需要导入模块: from node import Node [as 别名]
# 或者: from node.Node import value [as 别名]
def p_vaciaList(p):
  'vaciaList : ID idCheck_Add POINT VACIA LPAR RPAR'
  global pila_Oz
  global temp_cont
  global mem_temp
  global list_temp

  #TEMP de lenght
  largo       = Node()
  nombreL       = "t" + str(temp_cont)
  largo.name  = nombreL
  largo.mem   = mem_temp
  
  aux = pila_Oz.pop()
  largo.value = len(aux.lista)

  #pila_Oz.append(largo)
  list_temp.append(largo)

  temp_cont += 1
  mem_temp  += 1
 
  #Si la lista esta vacia -> PASA
  if not aux.lista:
    temp       = Node()
    tname      = "t" + str(temp_cont)
    temp.name  = tname
    temp.mem   = mem_temp
    temp.value = False
  else:
    temp       = Node()
    tname      = "t" + str(temp_cont)
    temp.name  = tname
    temp.mem   = mem_temp
    temp.value = True

  cte_memoryAssign(0)
  ctememory = cte_list[0]

  createCuad('LEN', aux.mem, None, nombreL)
  createCuad('>', nombreL, ctememory, tname)
  pila_Oz.append(temp)
  list_temp.append(temp)



  temp_cont += 1
  mem_temp  += 1
开发者ID:lalokuyo,项目名称:Cat,代码行数:50,代码来源:rules.py

示例2: ID3_recursive

# 需要导入模块: from node import Node [as 别名]
# 或者: from node.Node import value [as 别名]
def ID3_recursive(data_set, attribute_metadata, numerical_splits_count, depth, attribute_modes_dict):
    if depth == 0 or check_homogenous(data_set) is not None or len(attribute_metadata) == 0:
        return default_node(data_set)    
    else:
        (best_attribute, split_value) = pick_best_attribute(data_set, attribute_metadata, numerical_splits_count)
        if best_attribute == False:
            return default_node(data_set)
        
        node = Node()
        node.decision_attribute = best_attribute
        node.name = attribute_metadata[best_attribute]['name']
        node.is_nominal = attribute_metadata[best_attribute]['is_nominal']
        node.value = attribute_modes_dict[best_attribute]
        updated_numerical_splits_count = copy.deepcopy(numerical_splits_count)
        updated_numerical_splits_count[best_attribute] -= 1

        if node.is_nominal:
            examples = split_on_nominal(data_set, best_attribute)
            for key, values in examples.items():
                node.children[key] = ID3_recursive(values, attribute_metadata, updated_numerical_splits_count, depth - 1, attribute_modes_dict)
        else:
            node.splitting_value = split_value
            (less, greater_or_equal) = split_on_numerical(data_set, best_attribute, split_value)
            node.children[0] = ID3_recursive(less, attribute_metadata, updated_numerical_splits_count, depth - 1, attribute_modes_dict)
            node.children[1] = ID3_recursive(greater_or_equal, attribute_metadata, updated_numerical_splits_count, depth - 1, attribute_modes_dict)
        
        return node
开发者ID:benmel,项目名称:ml_ps2,代码行数:29,代码来源:ID3.py

示例3: p_call

# 需要导入模块: from node import Node [as 别名]
# 或者: from node.Node import value [as 别名]
def p_call(p):
  '''call : ID id_call LPAR par_call RPAR par_call2
            | ID id_call LPAR par_call params RPAR par_call2
           '''
  global pila_Oz
  global cont
  global param_cont
  global temp_cont
  global mem_temp
  global list_temp

  #Check for ")"
  item = pila_Oz.pop()
  if item == ")":
    #Take elements out of stack until no params
    while item != "(":
      item = pila_Oz.pop()
      if item != "(":
        param = "param" + str(param_cont)
        #IF ID
        if isinstance(item, str):
          var = variableFetch(item)
          if isinstance(var, Node):
            op1 = var.mem
        #IF TMP
        elif isinstance(item, Node):
          op1 = item.name
        #IF CTE
        else:
          cte_memoryAssign(item)
          item = cte_list[item]
          op1 = item
        #PARAMS
        cuadruplo_temp = Cuadruplo()
        cuadruplo_temp.set_cont(cont)
        cuadruplo_temp.set_operator("param")
        cuadruplo_temp.set_operand1(op1)
        cuadruplo_temp.set_result(param)
        cuadruplos_list.append(cuadruplo_temp)
        cont += 1
        param_cont += 1

    #POPS name
    subname = pila_Oz.pop()
     #GO SUB
    createCuad("goSub", subname, None, None)
    #TEMPORAL output
    func = functionFetch(subname)
    if func.ret:
      temp = Node()
      tname = subname
      temp.name = tname
      temp.mem  = mem_temp
      temp.value = func.ret.value
      list_temp.append(temp)
      pila_Oz.append(temp)
  
    temp_cont += 1
    mem_temp += 1
    param_cont = 0
开发者ID:lalokuyo,项目名称:Cat,代码行数:62,代码来源:rules.py

示例4: sumNumbersWithLists

# 需要导入模块: from node import Node [as 别名]
# 或者: from node.Node import value [as 别名]
def sumNumbersWithLists(listA, listB):
    if not (listA and listB):
        return 0

    result = Node()
    firstNode = result
    while listA or listB:
        a = listA.value
        b = listB.value
        carry = (a + b) / 10
        sumatory = (a + b) % 10
        result.value = result.value + sumatory
        if carry:
            result.nextNode = Node(carry)
            result = result.nextNode

        if listA.nextNode:
            listA = listA.nextNode
        else:
            listA.value = 0

        if listB.nextNode:
            listB = listB.nextNode
        else:
            listB.value = 0

        result.nextNode = Node()
        result = result.nextNode

    return firstNode
开发者ID:setzer777,项目名称:cracking-the-code-interview,代码行数:32,代码来源:utils_lists.py

示例5: _read_blt

# 需要导入模块: from node import Node [as 别名]
# 或者: from node.Node import value [as 别名]
def _read_blt(path):
    '''Parse a .blt file and return the L{Election}.

    @type  path: string
    @param path: File path.
    @rtype: L{Election}
    @return: Returns the L{Election}.
    '''
    f = open(path)
    # Skip over leading comments
    while True:
        line = f.readline()
        if len(line) == 0:
            raise Exception('Invalid blt')
        if len(line) and line[0] != '#':
            break

    # Get the number of candidates and seats
    num_candidates, seats = [int(x) for x in line.split()]
    root = Node()
    ranks = 0
    # Make sure the root has a child for every candidate
    for c in xrange(1, num_candidates+1):
        root.get_child(c)
    num_ballots = 0
    while True:
        line = f.readline()
        m = re.match(r'(\(.*?\) )?1 ([-=0-9 ]*)0', line)
        if not m:
            break
        num_ballots += 1
        choices = m.group(2).split()
        ranks = max(ranks, len(choices))
        seen = set()
        curr = root
        for c in choices:
            if c == '-':
                continue
            if '=' in c:
                break
            c = int(c)
            if c not in seen:
                seen.add(c)
                curr = curr.get_child(c)
                curr.value += 1

    if line != '0\n':
        raise Exception( 'Expected 0 after ballots "%s"' % line )

    names = dict()
    for c in xrange(1, num_candidates+1):
        names[c] = f.readline()[1:-2]
    description = f.readline()[1:-2]
    f.close()
    root.value = num_ballots
    return Election(names=names, profile=root, ranks=ranks, seats=seats, description=description)
开发者ID:stevecheckoway,项目名称:elections-code,代码行数:58,代码来源:blt.py

示例6: copy_node

# 需要导入模块: from node import Node [as 别名]
# 或者: from node.Node import value [as 别名]
def copy_node(node):
    new_node = Node()
    new_node.label = node.label
    new_node.decision_attribute = node.decision_attribute
    new_node.is_nominal = node.is_nominal
    new_node.value = node.value
    new_node.splitting_value = node.splitting_value

    if node.is_nominal:
        new_node.children = {}
        for key in node.children:
            new_node.children[key] = copy_node(node.children[key])
    else:
        new_node.children = []
        for i in range(len(node.children)):
            new_node.children.append(copy_node(node.children[i]))
    new_node.name = node.name

    return new_node
开发者ID:obiorahm,项目名称:PS2code,代码行数:21,代码来源:pruning.py

示例7: putItem

# 需要导入模块: from node import Node [as 别名]
# 或者: from node.Node import value [as 别名]
    def putItem(self, node, key, value, index):
        c = key[index]

        if node == None:
            node = Node(c)

        print("Key is %s" % key)
        print("Value is %s" % value)
        print("Index is %s" % index)

        if c < node.character:
            node.leftChild = self.putItem(node.leftChild, key, value, index)
        elif c > node.character:
            node.rightChild = self.putItem(node.rightChild, key, value, index)
        elif index < len(key)-1:
            node.middleNode = self.putItem(node.middleNode, key, value, index+1)
        else:
            node.value = value

        return node
开发者ID:bjorncooley,项目名称:algorithms-python,代码行数:22,代码来源:tst.py

示例8: main

# 需要导入模块: from node import Node [as 别名]
# 或者: from node.Node import value [as 别名]
def main(args):
    print "Parse Tree..."
    if ( len( args ) < 2 ):
        print "Usage ./parse_tree.py 'List of arguments in string'"
        sys.exit(-1) 

    print "Arguments:[ " + args[1] + " ]"
    tokens = args[1].split()

    z = Node()
    z.left  = z
    z.right = z

    stack = Stack()
    stack.print_stack()

    root = None

    for token in tokens:
        print token 
        x = Node()
        x.value = token 

        # If the token is an operator. Pop and set the right link 
        # then pop and set the left link then push the token on the stack.
        # Otherwise, push the token on to the stack.
        if token == '+' or token == '*':
            x.right = stack.pop()
            print "Poping " + x.right.value + " from the stack and set to right link of " + token 
            x.left  = stack.pop()
            print "Poping " + x.left.value + " from the stack and set to left link of " + token 
        print "Pushing " + str( x.value ) + " to the stack"
        stack.push( x )
        print "stack after the push..."
        stack.print_stack()
        root = x

    stack.print_stack()

    traverse( root );
开发者ID:Ross-Marshall,项目名称:Algorithms-Robert-Sedgewick,代码行数:42,代码来源:parse_tree.py

示例9: ID3

# 需要导入模块: from node import Node [as 别名]
# 或者: from node.Node import value [as 别名]
def ID3(data_set, attribute_metadata, numerical_splits_count, depth):
    '''
    See Textbook for algorithm.
    Make sure to handle unknown values, some suggested approaches were
    given in lecture.
    ========================================================================================================
    Input:  A data_set, attribute_metadata, maximum number of splits to consider for numerical attributes,
	maximum depth to search to (depth = 0 indicates that this node should output a label)
    ========================================================================================================
    Output: The node representing the decision tree learned over the given data set
    ========================================================================================================
    '''
    # Your code here

    # decision tree to be returned
    node = Node()

    # base case
    theta = 0.0 # threshold of entropy
    if not data_set:
        node.label = '?'
        return node
    elif depth == 0:
        node.label = mode(data_set)
        return node
    elif check_homogenous(data_set):
        node.label = data_set[0][0]
        return node
    # no attributes to split
    elif numerical_splits_count[1:] == [0] * (len(numerical_splits_count) - 1):
        node.label = mode(data_set)
        return node
    elif entropy(data_set) == theta:
        node.label = mode(data_set)
        return node

    # split on best attribute
    splitting_attr, splitting_value = pick_best_attribute(data_set, attribute_metadata, numerical_splits_count)

    # avoid pass by reference error
    numerical_splits_count = list(numerical_splits_count)
    numerical_splits_count[splitting_attr] -= 1

    # describe the node
    node.decision_attribute = splitting_attr
    node.is_nominal = attribute_metadata[splitting_attr]['is_nominal']
    node.splitting_value = splitting_value
    node.name = attribute_metadata[splitting_attr]['name']
    node.value = mode(data_set) # value store mode of non-leaf node

    # if is nominal
    if node.is_nominal:
        # put data in data_set into different branches
        branches = {}
        for data in data_set:
            if data[splitting_attr] not in branches:
                branches[data[splitting_attr]] = []
            branches[data[splitting_attr]].append(data)
        for attr, sub_data_set in branches.items():
            node.children[attr] = ID3(sub_data_set, attribute_metadata, numerical_splits_count, depth - 1)
    # else is numeric
    else:
        left_sub_data_set = []
        right_sub_data_set = []
        for data in data_set:
            if data[splitting_attr] < splitting_value:
                left_sub_data_set.append(data)
            else:
                right_sub_data_set.append(data)
        node.children = []
        node.children.append(ID3(left_sub_data_set, attribute_metadata, numerical_splits_count, depth - 1))
        if node.children[0].label == '?':
            node.children[0].label = mode(data_set)
        node.children.append(ID3(right_sub_data_set, attribute_metadata, numerical_splits_count, depth - 1))
        if node.children[1].label == '?':
            node.children[1].label = mode(data_set)

    # return the generated tree
    return node
开发者ID:SHvsMK,项目名称:Decision_Tree,代码行数:81,代码来源:ID3.py

示例10: p_termino

# 需要导入模块: from node import Node [as 别名]
# 或者: from node.Node import value [as 别名]
def p_termino(p):
  '''termino : factor
              | factor MULTIPLY op_val termino 
              | factor DIVIDE op_val termino
              '''
  global cont
  global pila_Operador
  global pila_temp
  global temp_cont
  global mem_cte
  global mem_temp
  global cte_list

  pos_ops = ['*', '/']

  if pila_Operador and pila_Operador[-1] in pos_ops: 

   # print pila_Oz, "checa", pila_Operador
    #print pila_Oz, "poz"
    operator = pila_Operador.pop()
    operand2 = pila_Oz.pop() #4
    operand1 = pila_Oz.pop() #3
    op1_name = ""
    op2_name = ""

    #****** VALUES *****
    #IF CTE - MEMORY DIRECTIONS
    if isinstance(operand2, Node) == False and verify(operand2) != "string":
      op2_name = cte_list[operand2]  #80808
    if isinstance(operand1, Node) == False and verify(operand1) != "string":
      op1_name = cte_list[operand1]

    #IF ID
    if verify(operand1) == "string":
      varx = variableFetch(operand1)
      operand1 = varx.value
      op1_name = varx.mem
    if verify(operand2) == "string":
      vary = variableFetch(operand2)
      operand2 = vary.value
      op2_name = vary.mem

    #IF TEMPORAL
    if isinstance(operand1, Node):
      op1_name = operand1.name
      operand1 = operand1.value
    if isinstance(operand2, Node):
      op2_name = operand2.name
      operand2 = operand2.value

    term2 = verify(operand2) #int, float, str, bool
    term1 = verify(operand1)

    #print term1, term2, "CURE"
    if semantic_cube[term1][term2][operator] != 'error':
      temp      = Node()
      tname     = "t" + str(temp_cont)
      temp.name = tname
      temp.mem  = mem_temp
      
      if operator == "*":
        total = operand1 * operand2
        cte_memoryAssign(total)
        temp.value = total
        
        #SET CUADRUPLE -op, tmp, tmp, tmp
        createCuad(operator, op1_name, op2_name, tname)
        pila_Oz.append(temp)
        list_temp.append(temp)

        temp_cont += 1
        mem_temp  += 1
        p[0] = p[1]

      if operator == "/":
        total = operand1 / operand2
        cte_memoryAssign(total)
        temp.value = total

        #SET CUADRUPLE -op, tmp, tmp, tmp
        createCuad(operator, op1_name, op2_name, tname)
        pila_Oz.append(temp)
        list_temp.append(temp)

        temp_cont += 1
        mem_temp  += 1
        p[0] = p[1]
    else:
      print "Semantic Error EXP"
  p[0] = p[1]
开发者ID:lalokuyo,项目名称:Cat,代码行数:92,代码来源:rules.py

示例11: p_exp

# 需要导入模块: from node import Node [as 别名]
# 或者: from node.Node import value [as 别名]
def p_exp(p):
  '''exp : termino
          | termino PLUS op_val exp
          | termino MINUS op_val exp
          '''
  global pila_Operador
  global pila_temp
  global temp_cont
  global mem_cte
  global mem_temp
  global cte_list
  global list_temp
  
  
  pos_ops = ['+', '-']
  if pila_Operador and pila_Operador[-1] in pos_ops: 
    operator = pila_Operador.pop()
    operand2 = pila_Oz.pop() #4
    operand1 = pila_Oz.pop() #3

    op1_name = ""
    op2_name = ""
    #****** VALUES *****
    #IF CTE - MEMORY DIRECTIONS
    if isinstance(operand2, Node) == False and verify(operand2) != "string":
      op2_name = cte_list[operand2]  #80808
    if isinstance(operand1, Node) == False and verify(operand1) != "string":
      op1_name = cte_list[operand1]

      #IF TEMPORAL
    if isinstance(operand1, Node):
      op1_name = operand1.name
      operand1 = operand1.value
    if isinstance(operand2, Node):
      op2_name = operand2.name
      operand2 = operand2.value

    #IF ID
    if verify(operand1) == "string":
      varx = variableFetch(operand1)
      operand1 = varx.value
      op1_name = varx.mem
    if verify(operand2) == "string":
      vary = variableFetch(operand2)
      operand2 = vary.value
      op2_name = vary.mem

    term2 = verify(operand2) #int, float, str, bool
    term1 = verify(operand1)

    if semantic_cube[term1][term2][operator] != 'error':
      temp      = Node()
      tname     = "t" + str(temp_cont)
      temp.name = tname
      temp.mem  = mem_temp

      if operator == "+":
        total = operand1 + operand2
        cte_memoryAssign(total)
        temp.value = total

        #SET CUADRUPLE -op, tmp, tmp, tmp
        createCuad(operator, op1_name, op2_name, tname)
        pila_Oz.append(temp)
        list_temp.append(temp)

        temp_cont += 1
        mem_temp  += 1
        p[0] = p[1]
        
      if operator == "-":
        total = operand1 - operand2
        cte_memoryAssign(total)
        temp.value = total

        #SET CUADRUPLE -op, tmp, tmp, tmp
        createCuad(operator, op1_name, op2_name, tname)
        pila_Oz.append(temp)
        list_temp.append(temp)

        temp_cont += 1
        mem_temp  += 1
        p[0] = p[1]
    else:
      print "Semantic Error EXP", pila_Oz

  p[0] = p[1]
开发者ID:lalokuyo,项目名称:Cat,代码行数:89,代码来源:rules.py

示例12: p_expression

# 需要导入模块: from node import Node [as 别名]
# 或者: from node.Node import value [as 别名]
def p_expression(p):
  '''expression : exp
                | exp COMPARISON op_val expression
                '''
  global pila_Operador
  global pila_temp
  global temp_cont
  global mem_cte
  global mem_temp
  global cte_list
  global list_temp

  pos_ops = ['>', '<', '>=', '<=', '==', '!=','&&', '||']

  if pila_Operador and pila_Operador[-1] in pos_ops: 
    operator = pila_Operador.pop()
    operand2 = pila_Oz.pop() #4
    operand1 = pila_Oz.pop() #3

    op1_name = ""
    op2_name = ""

    #****** VALUES *****
    #IF CTE - MEMORY DIRECTIONS
    if isinstance(operand2, Node) == False and verify(operand2) != "string":
      op2_name = cte_list[operand2]  #80808
    if isinstance(operand1, Node) == False and verify(operand1) != "string":
      op1_name = cte_list[operand1]

    #IF ID
    if verify(operand1) == "string":
      varx = variableFetch(operand1)
      operand1 = varx.value
      op1_name = varx.mem
    if verify(operand2) == "string":
      vary = variableFetch(operand2)
      operand2 = vary.value
      op2_name = vary.mem

    #IF TEMPORAL
    if isinstance(operand1, Node):
      op1_name = operand1.name
      operand1 = operand1.value
    if isinstance(operand2, Node):
      op2_name = operand2.name
      operand2 = operand2.value

    term2 = verify(operand2) #int, float, str, bool
    term1 = verify(operand1)
    #print operand1, operand2, "EXP"
    if semantic_cube[term1][term2][operator] != 'error':
      temp      = Node()
      tname     = "t" + str(temp_cont)
      temp.name = tname
      temp.mem  = mem_temp
      
      if operator == "<":
        total = operand1 < operand2
        cte_memoryAssign(total)
        temp.value = total
        #SET CUADRUPLE -op, tmp, tmp, tmp
        createCuad(operator, op1_name, op2_name, tname)
        pila_Oz.append(temp)
        list_temp.append(temp)

        temp_cont += 1
        mem_temp  += 1
        p[0] = p[1]

      if operator == ">":
        total = operand1 > operand2
        cte_memoryAssign(total)
        temp.value = total

        #SET CUADRUPLE -op, tmp, tmp, tmp
        createCuad(operator, op1_name, op2_name, tname)
        pila_Oz.append(temp)
        list_temp.append(temp)

        temp_cont += 1
        mem_temp  += 1
        p[0] = p[1]

      if operator == "<=":
        total = operand1 <= operand2
        cte_memoryAssign(total)
        temp.value = total

        #SET CUADRUPLE -op, tmp, tmp, tmp
        createCuad(operator, op1_name, op2_name, tname)
        pila_Oz.append(temp)
        list_temp.append(temp)

        temp_cont += 1
        mem_temp  += 1
        p[0] = p[1]

      if operator == ">=":
        total = operand1 >= operand2
        cte_memoryAssign(total)
#.........这里部分代码省略.........
开发者ID:lalokuyo,项目名称:Cat,代码行数:103,代码来源:rules.py

示例13: print

# 需要导入模块: from node import Node [as 别名]
# 或者: from node.Node import value [as 别名]
				node.add_to_new_segment(segment.left);
				return;
			else:
				self.down_to_segment(segment.left,node)
				return;

		if segment.right.in_range(node):
			if segment.right.is_leaf():
				node.add_to_new_segment(segment.right);
				return;
			else:
				self.down_to_segment(segment.right,node);
				return;
		print("down_to_segment.........out of range ");



if __name__ == '__main__':
	segmentTree = SegmentTree(1,10);
	segmentTree.build_tree(segmentTree.root);
	node = Node("gabriel");
	node.value = 6;
	node2 = Node("chen");
	node2.value = 3;
	segmentTree.down_to_segment(segmentTree.root,node);
	segmentTree.down_to_segment(segmentTree.root,node2)
	segmentTree.print_all_tree(segmentTree.root);


		
开发者ID:823126028,项目名称:py_game,代码行数:29,代码来源:segment_tree.py

示例14: ID3_helper

# 需要导入模块: from node import Node [as 别名]
# 或者: from node.Node import value [as 别名]
def ID3_helper(data_set, attribute_metadata, numerical_splits_count, depth):
    '''
    See Textbook for algorithm.
    Make sure to handle unknown values, some suggested approaches were
    given in lecture.
    ========================================================================================================
    Input:  A data_set, attribute_metadata, maximum number of splits to consider for numerical attributes,
	maximum depth to search to (depth = 0 indicates that this node should output a label)
    ========================================================================================================
    Output: The node representing the decision tree learned over the given data set
    ========================================================================================================
    # '''

    leaf = Node()
    threshold =0.1
    if(len(data_set) == 0 or depth == 0 or check_homogenous(data_set) != None or entropy(data_set)<threshold or len(attribute_metadata) == 0):
        #if examples empty return default default(mode)
        #or if all examples have same classification return that classification (mode of the dataset is the same as the homogenous classification)
        #or if depth has reached its limit
        # attributes is empty return mode
        leaf.label = mode(data_set)
        leaf.decision_attribute = None
        leaf.is_nominal = None
        leaf.value = mode(data_set)
        leaf.splitting_value = None
        leaf.name = None
        return leaf
    else:
        best_attribute,splitting_value = pick_best_attribute(data_set,attribute_metadata,numerical_splits_count)
        #tree<- a new decision tree with root best
        leaf.label = None
        leaf.decision_attribute = best_attribute
        leaf.name = attribute_metadata[best_attribute]['name']
        # attribute_metadata.pop(best_attribute)      #remove best attribute from list of attributes
        numerical_splits_count[best_attribute] -= 1 #lower numerical splits of this attribute by 1 

        #case of zero information gain on all possible splitting attributes
        if(best_attribute == False):
            leaf.label = mode(data_set)
            leaf.decision_attribute= None
            leaf.name = None
            leaf.splitting_value = None
            leaf.value = None
            return leaf
        elif(splitting_value == False): #case of nominal attribute
            leaf.is_nominal = True
            examples = split_on_nominal(data_set,best_attribute)
            leaf.splitting_value = splitting_value
            # dictionary (key=attribute value, value=node)
            dictionary = {}
            for value, data in examples.iteritems():
                dictionary[value]= ID3_helper(data,attribute_metadata,numerical_splits_count,depth-1)
            leaf.children = dictionary
            return leaf
            # recursive call to ID3
        else: #case of numeric
            examples = split_on_numerical(data_set,best_attribute,splitting_value)
            leaf.is_nominal = False
            leaf.splitting_value=splitting_value
            #list of 2 nodes
            leaf.children = [
            ID3_helper(examples[0],attribute_metadata,numerical_splits_count,depth-1),
            ID3_helper(examples[1],attribute_metadata,numerical_splits_count,depth-1)
            ]
            return leaf
    return leaf
开发者ID:rromo12,项目名称:EECS349_DecisionTree,代码行数:68,代码来源:ID3.py

示例15: ID3

# 需要导入模块: from node import Node [as 别名]
# 或者: from node.Node import value [as 别名]
def ID3(data_set, attribute_metadata, numerical_splits_count, depth):
    '''
    See Textbook for algorithm.
    Make sure to handle unknown values, some suggested approaches were
    given in lecture.
    ========================================================================================================
    Input:  A data_set, attribute_metadata, maximum number of splits to consider for numerical attributes,
    maximum depth to search to (depth = 0 indicates that this node should output a label)
    ========================================================================================================
    Output: The node representing the decision tree learned over the given data set
    ========================================================================================================

    '''
    if not data_set:
        return Node()
    elif check_homogenous(data_set) != None:
        n = Node()
        n.label = check_homogenous(data_set)
        return n
    elif not attribute_metadata:
        n = Node()
        n.label = mode(data_set)
        return n
    elif depth == 0:
        n = Node()
        n.label = mode(data_set)
        return n
    else:
        best, split_value = pick_best_attribute(data_set, attribute_metadata, numerical_splits_count)
        #Find mode of best attribute column
        best_data = []
        for sublist in data_set:
            if sublist[best] != None:
                best_data.append(sublist[best])
        best_mode = max(set(best_data), key=best_data.count)
        #Replace missing values of best attribute column with mode
        data_copy = copy.deepcopy(data_set)
        for row in data_copy:
            if row[best] == None:
                row[best] = best_mode
        if attribute_metadata[best]['is_nominal'] == False:
            numerical_splits_count[best] -= 1
        if best == False:
            n = Node()
            n.label = mode(data_set)
            return n
        tree = Node() #the root 
        tree.is_nominal = attribute_metadata[best]['is_nominal']
        tree.decision_attribute = best
        tree.splitting_value = split_value
        tree.name = attribute_metadata[best]['name']
        tree.value = best_mode
        data_sub = []
        #if a nominal attribute
        if attribute_metadata[best]['is_nominal'] == True:
            best_attributes_dict = split_on_nominal(data_copy, best)
            for v in best_attributes_dict:
                subtree = ID3(best_attributes_dict[v], attribute_metadata, numerical_splits_count, depth - 1)
                tree.children[v] = subtree #adding branch to the tree
        #if numerical attribute
        else:
            splits = split_on_numerical(data_copy, best, split_value)
            for v in splits:
                subtree = ID3(v, attribute_metadata, numerical_splits_count, depth - 1)
                tree.children[splits.index(v)] = subtree #adding branch to the tree
        return tree
开发者ID:olivergoodman,项目名称:idthree,代码行数:68,代码来源:ID3.py


注:本文中的node.Node.value方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。