sklearn降维方法举例
以datasets.digits数据为例导入相关包
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import time
from sklearn.datasets import load_digits
大样本数据的可视化是一个相对比较麻烦的事情,
一般情况下我们都要用到降维的方法先处理特征。我们找一个例子来看看,可以怎么做,比如我们数据集取经典的『手写数字集』
Each datapoint is a 8x8 image of a digit.
Classes->10
Samples per class->180
Samples total->1797
Dimensionality->64
Features integers->0-16
导入数据,0,1,2,3,4,5,6这7个数字的手写图像
digits = load_digits(n_class=7)#integer
X = digits.data
y = digits.target
n_samples,n_features = X.shape
输出图像
from matplotlib import offsetbox
def plot_embedding(X, title=None):
x_min, x_max = np.min(X, 0), np.max(X, 0)
X = (X - x_min) / (x_max - x_min)#正则化
print X
plt.figure(figsize=(10, 10))
ax = plt.subplot(111)
for i in range(X.shape[0]):
plt.text(X[i, 0], X[i, 1], str(digits.target[i]),
color=plt.cm.Set1(y[i] / 10.),
fontdict={
'weight': 'bold', 'size': 12})
#打印彩色字体
if hasattr(offsetbox, 'AnnotationBbox'):
# only print thumbnails with matplotlib > 1.0
shown_images = np.array([[1., 1.]]) # just something big
for i in range(digits.data.shape[0]):
dist = np.sum((X[i] - shown_images) ** 2, 1)
if np.min(dist) < 4e-3:
# don't show points that are too close
continue
shown_images = np.r_[shown_images, [X[i]]]
imagebox = offsetbox.AnnotationBbox(
offsetbox.OffsetImage(digits.images[i], cmap=plt.cm.gray_r),
X[i])
ax.add_artist(imagebox)#输出图上输出图片
plt.xticks([]), plt.yticks([])
if title is not None:
plt.title(title)
1.随机投射(Random-Projection)
首先我们来看一个问题, 如果你手头有一组数据 X ∈ R n X \in R^n X∈Rn, 它的维数太高, 从而不得不进行降维至 R k R^k Rk, 你会怎么办?
相信不少人反射性地求它的 x ’ x x’x x’x,然后转化为延最大方差展开的问题。 当然这个方法需要求解固有值和固有向量。对于测试用的小数据一切似乎都很好, 但如果我给你的是50G大小csv格式的Twitter发言呢?如果需要对全部单词降维, 恐怕半个月吧。 因此我们需要个更加快速的方法。
那么现在再来想, 既然要快, 那我们就用个最简单的方法: 随机在高维空间里选几个单位向量 e i e_i ei, 但注意, 这里我们仅仅要求是单位向量, 并没有要求它们之间必须正交 < e i , e j > = 0 <e_i,e_j>=0 <ei,ej