1.2 Data Visualization & Dimension Reduction
Last updated
Was this helpful?
Was this helpful?
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn.preprocessing import StandardScaler
from matplotlib import pyplot as pltiris_dataset = load_iris()
X = iris_dataset['data']
y = iris_dataset['target']
names = iris_dataset['target_names']
X = StandardScaler().fit_transform(X) # Z score scalingX2d = PCA(2).fit_transform(X)
fig,ax = plt.subplots(figsize=(4.5,4))
for i in range(3):
plt.scatter(X2d[y==i,0],X2d[y==i,1],label=names[i])
ax.set_xlabel("PC-1")
ax.set_ylabel("PC-2")
plt.legend()
plt.show()
#plt.savefig("PCA-plot.png",bbox_inches="tight")X2d = TSNE(2).fit_transform(X)
fig,ax = plt.subplots(figsize=(4.5,4))
for i in range(3):
plt.scatter(X2d[y==i,0],X2d[y==i,1],label=names[i])
ax.set_xlabel("tSNE-1")
ax.set_ylabel("tSNE-2")
plt.legend()
plt.show()
#plt.savefig("tSNE-plot.png",bbox_inches="tight")library("Rtsne")
library("ggplot2")X <- as.matrix(iris[,1:4])
X <- scale(X, center = T, scale = T)pca.res <- prcomp(X, center = F, scale = F, rank. = 2)
iris$PC1 <- pca.res$x[,1]
iris$PC2 <- pca.res$x[,2]
ggplot(iris, aes(x=PC1, y=PC2,color=species)) + geom_point() + theme_bw()tsne.res <- Rtsne(X, dims = 2, check_duplicates = F)
iris$tSNE1 <- tsne.res$Y[,1]
iris$tSNE2 <- tsne.res$Y[,2]
ggplot(iris, aes(x=tSNE1, y=tSNE2,color=species)) + geom_point() + theme_bw()