使用 (arr.transpose() == arr).all() 的意外对称测试结果
Unexpected symmetric test result using (arr.transpose() == arr).all()
我有
temp = np.power(np.sum(S,1),-0.5)
S_hat = np.diagflat(temp).dot(S).dot(np.diagflat(temp))
S
的对称测试产生 True
但 S_hat
、returns False
。我无法理解这个。
[EDIT] S和数据定义如下:
from math import pi
def make_moons(n):
"""Create a 'two moons' dataset with n feature vectors,
and 2 features per vector."""
assert n%2==0, 'n must be even'
# create upper moon
theta = np.linspace(-pi / 2, pi / 2, n/2)
# create lower moon
x = np.r_[np.sin(theta) - pi / 4, np.sin(theta)]
y = np.r_[np.cos(theta), -np.cos(theta) + .5]
data = np.c_[x, y]
# Add some noise
data = data + 0.03 * np.random.standard_normal(data.shape)
# create labels
labels = np.r_[np.ones((n//2, 1)), -np.ones((n//2, 1))]
labels = labels.ravel().astype(np.int32)
return data,labels
S = np.zeros((100,100));
sig = 0.09;
from scipy.spatial.distance import pdist, squareform, cdist
B = pdist(data);
C = squareform(B);
S = np.exp(-C/sig);
很可能您遇到了舍入错误。尝试使用 numpy.allclose()
:
而不是严格的相等性测试
np.allclose(S_hat.T, S_hat, rtol=1e-7, atol=1e-8)
根据您的特定数据量级调整容差。特别是,对于您的示例数据,似乎 atol
应该设置为 0(您的数据范围从 1 到 1e-14)。
我有
temp = np.power(np.sum(S,1),-0.5)
S_hat = np.diagflat(temp).dot(S).dot(np.diagflat(temp))
S
的对称测试产生 True
但 S_hat
、returns False
。我无法理解这个。
[EDIT] S和数据定义如下:
from math import pi
def make_moons(n):
"""Create a 'two moons' dataset with n feature vectors,
and 2 features per vector."""
assert n%2==0, 'n must be even'
# create upper moon
theta = np.linspace(-pi / 2, pi / 2, n/2)
# create lower moon
x = np.r_[np.sin(theta) - pi / 4, np.sin(theta)]
y = np.r_[np.cos(theta), -np.cos(theta) + .5]
data = np.c_[x, y]
# Add some noise
data = data + 0.03 * np.random.standard_normal(data.shape)
# create labels
labels = np.r_[np.ones((n//2, 1)), -np.ones((n//2, 1))]
labels = labels.ravel().astype(np.int32)
return data,labels
S = np.zeros((100,100));
sig = 0.09;
from scipy.spatial.distance import pdist, squareform, cdist
B = pdist(data);
C = squareform(B);
S = np.exp(-C/sig);
很可能您遇到了舍入错误。尝试使用 numpy.allclose()
:
np.allclose(S_hat.T, S_hat, rtol=1e-7, atol=1e-8)
根据您的特定数据量级调整容差。特别是,对于您的示例数据,似乎 atol
应该设置为 0(您的数据范围从 1 到 1e-14)。