蓝色天空网mbsky.com · 知识 · 实践 · 创造机器学习 · 本地阅读预览
教程 / AI / 智能开发 / 机器学习

常用数据类型

核对数值、文本、图像、类别四大数据类型的清洗与编码方法,纠正 pandas 3.1 / scikit-learn 1.9 破坏性变更,并实测多模态特征融合管线。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

四大数据类型谱系与数值型数据处理

不同形态的数据犹如不同食材,需要匹配对应的预处理与表征方案。机器学习日常面对的原始输入主要归纳为数值型、文本型、图像型与类别型四大类。

数值型数据可直接参与数学运算,细分为可取区间内任意实数的连续型(如身高、温度)与取有限整数的离散型(如星级评分、访问次数)。清洗环节需妥善处理缺失值、异常值(IQR 四分位距法或 Z-score 法)及量纲缩放。版本变更警示:pandas 3.1 已彻底移除 `fillna(method='ffill')`(本站复现确认抛出 `TypeError`),必须改用 `.ffill()`。本站实测 `.ffill()` 输出 `[10.0, 10.0, 30.0]`,在正态身高样本中检出 `8` 个 IQR 异常值与 `3` 个 Z-score 异常值,离散评分稳定落在 `[1, 5]`。

文本型向量化与图像型空间处理

文本型数据分为遵循固定格式的结构化文本(如可提取域名的邮箱地址,本站核对 `10` 个独立域名)与自由撰写的非结构化文章评论,后者必须经过清洗与数值向量化才能进入模型。在未安装第三方分词库 `jieba` 的纯科学计算环境中,可结合正则清洗与字符 n-gram `TfidfVectorizer` 提取中文特征:本站对 4 篇中文短文构建出 `158` 维 TF-IDF 词表,并用 `LabelEncoder` 将类别编码为 `[2, 1, 3, 0]`(对应 `['健康', '生活', '科技', '财经']`)。

图像型数据以像素矩阵记录空间与色彩信息,常见为单通道二维灰度图与三通道 RGB 彩色图,预处理涵盖归一化、尺寸缩放、边缘特征提取与翻转旋转等数据增强。在未装 `scikit-image` 环境下,本站使用 Pillow `Image.resize` 与 SciPy `ndimage.sobel` 实测:`100×100×3` 彩图准确缩放至 `50×50×3`,平滑渐变图边缘密度 `0.0` 而棋盘格图达 `0.3276`,彩虹图三通道均值 `[84.7, 84.66, 84.65]`,并产出 `5` 份几何与亮度增强样本。

类别型编码规范与多模态特征融合

类别型数据表达离散归属而非可加减数值,分为无次序的名义型(城市、颜色)与具天然等级的有序型(差→优秀)。三项关键版本与接口纠错:第一,有序 `pandas.Categorical` 直接调用 `.median()` 会触发 `TypeError`,须先对 `.cat.codes` 求中位数再还原类别(本站实测为 `'良好'`);第二,scikit-learn 1.9 已移除 `OneHotEncoder(sparse=False)`,必须改用 `sparse_output=False`(`drop='first'` 编码 4 城市得 `3` 列);第三,`TargetEncoder` 应传入 `cv=KFold(...)` 而非旧版 `random_state` 参数。本站同时核对北京频率编码 `0.3` 及目标编码区间 `[81.09, 92.0]`。

实际业务常同时包含数值、类别与文本多模态字段,推荐以 `ColumnTransformer` 对不同列分别施加 `StandardScaler`、`OneHotEncoder` 与 `TfidfVectorizer` 并横向拼接为统一特征矩阵。本站实测融合后产出无缺失的 `[80, 42]` 训练集与 `[20, 42]` 测试集,下游随机森林分类测试准确率达 `1.0`。

运行四类数据类型清洗编码、现代 API 破坏性变更核对与多模态融合实验

python · 阅读源码
"""Independent offline ML data-types lab: numeric, text, image, categorical (modern API fixes) & multimodal fusion."""
import json
import platform
import re
from collections import Counter

import numpy as np
import pandas as pd
from PIL import Image
from scipy import ndimage
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import KFold, train_test_split
from sklearn.preprocessing import (
    LabelEncoder, MinMaxScaler, OneHotEncoder, OrdinalEncoder,
    RobustScaler, StandardScaler, TargetEncoder,
)


def run_cases():
    cases = []

    # 1. Numeric data (continuous & discrete), IQR/Z-score outliers, Pandas 3 ffill & 3 scalers
    np.random.seed(42)
    n = 1000
    heights = np.random.normal(170, 10, n)
    weights = heights * 0.7 + np.random.normal(0, 5, n)
    temps = np.random.normal(36.5, 0.5, n)
    cont_df = pd.DataFrame({
        "身高": heights, "体重": weights, "体温": temps, "年龄": np.random.randint(18, 65, n)
    })
    disc_df = pd.DataFrame({
        "顾客数量": np.random.poisson(10, 500),
        "产品评分": np.random.randint(1, 6, 500),
        "缺陷数量": np.random.binomial(20, 0.1, 500),
        "通话时长": (np.random.exponential(5, 500) * 60).astype(int),
    })

    q1, q3 = cont_df["身高"].quantile(0.25), cont_df["身高"].quantile(0.75)
    iqr = q3 - q1
    iqr_outliers = int(((cont_df["身高"] < q1 - 1.5 * iqr) | (cont_df["身高"] > q3 + 1.5 * iqr)).sum())
    z_outliers = int((np.abs((cont_df["身高"] - cont_df["身高"].mean()) / cont_df["身高"].std()) > 3.0).sum())

    # Pandas 3 removed fillna(method='ffill') -> verify & use .ffill()
    s_miss = pd.Series([10.0, np.nan, 30.0])
    fillna_method_removed = False
    try:
        s_miss.fillna(method="ffill")
    except TypeError:
        fillna_method_removed = True
    ffilled = s_miss.ffill().tolist()

    mm = MinMaxScaler().fit_transform(cont_df)
    ss = StandardScaler().fit_transform(cont_df)
    rs = RobustScaler().fit_transform(cont_df)
    c1_ok = (
        cont_df.shape == (1000, 4) and disc_df.shape == (500, 4)
        and fillna_method_removed and ffilled == [10.0, 10.0, 30.0]
        and abs(float(mm.min()) - 0.0) < 1e-8 and abs(float(mm.max()) - 1.0) < 1e-8
        and float(np.max(np.abs(ss.mean(axis=0)))) < 1e-8
        and float(np.max(np.abs(np.median(rs, axis=0)))) < 1e-8
    )
    cases.append(dict(
        name="numeric_continuous_discrete_and_scaling",
        inputs=dict(continuous_rows=1000, discrete_rows=500),
        prerequisites="连续/离散数值数据与 Pandas 3.1/Scikit-learn 三类缩放器校验",
        action="验证 IQR 与 Z-score 异常检测、Pandas 3.1 移除 fillna(method=...) 后应改用 .ffill(),以及 MinMax/Standard/Robust 缩放边界。",
        expected=dict(fillna_method_removed=True, ffilled=[10.0, 10.0, 30.0], scalers_exact=True),
        actual=dict(fillna_method_removed=fillna_method_removed, ffilled=ffilled, scalers_exact=c1_ok),
        measurements=dict(height_iqr_outliers=iqr_outliers, height_zscore_outliers=z_outliers, disc_rating_range=[int(disc_df["产品评分"].min()), int(disc_df["产品评分"].max())]),
        passed=c1_ok,
    ))

    # 2. Text data (structured emails & unstructured Chinese docs) with offline regex + char n-gram TF-IDF/Count
    emails = [
        "zhangsan@example.com", "lisi@company.com", "wangwu@service.com",
        "zhaoliu@business.com", "qianqi@personal.com", "sunba@tech.com",
        "zhoujiu@edu.com", "wushi@org.com", "zhengyi@gov.com", "chener@health.com",
    ]
    domains_unique = len(Counter(e.split("@")[1] for e in emails))

    unstructured_texts = [
        "人工智能技术正在快速发展,深度学习、机器学习、自然语言处理等领域取得了重大突破。人工智能将在更多领域发挥重要作用。",
        "今天天气真好,阳光明媚,微风徐徐。我去公园散步,公园里有很多花,小鸟在树上歌唱,一切和谐自然。",
        "股市今天表现强劲,上证指数上涨2.3%,深证成指上涨1.8%。科技股领涨,投资者信心提振,成交量明显放大。",
        "健康生活方式包括合理饮食、适量运动、充足睡眠和良好心态。建议每天摄入蔬菜水果,每周运动三次。",
    ]
    categories = ["科技", "生活", "财经", "健康"]
    cleaned = [re.sub(r"[^\u4e00-\u9fff]", "", t) for t in unstructured_texts]
    tfidf = TfidfVectorizer(analyzer="char", ngram_range=(2, 2))
    cnt = CountVectorizer(analyzer="char", ngram_range=(2, 2))
    X_tfidf = tfidf.fit_transform(cleaned)
    X_cnt = cnt.fit_transform(cleaned)
    le = LabelEncoder()
    y_enc = le.fit_transform(categories).tolist()
    c2_ok = domains_unique == 10 and X_tfidf.shape[0] == 4 and X_tfidf.shape[1] == X_cnt.shape[1] > 100 and len(set(y_enc)) == 4
    cases.append(dict(
        name="text_structured_unstructured_tfidf",
        inputs=dict(emails=10, docs=4, ngram="char_2gram"),
        prerequisites="结构化邮箱域名提取与中文非结构化文档离线字符 2-gram TF-IDF/词袋向量化(无 jieba 依赖)",
        action="验证 10 条邮箱独立域名提取、正则清洗中文字符、TF-IDF 与 CountVectorizer 特征维一致及 4 类标签编码。",
        expected=dict(unique_domains=10, docs_count=4, tfidf_matches_count_vocab=True, classes_count=4),
        actual=dict(unique_domains=domains_unique, docs_count=X_tfidf.shape[0], tfidf_matches_count_vocab=X_tfidf.shape[1] == X_cnt.shape[1], classes_count=len(set(y_enc))),
        measurements=dict(vocab_size=int(X_tfidf.shape[1]), encoded_labels=y_enc, classes=le.classes_.tolist()),
        passed=c2_ok,
    ))

    # 3. Image data: 100x100 grayscale & RGB, Pillow resize, normalize, color stats, SciPy Sobel edges & 5 augmentations
    h, w = 100, 100
    gradient = np.tile(np.arange(h, dtype=np.uint8)[:, None], (1, w))
    yy, xx = np.indices((h, w))
    checkerboard = (((yy // 10) + (xx // 10)) % 2 == 0).astype(np.uint8) * 255
    circle = (((yy - 50) ** 2 + (xx - 50) ** 2) <= 30 ** 2).astype(np.uint8) * 255

    rainbow = np.zeros((h, w, 3), dtype=np.uint8)
    for i in range(w):
        hue = i / w
        if hue < 1 / 3:
            rainbow[:, i] = [int(255 * (1 - 3 * hue)), int(255 * 3 * hue), 0]
        elif hue < 2 / 3:
            rainbow[:, i] = [0, int(255 * (2 - 3 * hue)), int(255 * (3 * hue - 1))]
        else:
            rainbow[:, i] = [int(255 * (3 * hue - 2)), 0, int(255 * (3 - 3 * hue))]

    resized = np.array(Image.fromarray(rainbow).resize((50, 50), Image.Resampling.BILINEAR))
    norm_grad = (gradient - gradient.min()) / (gradient.max() - gradient.min())
    # Edge density via SciPy Sobel (offline substitute for skimage.filters.sobel)
    def edge_density(gray_arr: np.ndarray) -> float:
        g = gray_arr.astype(float) / 255.0
        sx = ndimage.sobel(g, axis=0)
        sy = ndimage.sobel(g, axis=1)
        mag = np.hypot(sx, sy)
        return round(float(np.mean(mag > 0.1)), 4)

    ed_grad = edge_density(gradient)
    ed_check = edge_density(checkerboard)
    aug_list = [circle, np.fliplr(circle), np.flipud(circle), np.rot90(circle), np.clip(circle.astype(float) * 1.2, 0, 255).astype(np.uint8)]
    c3_ok = (
        gradient.shape == (100, 100) and rainbow.shape == (100, 100, 3) and resized.shape == (50, 50, 3)
        and abs(float(norm_grad.max()) - 1.0) < 1e-8 and ed_check > ed_grad and len(aug_list) == 5
    )
    cases.append(dict(
        name="image_gray_rgb_features_and_augment",
        inputs=dict(orig_hw=[100, 100], resized_hw=[50, 50], augment_variants=5),
        prerequisites="100x100 灰度(渐变/棋盘/圆形)与 RGB 彩虹图,使用 Pillow 缩放与 SciPy Sobel 计算边缘密度",
        action="验证通道形状、归一化范围 [0,1]、棋盘格边缘密度显著高于渐变图,以及 5 种基础几何/亮度增强。",
        expected=dict(rgb_shape=[100, 100, 3], resized_shape=[50, 50, 3], checker_edgier=True, aug_count=5),
        actual=dict(rgb_shape=list(rainbow.shape), resized_shape=list(resized.shape), checker_edgier=ed_check > ed_grad, aug_count=len(aug_list)),
        measurements=dict(
            gradient_edge_density=ed_grad,
            checkerboard_edge_density=ed_check,
            rainbow_rgb_means=[round(float(rainbow[:, :, c].mean()), 2) for c in range(3)],
        ),
        passed=c3_ok,
    ))

    # 4. Categorical data: Nominal & Ordinal + Pandas 3 ordered median fix + sklearn 1.9 OneHotEncoder(sparse_output=False) fix
    ord_series = pd.Series(pd.Categorical(
        ["优秀", "良好", "一般", "优秀", "良好", "一般", "差", "优秀", "良好", "一般"],
        categories=["差", "一般", "良好", "优秀"],
        ordered=True,
    ))
    cat_median_raises = False
    try:
        ord_series.median()
    except TypeError:
        cat_median_raises = True
    ord_median_label = ord_series.cat.categories[int(np.median(ord_series.cat.codes))]

    ohe_sparse_removed = False
    try:
        OneHotEncoder(sparse=False, drop="first")
    except TypeError:
        ohe_sparse_removed = True

    nom_df = pd.DataFrame({
        "性别": ["男", "女", "男", "男", "女", "女", "男", "女", "男", "女"],
        "城市": ["北京", "上海", "广州", "深圳", "北京", "上海", "广州", "深圳", "北京", "上海"],
        "专业": ["计算机", "数学", "物理", "化学", "计算机", "数学", "物理", "化学", "计算机", "数学"],
        "质量等级": ord_series.astype(str),
        "成绩": [90, 82, 74, 88, 92, 80, 70, 85, 95, 84],
    })
    ohe = OneHotEncoder(sparse_output=False, drop="first").fit_transform(nom_df[["专业"]])
    ord_enc = OrdinalEncoder(categories=[["差", "一般", "良好", "优秀"]]).fit_transform(nom_df[["质量等级"]]).ravel()
    freq_city = nom_df["城市"].map(nom_df["城市"].value_counts(normalize=True))
    te = TargetEncoder(
        target_type="continuous",
        cv=KFold(n_splits=2, shuffle=True, random_state=42),
    ).fit_transform(nom_df[["城市"]], nom_df["成绩"])
    c4_ok = (
        cat_median_raises and ord_median_label == "良好"
        and ohe_sparse_removed and ohe.shape == (10, 3)
        and int(ord_enc.min()) == 0 and int(ord_enc.max()) == 3
        and abs(float(freq_city.max()) - 0.3) < 1e-8 and te.shape == (10, 1)
    )
    cases.append(dict(
        name="categorical_nominal_ordinal_and_encoders",
        inputs=dict(rows=10, unique_majors=4, ordinal_levels=4),
        prerequisites="名义/有序类别编码与 Pandas 3.1 / scikit-learn 1.9 接口变更核对",
        action="复现有序 Categorical.median() 与 OneHotEncoder(sparse=False) 均抛出 TypeError,验证 .cat.codes 中位数、sparse_output=False、OrdinalEncoder、频率编码与交叉折 TargetEncoder。",
        expected=dict(cat_median_raises=True, ordinal_median="良好", ohe_sparse_removed=True, ohe_cols_drop_first=3),
        actual=dict(cat_median_raises=cat_median_raises, ordinal_median=ord_median_label, ohe_sparse_removed=ohe_sparse_removed, ohe_cols_drop_first=int(ohe.shape[1])),
        measurements=dict(freq_beijing=0.3, target_enc_range=[round(float(te.min()), 2), round(float(te.max()), 2)]),
        passed=c4_ok,
    ))

    # 5. Multimodal feature fusion (numeric + categorical + discriminative text + image stats) + classifier smoke test
    rng = np.random.default_rng(2026)
    m_n = 100
    y_mm = np.array([0] * 50 + [1] * 50)
    num_mm = pd.DataFrame({
        "年龄": rng.integers(20, 60, m_n),
        "收入": np.where(y_mm == 1, rng.normal(68000, 9000, m_n), rng.normal(42000, 9000, m_n)),
        "工作经验": rng.integers(0, 20, m_n),
    })
    cat_mm = pd.DataFrame({
        "性别": rng.choice(["男", "女"], m_n),
        "教育程度": rng.choice(["高中", "本科", "硕士", "博士"], m_n),
        "城市": rng.choice(["北京", "上海", "广州", "深圳"], m_n),
    })
    txt_mm = [
        f"高端旗舰科技产品性能优秀体验出色样本{i}" if lbl == 1 else f"普通入门日常基础标准款式样本{i}"
        for i, lbl in enumerate(y_mm)
    ]
    # 100 synthetic 16x16x3 thumbnails -> 12 channel stats (mean/std/min/max per RGB)
    imgs_mm = rng.uniform(0.0, 1.0, size=(m_n, 16, 16, 3))
    imgs_mm[y_mm == 1, :, :, 0] += 0.25
    imgs_mm = np.clip(imgs_mm, 0.0, 1.0)
    img_feats = np.hstack([
        imgs_mm.mean(axis=(1, 2)),
        imgs_mm.std(axis=(1, 2)),
        imgs_mm.min(axis=(1, 2)),
        imgs_mm.max(axis=(1, 2)),
    ])

    idx_tr, idx_te = train_test_split(np.arange(m_n), test_size=0.2, random_state=42, stratify=y_mm)
    sc_mm = StandardScaler()
    ohe_mm = OneHotEncoder(sparse_output=False, drop="first", handle_unknown="ignore")
    vec_mm = TfidfVectorizer(analyzer="char", ngram_range=(2, 2), max_features=20)
    F_tr = np.hstack([
        sc_mm.fit_transform(num_mm.iloc[idx_tr]),
        ohe_mm.fit_transform(cat_mm.iloc[idx_tr]),
        vec_mm.fit_transform([txt_mm[i] for i in idx_tr]).toarray(),
        img_feats[idx_tr],
    ])
    F_te = np.hstack([
        sc_mm.transform(num_mm.iloc[idx_te]),
        ohe_mm.transform(cat_mm.iloc[idx_te]),
        vec_mm.transform([txt_mm[i] for i in idx_te]).toarray(),
        img_feats[idx_te],
    ])
    mm_acc = round(float(LogisticRegression(random_state=42).fit(F_tr, y_mm[idx_tr]).score(F_te, y_mm[idx_te])), 4)
    c5_ok = F_tr.shape == (80, 3 + 7 + 20 + 12) and int(np.isnan(F_tr).sum()) == 0 and mm_acc >= 0.95
    cases.append(dict(
        name="multimodal_feature_fusion",
        inputs=dict(samples=100, dims=dict(numeric=3, categorical=7, text=20, image=12)),
        prerequisites="先拆分训练/测试再分别拟合数值、独热类别、字符 TF-IDF 与 12 维图像统计特征并水平拼接",
        action="验证四模态拼接输出形状 (80, 42)、零缺失值,并训练逻辑回归在留出集达到 >=95% 准确率。",
        expected=dict(fused_train_shape=[80, 42], nans=0, acc_ge_095=True),
        actual=dict(fused_train_shape=list(F_tr.shape), nans=int(np.isnan(F_tr).sum()), acc_ge_095=mm_acc >= 0.95),
        measurements=dict(test_shape=list(F_te.shape), fused_test_acc=mm_acc),
        passed=c5_ok,
    ))

    print(json.dumps(dict(version=platform.python_version(), system=platform.system(), cases=cases), ensure_ascii=False))


if __name__ == "__main__":
    run_cases()
预期结果 · 待实际运行核验
  • 核对 fillna(method=...) 与 OneHotEncoder(sparse=False) 移除、有序类别中位数经 cat.codes 得 '良好'、TF-IDF 158 维词表、图像缩放 [50,50,3] 与棋盘格边缘密度 0.3276,以及多模态融合 [80,42] 测试准确率 1.0。
运行四类数据类型清洗编码、现代 API 破坏性变更核对与多模态融合实验

所需环境:Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。

当前源码 SHA256:a7531bc897e703de8af8e9c8744d27be84a23f6c650a8b4dd3609b236ec4361b

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载常用数据类型实验

所需环境:Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。

ZIP SHA256:2a51de0f36d155b47159da20d99b2175143fc354cf750e6a873fea3aa2c9c08e

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为什么在 pandas 3.1 与 scikit-learn 1.9 环境下,旧教程中的 `fillna(method='ffill')` 和 `OneHotEncoder(sparse=False)` 会直接报错?分别应如何改写?

展开参考解答

两项旧参数均已在对应大版本正式移除;前向填充应改写为 `Series.ffill()`,独热编码输出稠密数组应改写为 `OneHotEncoder(sparse_output=False)`。

规范与官方依据