"""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()
本例需在 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。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境: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。
入口文件:projects/ml-datatype-lab/explore-datatype.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-datatype.py,或下载右侧课程工程包。 - 确认本地已准备 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。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a462.zip
课程关联工程包(登记关联58章) · 含当前章节或实例 · mbskycom202612a449.zip