随笔 - 363, 文章 - 0, 评论 - 2, 阅读 - 23万
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

03scikit-learn非监督学习

Posted on   心默默言  阅读(151)  评论(0编辑  收藏  举报
In [1]:
from sklearn.decomposition import PCA
from sklearn.datasets import load_iris

pca = PCA(n_components=2, whiten=True)  # 主成分是两个,正则化为True
iris = load_iris()
pca.fit(iris.data)
pca.components_ # 打印主成分
Out[1]:
array([[ 0.36138659, -0.08452251,  0.85667061,  0.3582892 ],
       [ 0.65658877,  0.73016143, -0.17337266, -0.07548102]])
In [2]:
pca.explained_variance_ratio_  # 这两个主成分可以多大程度上去表现这个数据
Out[2]:
array([0.92461872, 0.05306648])
In [4]:
pca.explained_variance_ratio_.sum()  # 两个主成分一共可以表达数据的程度
Out[4]:
0.9776852063187949
In [5]:
x_pca = pca.transform(iris.data)
iris.data.shape, x_pca.shape
Out[5]:
((150, 4), (150, 2))
 

原始数据是150个样本,4个特征;降维之后的数据是150个样本,2个特征。

In [8]:
import matplotlib.pyplot as plt
from itertools import cycle


def plot_PCA_2D(data, target, target_names):
    colors = cycle('rgbcmykw')
    target_ids = range(len(target_names))
    plt.figure()
    for i, c, label in zip(target_ids, colors, target_names):
        plt.scatter(data[target == i, 0], data[target == i, 1],
                    c=c, label=label)
In [9]:
plot_PCA_2D(iris.data, iris.target, iris.target_names)
 
In [10]:
from sklearn.cluster import KMeans

k_means = KMeans(n_clusters=3)
k_means.fit(x_pca)
k_means.labels_
Out[10]:
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,
       0, 0, 0, 0, 0, 0, 2, 2, 2, 1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 2,
       1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 2, 2, 1, 2, 1, 2,
       2, 1, 2, 1, 1, 2, 2, 2, 2, 1, 2, 1, 2, 1, 2, 2, 1, 1, 1, 2, 2, 2,
       1, 1, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 1])
In [11]:
plot_PCA_2D(x_pca, k_means.labels_, ['c0', 'c1', 'c2'])
plt.title('kmeans_labels')
Out[11]:
Text(0.5, 1.0, 'kmeans_labels')
 
(评论功能已被禁用)
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示