本文整理汇总了Python中sklearn.neighbors.NearestNeighbors.kneighbors_graph方法的典型用法代码示例。如果您正苦于以下问题:Python NearestNeighbors.kneighbors_graph方法的具体用法?Python NearestNeighbors.kneighbors_graph怎么用?Python NearestNeighbors.kneighbors_graph使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sklearn.neighbors.NearestNeighbors
的用法示例。
在下文中一共展示了NearestNeighbors.kneighbors_graph方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: construct_A
# 需要导入模块: from sklearn.neighbors import NearestNeighbors [as 别名]
# 或者: from sklearn.neighbors.NearestNeighbors import kneighbors_graph [as 别名]
def construct_A(X, k, binary=False):
nbrs = NearestNeighbors(n_neighbors=1 + k).fit(X)
if binary:
return nbrs.kneighbors_graph(X)
else:
return nbrs.kneighbors_graph(X, mode='distance')
示例2: _compute_neighbors
# 需要导入模块: from sklearn.neighbors import NearestNeighbors [as 别名]
# 或者: from sklearn.neighbors.NearestNeighbors import kneighbors_graph [as 别名]
def _compute_neighbors(self):
V,dim = self.data_frame.shape
neighbors = NearestNeighbors(n_neighbors=self.num_neighbors,algorithm='auto').fit(self.data_frame)
_,indices = neighbors.kneighbors(self.data_frame)
self._adjacency_graph = neighbors.kneighbors_graph(self.data_frame,mode='connectivity')
self._knn_graph = neighbors.kneighbors_graph(self.data_frame,mode='distance')
self._neighbors = indices
示例3: test_connectivity_popagation
# 需要导入模块: from sklearn.neighbors import NearestNeighbors [as 别名]
# 或者: from sklearn.neighbors.NearestNeighbors import kneighbors_graph [as 别名]
def test_connectivity_popagation():
"""
Check that connectivity in the ward tree is propagated correctly during
merging.
"""
from sklearn.neighbors import NearestNeighbors
X = np.array(
[
(0.014, 0.120),
(0.014, 0.099),
(0.014, 0.097),
(0.017, 0.153),
(0.017, 0.153),
(0.018, 0.153),
(0.018, 0.153),
(0.018, 0.153),
(0.018, 0.153),
(0.018, 0.153),
(0.018, 0.153),
(0.018, 0.153),
(0.018, 0.152),
(0.018, 0.149),
(0.018, 0.144),
]
)
nn = NearestNeighbors(n_neighbors=10).fit(X)
connectivity = nn.kneighbors_graph(X)
ward = Ward(n_clusters=4, connectivity=connectivity)
# If changes are not propagated correctly, fit crashes with an
# IndexError
ward.fit(X)
示例4: kNN_graph
# 需要导入模块: from sklearn.neighbors import NearestNeighbors [as 别名]
# 或者: from sklearn.neighbors.NearestNeighbors import kneighbors_graph [as 别名]
def kNN_graph(self, k, metric, mutual=False):
# self.latex = []
nn = NearestNeighbors(k, algorithm="brute", metric=metric, n_jobs=-1).fit(self.X)
UAM = nn.kneighbors_graph(self.X).toarray() #unweighted adjacency matrix
m = UAM.shape[0]
self.W = np.zeros((m, m)) #(weighted) adjecancy matrix
self.D = np.zeros((m, m)) #degree matrix
if mutual == False:
if self.full_calculated:
indices = np.where(UAM == 1)
self.W[indices] = self.full_W[indices]
self.D[np.diag_indices(m)] = np.sum(self.W, 1)
else:
for i in range(m):
for j in range(m):
if UAM[i,j] == 1:
sim = self.s(self.X[i], self.X[j], self.d)
self.W[i,j] = sim
self.D[i,i] += sim
else:
if self.full_calculated:
indices = np.where(np.logical_and(UAM == 1, UAM.T == 1).astype(int) == 1)
self.W[indices] = self.full_W[indices]
self.D[np.diag_indices(m)] = np.sum(self.W != 0, 1)
else:
for i in range(m):
for j in range(m):
if UAM[i,j] == 1 and UAM[j,i] == 1:
sim = self.s(self.X[i], self.X[j], self.d)
self.W[i,j] = sim
self.D[i,i] += sim
self.W = np.nan_to_num(self.W)
self.graph = "kNN graph, k = " + str(k) + ", mutual:" + str(mutual)
示例5: _sparse_neighbor_graph
# 需要导入模块: from sklearn.neighbors import NearestNeighbors [as 别名]
# 或者: from sklearn.neighbors.NearestNeighbors import kneighbors_graph [as 别名]
def _sparse_neighbor_graph(X, k, binary=False):
'''Construct a sparse adj matrix from a matrix of points (one per row).
Non-zeros are unweighted/binary distance values, depending on the binary arg.
Doesn't include self-edges.'''
knn = NearestNeighbors(n_neighbors=k).fit(X)
mode = 'connectivity' if binary else 'distance'
try:
adj = knn.kneighbors_graph(None, mode=mode)
except IndexError:
# XXX: we must be running an old (<0.16) version of sklearn
# We have to hack around an old bug:
if binary:
adj = knn.kneighbors_graph(X, k+1, mode=mode)
adj.setdiag(0)
else:
adj = knn.kneighbors_graph(X, k, mode=mode)
return Graph.from_adj_matrix(adj)
示例6: diffusionKernel
# 需要导入模块: from sklearn.neighbors import NearestNeighbors [as 别名]
# 或者: from sklearn.neighbors.NearestNeighbors import kneighbors_graph [as 别名]
def diffusionKernel(X, eps, knn, D=None):
nbrs = NearestNeighbors(n_neighbors=knn, algorithm='ball_tree').fit(X)
D = nbrs.kneighbors_graph(X, mode='distance')
term = D.multiply(D)/-eps
G = np.exp(term.toarray())
G[np.where(G==1)]=0
G = G + np.eye(G.shape[0])
deg = np.sum(G,axis=0)
P = G/deg
return P, D
示例7: test_lle_with_sklearn
# 需要导入模块: from sklearn.neighbors import NearestNeighbors [as 别名]
# 或者: from sklearn.neighbors.NearestNeighbors import kneighbors_graph [as 别名]
def test_lle_with_sklearn():
N = 10
X, color = datasets.samples_generator.make_s_curve(N, random_state=0)
n_components = 2
n_neighbors = 3
knn = NearestNeighbors(n_neighbors + 1).fit(X)
G = geom.Geometry()
G.set_data_matrix(X)
G.set_adjacency_matrix(knn.kneighbors_graph(X, mode = 'distance'))
sk_Y_lle = manifold.LocallyLinearEmbedding(n_neighbors, n_components, method = 'standard').fit_transform(X)
(mm_Y_lle, err) = lle.locally_linear_embedding(G, n_components)
assert(_check_with_col_sign_flipping(sk_Y_lle, mm_Y_lle, 0.05))
示例8: test_isomap_with_sklearn
# 需要导入模块: from sklearn.neighbors import NearestNeighbors [as 别名]
# 或者: from sklearn.neighbors.NearestNeighbors import kneighbors_graph [as 别名]
def test_isomap_with_sklearn():
N = 10
X, color = datasets.samples_generator.make_s_curve(N, random_state=0)
n_components = 2
n_neighbors = 3
knn = NearestNeighbors(n_neighbors + 1).fit(X)
# Assign the geometry matrix to get the same answer since sklearn using k-neighbors instead of radius-neighbors
g = geom.Geometry(X)
g.set_adjacency_matrix(knn.kneighbors_graph(X, mode = 'distance'))
# test Isomap with sklearn
sk_Y_iso = manifold.Isomap(n_neighbors, n_components, eigen_solver = 'arpack').fit_transform(X)
mm_Y_iso = iso.isomap(g, n_components)
assert(_check_with_col_sign_flipping(sk_Y_iso, mm_Y_iso, 0.05))
示例9: getNeighborStatistics
# 需要导入模块: from sklearn.neighbors import NearestNeighbors [as 别名]
# 或者: from sklearn.neighbors.NearestNeighbors import kneighbors_graph [as 别名]
def getNeighborStatistics(self,data,samples,pcntl):
neigh = NearestNeighbors(n_neighbors=samples)
neigh.fit(data)
A = neigh.kneighbors_graph(data,mode='distance')
b = A.nonzero()
c = np.log10(np.array(A[b[0],b[1]]))
mean = c[0].mean()
std = c[0].std()
pc = np.percentile(c[0],pcntl)
n,bins,patches = plt.hist(c[0],50)
plt.show()
mx = bins[n.argmax()]
ret = {'mean':np.power(10,mean),'std':np.power(10,std),'pcntl':np.power(10,pc), 'max':np.power(10,mx)}
return ret
示例10: test_ltsa_with_sklearn
# 需要导入模块: from sklearn.neighbors import NearestNeighbors [as 别名]
# 或者: from sklearn.neighbors.NearestNeighbors import kneighbors_graph [as 别名]
def test_ltsa_with_sklearn():
from sklearn import manifold
from sklearn import datasets
from sklearn.neighbors import NearestNeighbors
N = 10
X, color = datasets.samples_generator.make_s_curve(N, random_state=0)
n_components = 2
n_neighbors = 3
knn = NearestNeighbors(n_neighbors + 1).fit(X)
Geometry = geom.Geometry(X)
Geometry.assign_distance_matrix(knn.kneighbors_graph(X, mode = 'distance'))
sk_Y_ltsa = manifold.LocallyLinearEmbedding(n_neighbors, n_components,
method = 'ltsa',
eigen_solver = 'arpack').fit_transform(X)
(mm_Y_ltsa, err) = ltsa.ltsa(Geometry, n_components, eigen_solver = 'arpack')
assert(_check_with_col_sign_flipping(sk_Y_ltsa, mm_Y_ltsa, 0.05))
示例11: fit
# 需要导入模块: from sklearn.neighbors import NearestNeighbors [as 别名]
# 或者: from sklearn.neighbors.NearestNeighbors import kneighbors_graph [as 别名]
def fit(self, X):
'''Obtain the top-k eigensystem of the graph Laplacian
The eigen solver adopts shift-invert mode as described in
http://docs.scipy.org/doc/scipy/reference/tutorial/arpack.html
'''
nbrs = NearestNeighbors(n_neighbors=self.n_nbrs).fit(X)
# NOTE W is a dense graph thus may lead to memory leak
W = nbrs.kneighbors_graph(X).toarray()
W_sym = np.maximum(W, W.T)
L = csr_matrix(csgraph.laplacian(W_sym, normed=True))
[Sigma, U] = eigsh(L, self.n_clusters+1, sigma=0, which='LM')
# remove the trivial (smallest) eigenvalues & vectors
self.Sigma, self.U = Sigma[1:], U[:,1:]
示例12: getCollectionStatistics
# 需要导入模块: from sklearn.neighbors import NearestNeighbors [as 别名]
# 或者: from sklearn.neighbors.NearestNeighbors import kneighbors_graph [as 别名]
def getCollectionStatistics(self,samples):
neigh = NearestNeighbors(n_neighbors=samples)
neigh.fit(self.coordinates)
A = neigh.kneighbors_graph(self.coordinates,mode='distance')
b = A.nonzero()
c = np.log10(np.array(A[b[0],b[1]]))
mean = c[0].mean()
std = c[0].std()
pc = np.percentile(c[0],50)
n,bins,patches = plt.hist(c[0],80)
plt.show()
mx = bins[n.argmax()]
self.collection_stats = {'mean':np.power(10,mean),'std':np.power(10,std),'pcntl':np.power(10,pc), 'max':np.power(10,mx)}
return self.collection_stats
示例13: netview
# 需要导入模块: from sklearn.neighbors import NearestNeighbors [as 别名]
# 或者: from sklearn.neighbors.NearestNeighbors import kneighbors_graph [as 别名]
def netview(matrix, k, mst, algorithm, tree):
nbrs = NearestNeighbors(n_neighbors=k + 1, algorithm=algorithm).fit(matrix)
adj_knn = nbrs.kneighbors_graph(matrix).toarray()
np.fill_diagonal(adj_knn, 0)
adj_mknn = (adj_knn == adj_knn.T) * adj_knn
if tree:
adj = mst + adj_mknn
else:
adj = adj_mknn
adjacency = np.tril(adj)
mst_edges = np.argwhere(adjacency < 1)
adjacency[adjacency > 0] = 1.0
edges = np.argwhere(adjacency != 0)
weights = matrix[edges[:, 0], edges[:, 1]]
return [k, edges, weights, adjacency, mst_edges]
示例14: test_isomap_with_sklearn
# 需要导入模块: from sklearn.neighbors import NearestNeighbors [as 别名]
# 或者: from sklearn.neighbors.NearestNeighbors import kneighbors_graph [as 别名]
def test_isomap_with_sklearn():
try:
from sklearn import manifold
from sklearn import datasets
from sklearn.neighbors import NearestNeighbors
N = 10
X, color = datasets.samples_generator.make_s_curve(N, random_state=0)
n_components = 2
n_neighbors = 3
knn = NearestNeighbors(n_neighbors + 1).fit(X)
# Assign the geometry matrix to get the same answer since sklearn using k-neighbors instead of radius-neighbors
Geometry = geom.Geometry(X)
Geometry.assign_distance_matrix(knn.kneighbors_graph(X, mode = 'distance'))
# test Isomap with sklearn
sk_Y_iso = manifold.Isomap(n_neighbors, n_components, eigen_solver = 'arpack').fit_transform(X)
mm_Y_iso = iso.isomap(Geometry, n_components)
assert(_check_with_col_sign_flipping(sk_Y_iso, mm_Y_iso, 0.05))
except ImportError:
return True
示例15: get_knn_graph
# 需要导入模块: from sklearn.neighbors import NearestNeighbors [as 别名]
# 或者: from sklearn.neighbors.NearestNeighbors import kneighbors_graph [as 别名]
def get_knn_graph(data_file, data_format, k, d, N, alg):
if data_format == "binary":
a = np.fromfile(data_file, dtype=float).reshape((N,d))
elif data_format == "libsvm":
x, labels = load_svmlight_file(data_file)
del labels
a = x.todense()
del x
else:
print "wrong data format!"
return 0
k_plus_1 = k+1
t_start = time.time()
nbrs = NearestNeighbors(n_neighbors=(k_plus_1), algorithm=alg, leaf_size=1).fit(a)
t_tree = time.time()
knn_graph = nbrs.kneighbors_graph(a)
t_graph = time.time() - t_tree
t = time.time() - t_start
print 'overall time = ' + str(t) + " seconds"
return knn_graph