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


Python FastICA.fit方法代码示例

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


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

示例1: main

# 需要导入模块: from sklearn.decomposition import FastICA [as 别名]
# 或者: from sklearn.decomposition.FastICA import fit [as 别名]
def main(mode):
    path = "/local/attale00/extracted_pascal__4__Multi-PIE"
    path_ea = path + "/color128/"

    allLabelFiles = utils.getAllFiles("/local/attale00/a_labels")

    labeledImages = [i[0:16] + ".png" for i in allLabelFiles]

    # labs=utils.parseLabelFiles(path+'/Multi-PIE/labels','mouth',labeledImages,cutoffSeq='.png',suffix='_face0.labels')
    labs = utils.parseLabelFiles(
        "/local/attale00/a_labels", "mouth", labeledImages, cutoffSeq=".png", suffix="_face0.labels"
    )

    testSet = fg.dataContainer(labs)
    roi = (50, 74, 96, 160)
    X = fg.getAllImagesFlat(path_ea, testSet.fileNames, (128, 256), roi=roi)

    # perform ICA
    if mode not in ["s", "v"]:
        ica = FastICA(n_components=100, whiten=True)
        ica.fit(X)
        meanI = np.mean(X, axis=0)
        X1 = X - meanI
        data = ica.transform(X1)
        filters = ica.components_

    elif mode in ["s", "v"]:
        W = np.load("/home/attale00/Desktop/classifiers/ica/filter1.npy")
        m = np.load("/home/attale00/Desktop/classifiers/ica/meanI1.npy")
        X1 = X - m
        data = np.dot(X1, W.T)

    for i in range(len(testSet.data)):
        testSet.data[i].extend(data[i, :])

    strel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))

    # fg.getHogFeature(testSet,roi,path=path_ea,ending='.png',extraMask = None,orientations = 3, cells_per_block=(6,2),maskFromAlpha=False)
    # fg.getColorHistogram(testSet,roi,path=path_ea,ending='.png',colorspace='lab',bins=10)
    testSet.targetNum = map(utils.mapMouthLabels2Two, testSet.target)

    rf = classifierUtils.standardRF(max_features=np.sqrt(len(testSet.data[0])), min_split=5, max_depth=40)
    if mode in ["s", "v"]:
        print "Classifying with loaded classifier"
        classifierUtils.classifyWithOld(
            path, testSet, mode, clfPath="/home/attale00/Desktop/classifiers/ica/rf128ICA_1"
        )
    elif mode in ["c"]:
        print "cross validation of data"
        print "Scores"
        # print classifierUtils.standardCrossvalidation(rf,testSet,n_jobs=5)
        # _cvDissect(testSet,rf)
        classifierUtils.dissectedCV(rf, testSet)
        print "----"

    elif mode in ["save"]:
        print "saving new classifier"
        _saveRF(testSet)
    else:
        print "not doing anything"
开发者ID:alex-attinger,项目名称:fc_attributes,代码行数:62,代码来源:MultiPiePascal128.py

示例2: wrapper_fastica

# 需要导入模块: from sklearn.decomposition import FastICA [as 别名]
# 或者: from sklearn.decomposition.FastICA import fit [as 别名]
 def wrapper_fastica(data, random_state=None):
     """Call FastICA implementation from scikit-learn."""
     ica = FastICA(random_state=random_state)
     ica.fit(cat_trials(data).T)
     u = ica.components_.T
     m = ica.mixing_.T
     return m, u
开发者ID:cbrnr,项目名称:scot,代码行数:9,代码来源:backend_sklearn.py

示例3: ICA

# 需要导入模块: from sklearn.decomposition import FastICA [as 别名]
# 或者: from sklearn.decomposition.FastICA import fit [as 别名]
class ICA(method.Method):
	
	def __init__(self, params):
		self.params = params
		self.ica = FastICA(**params)
	
	def __str__(self):
		return "FastICA"
		
	def train(self, data):
		"""
		Train the FastICA on the withened data
		
		:param data: whitened data, ready to use
		"""
		self.ica.fit(data)
	
	def encode(self, data):
		"""
		Encodes the ready to use data
		
		:returns: encoded data with dimension n_components
		"""
		return self.ica.transform(data)
	
	def decode(self, components):
		"""
		Decode the data to return whitened reconstructed data
		
		:returns: reconstructed data
		"""
		return self.ica.inverse_transform(components)
开发者ID:kuntzer,项目名称:sclas,代码行数:34,代码来源:ica.py

示例4: align

# 需要导入模块: from sklearn.decomposition import FastICA [as 别名]
# 或者: from sklearn.decomposition.FastICA import fit [as 别名]
def align(movie_data, options, args, lrh):
  print 'pICA(scikit-learn)'
  nvoxel = movie_data.shape[0]
  nTR    = movie_data.shape[1]
  nsubjs = movie_data.shape[2]

  align_algo = args.align_algo
  nfeature   = args.nfeature
  randseed    = args.randseed
  if not os.path.exists(options['working_path']):
    os.makedirs(options['working_path'])

  # zscore the data
  bX = np.zeros((nsubjs*nTR,nvoxel))
  for m in range(nsubjs):
    for t in range(nTR):
      bX[nTR*m+t,:] = stats.zscore(movie_data[:,t,m].T ,axis=0, ddof=1)
  del movie_data
 
  np.random.seed(randseed)
  A = np.mat(np.random.random((nfeature,nfeature)))

  ica = FastICA(n_components= nfeature, max_iter=500,w_init=A,random_state=randseed)
  ica.fit(bX.T)
  R = ica.transform(bX.T)

  niter = 10  
  # initialization when first time run the algorithm
  np.savez_compressed(options['working_path']+align_algo+'_'+lrh+'_'+str(niter)+'.npz',\
                                R = R,  niter=niter)
  return niter
开发者ID:cameronphchen,项目名称:pHA,代码行数:33,代码来源:pica_hor.py

示例5: wrapper_fastica

# 需要导入模块: from sklearn.decomposition import FastICA [as 别名]
# 或者: from sklearn.decomposition.FastICA import fit [as 别名]
def wrapper_fastica(data):
    """ Call FastICA implementation from scikit-learn.
    """
    ica = FastICA()
    ica.fit(datatools.cat_trials(data))
    u = ica.components_.T
    m = ica.mixing_.T
    return m, u
开发者ID:BioinformaticsArchive,项目名称:SCoT,代码行数:10,代码来源:sklearn.py

示例6: ica

# 需要导入模块: from sklearn.decomposition import FastICA [as 别名]
# 或者: from sklearn.decomposition.FastICA import fit [as 别名]
def ica(tx, ty, rx, ry):
    compressor = ICA(whiten=True)  # for some people, whiten needs to be off
    compressor.fit(tx, y=ty)
    newtx = compressor.transform(tx)
    newrx = compressor.transform(rx)
    em(newtx, ty, newrx, ry, add="wICAtr", times=10)
    km(newtx, ty, newrx, ry, add="wICAtr", times=10)
    nn(newtx, ty, newrx, ry, add="wICAtr")
开发者ID:iRapha,项目名称:Machine-Learning,代码行数:10,代码来源:analysis.py

示例7: fastica

# 需要导入模块: from sklearn.decomposition import FastICA [as 别名]
# 或者: from sklearn.decomposition.FastICA import fit [as 别名]
def fastica(eeg_data):
    """
    Sample function to apply `FastICA`_ to the EEG data.

    Parameters
    ----------
    eeg_data : array
        EEG data in a CxTxE array. With C the number of channels, T the number
        of time samples and E the number of events.

    Returns
    -------
    ica : ICA object
        Trained `FastICA`_ object.
    ica_data : array
        EEG projected data in a CxTxE array. With C the number of components, T
        the number of time samples and E the number of events.
    """

    # Dimension shapes
    ch_len = eeg_data.shape[ch_dim]
    t_len = eeg_data.shape[t_dim]
    ev_len = eeg_data.shape[ev_dim]

    # -------------------------------------------------------------------------
    # 1. Fit the FastICA model

    # We need to collapse time and events dimensions
    coll_data = eeg_data.transpose([t_dim, ev_dim, ch_dim])\
        .reshape([t_len*ev_len, ch_len])

    # Fit model
    ica = FastICA()
    ica.fit(coll_data)

    # Normalize ICs to unit norm
    k = np.linalg.norm(ica.mixing_, axis=0)  # Frobenius norm
    ica.mixing_ /= k
    ica.components_[:] = (ica.components_.T * k).T

    # -------------------------------------------------------------------------
    # 2. Transform data

    # Project data
    bss_data = ica.transform(coll_data)

    # Adjust shape and dimensions back to "eeg_data" shape
    ic_len = bss_data.shape[1]
    bss_data = np.reshape(bss_data, [ev_len, t_len, ic_len])
    new_order = [0, 0, 0]
    # TODO: Check the following order
    new_order[ev_dim] = 0
    new_order[ch_dim] = 2
    new_order[t_dim] = 1
    bss_data = bss_data.transpose(new_order)

    # End
    return ica, bss_data
开发者ID:ctw,项目名称:eeglcf,代码行数:60,代码来源:lazy.py

示例8: ica

# 需要导入模块: from sklearn.decomposition import FastICA [as 别名]
# 或者: from sklearn.decomposition.FastICA import fit [as 别名]
 def ica(self):
     '''
     Perform ICA on the data
         source_matrix -- rows are sources, columns are time points, values are ?
         mixing_matrix -- rows are electrodes, columns are source, values are contributions of the electrode to the source
     '''
     ica = FastICA(self.number_of_sources)
     ica.fit(self.data)
     self.mixing_matrix = ica.mixing_  # estimated mixing matrix
开发者ID:kuz,项目名称:BrainActivity3D,代码行数:11,代码来源:sourcelocalizer.py

示例9: independent_component

# 需要导入模块: from sklearn.decomposition import FastICA [as 别名]
# 或者: from sklearn.decomposition.FastICA import fit [as 别名]
def independent_component(x, y):
    clf = FastICA(random_state=1)
    clf.fit(x.reshape(-1, 1), y)
    comp = clf.components_[0][0]
    mm = clf.get_mixing_matrix()[0][0]
    sources = clf.sources_.flatten()
    src_max = max(sources)
    src_min = min(sources)
    return [comp, mm, src_max, src_min]
开发者ID:Diviyan-Kalainathan,项目名称:causal-humans,代码行数:11,代码来源:binary_features.py

示例10: ICA

# 需要导入模块: from sklearn.decomposition import FastICA [as 别名]
# 或者: from sklearn.decomposition.FastICA import fit [as 别名]
def ICA(model_data, components = None, transform_data = None):
    t0 = time()
    ica = FastICA(n_components=components)
    if transform_data == None:
        projection = ica.fit_transform(model_data)
    else:
        ica.fit(model_data)
        projection = ica.transform(transform_data)
    print "ICA Time: %0.3f" % (time() - t0)
    return projection
开发者ID:krishnatray,项目名称:CS7641,代码行数:12,代码来源:Clustering.py

示例11: var_test_ica

# 需要导入模块: from sklearn.decomposition import FastICA [as 别名]
# 或者: from sklearn.decomposition.FastICA import fit [as 别名]
def var_test_ica(flux_arr_orig, exposure_list, wavelengths, low_n=3, hi_n=100, n_step=1, show_plots=False,
                    show_summary_plot=False, save_summary_plot=True, test_ind=7, real_time_progress=False,
                    idstr=None):
    start_ind = np.min(np.nonzero(flux_arr_orig[test_ind]))
    end_ind = np.max(np.nonzero(flux_arr_orig[test_ind]))

    perf_table = Table(names=["n", "avg_diff2", "max_diff_scaled"], dtype=["i4", "f4", "f4"])
    if hi_n > flux_arr_orig.shape[0]-1:
        hi_n = flux_arr_orig.shape[0]-1

    for n in range(low_n, hi_n, n_step):
        ica = FastICA(n_components = n, whiten=True, max_iter=750, random_state=1234975)
        test_arr = flux_arr_orig[test_ind].copy()

        flux_arr = np.vstack([flux_arr_orig[:test_ind], flux_arr_orig[test_ind+1:]])
        ica_flux_arr = flux_arr.copy()  #keep back one for testing
        ica.fit(ica_flux_arr)

        ica_trans = ica.transform(test_arr.copy(), copy=True)
        ica_rev = ica.inverse_transform(ica_trans.copy(), copy=True)

        avg_diff2 = np.ma.sum(np.ma.power(test_arr-ica_rev[0],2)) / (end_ind-start_ind)
        max_diff_scaled = np.ma.max(np.ma.abs(test_arr-ica_rev[0])) / (end_ind-start_ind)
        perf_table.add_row([n, avg_diff2, max_diff_scaled])

        if real_time_progress:
            print "n: {:4d}, avg (diff^2): {:0.5f}, scaled (max diff): {:0.5f}".format(n, avg_diff2, max_diff_scaled)

        if show_plots:
            plt.plot(wavelengths, test_arr)
            plt.plot(wavelengths, ica_rev[0])
            plt.plot(wavelengths, test_arr-ica_rev[0])

            plt.legend(['orig', 'ica', 'orig-ica'])
            plt.xlim((wavelengths[start_ind], wavelengths[end_ind]))

            plt.title("n={}, avg (diff^2)={}".format(n, avg_diff2))
            plt.tight_layout()
            plt.show()
            plt.close()

    if show_summary_plot or save_summary_plot:
        plt.plot(perf_table['n'], perf_table['avg_diff2'])
        plt.plot(perf_table['n'], perf_table['max_diff_scaled'])
        plt.title("performance")
        plt.tight_layout()
        if show_summary_plot:
            plt.show()
        if save_summary_plot:
            if idstr is None:
                idstr = random.randint(1000000, 9999999)
            plt.savefig("ica_performance_{}.png".format(idstr))
        plt.close()

    return perf_table
开发者ID:dcunning11235,项目名称:skyflux,代码行数:57,代码来源:ICA_continuua.py

示例12: test_fastica_nowhiten

# 需要导入模块: from sklearn.decomposition import FastICA [as 别名]
# 或者: from sklearn.decomposition.FastICA import fit [as 别名]
def test_fastica_nowhiten():
    m = [[0, 1], [1, 0]]
    ica = FastICA(whiten=False, random_state=0)
    ica.fit(m)
    ica.mixing_

    # test for issue #697
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter("always")
        ica = FastICA(n_components=1, whiten=False, random_state=0)
        ica.fit(m)  # should raise warning
        assert_true(len(w) == 1)  # 1 warning should be raised
开发者ID:cpa,项目名称:scikit-learn,代码行数:14,代码来源:test_fastica.py

示例13: independent_component

# 需要导入模块: from sklearn.decomposition import FastICA [as 别名]
# 或者: from sklearn.decomposition.FastICA import fit [as 别名]
def independent_component( (x, y) ):
    lenX = len(x)
    newX = np.array(x).reshape(lenX, 1)
    g = FastICA()
    g.fit(newX, y)
    ret = [0.0, 0.0, 0.0, 0.0]
    ret[0] = g.components_[0][0]
    ret[1] = g.get_mixing_matrix()[0][0]
    sources = g.sources_.flatten()
    ret[2] = max(sources)
    ret[3] = min(sources)
    return ret
开发者ID:sibelius,项目名称:CauseEffect,代码行数:14,代码来源:independent_component.py

示例14: learnICADict

# 需要导入模块: from sklearn.decomposition import FastICA [as 别名]
# 或者: from sklearn.decomposition.FastICA import fit [as 别名]
def learnICADict(features, components=25):
	

	icaHOG = FastICA(n_components=components)
	icaHOF = FastICA(n_components=components)

	icaHOG.fit(np.array([x['hog'] for x in features]).T)
	icaHOF.fit(np.array([x['hof'] for x in features]).T)

	hogComponents = icaHOG.components_.T
	hofComponents = icaHOF.components_.T

	return hogComponents, hofComponents
开发者ID:MerDane,项目名称:pyKinectTools,代码行数:15,代码来源:FeatureUtils.py

示例15: main

# 需要导入模块: from sklearn.decomposition import FastICA [as 别名]
# 或者: from sklearn.decomposition.FastICA import fit [as 别名]
def main(mode):
    path = '/local/attale00/AFLW_ALL/'
    path_ea = '/local/attale00/AFLW_cropped/mouth_img_error/'
#    
    fileNames = utils.getAllFiles(path_ea);

    
    labs=utils.parseLabelFiles(path+'/labels/labels','mouth_opening',fileNames,cutoffSeq='.png',suffix='_face0.labels')
    
    testSet = fg.dataContainer(labs)
    components = 150
    roi=None
    X=fg.getAllImagesFlat(path_ea,testSet.fileNames,(40,120),roi=roi)
#    X=fg.getAllImagesFlat(path_ea,testSet.fileNames,(120,40),roi=roi,resizeFactor = .5)
# 
# perform ICA
    if mode not in ['s','v']:
        ica = FastICA(n_components=components,whiten=True)
        ica.fit(X)
        meanI=np.mean(X,axis=0)
        X1=X-meanI
        data=ica.transform(X1)
        filters=ica.components_
        
    elif mode in ['s','v']:
        W=np.load('/home/attale00/Desktop/classifiers/patches/filterMP1.npy')
        m=np.load('/home/attale00/Desktop/classifiers/patches/meanIMP1.npy')
        X1=X-m
        data=np.dot(X1,W.T)    
    
    for i in range(len(fileNames)):
            testSet.data[i].extend(data[i,:])
            
    print 'feature vector length: {}'.format(len(testSet.data[0]))

    testSet.targetNum=map(utils.mapMouthLabels2Two,testSet.target)
    rf=classifierUtils.standardRF(max_features = np.sqrt(len(testSet.data[0])),min_split=13,max_depth=40)
    #rf = svm.NuSVC()
    #rf = linear_model.SGDClassifier(loss='perceptron', eta0=1, learning_rate='constant', penalty=None)    
    if mode in ['s','v']:
        print 'Classifying with loaded classifier'
        _classifyWithOld(path,testSet,mode)
    elif mode in ['c']:
        print 'cross validation of data'
        rValues = classifierUtils.dissectedCV(rf,testSet)
        pickle.dump(rValues,open('errorpatch_ica','w'))
    elif mode in ['save']:
        print 'saving new classifier'
        _saveRF(testSet,rf,filters=filters,meanI=meanI)
    else:
        print 'not doing anything'
开发者ID:alex-attinger,项目名称:fc_attributes,代码行数:53,代码来源:aflw_errorpatches_ica.py


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