【问题标题】:I don't know why I keep getting AttributeError: 'tuple' object has no attribute 'size'我不知道为什么我不断收到 AttributeError: 'tuple' object has no attribute 'size'
【发布时间】:2020-10-08 04:34:20
【问题描述】:

我不断收到以下错误:AttributeError: 'tuple' object has no attribute 'size'。还添加了拆分功能

import numpy as np
def split(array):
    N = {}
    uniqe_array = np.unique(array)
    for i in uniqe_array:
        N[i] = np.where(array==i)
    
    return N




def information_gain(x_array, y_array): 
    parent_entropy = entropy(x_array)
    split_dict = split(y_array)
    for val in split_dict.values():
        freq = val.size / x_array.size
        child_entropy = entropy([x_array[i] for i in val])
        parent_entropy -= child_entropy* freq
    return parent_entropy

x = np.array([0, 1, 0, 1, 0, 1])
y = np.array([0, 1, 0, 1, 1, 1]) 
print(round(information_gain(x, y), 4))
x = np.array([0, 0, 1, 1, 2, 2])
y = np.array([0, 1, 0, 1, 1, 1]) 
print(round(information_gain(x, y), 4))

【问题讨论】:

  • 附加回溯
  • 你在哪里定义“熵”?这会导致某人收到 NameError,因为您没有在您提供的代码中定义它
  • 能否提供函数split的代码?
  • 在某个地方,您在实际上是元组的东西上使用 .size 方法..

标签: python


【解决方案1】:

看来split_dict 的值是元组,而不是我认为应该是np.array 的值。我建议看一下 split 正在返回到 split_dict 的函数,因为它可能正在创建元组而不是 np.array 的。

编辑:

基于函数 split 内部的内容,它会将 {0: (array([0, 2], dtype=int64),), 1: (array([1, 3, 4, 5], dtype=int64),)} 返回到 split_dict,因此这些值是包含 numpy.array 和数据类型(在本例中为 int64)作为元素的元组,从而提高了AttributeError.

稍加修改的split 可以满足您的需求:

def split(array):
    N={}
    uniqe_array=np.unique(array)
    for i in uniqe_array:
        N[i]=np.where(array==i)[0]     #Notice change here to take first element 
    return N

有关更多信息,请参阅此答案:What is the purpose of numpy.where returning a tuple?

【讨论】:

  • 您认为我的拆分功能有问题吗? def split(array): N={} uniqe_array=np.unique(array) for i in uniqe_array: N[i]=np.where(array==i) return N
  • 你能把它编辑成一个代码块吗?它没有任何格式哈哈
  • 我添加了它。感谢您尝试帮助我
  • 能否请您发布拆分功能的正确形式?
【解决方案2】:

我认为函数的名称是 len 而不是 size

objects = (1,2,3)
len(objects)

将输出为 3

【讨论】:

  • ValueError: 对象对所需数组来说太深
  • 请分享 entropy() 的代码,以便我们找出问题所在
  • @Mihir 我不确定函数entropy 是错误所在。它无法修改 x_array 以将其类型从 numpy.array 更改为元组
  • 我添加了熵函数
  • @Pouria 你也可以发布你的split 函数吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-04
  • 1970-01-01
  • 1970-01-01
  • 2017-10-26
相关资源
最近更新 更多