本文整理汇总了Python中sklearn.manifold.MDS属性的典型用法代码示例。如果您正苦于以下问题:Python manifold.MDS属性的具体用法?Python manifold.MDS怎么用?Python manifold.MDS使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类sklearn.manifold
的用法示例。
在下文中一共展示了manifold.MDS属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: learn_manifold
# 需要导入模块: from sklearn import manifold [as 别名]
# 或者: from sklearn.manifold import MDS [as 别名]
def learn_manifold(manifold_type, feats, n_components=2):
if manifold_type == 'tsne':
feats_fitted = manifold.TSNE(n_components=n_components, random_state=0).fit_transform(feats)
elif manifold_type == 'isomap':
feats_fitted = manifold.Isomap(n_components=n_components).fit_transform(feats)
elif manifold_type == 'mds':
feats_fitted = manifold.MDS(n_components=n_components).fit_transform(feats)
elif manifold_type == 'spectral':
feats_fitted = manifold.SpectralEmbedding(n_components=n_components).fit_transform(feats)
else:
raise Exception('wrong maniford type!')
# methods = ['standard', 'ltsa', 'hessian', 'modified']
# feats_fitted = manifold.LocallyLinearEmbedding(n_components=n_components, method=methods[0]).fit_transform(pred)
return feats_fitted
示例2: mds
# 需要导入模块: from sklearn import manifold [as 别名]
# 或者: from sklearn.manifold import MDS [as 别名]
def mds(features, n_components=2):
"""
Returns the embedded points for MDS.
Parameters
----------
features: numpy.ndarray
contains the input feature vectors.
n_components: int
number of components to transform the features into
Returns
-------
embedding: numpy.ndarray
x,y(z) points that the feature vectors have been transformed into
"""
embedding = MDS(n_components=n_components, n_jobs=-1).fit_transform(features)
return embedding
示例3: apply_lens
# 需要导入模块: from sklearn import manifold [as 别名]
# 或者: from sklearn.manifold import MDS [as 别名]
def apply_lens(df, lens='pca', dist='euclidean', n_dim=2, **kwargs):
"""
input: N x F dataframe of observations
output: N x n_dim image of input data under lens function
"""
if n_dim != 2:
raise 'error: image of data set must be two-dimensional'
if dist not in ['euclidean', 'correlation']:
raise 'error: only euclidean and correlation distance metrics are supported'
if lens == 'pca' and dist != 'euclidean':
raise 'error: PCA requires the use of euclidean distance metric'
if lens == 'pca':
df_lens = pd.DataFrame(decomposition.PCA(n_components=n_dim, **kwargs).fit_transform(df), df.index)
elif lens == 'mds':
D = metrics.pairwise.pairwise_distances(df, metric=dist)
df_lens = pd.DataFrame(manifold.MDS(n_components=n_dim, **kwargs).fit_transform(D), df.index)
elif lens == 'neighbor':
D = metrics.pairwise.pairwise_distances(df, metric=dist)
df_lens = pd.DataFrame(manifold.SpectralEmbedding(n_components=n_dim, **kwargs).fit_transform(D), df.index)
else:
raise 'error: only PCA, MDS, neighborhood lenses are supported'
return df_lens
示例4: get_scaled_vectors
# 需要导入模块: from sklearn import manifold [as 别名]
# 或者: from sklearn.manifold import MDS [as 别名]
def get_scaled_vectors(vectors, user_seed=None, n_components=12, normalize=True, progress=progress):
if user_seed:
seed = np.random.RandomState(seed=user_seed)
else:
seed = np.random.RandomState()
# FIXME: Make this optional:
from sklearn.metrics.pairwise import euclidean_distances as d
vectors = get_normalized_vectors(np.array(vectors)) if normalize else np.array(vectors)
# compute similarities based on d
progress.update('Computing similarity matrix')
similarities = d(vectors)
progress.update('Scaling using %d components' % n_components)
mds = manifold.MDS(n_components=n_components, max_iter=300, eps=1e-10, random_state=seed,
dissimilarity="precomputed", n_jobs=1)
progress.update('Fitting')
scaled_vectors = mds.fit(similarities).embedding_
return scaled_vectors
示例5: compute_theta_all
# 需要导入模块: from sklearn import manifold [as 别名]
# 或者: from sklearn.manifold import MDS [as 别名]
def compute_theta_all(D, vertices, faces, normals, idx, radius):
mymds = MDS(n_components=2, n_init=1, max_iter=50, dissimilarity='precomputed', n_jobs=10)
all_theta = []
for i in range(D.shape[0]):
if i % 100 == 0:
print(i)
# Get the pairs of geodesic distances.
neigh = D[i].nonzero()
ii = np.where(D[i][neigh] < radius)[1]
neigh_i = neigh[1][ii]
pair_dist_i = D[neigh_i,:][:,neigh_i]
pair_dist_i = pair_dist_i.todense()
# Plane_i: the 2D plane for all neighbors of i
plane_i = call_mds(mymds, pair_dist_i)
# Compute the angles on the plane.
theta = compute_thetas(plane_i, i, vertices, faces, normals, neigh_i, idx)
all_theta.append(theta)
return all_theta
示例6: mds
# 需要导入模块: from sklearn import manifold [as 别名]
# 或者: from sklearn.manifold import MDS [as 别名]
def mds(utv):
rdm = scipy.spatial.distance.squareform(utv)
seed = numpy.random.RandomState(seed=3)
mds = MDS(n_components=2, max_iter=3000, eps=1e-9, random_state=seed,
dissimilarity="precomputed", n_jobs=1)
pos = mds.fit_transform(rdm)
# rescale
#pos *= sqrt((X_true ** 2).sum()) / sqrt((pos ** 2).sum())
# Y = mds.fit_transform(RDM)
# if itime == 0:
# Y = mds.fit_transform(RDM)
# else:
# d, Y, _ = procrustes(
# Y, mds.fit_transform(RDM), scaling=False)
# Rotate the data
# clf = PCA(n_components=2)
# pos = clf.fit_transform(pos)
return pos
示例7: plot_cluster
# 需要导入模块: from sklearn import manifold [as 别名]
# 或者: from sklearn.manifold import MDS [as 别名]
def plot_cluster(cluster):
'''
Plot scatter diagram for final points that using multi-dimensional scaling for data
Args:
cluster : DensityPeakCluster object
'''
logger.info("PLOT: cluster result, start multi-dimensional scaling")
dp = np.zeros((cluster.max_id, cluster.max_id), dtype = np.float32)
cls = []
for i in xrange(1, cluster.max_id):
for j in xrange(i + 1, cluster.max_id + 1):
dp[i - 1, j - 1] = cluster.distances[(i, j)]
dp[j - 1, i - 1] = cluster.distances[(i, j)]
cls.append(cluster.cluster[i])
cls.append(cluster.cluster[cluster.max_id])
cls = np.array(cls, dtype = np.float32)
fo = open(r'./tmp.txt', 'w')
fo.write('\n'.join(map(str, cls)))
fo.close()
#seed = np.random.RandomState(seed=3)
mds = manifold.MDS(max_iter=200, eps=1e-4, n_init=1,dissimilarity='precomputed')
dp_mds = mds.fit_transform(dp.astype(np.float64))
logger.info("PLOT: end mds, start plot")
plot_scatter_diagram(1, dp_mds[:, 0], dp_mds[:, 1], title='2D Nonclassical Multidimensional Scaling', style_list = cls)
plt.savefig("2D Nonclassical Multidimensional Scaling.jpg")
示例8: plot_demo_1
# 需要导入模块: from sklearn import manifold [as 别名]
# 或者: from sklearn.manifold import MDS [as 别名]
def plot_demo_1():
X = np.c_[np.ones(5), 2 * np.ones(5), 10 * np.ones(5)].T
y = np.array([0, 1, 2])
fig = pylab.figure(figsize=(10, 4))
ax = fig.add_subplot(121, projection='3d')
ax.set_axis_bgcolor('white')
mds = manifold.MDS(n_components=3)
Xtrans = mds.fit_transform(X)
for cl, color, marker in zip(np.unique(y), colors, markers):
ax.scatter(
Xtrans[y == cl][:, 0], Xtrans[y == cl][:, 1], Xtrans[y == cl][:, 2], c=color, marker=marker, edgecolor='black')
pylab.title("MDS on example data set in 3 dimensions")
ax.view_init(10, -15)
mds = manifold.MDS(n_components=2)
Xtrans = mds.fit_transform(X)
ax = fig.add_subplot(122)
for cl, color, marker in zip(np.unique(y), colors, markers):
ax.scatter(
Xtrans[y == cl][:, 0], Xtrans[y == cl][:, 1], c=color, marker=marker, edgecolor='black')
pylab.title("MDS on example data set in 2 dimensions")
filename = "mds_demo_1.png"
pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight")
开发者ID:PacktPublishing,项目名称:Building-Machine-Learning-Systems-With-Python-Second-Edition,代码行数:31,代码来源:demo_mds.py
示例9: do_mds
# 需要导入模块: from sklearn import manifold [as 别名]
# 或者: from sklearn.manifold import MDS [as 别名]
def do_mds(X):
"""Do MDS"""
from sklearn import manifold
seed = np.random.RandomState(seed=3)
mds = manifold.MDS(n_components=3, max_iter=3000, eps=1e-9, random_state=seed,
n_jobs=1)
pX = mds.fit(X.values).embedding_
pX = pd.DataFrame(pX,index=X.index)
return pX
示例10: plot_cluster
# 需要导入模块: from sklearn import manifold [as 别名]
# 或者: from sklearn.manifold import MDS [as 别名]
def plot_cluster(cluster):
'''
Plot scatter diagram for final points that using multi-dimensional scaling for data
Args:
cluster : DensityPeakCluster object
'''
logger.info("PLOT: cluster result, start multi-dimensional scaling")
dp = np.zeros((cluster.max_id, cluster.max_id), dtype=np.float32)
cls = []
for i in xrange(1, cluster.max_id):
for j in xrange(i + 1, cluster.max_id + 1):
dp[i - 1, j - 1] = cluster.distances[(i, j)]
dp[j - 1, i - 1] = cluster.distances[(i, j)]
cls.append(cluster.cluster[i])
cls.append(cluster.cluster[cluster.max_id])
cls = np.array(cls, dtype=np.float32)
fo = open(r'./tmp.txt', 'w')
fo.write('\n'.join(map(str, cls)))
fo.close()
version = versiontuple(sklearn_version)[1] > 14
if version[0] > 0 or version[1] > 14:
mds = manifold.MDS(max_iter=200, eps=1e-4, n_init=1,
dissimilarity='precomputed')
else:
mds = manifold.MDS(max_iter=200, eps=1e-4, n_init=1)
dp_mds = mds.fit_transform(dp)
logger.info("PLOT: end mds, start plot")
plot_scatter_diagram(1, dp_mds[:, 0], dp_mds[
:, 1], title='cluster', style_list=cls)
示例11: generate_missing_coordinates
# 需要导入模块: from sklearn import manifold [as 别名]
# 或者: from sklearn.manifold import MDS [as 别名]
def generate_missing_coordinates(for_D):
from sklearn import manifold
mds = manifold.MDS(n_components=2, dissimilarity='precomputed',
random_state=42)
mds_results = mds.fit(for_D)
points = list( mds_results.embedding_ )
edge_weight_type = "EUC_2D" if _is_all_integer_array(for_D) else "EXACT_2D"
return points, edge_weight_type
示例12: fill_missing_pts_as_needed
# 需要导入模块: from sklearn import manifold [as 别名]
# 或者: from sklearn.manifold import MDS [as 别名]
def fill_missing_pts_as_needed(points, D):
#print(points, dd_points)
if points is None:
# We do not have point coodrinates, but we have D!
from sklearn import manifold
mds = manifold.MDS(n_components=2, dissimilarity='precomputed',
random_state=42)
mds_results = mds.fit(D)
return list( mds_results.embedding_ )
return points
示例13: generate_qc_plot
# 需要导入模块: from sklearn import manifold [as 别名]
# 或者: from sklearn.manifold import MDS [as 别名]
def generate_qc_plot(method, input_files, outdir, n_cpu, ref_db=None):
# plot MDS
if method in ["mds", "all"]:
dist_mat, file_names = get_mash_dist(input_gffs=input_files,
outdir=outdir,
n_cpu=n_cpu,
quiet=True)
plot_MDS(dist_mat, file_names, outdir)
# plot number of genes
if method in ["ngenes", "all"]:
plot_ngenes(input_gffs=input_files, outdir=outdir)
# plot number of contigs
if method in ["ncontigs", "all"]:
plot_ncontigs(input_gffs=input_files, outdir=outdir)
# plot contamination scatter plot
if (method in ["contam", "all"]):
if ref_db is None:
print(
"No reference mash database given! Skipping contamination plot..."
)
print(("One can be downloaded from https://mash.readthedocs.io" +
"/en/latest/tutorials.html#screening-a-read-set-for" +
"-containment-of-refseq-genomes"))
else:
mash_contam_file = get_mash_contam(input_gffs=input_files,
mash_ref=ref_db,
n_cpu=n_cpu,
outdir=outdir)
plot_mash_contam(mash_contam_file=mash_contam_file, outdir=outdir)
return
示例14: __init__
# 需要导入模块: from sklearn import manifold [as 别名]
# 或者: from sklearn.manifold import MDS [as 别名]
def __init__(self, options):
self.handle_options(options)
out_params = convert_params(
options.get('params', {}),
ints=['k', 'max_iter', 'n_init', 'n_jobs'],
floats=['eps'],
bools=['metric'],
aliases={'k': 'n_components'}
)
if 'max_iter' not in out_params:
out_params.setdefault('max_iter', 300)
if 'n_init' not in out_params:
out_params.setdefault('n_init', 4)
if 'n_jobs' not in out_params:
out_params.setdefault('n_jobs', 1)
if 'eps' not in out_params:
out_params.setdefault('eps', 0.001)
if 'metric' not in out_params:
out_params.setdefault('metric', True)
self.estimator = _MDS(**out_params)
示例15: sklearn_mds
# 需要导入模块: from sklearn import manifold [as 别名]
# 或者: from sklearn.manifold import MDS [as 别名]
def sklearn_mds(n_com=2):
mds = MDS(n_components=n_com)
data = load_digits().data
target = load_digits().target
data_2d = mds.fit_transform(data)
plt.scatter(data_2d[:, 0], data_2d[:, 1], c = target)
plt.show()