import numpy as np
def sigmoid(x):
## 对正值与负值分别处理,避免溢出
positive_mask = (x >= 0)
negative_mask = ~positive_mask
## 处理正值
result = np.zeros_like(x, dtype=float)
result[positive_mask] = 1 / (1 + np.exp(-x[positive_mask]))
## 处理负值
result[negative_mask] = np.exp(x[negative_mask]) / (1 + np.exp(x[negative_mask]))
return result
z = np.array([[100000, 1, -1, -100000]])
result = sigmoid(z)
print(result)
[[1. 0.73105858 0.26894142 0. ]]
Numpy整型数组向下截断问题
import numpy as np
a = np.array([[1, 2, 3, 4]])
a_int = np.zeros_like(a)
a_float = np.zeros_like(a, dtype=float)
a_sqrt = np.sqrt(a)
a_int[:] = np.sqrt(a)
a_float[:] = np.sqrt(a)
print("原始开平方结果:", a_sqrt)
print("不指定dtype时的结果:", a_int)
print("指定dtype时的结果:", a_float)
原始开平方结果: [[1. 1.41421356 1.73205081 2. ]]
不指定dtype时的结果: [[1 1 1 2]]
指定dtype时的结果: [[1. 1.41421356 1.73205081 2. ]]
np.where()使用误区
import numpy as np
a = np.array([[10000, 1, 2, 3]])
print("表达式1、2都成立:", np.where(a >= 0, 1, 0))
print("表达式2溢出:", np.where(a>=0, 1, np.exp(a)))
表达式1、2都成立: [[1 1 1 1]]
表达式2溢出: [[1. 1. 1. 1.]]
/tmp/ipykernel_33/4034753557.py:6: RuntimeWarning: overflow encountered in exp
print("表达式2溢出:", np.where(a>=0, 1, np.exp(a)))