• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python decomposition.FastICA类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: test_inverse_transform

def test_inverse_transform():
    # Test FastICA.inverse_transform
    n_features = 10
    n_samples = 100
    n1, n2 = 5, 10
    rng = np.random.RandomState(0)
    X = rng.random_sample((n_samples, n_features))
    expected = {(True, n1): (n_features, n1),
                (True, n2): (n_features, n2),
                (False, n1): (n_features, n2),
                (False, n2): (n_features, n2)}
    for whiten in [True, False]:
        for n_components in [n1, n2]:
            n_components_ = (n_components if n_components is not None else
                             X.shape[1])
            ica = FastICA(n_components=n_components, random_state=rng,
                          whiten=whiten)
            with warnings.catch_warnings(record=True):
                # catch "n_components ignored" warning
                Xt = ica.fit_transform(X)
            expected_shape = expected[(whiten, n_components_)]
            assert_equal(ica.mixing_.shape, expected_shape)
            X2 = ica.inverse_transform(Xt)
            assert_equal(X.shape, X2.shape)

            # reversibility test in non-reduction case
            if n_components == X.shape[1]:
                assert_array_almost_equal(X, X2)
开发者ID:manhhomienbienthuy,项目名称:scikit-learn,代码行数:28,代码来源:test_fastica.py


示例2: getHeartRate

def getHeartRate(window, lastHR):
    # Normalize across the window to have zero-mean and unit variance
    mean = np.mean(window, axis=0)
    std = np.std(window, axis=0)
    normalized = (window - mean) / std

    # Separate into three source signals using ICA
    ica = FastICA()
    srcSig = ica.fit_transform(normalized)

    # Find power spectrum
    powerSpec = np.abs(np.fft.fft(srcSig, axis=0))**2
    freqs = np.fft.fftfreq(WINDOW_SIZE, 1.0 / FPS)

    # Find heart rate
    maxPwrSrc = np.max(powerSpec, axis=1)
    validIdx = np.where((freqs >= MIN_HR_BPM / SEC_PER_MIN) & (freqs <= MAX_HR_BMP / SEC_PER_MIN))
    validPwr = maxPwrSrc[validIdx]
    validFreqs = freqs[validIdx]
    maxPwrIdx = np.argmax(validPwr)
    hr = validFreqs[maxPwrIdx]
    print hr

    #plotSignals(normalized, "Normalized color intensity")
    #plotSignals(srcSig, "Source signal strength")
    #plotSpectrum(freqs, powerSpec)

    return hr
开发者ID:ibush,项目名称:231A_Project,代码行数:28,代码来源:hrFaceDetection.py


示例3: wrapper_fastica

 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,代码行数:7,代码来源:backend_sklearn.py


示例4: ica_analysis

    def ica_analysis(self, X_train, X_test, y_train, y_test, data_set_name):
        scl = RobustScaler()
        X_train_scl = scl.fit_transform(X_train)
        X_test_scl = scl.transform(X_test)
        
        ##
        ## ICA
        ##
        ica = FastICA(n_components=X_train_scl.shape[1])
        X_ica = ica.fit_transform(X_train_scl)
        
        ##
        ## Plots
        ##
        ph = plot_helper()

        kurt = kurtosis(X_ica)
        print(kurt)
        
        title = 'Kurtosis (FastICA) for ' + data_set_name
        name = data_set_name.lower() + '_ica_kurt'
        filename = './' + self.out_dir + '/' + name + '.png'
        
        ph.plot_simple_bar(np.arange(1, len(kurt)+1, 1),
                           kurt,
                           np.arange(1, len(kurt)+1, 1).astype('str'),
                           'Feature Index',
                           'Kurtosis',
                           title,
                           filename)
开发者ID:rbaxter1,项目名称:CS7641,代码行数:30,代码来源:part2.py


示例5: run_ica

def run_ica(data, comp):
    ica = FastICA(n_components=comp, whiten=True, max_iter=5000)
    data_out=np.zeros((comp,np.shape(data[0,:,0])[0],np.shape(data[0,0,:])[0]))
    for i in range(np.shape(data[0,:,0])[0]):
        print i
        data_out[:,i,:]=np.transpose(ica.fit_transform(np.transpose(data[:,i,:])))
    return data_out
开发者ID:rchau,项目名称:sleep-eeg,代码行数:7,代码来源:ICA.py


示例6: best_ica_nba

 def best_ica_nba(self):
     dh = data_helper()
     X_train, X_test, y_train, y_test = dh.get_nba_data()
     
     scl = RobustScaler()
     X_train_scl = scl.fit_transform(X_train)
     X_test_scl = scl.transform(X_test)
     
     ica = FastICA(n_components=X_train_scl.shape[1])
     X_train_transformed = ica.fit_transform(X_train_scl, y_train)
     X_test_transformed = ica.transform(X_test_scl)
     
     ## top 2
     kurt = kurtosis(X_train_transformed)
     i = kurt.argsort()[::-1]
     X_train_transformed_sorted = X_train_transformed[:, i]
     X_train_transformed = X_train_transformed_sorted[:,0:2]
     
     kurt = kurtosis(X_test_transformed)
     i = kurt.argsort()[::-1]
     X_test_transformed_sorted = X_test_transformed[:, i]
     X_test_transformed = X_test_transformed_sorted[:,0:2]
     
     # save
     filename = './' + self.save_dir + '/nba_ica_x_train.txt'
     pd.DataFrame(X_train_transformed).to_csv(filename, header=False, index=False)
     
     filename = './' + self.save_dir + '/nba_ica_x_test.txt'
     pd.DataFrame(X_test_transformed).to_csv(filename, header=False, index=False)
     
     filename = './' + self.save_dir + '/nba_ica_y_train.txt'
     pd.DataFrame(y_train).to_csv(filename, header=False, index=False)
     
     filename = './' + self.save_dir + '/nba_ica_y_test.txt'
     pd.DataFrame(y_test).to_csv(filename, header=False, index=False)
开发者ID:rbaxter1,项目名称:CS7641,代码行数:35,代码来源:part2.py


示例7: fit

    def fit(self, x, y, i=0):
        # if gaussian processes are being used, data dimensionality needs to be reduced before fitting
        if self.method[i] == 'GP':
            if self.reduce_dim == 'FastICA':
                print('Reducing dimensionality with ICA')
                do_ica = FastICA(n_components=self.n_components)
                self.do_reduce_dim = do_ica.fit(x)
            if self.reduce_dim == 'PCA':
                print('Reducing dimensionality with PCA')
                do_pca = PCA(n_components=self.n_components)
                self.do_reduce_dim = do_pca.fit(x)

            x = self.do_reduce_dim.transform(x)
        #try:
            print('Training model...')
        try:
            self.model.fit(x, y)
            self.goodfit = True
            print(self.model)
        except:
            self.goodfit = False
            if self.method[i] == 'GP':
                print('Model failed to train! (For GP this does not always indicate a problem, especially for low numbers of components.)')
                pass
            else:
                print('Model failed to train!')
                traceback.print_stack()

        if self.ransac:
            self.outliers = np.logical_not(self.model.inlier_mask_)
            print(str(np.sum(self.outliers)) + ' outliers removed with RANSAC')
开发者ID:USGS-Astrogeology,项目名称:PySAT,代码行数:31,代码来源:regression.py


示例8: test_inverse_transform

def test_inverse_transform():
    """Test FastICA.inverse_transform"""
    rng = np.random.RandomState(0)
    X = rng.random_sample((100, 10))
    rng = np.random.RandomState(0)
    X = rng.random_sample((100, 10))
    n_features = X.shape[1]
    expected = {(True, 5): (n_features, 5),
                (True, 10): (n_features, 10),
                (False, 5): (n_features, 10),
                (False, 10): (n_features, 10)}

    for whiten in [True, False]:
        for n_components in [5, 10]:
            ica = FastICA(n_components=n_components, random_state=rng,
                          whiten=whiten)
            Xt = ica.fit_transform(X)
            expected_shape = expected[(whiten, n_components)]
            assert_equal(ica.mixing_.shape, expected_shape)
            X2 = ica.inverse_transform(Xt)
            assert_equal(X.shape, X2.shape)

            # reversibility test in non-reduction case
            if n_components == X.shape[1]:
                assert_array_almost_equal(X, X2)
开发者ID:cpa,项目名称:scikit-learn,代码行数:25,代码来源:test_fastica.py


示例9: test_ica

def test_ica(eng):
    t = linspace(0, 10, 100)
    s1 = sin(t)
    s2 = square(sin(2*t))
    x = c_[s1, s2, s1+s2]
    random.seed(0)
    x += 0.001*random.randn(*x.shape)
    x = fromarray(x, engine=eng)

    def normalize_ICA(s, aT):
        a = aT.T
        c = a.sum(axis=0)
        return s*c, (a/c).T

    from sklearn.decomposition import FastICA
    ica = FastICA(n_components=2, fun='cube', random_state=0)
    s1 = ica.fit_transform(x.toarray())
    aT1 = ica.mixing_.T
    s1, aT1 = normalize_ICA(s1, aT1)

    s2, aT2 = ICA(k=2, svd_method='direct', max_iter=200, seed=0).fit(x)
    s2, aT2 = normalize_ICA(s2, aT2)
    tol=1e-1
    assert allclose_sign_permute(s1, s2, atol=tol)
    assert allclose_sign_permute(aT1, aT2, atol=tol)
开发者ID:thunder-project,项目名称:thunder-factorization,代码行数:25,代码来源:test_algorithms.py


示例10: ica

    def ica(self, n_components=None):
        """Return result from independent component analysis.

        X = SA + m

        Sklearn's FastICA implementation is used.

        Parameters
        ----------
        n_components : int, optional
            Number of ICA components.

        Returns
        -------
        source : Matrix
            Estimated source matrix (S)
        mixing_matrix : Matrix
            Estimated mixing matrix (A)
        mean_vector : brede.core.vector.Vector
            Estimated mean vector

        References
        ----------
        http://scikit-learn.org/stable/modules/decomposition.html#ica

        """
        if n_components is None:
            n_components = int(np.ceil(np.sqrt(float(min(self.shape)) / 2)))

        ica = FastICA(n_components=n_components)
        sources = Matrix(ica.fit_transform(self.values), index=self.index)
        mixing_matrix = Matrix(ica.mixing_.T, columns=self.columns)
        mean_vector = Vector(ica.mean_, index=self.columns)

        return sources, mixing_matrix, mean_vector
开发者ID:fnielsen,项目名称:brede,代码行数:35,代码来源:matrix.py


示例11: __create_image_obser

 def __create_image_obser(self, image_observations) :
     """
     Creation of a space in which the images will be compared (learning stage).
     Firstly PCA is applied in order to reduce the number of features in the
     images. Reduction is done so that 99% of measured variance is covered.
     
     After that, ICA is performed on the coefficients calculated by transforming
     (reducing) the face images with PCA. From the learned ICA components
     basis_images (vectors), original images coefficients and transformation
     for new comming images are extracted.
     """
     pca = PCA()
     pca.fit(image_observations)
     sum = 0
     components_to_take = 0
     for ratio in pca.explained_variance_ratio_:
         components_to_take += 1
         sum += ratio
         if (sum > 0.99):
             break 
     print("PCA reduces the number of dimensions to: " + str(components_to_take))
     pca = PCA(whiten=True, n_components=components_to_take)
     self.__transformed_images = pca.fit_transform(image_observations)
     self.__transformed_images_mean = np.mean(self.__transformed_images, axis=0)
     self.__transformed_images -= self.__transformed_images_mean
     self.__pca = pca
     
     
     ica = FastICA(whiten=True, max_iter=100000)
     self.__original_images_repres = ica.fit_transform(self.__transformed_images)
     self.__basis_images = ica.mixing_.T
     self.__transformation = ica.components_
开发者ID:flor385,项目名称:face_detection_FER_2014,代码行数:32,代码来源:recognition.py


示例12: ICA

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,代码行数:32,代码来源:ica.py


示例13: RunICAScikit

    def RunICAScikit():
      totalTimer = Timer()

      # Load input dataset.
      data = np.genfromtxt(self.dataset, delimiter=',')

      opts = {}
      if "num_components" in options:
        opts["n_components"] = int(options.pop("num_components"))

      if "algorithm" in options:
        opts["algorithm"] = str(options.pop("algorithm"))
        if opts["algorithm"] not in ['parallel', 'deflation']:
          Log.Fatal("Invalid value for algorithm: "+ str(algorithm.group(1))+" .Must be either parallel or deflation")
          return -1

      if "function" in options:
        opts["fun"] = str(options.pop("function"))
        if opts["fun"] not in ['logcosh', 'exp', 'cube']:
          Log.Fatal("Invalid value for fun: "+ str(fun.group(1))+" .Must be either logcosh,exp or cube")
          return -1

      if "tolerance" in options:
        opts["tol"] = float(options.pop("tolerance"))

      try:
        # Perform ICA.
        with totalTimer:
          model = FastICA(**opts)
          ic = model.fit(data).transform(data)
      except Exception as e:
        return -1

      return totalTimer.ElapsedTime()
开发者ID:rcurtin,项目名称:benchmarks,代码行数:34,代码来源:ica.py


示例14: dim_survey

def dim_survey(X, entry_id):

    # convert to numpy
    X = np.array(X)

    # run the reduction.
    X_pca = PCA(n_components=3).fit_transform(X)
    X_tsne = TSNE(n_components=3).fit_transform(X)
    X_ica = FastICA(n_components=3).fit_transform(X)

    # connect to db.
    with mongoctx() as db:

        # update the stuff.
        db['entry'].update(
            {
                '_id': ObjectId(entry_id)
            },
            {
                '$set': {
                    'pca': X_pca.tolist(),
                    'tsne': X_tsne.tolist(),
                    'ica': X_ica.tolist(),
                }
            }
        )
开发者ID:jim-bo,项目名称:dimwit,代码行数:26,代码来源:tasks.py


示例15: main

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,代码行数:60,代码来源:MultiPiePascal128.py


示例16: filter_frames

    def filter_frames(self, data):
        logging.debug("I am starting the old componenty vous")
        data = data[0]
        print 'The length of the data is'+str(data.shape)
        sh = data.shape
        newshape = (np.prod(sh[:-1]), sh[-1])
        print "The shape of the data is:"+str(data.shape) + str(newshape)
        data = np.reshape(data, (newshape))
        # data will already be shaped correctly
        logging.debug("Making the matrix")
        ica = FastICA(n_components=self.parameters['number_of_components'],
                      algorithm='parallel',
                      whiten=self.parameters['whiten'],
                      w_init=self.parameters['w_init'],
                      random_state=self.parameters['random_state'])
        logging.debug("Performing the fit")
        data = self.remove_nan_inf(data)  #otherwise the fit flags up an error for obvious reasons
#         print "I'm here"
        S_ = ica.fit_transform(data)
#         print "S_Shape is:"+str(S_.shape)
#         print "self.images_shape:"+str(self.images_shape)
        scores = np.reshape(S_, (self.images_shape))
        eigenspectra = ica.components_
        logging.debug("mange-tout")
        return [scores, eigenspectra]
开发者ID:FedeMPouzols,项目名称:Savu,代码行数:25,代码来源:ica.py


示例17: align

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*nvoxel,nTR))
    for m in range(nsubjs):
        bX[m*nvoxel:(m+1)*nvoxel,:] = stats.zscore(movie_data[:, :, m].T ,axis=0, ddof=1).T
    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)
    St = ica.fit_transform(bX.T)
    ES = St.T
    bW = ica.mixing_

    R = np.zeros((nvoxel,nfeature,nsubjs))
    for m in range(nsubjs):
        R[:,:,m] = bW[m*nvoxel:(m+1)*nvoxel,:]

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


示例18: reduceDataset

 def reduceDataset(self,nr=3,method='PCA'):
     '''It reduces the dimensionality of a given dataset using different techniques provided by Sklearn library
      Methods available:
                         'PCA'
                         'FactorAnalysis'
                         'KPCArbf','KPCApoly'
                         'KPCAcosine','KPCAsigmoid'
                         'IPCA'
                         'FastICADeflation'
                         'FastICAParallel'
                         'Isomap'
                         'LLE'
                         'LLEmodified'
                         'LLEltsa'
     '''
     dataset=self.ModelInputs['Dataset']
     #dataset=self.dataset[Model.in_columns]
     #dataset=self.dataset[['Humidity','TemperatureF','Sea Level PressureIn','PrecipitationIn','Dew PointF','Value']]
     #PCA
     if method=='PCA':
         sklearn_pca = sklearnPCA(n_components=nr)
         reduced = sklearn_pca.fit_transform(dataset)
     #Factor Analysis
     elif method=='FactorAnalysis':
         fa=FactorAnalysis(n_components=nr)
         reduced=fa.fit_transform(dataset)
     #kernel pca with rbf kernel
     elif method=='KPCArbf':
         kpca=KernelPCA(nr,kernel='rbf')
         reduced=kpca.fit_transform(dataset)
     #kernel pca with poly kernel
     elif method=='KPCApoly':
         kpca=KernelPCA(nr,kernel='poly')
         reduced=kpca.fit_transform(dataset)
     #kernel pca with cosine kernel
     elif method=='KPCAcosine':
         kpca=KernelPCA(nr,kernel='cosine')
         reduced=kpca.fit_transform(dataset)
     #kernel pca with sigmoid kernel
     elif method=='KPCAsigmoid':
         kpca=KernelPCA(nr,kernel='sigmoid')
         reduced=kpca.fit_transform(dataset)
     #ICA
     elif method=='IPCA':
         ipca=IncrementalPCA(nr)
         reduced=ipca.fit_transform(dataset)
     #Fast ICA
     elif method=='FastICAParallel':
         fip=FastICA(nr,algorithm='parallel')
         reduced=fip.fit_transform(dataset)
     elif method=='FastICADeflation':
         fid=FastICA(nr,algorithm='deflation')
         reduced=fid.fit_transform(dataset)
     elif method == 'All':
         self.dimensionalityReduction(nr=nr)
         return self
     
     self.ModelInputs.update({method:reduced})
     self.datasetsAvailable.append(method)
     return self
开发者ID:UIUC-SULLIVAN,项目名称:ThesisProject_Andrea_Mattera,代码行数:60,代码来源:Classes.py


示例19: dimensionalityReduction

 def dimensionalityReduction(self,nr=5):
     '''It applies all the dimensionality reduction techniques available in this class:
     Techniques available:
                         'PCA'
                         'FactorAnalysis'
                         'KPCArbf','KPCApoly'
                         'KPCAcosine','KPCAsigmoid'
                         'IPCA'
                         'FastICADeflation'
                         'FastICAParallel'
                         'Isomap'
                         'LLE'
                         'LLEmodified'
                         'LLEltsa'
     '''
     dataset=self.ModelInputs['Dataset']
     sklearn_pca = sklearnPCA(n_components=nr)
     p_components = sklearn_pca.fit_transform(dataset)
     fa=FactorAnalysis(n_components=nr)
     factors=fa.fit_transform(dataset)
     kpca=KernelPCA(nr,kernel='rbf')
     rbf=kpca.fit_transform(dataset)
     kpca=KernelPCA(nr,kernel='poly')
     poly=kpca.fit_transform(dataset)
     kpca=KernelPCA(nr,kernel='cosine')
     cosine=kpca.fit_transform(dataset)
     kpca=KernelPCA(nr,kernel='sigmoid')
     sigmoid=kpca.fit_transform(dataset)
     ipca=IncrementalPCA(nr)
     i_components=ipca.fit_transform(dataset)
     fip=FastICA(nr,algorithm='parallel')
     fid=FastICA(nr,algorithm='deflation')
     ficaD=fip.fit_transform(dataset)
     ficaP=fid.fit_transform(dataset)
     '''isomap=Isomap(n_components=nr).fit_transform(dataset)
     try:
         lle1=LocallyLinearEmbedding(n_components=nr).fit_transform(dataset)
     except ValueError:
         lle1=LocallyLinearEmbedding(n_components=nr,eigen_solver='dense').fit_transform(dataset)
     try:
         
         lle2=LocallyLinearEmbedding(n_components=nr,method='modified').fit_transform(dataset)
     except ValueError:
         lle2=LocallyLinearEmbedding(n_components=nr,method='modified',eigen_solver='dense').fit_transform(dataset) 
     try:
         lle3=LocallyLinearEmbedding(n_components=nr,method='ltsa').fit_transform(dataset)
     except ValueError:
         lle3=LocallyLinearEmbedding(n_components=nr,method='ltsa',eigen_solver='dense').fit_transform(dataset)'''
     values=[p_components,factors,rbf,poly,cosine,sigmoid,i_components,ficaD,ficaP]#,isomap,lle1,lle2,lle3]
     keys=['PCA','FactorAnalysis','KPCArbf','KPCApoly','KPCAcosine','KPCAsigmoid','IPCA','FastICADeflation','FastICAParallel']#,'Isomap','LLE','LLEmodified','LLEltsa']
     self.ModelInputs.update(dict(zip(keys, values)))
     [self.datasetsAvailable.append(key) for key in keys ]
     
     #debug
     #dataset=pd.DataFrame(self.ModelInputs['Dataset'])
     #dataset['Output']=self.ModelOutput
     #self.debug['Dimensionalityreduction']=dataset
     ###
     return self
开发者ID:UIUC-SULLIVAN,项目名称:ThesisProject_Andrea_Mattera,代码行数:59,代码来源:Classes.py


示例20: ica

    def ica(self, n_components=None, sources='left'):
        """Return result from independent component analysis.

        X = SA + m

        Sklearn's FastICA implementation is used.

        When sources=left the sources are returned in the first (left) matrix
        and the mixing matrix is returned in the second (right) matrix,
        corresponding to X = SA.

        When sources=right the sources are returned in the second matrix while
        the mixing matrix is returned in the first, corresponding to X = AS.

        Parameters
        ----------
        n_components : int, optional
            Number of ICA components.
        sources : left or right, optional
            Indicates whether the sources should be the left or right matrix.

        Returns
        -------
        first : Matrix
            Estimated source matrix (S) if sources=left.
        second : Matrix
            Estimated mixing matrix (A) if sources=right.
        mean_vector : brede.core.vector.Vector
            Estimated mean vector

        References
        ----------
        http://scikit-learn.org/stable/modules/decomposition.html#ica

        """
        if n_components is None:
            min_shape = min(self.shape[0], len(self._eeg_columns))
            n_components = int(np.ceil(sqrt(float(min_shape) / 2)))

        ica = FastICA(n_components=n_components)

        if sources == 'left':
            sources = Matrix(ica.fit_transform(
                self.ix[:, self._eeg_columns].values),
                index=self.index)
            mixing_matrix = Matrix(ica.mixing_.T, columns=self._eeg_columns)
            mean_vector = Vector(ica.mean_, index=self._eeg_columns)
            return sources, mixing_matrix, mean_vector

        elif sources == 'right':
            sources = Matrix(ica.fit_transform(
                self.ix[:, self._eeg_columns].values.T).T,
                columns=self._eeg_columns)
            mixing_matrix = Matrix(ica.mixing_, index=self.index)
            mean_vector = Vector(ica.mean_, index=self.index)
            return mixing_matrix, sources, mean_vector

        else:
            raise ValueError('Wrong argument to "sources"')
开发者ID:fnielsen,项目名称:brede,代码行数:59,代码来源:core.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python decomposition.IncrementalPCA类代码示例发布时间:2022-05-27
下一篇:
Python decomposition.FactorAnalysis类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap