我正在尝试使用sklearn,pandas和numpy进行多维缩放。使用的数据文件Im具有10个数字列且没有缺失值。我正在尝试使用这个十维数据并使用sklearn.manifold的多维缩放在2维中将其可视化,如下所示:
import numpy as np
import pandas as pd
from sklearn import manifold
from sklearn.metrics import euclidean_distances
seed = np.random.RandomState(seed=3)
data = pd.read_csv('data/big-file.csv')
# start small dont take all the data,
# its about 200k records
subset = data[:10000]
similarities = euclidean_distances(subset)
mds = manifold.MDS(n_components=2, max_iter=3000, eps=1e-9,
random_state=seed, dissimilarity="precomputed", n_jobs=1)
pos = mds.fit(similarities).embedding_
但是我得到了这个值错误:
Traceback (most recent call last):
File "demo/mds-demo.py", line 18, in <module>
pos = mds.fit(similarities).embedding_
File "/Users/dwilliams/Desktop/Anaconda/lib/python2.7/site-packages/sklearn/manifold/mds.py", line 360, in fit
self.fit_transform(X, init=init)
File "/Users/dwilliams/Desktop/Anaconda/lib/python2.7/site-packages/sklearn/manifold/mds.py", line 395, in fit_transform
eps=self.eps, random_state=self.random_state)
File "/Users/dwilliams/Desktop/Anaconda/lib/python2.7/site-packages/sklearn/manifold/mds.py", line 242, in smacof
eps=eps, random_state=random_state)
File "/Users/dwilliams/Desktop/Anaconda/lib/python2.7/site-packages/sklearn/manifold/mds.py", line 73, in _smacof_single
raise ValueError("similarities must be symmetric")
ValueError: similarities must be symmetric
我认为euclidean_distances返回了一个对称矩阵。我做错了什么,如何解决?
答案 0 :(得分:10)
我遇到了同样的问题;事实证明,我的数据是np.float32
的数组,并且降低的浮点精度导致距离矩阵不对称。我通过在运行MDS之前将数据转换为np.float64
来修复此问题。
以下是使用随机数据来说明问题的示例:
import numpy as np
from sklearn.manifold import MDS
from sklearn.metrics import euclidean_distances
from sklearn.datasets import make_classification
data, labels = make_classification()
mds = MDS(n_components=2)
similarities = euclidean_distances(data.astype(np.float64))
print np.abs(similarities - similarities.T).max()
# Prints 1.7763568394e-15
mds.fit(data.astype(np.float64))
# Succeeds
similarities = euclidean_distances(data.astype(np.float32))
print np.abs(similarities - similarities.T).max()
# Prints 9.53674e-07
mds.fit(data.astype(np.float32))
# Fails with "ValueError: similarities must be symmetric"
答案 1 :(得分:6)
前一段时间遇到同样的问题。我认为更有效的另一种解决方案是仅计算上三角矩阵的距离,然后复制到下半部分。
可以用scipy完成如下:
from scipy.spatial.distance import squareform,pdist
similarities = squareform(pdist(data,'speuclidean'))