當(dāng)前位置:
首頁(yè) >
python 实现 softmax
發(fā)布時(shí)間:2025/4/5
22
豆豆
生活随笔
收集整理的這篇文章主要介紹了
python 实现 softmax
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
# -*-coding: utf-8 -*-import tensorflow as tf
import numpy as npdef softmax(x, axis=1):# 計(jì)算每行的最大值row_max = x.max(axis=axis)# 每行元素都需要減去對(duì)應(yīng)的最大值,否則求exp(x)會(huì)溢出,導(dǎo)致inf情況row_max=row_max.reshape(-1, 1)x = x - row_max# 計(jì)算e的指數(shù)次冪x_exp = np.exp(x)x_sum = np.sum(x_exp, axis=axis, keepdims=True)s = x_exp / x_sumreturn sA = [[1, 1, 5, 3],[0.2, 0.2, 0.5, 0.1]]
A= np.array(A)
axis = 1 # 默認(rèn)計(jì)算最后一維# [1]使用自定義softmax
s1 = softmax(A, axis=axis)
print("s1:{}".format(s1))tf_s2=tf.nn.softmax(A, axis=axis)
總結(jié)
以上是生活随笔為你收集整理的python 实现 softmax的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: attention mechanis
- 下一篇: sql substr切割字符串