【sklearn练习】preprocessing的使用

介绍

scikit-learn 中的 preprocessing 模块提供了多种数据预处理工具,用于准备和转换数据以供机器学习模型使用。这些工具可以帮助您处理数据中的缺失值、标准化特征、编码分类变量、降维等。以下是一些常见的 preprocessing 模块中的功能和用法示例:

  1. 标准化特征(Feature Scaling):

    • 使用 StandardScaler 类可以对特征进行标准化,使其具有零均值和单位方差。这对于许多机器学习算法来说是必要的。

    示例使用方法:

    python 复制代码
    from sklearn.preprocessing import StandardScaler
    
    scaler = StandardScaler()
    X_train_scaled = scaler.fit_transform(X_train)
    X_test_scaled = scaler.transform(X_test)
  2. 最小-最大缩放(Min-Max Scaling):

    • 使用 MinMaxScaler 类可以将特征缩放到指定的最小值和最大值之间,通常在0到1之间。

    示例使用方法:

    python 复制代码
    from sklearn.preprocessing import MinMaxScaler
    
    scaler = MinMaxScaler()
    X_train_scaled = scaler.fit_transform(X_train)
    X_test_scaled = scaler.transform(X_test)
  3. 编码分类变量:

    • 使用 LabelEncoder 类可以将分类变量编码为整数标签。

    示例使用方法:

    python 复制代码
    from sklearn.preprocessing import LabelEncoder
    
    encoder = LabelEncoder()
    y_encoded = encoder.fit_transform(y)
  4. 独热编码(One-Hot Encoding):

    • 使用 OneHotEncoder 类可以将分类变量转换为独热编码形式,创建虚拟变量。

    示例使用方法:

    python 复制代码
    from sklearn.preprocessing import OneHotEncoder
    
    encoder = OneHotEncoder()
    X_encoded = encoder.fit_transform(X_categorical).toarray()
  5. 处理缺失值:

    • 使用 SimpleImputer 类可以填充数据中的缺失值,可以选择使用均值、中位数、众数等填充策略。

    示例使用方法:

    python 复制代码
    from sklearn.impute import SimpleImputer
    
    imputer = SimpleImputer(strategy="mean")
    X_imputed = imputer.fit_transform(X_missing)
  6. 降维:

    • 使用 PCA 类可以进行主成分分析(PCA)降维,将高维数据投影到低维空间。

    示例使用方法:

    python 复制代码
    from sklearn.decomposition import PCA
    
    pca = PCA(n_components=2)
    X_pca = pca.fit_transform(X)

以上是一些 preprocessing 模块中常见功能的示例用法。数据预处理是机器学习中非常重要的一步,它有助于提高模型的性能和稳定性。您可以根据您的数据和任务选择适当的预处理方法,并将其应用于您的数据,以确保数据准备得当。

实例

例1:

python 复制代码
from sklearn import preprocessing
import numpy as np

a = np.array([[10,   2.7, 3.6],
             [-100, 5,   -2],
             [120,  20,  40]])
print(a)
print(preprocessing.scale(a))

输出:

python 复制代码
[[  10.     2.7    3.6]
 [-100.     5.    -2. ]
 [ 120.    20.    40. ]]
[[ 0.         -0.85170713 -0.55138018]
 [-1.22474487 -0.55187146 -0.852133  ]
 [ 1.22474487  1.40357859  1.40351318]]

例2:

python 复制代码
from sklearn import preprocessing                      #预处理的模块
import numpy as np
from sklearn.model_selection import train_test_split   #将数据打乱随机分为训练集和测试集的类train_test_split 
from sklearn.datasets import make_classification       #datasets中make开头的创建数据集的类make_classification 
from sklearn.svm import SVC                            #训练模型的类SVC
import matplotlib.pyplot as plt

X, y = make_classification(n_samples=300, n_features=2,
                           n_redundant=0, n_informative=2,
                           random_state=22,
                           n_clusters_per_class=1,
                           scale=100)
plt.scatter(X[:, 0], X[:, 1], c=y)
plt.show()

X = preprocessing.scale(X)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.3)
clf = SVC()
clf.fit(X_train, y_train)
print(clf.score(X_test, y_test))
#输出为0.9555555555555556,
#当删去对X的预处理语句X = preprocessing.scale(X),这里的输出理论上减小

输出:

相关推荐
砚底藏山河几秒前
python量化自定义周期 K 线合成
java·开发语言·数据库·python·金融
冬奇Lab5 分钟前
一天一个开源项目(第252篇):Lightpanda —— 用 Zig 从零写的 AI 专用无头浏览器,内存省 16 倍、速度快 9 倍
人工智能·开源·资讯
视觉小萌新7 分钟前
AI Class 3 · Chapter 1:变量、字符串、list/dict、if/for(python学习-小白版-有经验可跳过)
python·学习·list
在努力的前端小白31 分钟前
基于FastAPI+LangChain+LangGraph+Agent+多模态的AI Agent 有渔渔具网站
人工智能·langchain·vue·fastapi
薛定谔的猫-菜鸟程序员1 小时前
软件架构设计师开发资料大全(从入门到精通)
后端·python·系统架构·flask·架构设计师
锋行天下1 小时前
Langgraph-cli 本地构建失败,改用服务器docker构建的流程
人工智能·前端框架·全栈
释厄6231 小时前
群体投票双通道狭隘论——AI泡沫出清后的主角确权
人工智能
IT古董1 小时前
《Agent开发工程师成长指南》- 第4章 第2节:Prompt设计五要素——任务、角色、上下文、约束与输出格式
大数据·人工智能·prompt
霸道流氓气质2 小时前
AI 流式对话与实时聊天平台:SSE 解码竞态、有状态会话隔离与背压取消的 Vue3 + Spring AI 生产级实战
java·人工智能·spring
孟健2 小时前
我把9个AI助理迁到了Grok Bot,连远程服务器都省了
人工智能·aigc·ai编程