如何向量化多维矩阵的 Softmax 概率 [英] How to vectorize Softmax probability of a multi dimensional matrix

查看:79
本文介绍了如何向量化多维矩阵的 Softmax 概率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为斯坦福大学完成作业 1cs244n 类.问题 1b 强烈推荐对 Softmax 函数进行优化.我设法得到了 N 维向量的 Softmax.我还得到了 MxN 维矩阵的 Softmax,但在列中使用了 for 循环.我有以下代码:

I am trying to go through the assignment 1 for Stanford cs244n class. Problem 1b highly recommend optimization for the Softmax function. I managed to get the Softmax of the N dimensional vector. I also got the Softmax of the MxN dimensional matrix but used a for loop through the columns. I have the following code:

def softmax(x):
    orig_shape = x.shape

    # Matrix
    if len(x.shape) > 1:
        softmax = np.zeros(orig_shape)
        for i,col in enumerate(x):
            softmax[i] = np.exp(col - np.max(col))/np.sum(np.exp(col - np.max(col)))
    # Vector
    else:
        softmax = np.exp(x - np.max(x))/np.sum(np.exp(x - np.max(x)))
    return softmax

我可以实现更优化的矩阵实现吗?

Can I implement a more optimized Matrix implementation?

推荐答案

Using NumPy 广播 相关ufuncs 并且涵盖了通用维数的 ndarrays -

Using NumPy broadcasting on relevant ufuncs and that covers ndarrays of generic number of dimensions -

exp_max = np.exp(x - np.max(x,axis=-1,keepdims=True))
out = exp_max/np.sum(exp_max,axis=-1,keepdims=True)

这篇关于如何向量化多维矩阵的 Softmax 概率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆