import numpy as np
def softmax(x):
row_num = x.shape[0]
col_num = x.shape[1]
for m in row_num:
for n in col_num:
new_x[m,n] = np.exp(x[m,n])/sum(x[:,n])
return new_x
logits = [1.0, 2.0, 3.0]
logits2 = np.array([
[1, 2, 3, 6],
[2, 4, 5, 6],
[3, 8, 7, 6]])
print(softmax(logits1))
print(softmax(logits2))
以上为SOFTMAX函数(它是用来开启logits到概率)的Python:定义SOFTMAX功能
欲获得如下所示的解决方案:
[ 0.09003057 0.24472847 0.66524096]
[
[ 0.09003057 0.00242826 0.01587624 0.33333333]
[ 0.24472847 0.01794253 0.11731043 0.33333333]
[ 0.66524096 0.97962921 0.86681333 0.33333333]
]
然而,错误显示“'int'对象不可迭代”。另外,我希望看到一个更加高效的代码,这个函数的复杂度较低。
感谢您的解决方案。但是当我运行你的代码时,它显示“'list'对象没有属性'形状'” – FortranFun
@FortranFun在我的解决方案中,我没有使用形状,所以我猜你在添加范围后运行你的解决方案。这种情况下的问题是logits是一维向量,因此logits.shape是一个带有一个数字的元组,因此您无法访问logits.shape [1]。 \t 此外,写logits = np.array([1.0,2.0,3.0])(你的logits不是numpy数组,而logits2是,你需要使它成为一个numpy数组,以便它具有shape属性)。 –