首先,这是我的代码:

"""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 是我的列表的转置。但是,我似乎收到了错误:



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

最佳答案

查看代码中变量的类型和形状
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 的每一行进行矢量化操作,而不是对整个操作进行矢量化操作?

关于python - 试图计算 softmax 值,得到 AttributeError : 'list' object has no attribute 'T' ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35703963/

10-13 09:43