python deeplearning softmax with numpy

我使用numpy实现了softmax函数。如您在代码中所见,我们有一个矩阵,我们想要计算每行的softmax。例如,第一行的softmax是通过将np.sum(np.exp([1,3,6,-3,1]))除以1,3,5,-3,1来计算的。第二行的softmax是通过计算np.sum(np.exp([5,2,1,4,3]))的softmax来实现的。我应该如何做呢?

def softmax(x):    return np.exp(x)/np.sum(np.exp(x),axis=1)x = np.array([[1,3,6,-3,1],              [5,2,1,4,3]])print(softmax(x))print(f"1:{softmax(x)[0]} sum : {np.sum(softmax(x)[0])}")print(f"2:{softmax(x)[1]} sum : {np.sum(softmax(x)[1])}")

ValueError                                Traceback (most recent call last)<ipython-input-261-eb8c9feae03f> in <module>      5       6 ----> 7 print(softmax(x))      8 print(f"1:{softmax(x)[0]} sum : {np.sum(softmax(x)[0])}")      9 print(f"2:{softmax(x)[1]} sum : {np.sum(softmax(x)[1])}")<ipython-input-261-eb8c9feae03f> in softmax(x)      1 def softmax(x):----> 2     return np.exp(x)/np.sum(np.exp(x),axis=1)      3 x = np.array([[1,3,6,-3,1],      4               [5,2,1,4,3]])      5 ValueError: operands could not be broadcast together with shapes (2,5) (2,) >

回答:

这里的问题是sum(exp(x), axis=1)返回一个一维的numpy数组。将其更改为sum(esp(x), axis=1, keepdims=True)可以避免numpy自动丢弃一个维度。

def softmax(x):    return np.exp(x)/np.sum(np.exp(x),axis=1, keepdims=True)x = np.array([[1,3,6,-3,1],              [5,2,1,4,3]])print(softmax(x))print(f"1:{softmax(x)[0]} sum : {np.sum(softmax(x)[0])}")print(f"2:{softmax(x)[1]} sum : {np.sum(softmax(x)[1])}")

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注