python - softmax python 计算

标签 python machine-learning softmax

我是机器学习新手,正在学习如何在 python 中实现 softmax,我正在关注以下线程

Softmax function - python

我正在做一些分析并判断我们是否有一个数组

batch = np.asarray([[1000,2000,3000,6000],[2000,4000,5000,6000],[1000,2000,3000,6000]])
batch1 = np.asarray([[1,2,2,6000],[2,5,5,3],[3,5,2,1]])

并尝试通过以下方式实现softmax(如上面的链接所述):

1)帕布·托雷分享:

np.exp(z) / np.sum(np.exp(z), axis=1, keepdims=True)

2)在最初的问题中提出:

e_x = np.exp(x - np.max(x))
return e_x / e_x.sum() 

对于这两个我都遇到错误(值超出范围),所以我使用标准化并尝试运行它

x= np.mean(batch1)
y = np.std(batch1)
e_x = np.exp((batch1 - x)/y)
j = e_x / e_x.sum(axis = 0)

所以我想问大家,这是我可以实现的方式吗?如果不是,我该如何处理上述情况?

提前致谢

最佳答案

2)中的方法在数值上相当稳定。最有可能的是,错误是由其他线路产生的。请参阅这些示例(所有工作都没有错误):

def softmax(x):
  e_x = np.exp(x - np.max(x))
  return e_x / e_x.sum()

print softmax(np.array([0, 0, 0, 0]))
print softmax(np.array([1000, 2000, 3000, 6000]))
print softmax(np.array([2000, 4000, 5000, 6000]))
print softmax(np.array([1000, 2000, 3000, 6000]))
print softmax(np.array([2000, 2000, 2001, 2000]))
print softmax(np.array([1, 2, 2, 600000]))
print softmax(np.array([1, 2, 2, 60000000]))
print softmax(np.array([1, 2, 2, -60000000]))

您的替代实现使所有值更接近 0,这会压缩概率。例如:

def alternative_softmax(x):
  mean = np.mean(x)
  std = np.std(x)
  norm = (x - mean) / std
  e_x = np.exp(norm)
  return e_x / e_x.sum(axis=0)


print softmax(np.array([1, 2, 2, 6000]))
print softmax(np.array([2, 5, 5, 3]))
print softmax(np.array([3, 5, 2, 1]))
print

batch = np.asarray([[1, 2, 2, 6000],
                    [2, 5, 5, 3],
                    [3, 5, 2, 1]])
print alternative_softmax(batch)

输出为:

[ 0.  0.  0.  1.]
[ 0.02278457  0.45764028  0.45764028  0.06193488]
[ 0.11245721  0.83095266  0.0413707   0.01521943]

[[ 0.33313225  0.33293125  0.33313217  0.94909178]
 [ 0.33333329  0.33353437  0.33373566  0.02546947]
 [ 0.33353446  0.33353437  0.33313217  0.02543875]]

正如您所看到的,输出非常不同,并且行的总和甚至不等于一。

关于python - softmax python 计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46916446/

相关文章:

python - 插入 DataFrame 列并根据 PySpark 或 Pandas 中的另一列进行排序

python - Pandas:垃圾收集丢弃的列以释放内存

python - 如何使用 Flask 从 MySQL 数据库中检索保存为 BLOB 类型的选定图像

java - 如何在 WEKA 中打印出交叉验证后的预测类

python - Tensorflow softmax 函数返回 one-hot 编码数组

python - CNTK:如何获取C++-API中的类概率?

python - 如何从列表中选择单个表达式

machine-learning - 如何训练RBM等无监督神经网络?

machine-learning - Weka 添加多个元过滤分类器

python-2.7 - 有没有比这更好的方法来实现强化学习的 Softmax Action 选择?