当前位置: 首页>>代码示例>>Python>>正文


Python Isomap.fit_transform方法代码示例

本文整理汇总了Python中sklearn.manifold.Isomap.fit_transform方法的典型用法代码示例。如果您正苦于以下问题:Python Isomap.fit_transform方法的具体用法?Python Isomap.fit_transform怎么用?Python Isomap.fit_transform使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在sklearn.manifold.Isomap的用法示例。


在下文中一共展示了Isomap.fit_transform方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: isomap

# 需要导入模块: from sklearn.manifold import Isomap [as 别名]
# 或者: from sklearn.manifold.Isomap import fit_transform [as 别名]
def isomap(similarity, euclid=False):
    if not euclid:
        print('podvod')
    model = Isomap(n_neighbors=15)
    result = model.fit_transform(similarity)

    return result.T
开发者ID:thran,项目名称:experiments2.0,代码行数:9,代码来源:projection.py

示例2: plotTrajectory

# 需要导入模块: from sklearn.manifold import Isomap [as 别名]
# 或者: from sklearn.manifold.Isomap import fit_transform [as 别名]
def plotTrajectory(dfile):
    fin = open(dfile)

    Vsteps = []
    Vtarget = fin.readline().strip().split()
    Vtarget = map(float,Vtarget)
    Vsteps.append(Vtarget)
    for l in fin:
        l = l.strip().split()
        if len(l) != 26: continue
        l = map(float,l)
        Vsteps.append(l)


    distances = [euclidean(a,Vsteps[0]) for a in Vsteps[1:]]
    print len(distances)

    _map = plt.get_cmap("winter")
    distcolors = _map(distances)


    dimred = Isomap(n_components=2)
    Vsteps = dimred.fit_transform(Vsteps)



    #objective vector
    plt.scatter(Vsteps[0,0],Vsteps[0,1],color='red',s=30,marker=(5,1))
    #Optimization steps
    plt.scatter(Vsteps[1:,0],Vsteps[1:,1],color=distcolors,alpha=0.5)

    plt.show()
开发者ID:RicardoCorralC,项目名称:trajectory_plotter,代码行数:34,代码来源:plotTraj.py

示例3: plot_3d

# 需要导入模块: from sklearn.manifold import Isomap [as 别名]
# 或者: from sklearn.manifold.Isomap import fit_transform [as 别名]
def plot_3d(dataset):
    """TODO: Docstring for plot_3d.
    :returns: TODO

    """
    from mpl_toolkits.mplot3d import Axes3D

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')

    iso = Isomap(n_components=3)
    projected = iso.fit_transform(dataset.data.toarray())

    print 'projected: sample: %s, feature: %s'\
            % (projected.shape[0], projected.shape[1])

    all_scatter = []
    colors = cm.rainbow(np.linspace(0, 1, len(dataset.target_names)), alpha=0.5)
    for i in range(len(dataset.target_names)):
        points = projected[dataset.target==i,:]
        cur = ax.scatter(points[:,0], points[:,1], points[:,2],
                          color=colors[i], edgecolor='k', lw=0.1,
                          vmin=0, vmax=len(dataset.target_names))
        all_scatter.append(cur)
    ax.legend(all_scatter, dataset.target_names,
               loc='lower left', scatterpoints=1)
    plt.savefig('isomap3d', dpi=500)
    plt.show()

    return True
开发者ID:ShiehShieh,项目名称:Code_Identifier,代码行数:32,代码来源:visualization.py

示例4: iso_map

# 需要导入模块: from sklearn.manifold import Isomap [as 别名]
# 或者: from sklearn.manifold.Isomap import fit_transform [as 别名]
def iso_map(data, target, target_names):
    iso = Isomap(n_components=2)
    data_projected = iso.fit_transform(data)
    formatter = plt.FuncFormatter(lambda i, *args:target_names[int(i)])
    plt.figure(figsize=(8, 8))
    plt.scatter(data_projected[:, 0], data_projected[:, 1], c=target,edgecolor='none', alpha=0.5, cmap=plt.cm.get_cmap('rainbow', len(target_names)));
    plt.colorbar(ticks=sorted(list(set(target))), format=formatter)
    #plt.clim(-200, 0)
    return iso, data_projected
开发者ID:SamanthaChen,项目名称:codes,代码行数:11,代码来源:template.py

示例5: embedDistanceMatrix

# 需要导入模块: from sklearn.manifold import Isomap [as 别名]
# 或者: from sklearn.manifold.Isomap import fit_transform [as 别名]
def embedDistanceMatrix(dmatDf, method='kpca', n_components=2, **kwargs):
    """Two-dimensional embedding of sequence distances in dmatDf,
    returning Nx2 x,y-coords: tsne, isomap, pca, mds, kpca, sklearn-tsne"""
    if isinstance(dmatDf, pd.DataFrame):
        dmat = dmatDf.values
    else:
        dmat = dmatDf

    if method == 'tsne':
        xy = tsne.run_tsne(dmat, no_dims=n_components, perplexity=kwargs['perplexity'])
    elif method == 'isomap':
        isoObj = Isomap(n_neighbors=10, n_components=n_components)
        xy = isoObj.fit_transform(dmat)
    elif method == 'mds':
        mds = MDS(n_components=n_components,
                  max_iter=3000,
                  eps=1e-9,
                  random_state=15,
                  dissimilarity="precomputed",
                  n_jobs=1)
        xy = mds.fit(dmat).embedding_
        rot = PCA(n_components=n_components)
        xy = rot.fit_transform(xy)
    elif method == 'pca':
        pcaObj = PCA(n_components=None)
        xy = pcaObj.fit_transform(dmat)[:, :n_components]
    elif method == 'kpca':
        pcaObj = KernelPCA(n_components=dmat.shape[0], kernel='precomputed', eigen_solver='dense')
        try:
            gram = dist2kernel(dmat)
        except:
            print('Could not convert dmat to kernel for KernelPCA; using 1 - dmat/dmat.max() instead')
            gram = 1 - dmat / dmat.max()
        xy = pcaObj.fit_transform(gram)[:, :n_components]
    elif method == 'lle':
        lle = manifold.LocallyLinearEmbedding(n_neighbors=30, n_components=n_components, method='standard')
        xy = lle.fit_transform(dist)
    elif method == 'sklearn-tsne':
        tsneObj = TSNE(n_components=n_components, metric='precomputed', random_state=0, perplexity=kwargs['perplexity'])
        xy = tsneObj.fit_transform(dmat)
    elif method == 'umap':
        umapObj = umap.UMAP(n_components=n_components, metric='precomputed', **kwargs)
        xy = umapObj.fit_transform(dmat)
    else:
        print('Method unknown: %s' % method)
        return

    assert xy.shape[0] == dmatDf.shape[0]
    xyDf = pd.DataFrame(xy[:, :n_components], index=dmatDf.index, columns=np.arange(n_components))
    if method == 'kpca':
        """Not sure how negative eigenvalues should be handled here, but they are usually
        small so it shouldn't make a big difference"""
        setattr(xyDf, 'explained_variance_', pcaObj.lambdas_[:n_components]/pcaObj.lambdas_[pcaObj.lambdas_>0].sum())
    return xyDf
开发者ID:agartland,项目名称:utils,代码行数:56,代码来源:embedding.py

示例6: isomap

# 需要导入模块: from sklearn.manifold import Isomap [as 别名]
# 或者: from sklearn.manifold.Isomap import fit_transform [as 别名]
 def isomap(self, data):
     print 'Isomap neighbours :', self.parameters["n_neighbors"]
     print 'Isomap components, ie final number of coordinates :', self.k
     
     k_means_n_clusters=self.parameters['k_means_n_clusters']
     isomap_params = dict(self.parameters)
     del isomap_params["k_means_n_clusters"]
     m = Isomap(neighbors_algorithm = 'kd_tree',**isomap_params)#eigen_solver='auto', tol=0, path_method='auto', neighbors_algorithm='kd_tree')
     x = m.fit_transform(data)
     
     error=m.reconstruction_error() 
     geod_d = m.dist_matrix_.flatten()
     new_euclid_d = cdist(x, x, metric='euclidean').flatten()
     corr=1- pearsonr(geod_d, new_euclid_d)[0]**2
     
     new_data = x
     print self.parameters
     return self.batch_kmeans(new_data, parameters = dict(zip(params["mini-batchk-means"], [k_means_n_clusters, 1000, 500, 1000, 'k-means++', 5])))
开发者ID:PeterJackNaylor,项目名称:Xb_screen,代码行数:20,代码来源:clustering.py

示例7: isomap

# 需要导入模块: from sklearn.manifold import Isomap [as 别名]
# 或者: from sklearn.manifold.Isomap import fit_transform [as 别名]
def isomap(file_name, dimension, num_neighbors, label):
    balls = np.loadtxt(file_name)
    matrix = balls[:, 0:dimension]
    new_matrix = convert_angles_to_cos_sin(matrix)
    imap = Isomap(n_neighbors=num_neighbors, n_components=2, eigen_solver='auto', tol=0, max_iter=None,
                  path_method='auto', neighbors_algorithm='auto')
    transformed_matrix = imap.fit_transform(new_matrix)
    ball_coords = np.zeros((balls.shape[0], dimension+3))
    for i in xrange(balls.shape[0]):
        ball_coords[i, 0:dimension] = balls[i, 0:dimension].tolist()
        ball_coords[i, dimension:dimension+2] = transformed_matrix[i]
        if label == 'cluster':
            ball_coords[i, dimension+2] = balls[i, dimension].tolist()
        elif label == 'eq':
            ball_coords[i, dimension+2] = (-0.0019872041*300*np.log(abs(balls[i, dimension+1]))).tolist()
        elif label == 'committor':
            ball_coords[i, dimension+2] = (balls[i, dimension+2]/abs(balls[i, dimension+1])).tolist()
        print ' '.join([str(x) for x in ball_coords[i, :]])
开发者ID:shirleyahn,项目名称:CAS_Code,代码行数:20,代码来源:dim_reduction.py

示例8: outputBin

# 需要导入模块: from sklearn.manifold import Isomap [as 别名]
# 或者: from sklearn.manifold.Isomap import fit_transform [as 别名]
def outputBin(data, ctrlSize,nbPheno, lPheno, binSize, sigma, nbDim=2, nbNeighbours=20):
    m = Isomap(n_neighbors=nbNeighbours, n_components=nbDim, eigen_solver='auto', tol=0, max_iter=None, path_method='auto', neighbors_algorithm='kd_tree')
    D = m.fit_transform(data)
    ctrl = D[:ctrlSize]
    ctrlTree = KDTree(ctrl, leafsize=10)
    length=ctrlSize
    
    mini = np.amin(D, 0); maxi=np.amax(D, 0); 
    nbPointsX = int((maxi[0]-mini[0])/float(binSize))+1
    nbPointsY = int((maxi[1]-mini[1])/float(binSize))+1
    
    result = np.zeros(shape=(nbPheno, nbPointsX, nbPointsY))
    denomCtrl = np.zeros(shape=(nbPointsX, nbPointsY))
    
    for pointX, pointY in product(range(nbPointsX), range(nbPointsY)):
        x=mini[0]+(pointX+0.5)*binSize; y=mini[1]+(pointY+0.5)*binSize
        ctrldou, ctrli = ctrlTree.query((x, y), ctrlSize, distance_upper_bound=binSize/sqrt(2))
        if min(ctrldou)<100:
            ctrlPoint = filter(lambda t: t[1]<ctrl.shape[0] and np.all(np.abs(ctrl[t[1]]-(x, y))<(binSize/2.0, binSize/2.0)), zip(ctrldou, ctrli))        
            for distance, cPoint in ctrlPoint:
                denomCtrl[pointX, pointY]+=dist((x,y), ctrl[cPoint], sigma)
                
    for ifilm in range(nbPheno):
        print 'film ', ifilm
        pheno = D[length:length+lPheno[ifilm]]
        phenoTree = KDTree(pheno, leafsize=10)
        
        for pointX, pointY in product(range(nbPointsX), range(nbPointsY)):
            x=mini[0]+(pointX+0.5)*binSize; y=mini[1]+(pointY+0.5)*binSize
            denom=denomCtrl[pointX, pointY]
            phenodou, phenoi=phenoTree.query((x, y), data.shape[0]-ctrlSize, distance_upper_bound=binSize/sqrt(2))
            if min(phenodou)<100:
                phenoPoint =filter(lambda t: t[1]<pheno.shape[0] and np.all(np.abs(pheno[t[1]]-(x, y))<(binSize/2.0, binSize/2.0)), zip(phenodou, phenoi))
                for distance, pPoint in phenoPoint:
                    local = dist((x,y), pheno[pPoint], sigma)
                    result[ifilm, pointX, pointY]+=local; denom+=local
        length+=lPheno[ifilm]        
        if denom>0:result[ifilm, pointX, pointY]/=denom
    plotMovies('/media/lalil0u/New/workspace2/Tracking/images', result, 'pattern_b{}_s{}'.format(binSize, sigma))
    return result
开发者ID:PeterJackNaylor,项目名称:Xb_screen,代码行数:42,代码来源:exploiting_clustering.py

示例9: plot_2d

# 需要导入模块: from sklearn.manifold import Isomap [as 别名]
# 或者: from sklearn.manifold.Isomap import fit_transform [as 别名]
def plot_2d(dataset):
    """TODO: Docstring for plot_2d.
    :returns: TODO

    """
    iso = Isomap(n_components=2)
    projected = iso.fit_transform(dataset.data.toarray())

    print 'projected: sample: %s, feature: %s'\
            % (projected.shape[0], projected.shape[1])

    all_scatter = []
    colors = cm.rainbow(np.linspace(0, 1, len(dataset.target_names)), alpha=0.5)
    for i in range(len(dataset.target_names)):
        points = projected[dataset.target==i,:]
        cur = plt.scatter(points[:,0], points[:,1], color=colors[i],
                          edgecolor='k', lw=0.6,
                          vmin=0, vmax=len(dataset.target_names))
        all_scatter.append(cur)
    plt.legend(all_scatter, dataset.target_names,
               loc='lower left', scatterpoints=1)
    plt.clim(-0.5, 9.5)
    plt.savefig('isomap2d', dpi=500)
开发者ID:ShiehShieh,项目名称:Code_Identifier,代码行数:25,代码来源:visualization.py

示例10: embedDistanceMatrix

# 需要导入模块: from sklearn.manifold import Isomap [as 别名]
# 或者: from sklearn.manifold.Isomap import fit_transform [as 别名]
def embedDistanceMatrix(dist,method='tsne'):
    """MDS embedding of sequence distances in dist, returning Nx2 x,y-coords: tsne, isomap, pca, mds, kpca"""
    if method == 'tsne':
        xy = tsne.run_tsne(dist, no_dims=2)
        #xy=pytsne.run_tsne(adist,no_dims=2)
    elif method == 'isomap':
        isoObj = Isomap(n_neighbors=10, n_components=2)
        xy = isoObj.fit_transform(dist)
    elif method == 'mds':
        mds = manifold.MDS(n_components=2, max_iter=3000, eps=1e-9, random_state=15,
                           dissimilarity="precomputed", n_jobs=1)
        xy = mds.fit(dist).embedding_
        rot = PCA(n_components=2)
        xy = rot.fit_transform(xy)
    elif method == 'pca':
        pcaObj = PCA(n_components=2)
        xy = pcaObj.fit_transform(1-dist)
    elif method == 'kpca':
        pcaObj = KernelPCA(n_components=2, kernel='precomputed')
        xy = pcaObj.fit_transform(1-dist)
    elif method == 'lle':
        lle = manifold.LocallyLinearEmbedding(n_neighbors=30, n_components=2, method='standard')
        xy = lle.fit_transform(dist)
    return xy
开发者ID:agartland,项目名称:utils,代码行数:26,代码来源:seqdistance_old.py

示例11: range

# 需要导入模块: from sklearn.manifold import Isomap [as 别名]
# 或者: from sklearn.manifold.Isomap import fit_transform [as 别名]
X_pca = pca.fit_transform(T)
'''
# No, the accuracy levels off at the same value as before from 7 components onwards.

# If you are not, then forget about PCA entirely, unless you want to visualize your data. However if you are able to get a higher score,
# then be *sure* keep that figure in mind, and comment out all the PCA code.
# In the same spot, run Isomap on the data, before sending it to the train / test split. Manually experiment with every inclusive
# combination of n_neighbors between 2 and 5, and n_components between 4 and 6. Are you able to get a better accuracy?
from sklearn.manifold import Isomap

# You're going to have to write nested for loops that wrap around everything from here on down!
best_score = 0
for k in range(2, 6):
    for l in range(4, 7):
        iso = Isomap(n_neighbors = k, n_components = l)
        X_iso = iso.fit_transform(T)

        # Perform a train/test split. 30% test group size, with a random_state equal to 7.
        from sklearn.cross_validation import train_test_split
        X_train, X_test, y_train, y_test = train_test_split(X_iso, y, test_size = 0.3, random_state = 7)

        # Create a SVC classifier. Don't specify any parameters, just leave everything as default.
        # Fit it against your training data and then score your testing data.
        from sklearn.svm import SVC
        # Lines below are for the first lab question:
        '''
        model = SVC()
        model.fit(X_train, y_train)
        score = model.score(X_test, y_test)
        print score
        '''
开发者ID:anarayanan86,项目名称:Microsoft_DAT210x,代码行数:33,代码来源:assignment3.py

示例12: shuffle

# 需要导入模块: from sklearn.manifold import Isomap [as 别名]
# 或者: from sklearn.manifold.Isomap import fit_transform [as 别名]
    X_train.append(XX_train[i])
    y_train.append(yy_train[i])
num_samples_to_plot = 5000
X_train, y_train = shuffle(X_train, y_train)
X_train, y_train = X_train[:num_samples_to_plot], y_train[:num_samples_to_plot]  # lets subsample a bit for a first impression

for digit in mytargets:
  instances=[i for i in y_train if i==digit]
  print "Digit",digit,"appears ",len(instances), "times"

transformer = Isomap(n_neighbors = 10, n_components = 2)
fig, plot = plt.subplots()
fig.set_size_inches(50, 50)
plt.prism()

X_transformed = transformer.fit_transform(X_train)
plot.scatter(X_transformed[:, 0], X_transformed[:, 1], c=y_train)
plot.set_xticks(())
plot.set_yticks(())

count=0;
plt.tight_layout()
plt.suptitle("Isomap for MNIST digits ")
for label , x, y in zip(y_train, X_transformed[:, 0], X_transformed[:, 1]):
#Lets annotate every 1 out of 200 samples, otherwise graph will be cluttered with anotations
  if count % 200 == 0:
    plt.annotate(str(int(label)),xy=(x,y), color='black', weight='normal',size=10,bbox=dict(boxstyle="round4,pad=.5", fc="0.8"))
  count = count + 1
#plt.savefig("mnist_pca.png")
plt.show()
开发者ID:saradhix,项目名称:mnist_visual,代码行数:32,代码来源:isomap.py

示例13: Isomap

# 需要导入模块: from sklearn.manifold import Isomap [as 别名]
# 或者: from sklearn.manifold.Isomap import fit_transform [as 别名]
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.manifold import Isomap


resourceFolder = '../res/'

dataframe = pd.read_csv(resourceFolder + 'EnergyMix.csv')

df = dataframe.loc[:,['Oil','Gas','Coal','Nuclear','Hydro']]

print df

imap = Isomap()
df_reduced = imap.fit_transform(df)
print df_reduced

plt.plot(df_reduced[:,0],df_reduced[:,1],'.')
for index, country in enumerate(dataframe["Country"]):
        plt.text(df_reduced[index,0], df_reduced[index,1], country)

plt.savefig('../doc/EnergyMix_Reduced.png')
plt.show()
开发者ID:floriant,项目名称:DataMining,代码行数:26,代码来源:energyReduceDim.py

示例14: Isomap

# 需要导入模块: from sklearn.manifold import Isomap [as 别名]
# 或者: from sklearn.manifold.Isomap import fit_transform [as 别名]
from sklearn.manifold import Isomap
iso = Isomap(n_components=2)
digits_isomap = iso.fit_transform(digits.data)

plt.figure(figsize=(10, 10))
plt.xlim(digits_isomap[:, 0].min(), digits_isomap[:, 0].max() + 1)
plt.ylim(digits_isomap[:, 1].min(), digits_isomap[:, 1].max() + 1)
for i in range(len(digits.data)):
    # actually plot the digits as text instead of using scatter
    plt.text(digits_isomap[i, 0], digits_isomap[i, 1], str(digits.target[i]),
             color = colors[digits.target[i]],
             fontdict={'weight': 'bold', 'size': 9})
开发者ID:Knowa42,项目名称:Classes,代码行数:14,代码来源:22A_isomap_digits.py

示例15: enumerate

# 需要导入模块: from sklearn.manifold import Isomap [as 别名]
# 或者: from sklearn.manifold.Isomap import fit_transform [as 别名]
for i,s in enumerate(spectra):
    spec= s.spectrum
    wavsi = s.wavelength()
    intpol = spi.interp1d(wavsi,spec,bounds_error=False,fill_value = 0.)
    spec = intpol(wavs)
    spec/=spec.max()
    data[i]= spec

#print data

iso = Isomap(k,n)

#iso.fit(data)

print "projecting and fitting: "
proj = iso.fit_transform(data)

print "proj.shape"
print proj.shape

fig,axes = plt.subplots(2,3)


print proj[:,0]
print proj[:,1]
print proj

for prop,nprop,ax in zip(properties,nproperites,axes.flatten()):
    ax.set_title(nprop)
    ax.scatter(proj[:,0],proj[:,1],c=prop)
开发者ID:SU-AstroML,项目名称:AstroML-course,代码行数:32,代码来源:machine_ISOmap.py


注:本文中的sklearn.manifold.Isomap.fit_transform方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。