【问题标题】:Trying to compute softmax values, getting AttributeError: 'list' object has no attribute 'T'试图计算 softmax 值,得到 AttributeError: 'list' object has no attribute 'T'
【发布时间】:2016-06-12 18:03:39
【问题描述】:

首先,这是我的代码:

"""Softmax."""

scores = [3.0, 1.0, 0.2]

import numpy as np

def softmax(x):
    """Compute softmax values for each sets of scores in x."""
    num = np.exp(x)
    score_len = len(x)
    y = [0] * score_len
    for index in range(1,score_len):
        y[index] = (num[index])/(sum(num))
    return y

print(softmax(scores))

# Plot softmax curves
import matplotlib.pyplot as plt
x = np.arange(-2.0, 6.0, 0.1)
scores = np.vstack([x, np.ones_like(x), 0.2 * np.ones_like(x)])

plt.plot(x, softmax(scores).T, linewidth=2)
plt.show()

现在看this 问题,我可以看出 T 是我列表的转置。但是,我似乎得到了错误:

AttributeError: 'list' 对象没有属性 'T'

我不明白这里发生了什么。我对整个情况的理解是错误的吗?我正在尝试通过谷歌深度学习课程,我认为我可以通过实现程序来使用 Python,但我可能错了。我目前知道很多其他语言,如 C 和 Java,但新语法总是让我感到困惑。

【问题讨论】:

  • 你有一个普通的 Python list 对象,而不是 numpy.ndarraynumpy.matrix。后者可能支持 .T 属性,但 Python 列表不支持。
  • @MartijnPieters stackoverflow.com/questions/1514553/… 列表不与 Python 中的数组相同吗?
  • 不,他们不是。这个问题在这方面非常令人困惑。
  • 无论如何,如果有疑问,look at the documentation,您会看到没有记录在案的 .T 属性。
  • 我对numpy的工作其实并不多,我不知道它是否准确。我所做的只是快速浏览一下文档以确认 Numpy 的对象具有 .T 属性。

标签: python list numpy attributes softmax


【解决方案1】:

如 cmets 中所述,softmax(scores) 的输出必须是一个数组,因为列表没有 .T 属性。因此,如果我们用下面的代码替换问题中的相关位,我们可以再次访问.T 属性。

num = np.exp(x)
score_len = len(x)
y = np.array([0]*score_len)

必须注意,我们需要使用np.array,因为非numpy 库通常不能与普通的python 库一起使用。

【讨论】:

    【解决方案2】:

    查看代码中变量的类型和形状

    x 是一维数组; scores 是 2d(3 行):

    In [535]: x.shape
    Out[535]: (80,)
    In [536]: scores.shape
    Out[536]: (3, 80)
    

    softmax 生成一个包含 3 个项目的列表;第一个是数字 0,其余是形状像 x 的数组。

    In [537]: s=softmax(scores)
    In [538]: len(s)
    Out[538]: 3
    In [539]: s[0]
    Out[539]: 0
    In [540]: s[1].shape
    Out[540]: (80,)
    In [541]: s[2].shape
    Out[541]: (80,)
    

    您是否希望softmax 生成与其输入形状相同的数组,在本例中为(3,80)

    num=np.exp(scores)
    res = np.zeros(scores.shape)
    for i in range(1,3):
        res[i,:]= num[i,:]/sum(num)
    

    创建一个可以转置和绘制的二维数组。

    但您不必逐行执行此操作。您真的希望res 的第一行为 0 吗?

    res = np.exp(scores)
    res = res/sum(res)
    res[0,:] = 0    # reset 1st row to 0?
    

    你为什么要对scores 的每一行进行矢量化操作,而不是对整个事物进行矢量化操作?

    【讨论】:

      猜你喜欢
      • 2022-01-10
      • 2020-06-17
      • 1970-01-01
      • 1970-01-01
      • 2022-12-01
      • 2013-09-11
      • 1970-01-01
      • 2014-07-13
      • 1970-01-01
      相关资源
      最近更新 更多