【问题标题】:tflearn to_categorical: Processing data from pandas.df.values: array of arraystflearn to_categorical:处理来自 pandas.df.values 的数据:数组数组
【发布时间】:2018-01-31 23:03:24
【问题描述】:
labels = np.array([['positive'],['negative'],['negative'],['positive']])
# output from pandas is similar to the above
values = (labels=='positive').astype(np.int_)
to_categorical(values,2)

输出:

array([[ 1.,  1.],
       [ 1.,  1.],
       [ 1.,  1.],
       [ 1.,  1.]])

如果我删除每个元素的内部列表,它似乎工作得很好

labels = np.array([['positive'],['negative'],['negative'],['positive']])
values = (labels=='positive').astype(np.int_)
to_categorical(values.T[0],2)

输出:

array([[ 0.,  1.],
       [ 1.,  0.],
       [ 1.,  0.],
       [ 0.,  1.]])

为什么会这样?我正在关注一些教程,但即使对于数组数组,它​​们似乎也得到了正确的输出。是否最近升级为这种行为方式?

我在py362上使用tflearn (0.3.2)

【问题讨论】:

    标签: python numpy tflearn one-hot-encoding


    【解决方案1】:

    看看to_categorical的源代码:

    def to_categorical(y, nb_classes):
        """ to_categorical.
    
        Convert class vector (integers from 0 to nb_classes)
        to binary class matrix, for use with categorical_crossentropy.
    
        Arguments:
            y: `array`. Class vector to convert.
            nb_classes: `int`. Total number of classes.
    
        """
        y = np.asarray(y, dtype='int32')
        if not nb_classes:
            nb_classes = np.max(y)+1
        Y = np.zeros((len(y), nb_classes))
        Y[np.arange(len(y)),y] = 1.
        return Y
    

    核心部分是高级索引Y[np.arange(len(y)),y] = 1,它将输入向量y作为结果数组中的列索引;所以y 需要是一维数组才能正常工作,对于任意二维数组,您通常会收到广播错误:

    例如:

    to_categorical([[1,2,3],[2,3,4]], 2)
    

    ----------------------------------------------- ---------------------------- IndexError Traceback(最近调用 最后)在() ----> 1 to_categorical([[1,2,3],[2,3,4]], 2)

    c:\anaconda3\envs\tensorflow\lib\site-packages\tflearn\data_utils.py 在 to_categorical(y, nb_classes) 40 nb_classes = np.max(y)+1 41 Y = np.zeros((len(y), nb_classes)) ---> 42 Y[np.arange(len(y)),y] = 1。 43 返回 Y 44

    IndexError:形状不匹配:无法广播索引数组 连同形状 (2,) (2,3)

    这两种方法都可以正常工作:

    to_categorical(values.ravel(), 2)
    array([[ 0.,  1.],
           [ 1.,  0.],
           [ 1.,  0.],
           [ 0.,  1.]])
    
    to_categorical(values.squeeze(), 2)
    array([[ 0.,  1.],
           [ 1.,  0.],
           [ 1.,  0.],
           [ 0.,  1.]])
    
    to_categorical(values[:,0], 2)
    array([[ 0.,  1.],
           [ 1.,  0.],
           [ 1.,  0.],
           [ 0.,  1.]])
    

    【讨论】:

    • 最近更新了吗?看看this的笔记本,我一直卡在那个YIn [12],之前好像执行的很完美,不过现在有人用[xxx ,0]推送了更新
    • 也可能是之前的Y是pandas系列,现在Y改成了单列数据框。只是猜测。
    猜你喜欢
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-10
    • 1970-01-01
    • 2018-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多