使用 scikit-learn 创建合成数据集

Python 中的数据隐私与匿名化

Rebeca Gonzalez

Data engineer

使用 Scikit-learn 生成数据集

  • 我们可以从概率分布采样来创建数据集

  • 例如正态分布

正态分布直方图示意

Python 中的数据隐私与匿名化

正态分布

自然中常见

  • 身高
  • 血压
  • 智商分数

一个大型数据集中身高的直方图,呈正态分布

Python 中的数据隐私与匿名化

从正态分布采样

import numpy as np


# Create new pandas DataFrame new_measures = pd.DataFrame()
# Selecting the mean/center values and the standard deviation of the sample mean = 65 standard_deviation = 2
# Generating the sample new_measures['Height'] = np.random.normal(mean, standard_deviation, 10000)
Python 中的数据隐私与匿名化

从正态分布采样

# Draw histogram to see the resulting heights distribution
new_measures['Height'].hist(bins=50)

结果数据的直方图

Python 中的数据隐私与匿名化

使用 scikit-learn 创建数据集

Scikit-learn 提供简单易用的函数来生成用于:

  • 分类
  • 聚类
  • 回归
Python 中的数据隐私与匿名化

用于分类与聚类的合成数据

make_classification()

  • 分配正态分布的点簇
  • 可创建相关特征和无信息特征

make_blobs()

  • 对簇中心与标准差有更大控制
Python 中的数据隐私与匿名化

用于分类的合成数据

# Import make_classification from sklearn datasets module
from sklearn.datasets import make_classification


# Generate the samples and their labels x, y = make_classification(n_samples=1000,
n_classes=2,
n_informative=2,
n_features=4,
n_clusters_per_class=2,
class_sep=1)
Python 中的数据隐私与匿名化

用于分类的合成数据

# See the generated data and labels
print(x.shape)
print(y.shape)
print(x)
(1000, 4)
(1000,)
[[ 1.22914870e+00 -2.62386795e+00  2.25878743e+00  2.55377055e+00]
 [-1.10279812e+00 -1.15816087e+00  1.55571279e+00  7.80565898e-02]
 [ 2.65581977e-03 -2.33278818e+00  2.37837858e+00  1.57533194e+00]
 ...
 [ 4.51006972e-01  7.53435745e-01 -9.21597108e-01 -2.20659747e-01]
 [ 5.31925876e-01  7.42210504e-01 -9.37625248e-01 -1.61488855e-01]
 [ 1.62862108e+00 -2.72435345e+00  2.22562940e+00  2.87628246e+00]]
Python 中的数据隐私与匿名化

用于分类的合成数据

生成的二分类数据集中的数据点图

Python 中的数据隐私与匿名化

用于分类的合成数据

三幅图展示不同 class_sep 下生成的数据点:左侧点靠得很近,右侧则分离更明显

Python 中的数据隐私与匿名化

用于聚类的合成数据

# Import the datasets module for generating clustering datasets
from sklearn.datasets import make_blobs


# Specify a value for standard deviation standard_deviation = 1.5
# Generate the data and labels of the dataset x, labels = make_blobs(n_features=3, centers=4, cluster_std=standard_deviation)
# See the shape of the generated data print(x.shape)
(100, 3)
Python 中的数据隐私与匿名化

用于聚类的合成数据

聚类结果散点图,每个簇一种颜色;4 个中心对应 4 个簇

Python 中的数据隐私与匿名化

用于聚类的合成数据

三幅图展示标准差如何影响生成的数据点:左侧簇更集中,右侧点更分散

Python 中的数据隐私与匿名化

Vamos praticar!

Python 中的数据隐私与匿名化

Preparing Video For Download...