本文介绍了numpy数组的Softmax函数按行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将softmax函数应用于numpy数组.但是我没有得到预期的结果.这是我尝试过的代码:

I am trying to apply a softmax function to a numpy array. But I am not getting the desired results. This is the code I have tried:

 import numpy as np
 x = np.array([[1001,1002],[3,4]])
 softmax = np.exp(x - np.max(x))/(np.sum(np.exp(x - np.max(x)))
 print softmax

我认为x - np.max(x)代码没有减去每一行的最大值.必须从x中减去最大值,以防止出现很大的数字.

I think the x - np.max(x) code is not subtracting the max of each row. The max needs to be subtracted from x to prevent very large numbers.

这应该输出

 np.array([
    [0.26894142, 0.73105858],
    [0.26894142, 0.73105858]])

但是我得到了:

np.array([
    [0.26894142, 0.73105858],
    [0, 0]])

推荐答案

使用keepdims关键字是保持减少"操作(例如maxsum)消耗的轴的一种便捷方法: >

A convenient way to keep the axes that are consumed by "reduce" operations such as max or sum is the keepdims keyword:

mx = np.max(x, axis=-1, keepdims=True)
mx
# array([[1002],
#        [   4]])
x - mx
# array([[-1,  0],
#        [-1,  0]])
numerator = np.exp(x - mx)
denominator = np.sum(numerator, axis=-1, keepdims=True)
denominator
# array([[ 1.36787944],
#        [ 1.36787944]])
numerator/denominator
# array([[ 0.26894142,  0.73105858],
         [ 0.26894142,  0.73105858]])

这篇关于numpy数组的Softmax函数按行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 15:05