scRNA-seq: How to use TSNE python implementation using precalculated PCA score/load?

Viewed 61

Python t-sne implementation from this resource: https://lvdmaaten.github.io/tsne/

Btw I'm a beginner to scRNA-seq.

What I am trying to do: Use a scRNA-seq data set and run t-SNE on it but with using previously calculated PCAs (I have PCA.score and PCA.load files)

Q1: I should be able to use my selected calculated PCAs in the tSNE, but which file do I use the pca.score or pca.load when running Y = tsne.tsne(X)?

Q2: I've tried removing/replacing parts of the PCA calculating code to attempt to remove PCA preprocessing but it always seems to give an error. What should I change for it to properly use my already PCA data and not calculate PCA from it again?

The piece of PCA processing code is this in its raw form:

def pca(X=np.array([]), no_dims=50):
    """
        Runs PCA on the NxD array X in order to reduce its dimensionality to
        no_dims dimensions.
    """

    print("Preprocessing the data using PCA...")
    (n, d) = X.shape
    X = X - np.tile(np.mean(X, 0), (n, 1))
    (l, M) = X  #np.linalg.eig(np.dot(X.T, X))
    Y = np.dot(X, M[:, 0:no_dims])

    return Y
1 Answers

You should use the PCA score.

As for not running pca, you can just comment out this line:

X = pca(X, initial_dims).real

What I did is to add a parameter do_pca and edit the function such:

def tsne(X=np.array([]), no_dims=2, initial_dims=50, perplexity=30.0,do_pca=True):
    """
        Runs t-SNE on the dataset in the NxD array X to reduce its
        dimensionality to no_dims dimensions. The syntaxis of the function is
        `Y = tsne.tsne(X, no_dims, perplexity), where X is an NxD NumPy array.
    """

    # Check inputs
    if isinstance(no_dims, float):
        print("Error: array X should have type float.")
        return -1
    if round(no_dims) != no_dims:
        print("Error: number of dimensions should be an integer.")
        return -1

    # Initialize variables
    if do_pca:
        X = pca(X, initial_dims).real
    (n, d) = X.shape
    max_iter = 50
    [.. rest stays the same..]

Using an example dataset, without commenting out that line:

import numpy as np
from sklearn.manifold import TSNE
from sklearn.datasets import load_digits
import matplotlib.pyplot as plt
import sys
import os
from tsne import *

X,y = load_digits(return_X_y=True,n_class=3)

If we run the default:

res = tsne(X=X,initial_dims=20,do_pca=True)
plt.scatter(res[:,0],res[:,1],c=y)

enter image description here

If we pass it a pca :

pc = pca(X)[:,:20]
res = tsne(X=pc,initial_dims=20,do_pca=False)
plt.scatter(res[:,0],res[:,1],c=y)

enter image description here

Related