Numpy中输入指数和的对数(以2为底)
要获取输入指数和的对数(以2为底),可以使用Python Numpy中的**numpy.logaddexp()**方法。
计算**log2(2**x1 + 2**x2)**。此函数在机器学习中很有用,当计算出的事件概率可能非常小,以至于超出普通浮点数的范围时。在这种情况下,可以使用计算出的概率的以2为底的对数。此函数允许以这种方式存储的概率相加。
NumPy 提供了全面的数学函数、随机数生成器、线性代数例程、傅里叶变换等。它支持各种硬件和计算平台,并且与分布式、GPU 和稀疏数组库配合良好。
步骤
首先,导入所需的库 -
import numpy as np
以2为底的对数输入 -
one = np.log2(2e-50) two = np.log2(3.2e-50)
显示对数输入 -
print("Value 1...
", one) print("Value 2...
", two)
要获取输入指数和的对数(以2为底),可以使用numpy.logaddexp()方法 -
res = np.logaddexp(one, two) print("
Logarithm of the sum of exponentiations of the inputs in base 2...
",res)
示例
import numpy as np # Calculates log2(2**x1 + 2**x2). # This function is useful in machine learning when the calculated probabilities of events may be so small # as to exceed the range of normal floating point numbers. # In such cases the base-2 logarithm of the calculated probability can be used instead. # This function allows adding probabilities stored in such a fashion. # Log2 input one = np.log2(2e-50) two = np.log2(3.2e-50) # Display the log input print("Value 1...
", one) print("Value 2...
", two) # To get the Logarithm of the sum of exponentiations of the inputs in base 2, use the numpy.logaddexp() method in Python Numpy res = np.logaddexp(one, two) print("
Logarithm of the sum of exponentiations of the inputs in base 2...
",res)
输出
Value 1... -165.09640474436813 Value 2... -164.41833283925547 Logarithm of the sum of exponentiations of the inputs in base 2... -164.00781734564688
广告