日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python实现softmax函数

發布時間:2024/4/15 python 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python实现softmax函数 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

?Python實現softmax函數?:

PS:為了避免求exp(x)出現溢出的情況,一般需要減去最大值。

# -*-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))#[2]使用TF的softmax with tf.Session() as sess:tf_s2=tf.nn.softmax(A, axis=axis)s2=sess.run(tf_s2)print("s2:{}".format(s2))

C++實現Softmax函數

template<typename _Tp> int softmax(const _Tp* src, _Tp* dst, int length) { // double max = 0.0; // double sum = 0.0; // // for (int i = 0; i<k; i++) if (max < x[i]) max = x[i]; // for (int i = 0; i<k; i++) { // x[i] = exp(x[i] - max); // sum += x[i]; // } // for (int i = 0; i<k; i++) x[i] /= sum;//為了避免溢出,需要減去最大值const _Tp max_value = *std::max_element(src, src + length);_Tp denominator{ 0 };for (int i = 0; i < length; ++i) {dst[i] = std::exp(src[i] - max_value);denominator += dst[i];}for (int i = 0; i < length; ++i) {dst[i] /= denominator;}return 0; } std::vector<float> output_vector; std::vector<float> preds; softmax(output_vector.data(), preds.data(),output_vector.size());

?

總結

以上是生活随笔為你收集整理的Python实现softmax函数的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。