中国mooc北京理工大学机器学习第一周(二)

---恢复内容开始---

今天学习第一周的第二课时:降维。

一、PCA主成分分析

主成分分析(Principal Component Analysis,PCA),是一种统计方法,直观来讲是把数据按照weights来筛选出主成分消除(或者隐蔽)不太重要的方面,使得高纬度数据投射到低维度。

直观来讲是应用了统计学上方差和协方差的知识,若协方差越接近1则表示A,B越接近;反之,若等于零则无关。

这里可以理解在一个高纬度角度(n维空间)去找一个角度使得从你这个角度看过去很多cov(A,B)很小的数值为零,这样就达到降低维度的目的。

对应cs231n的第一课到第三课房价问题和无监督学习。这里依旧只是学习sklearn的方法运用,如果有时间的话端午回来补这方面的欠缺。

    import matplotlib.pyplot as plt
    from sklearn.decomposition import PCA
    from sklearn.datasets import load_iris

data = load_iris() #load数据集和(x,y)。因为pca需要传入两个参数 y = data.target#这里的target是参数 X = data.data

pca = PCA(n_components=2)#实例化 reduced_X = pca.fit_transform(X)#机器的降维处理 red_x, red_y = [], []#三种花 blue_x, blue_y = [], [] green_x, green_y = [], [] for i in range(len(reduced_X)): if y[i] == 0: red_x.append(reduced_X[i][0]) red_y.append(reduced_X[i][1]) elif y[i] == 1: blue_x.append(reduced_X[i][0]) blue_y.append(reduced_X[i][1]) else: green_x.append(reduced_X[i][0]) green_y.append(reduced_X[i][1]) plt.scatter(red_x, red_y, c='r', marker='x') plt.scatter(blue_x, blue_y, c='b', marker='D') plt.scatter(green_x, green_y, c='g', marker='.') plt.show()

基本上利用到pca就是pac=PCA(n_component=2)和reduced_X=pca.fit_transform(X)两句。

target是一组(150,)的数据,为0,1,2,代表三种不同的花。data是(150,4)是花的四种特征。

 

二、NMF非负矩阵分解

如名字所示,把一个非负矩阵V分解成两个非负矩阵的乘积(W,H)W是特征矩阵,H是系数矩阵。

NMF应用于图像处理和语音识别。

NMF分解的原则是最小化乘积矩阵和原矩阵的差。

    from numpy.random import RandomState
    import matplotlib.pyplot as plt
    from sklearn.datasets import fetch_olivetti_faces
    from sklearn import decomposition
     
     
    n_row, n_col = 2, 3
    n_components = n_row * n_col
    image_shape = (64, 64)
     
     
    ###############################################################################
    # Load faces data
    dataset = fetch_olivetti_faces(shuffle=True, random_state=RandomState(0))
    faces = dataset.data
     
    ###############################################################################
    def plot_gallery(title, images, n_col=n_col, n_row=n_row):
        plt.figure(figsize=(2. * n_col, 2.26 * n_row)) 
        plt.suptitle(title, size=16)
     
        for i, comp in enumerate(images):
            plt.subplot(n_row, n_col, i + 1)
            vmax = max(comp.max(), -comp.min())
     
            plt.imshow(comp.reshape(image_shape), cmap=plt.cm.gray,
                       interpolation='nearest', vmin=-vmax, vmax=vmax)
            plt.xticks(())
            plt.yticks(())
        plt.subplots_adjust(0.01, 0.05, 0.99, 0.94, 0.04, 0.)
     
         
    plot_gallery("First centered Olivetti faces", faces[:n_components])
    ###############################################################################
     
    estimators = [
        ('Eigenfaces - PCA using randomized SVD',
             decomposition.PCA(n_components=6,whiten=True)),
     
        ('Non-negative components - NMF',
             decomposition.NMF(n_components=6, init='nndsvda', tol=5e-3))
    ]
     
    ###############################################################################
     
    for name, estimator in estimators:
        print("Extracting the top %d %s..." % (n_components, name))
        print(faces.shape)
        estimator.fit(faces)
        components_ = estimator.components_
        plot_gallery(name, components_[:n_components])
     
    plt.show()

 

 

---恢复内容结束---

posted on 2017-05-21 17:14  胖咸鱼  阅读(515)  评论(0编辑  收藏  举报

导航