首页 > 试题广场 >

Log Softmax函数的实现

[编程题]Log Softmax函数的实现
  • 热度指数:939 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
实现log-softmax函数。log-softmax是softmax函数的对数形式,在深度学习中常用于提高数值计算的稳定性。
需要在运算之前减去最大值保证数值稳定性。

输入描述:
输入一个列表,列表中的元素为浮点数。


输出描述:
输出一个numpy数组,代表log-softmax的结果。
示例1

输入

[1.0, 2.0, 3.0]

输出

[-2.40760596 -1.40760596 -0.40760596]

备注:
1.对应的输入、输出已给出,您只用实现核心功能函数即可。
2.支持numpy、scipy、pandas、scikit-learn库。
有没有大佬教我一下我哪里写错了
import numpy as np

def log_softmax(scores: list) -> np.ndarray:
    a_max=np.max(scores)
    #logsoftmax (a)=a-a_max-log(sum (exp(ai-a_max)))
    return [round(x-a_max-np.log(np.sum(np.exp(scores-a_max))),8) for x in scores]

if __name__ == "__main__":
    scores = eval(input())
    print(log_softmax(scores))

这个结果难道不一样吗
发表于 2026-03-29 16:54:30 回复(0)