Beispiel #1
0
    def fit(self, data):
        max_sir = None
        self.ica = None
        for _ in range(self.n_iter):
            fca = FastICA(n_components=self.n_components,
                          max_iter=self.max_iter,
                          algorithm='deflation')
            fca.fit(data)
#            try:

            new_components = sorted(zip(fca.components_, np.argmax(np.abs(fca.components_), axis=1)), key= lambda x: x[1])
            new_components = np.stack(new_components)
            new_components = np.array([x[0] for x in new_components])
            fca.components_ = new_components

            m = new_components/(abs(norm(new_components, axis=1)).reshape(-1,1)) - np.identity(data.shape[1])
            sir = norm(m, axis=1)
#             except:
#                continue
            sir = -10*np.log10(sir).sum()
            # in the paper its >
            if max_sir is None or sir > max_sir:
                self.max_sir = sir
                max_sir = sir
                self.sir_log.append(sir)
                self.ica = fca
        return self.ica
def PerformIca(X,Y,num_components,random_state):
    result = {}
    algo = FastICA(random_state=random_state,max_iter=800)
    algo.fit(X)
    full_mixing_matrix = algo.mixing_
    full_unmixing_matrix = algo.components_
    _x = algo.transform(X)
    kt_value = np.abs(kt(_x))
    largest_kt_values_idx = np.argsort(kt_value)[::-1]
    result["ica_kt_all"] = kt_value

    for n in num_components:
        prefix = "ica_" + str(n) + "_"
        component_idx_to_select = largest_kt_values_idx[0:n]
        mixing_matrix = full_mixing_matrix.T[component_idx_to_select,:].T
        unmixing_matrix = full_unmixing_matrix[component_idx_to_select,:]
        algo.components_ = unmixing_matrix
        algo.mixing_ = mixing_matrix

        result[prefix+"mm"] = mixing_matrix
        result[prefix+"umm"] = unmixing_matrix

        _x = algo.transform(X)
        result[prefix+"data"] = _x
        X_recons = algo.inverse_transform(_x)
        result[prefix+"reconstruction_error"] = ComputeReconstructionSSE(X,X_recons)
        n_kt_value = kt_value[component_idx_to_select]
        avg_kt = n_kt_value.mean()
        #print("ICA num dim {0} : reconstruction error {1} avg kt {2}".format(str(n),str(result[prefix+"reconstruction_error"]),str(avg_kt)))
        #print(np.sort(n_kt_value))
    return result
def generate_components(
    images,
    hemi,
    term_scores=None,
    n_components=20,
    random_state=42,
    out_dir=None,
    memory=Memory(cachedir="nilearn_cache"),
):
    """
        images: list
            Can be nibabel images, can be file paths.
    """
    # Create grey matter mask from mni template
    target_img = datasets.load_mni152_template()

    # Reshape & mask images
    print("%s: Reshaping and masking images; may take time." % hemi)
    if hemi == "wb":
        masker = GreyMatterNiftiMasker(target_affine=target_img.affine, target_shape=target_img.shape, memory=memory)

    else:  # R and L maskers
        masker = HemisphereMasker(
            target_affine=target_img.affine, target_shape=target_img.shape, memory=memory, hemisphere=hemi
        )
    masker = masker.fit()

    # Images may fail to be transformed, and are of different shapes,
    # so we need to trasnform one-by-one and keep track of failures.
    X = []  # noqa
    xformable_idx = np.ones((len(images),), dtype=bool)
    for ii, im in enumerate(images):
        img = cast_img(im, dtype=np.float32)
        img = clean_img(img)
        try:
            X.append(masker.transform(img))
        except Exception as e:
            print("Failed to mask/reshape image %d/%s: %s" % (im.get("collection_id", 0), op.basename(im), e))
            xformable_idx[ii] = False

    # Now reshape list into 2D matrix
    X = np.vstack(X)  # noqa

    # Run ICA and map components to terms
    print("%s: Running ICA; may take time..." % hemi)
    fast_ica = FastICA(n_components=n_components, random_state=random_state)
    fast_ica = memory.cache(fast_ica.fit)(X.T)
    ica_maps = memory.cache(fast_ica.transform)(X.T).T

    # Tomoki's suggestion to normalize components_
    # X ~ ica_maps * fast_ica.components_
    #   = (ica_maps * f) * (fast_ica.components_ / f)
    #   = new_ica_map * new_components_
    C = fast_ica.components_
    factor = np.sqrt(np.multiply(C, C).sum(axis=1, keepdims=True))  # (n_components x 1)
    ica_maps = np.multiply(ica_maps, factor)
    fast_ica.components_ = np.multiply(C, 1.0 / (factor + 1e-12))

    if term_scores is not None:
        terms = term_scores.keys()
        term_matrix = np.asarray(term_scores.values())
        term_matrix[term_matrix < 0] = 0
        term_matrix = term_matrix[:, xformable_idx]  # terms x images
        # Don't use the transform method as it centers the data
        ica_terms = np.dot(term_matrix, fast_ica.components_.T).T

    # 2015/12/26 - sign matters for comparison, so don't do this!
    # 2016/02/01 - sign flipping is ok for R-L comparison, but RL concat
    #              may break this.
    # Pretty up the results
    for idx, ic in enumerate(ica_maps):
        if -ic.min() > ic.max():
            # Flip the map's sign for prettiness
            ica_maps[idx] = -ic
            if term_scores:
                ica_terms[idx] = -ica_terms[idx]

    # Create image from maps, save terms to the image directly
    ica_image = NiftiImageWithTerms.from_image(masker.inverse_transform(ica_maps))
    if term_scores:
        ica_image.terms = dict(zip(terms, ica_terms.T))

    # Write to disk
    if out_dir is not None:
        out_path = op.join(out_dir, "%s_ica_components.nii.gz" % hemi)
        if not op.exists(op.dirname(out_path)):
            os.makedirs(op.dirname(out_path))
        ica_image.to_filename(out_path)
    return ica_image