使用二维平均分布与二维正态分布随机生成学习样本 郝伟 2021/08/11 [TOC]

1. 简介

本文以身体和体重数据为例,介绍如何手工和使用make_classification函数生成所需要的数据。

2. 我国人口身高体重数据

根据2015年6月30日国务院新发布全国人口普查数据显示,18岁及以上成年男性和女性的平均身高分别为170.5cm和155.8cm,平均体重分别为66.2kg和57.3kg。

3. 二维平均分布

为了进行数据分析,我们先生成一组男女模拟数据,并以散点图的形式显示为以下效果。

```python{cmd=true matplotlib=true} import numpy as np import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties import random

def getData(sex): w = 66.2 if sex == 'm' else 57.3 h = 167.1 if sex == 'm' else 155.8 w += randValue(30) h += randValue(40) return w, h

def randValue(n): return random.random() (n / 2 - random.random() n)

xValue, yValue, x_males, y_males = [],[],[],[]

for _ in range(1000): w, h = getData('m') xValue.append(w) yValue.append(h) w, h = getData('f') x_males.append(w) y_males.append(h)

plt.title(u'Weights & Heights: male in blue x, female in red y') plt.xlabel('weight(kg)') plt.ylabel('height(cm)') plt.plot(xValue, yValue,'b+') plt.plot(x_males, y_males, 'r1') plt.show()



# 二维正态分布
以下是使用二维正态矩阵生成的数据。

```python{cmd=true matplotlib=true}
import numpy as np
import matplotlib.pyplot as plt

def generate_data(sex, sample_count=1000):
    meta = (66.2, 167.1) if sex=='m' else (57.3, 155.8)
    data = np.random.randn(sample_count, 2)
    sigma = np.array([[meta[0]/10, 0], [0, meta[1] / 30]])
    mu = np.array([meta[0], meta[1]])
    data = np.dot(data, sigma) + mu
    return data

data_male = generate_data('m')
data_female = generate_data('f')

plt.plot(data_male[:, 0], data_male[:, 1], 'b+')
plt.plot(data_female[:, 0], data_female[:, 1], 'r1')
plt.show()

4. 观察结果

通过对比可以发现,平均分布时,可以看到每种数据类型都有一个十字型的分布,并不是很均匀,而使用二维正态分布则不存在这样的问题,数据点能够向中心向四周均匀地分布,得到更好的数据显示效果。

results matching ""

    No results matching ""