python 实现 softmax
生活随笔
收集整理的這篇文章主要介紹了
python 实现 softmax
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
# -*-coding: utf-8 -*-import tensorflow as tf
import numpy as npdef softmax(x, axis=1):# 計算每行的最大值row_max = x.max(axis=axis)# 每行元素都需要減去對應的最大值,否則求exp(x)會溢出,導致inf情況row_max=row_max.reshape(-1, 1)x = x - row_max# 計算e的指數次冪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 # 默認計算最后一維# [1]使用自定義softmax
s1 = softmax(A, axis=axis)
print("s1:{}".format(s1))tf_s2=tf.nn.softmax(A, axis=axis)
總結
以上是生活随笔為你收集整理的python 实现 softmax的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: attention mechanis
- 下一篇: sql substr切割字符串