softmax函数python实现,,import num
softmax函数python实现,,import num
import numpy as npdef softmax(x): """ 对输入x的每一行计算softmax。 该函数对于输入是向量(将向量视为单独的行)或者矩阵(M x N)均适用。 代码利用softmax函数的性质: softmax(x) = softmax(x + c) 参数: x -- 一个N维向量,或者M x N维numpy矩阵. 返回值: x -- 在函数内部处理后的x """ orig_shape = x.shape # 根据输入类型是矩阵还是向量分别计算softmax if len(x.shape) > 1: # 矩阵 tmp = np.max(x,axis=1) # 得到每行的最大值,用于缩放每行的元素,避免溢出。 shape为(x.shape[0],) x -= tmp.reshape((x.shape[0],1)) # 利用性质缩放元素 x = np.exp(x) # 计算所有值的指数 tmp = np.sum(x, axis = 1) # 每行求和 x /= tmp.reshape((x.shape[0], 1)) # 求softmax else: # 向量 tmp = np.max(x) # 得到最大值 x -= tmp # 利用最大值缩放数据 x = np.exp(x) # 对所有元素求指数 tmp = np.sum(x) # 求元素和 x /= tmp # 求somftmax return xx = np.array([[1,2,3],[4,7,6]])print(softmax(x))
softmax函数python实现
相关内容
- Python - 函数属性方法装饰器(二),,1.给类绑定属性值
- Python可视化Matplotlib-K线图,,引入类库import
- python:递归算法求和1-100,,#递归算法求和1-1
- Python_案例_斐波那契数,,方法一:1 #!/u
- Python网络爬虫(上),,Python网络爬虫
- python3相对于python2有哪些改进呢?,,一、python3的
- python 9*9 乘法表,,row = 1whi
- python保存字典和读取字典pickle,,import pic
- python"TypeError: 'NoneType' object is not i
- 刷题记录:[SUCTF 2019]Pythonginx,, 目录
评论关闭