3

首先,这是我的代码:

"""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()

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

AttributeError:“列表”对象没有属性“T”

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

4

2 回答 2

4

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

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

必须注意的是,我们需要使用np.arrayas 非numpy库通常不会与普通python库一起使用。

于 2016-02-29T16:19:09.780 回答
1

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

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生成与其输入形状相同的数组,在本例中为 a (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,而不是对整个事物进行向量化操作?

于 2016-02-29T17:41:08.260 回答