-
python爬虫之机器学习算法的随机数据生成总结(2)
试听地址 https://www.xin3721.com/eschool/pythonxin3721/
再比如: np.random.randint(3, 6, size=[2,3]) 返回维数为2x3的数据。取值范围为[3,6).
|
1
2
|
array([[4, 5, 3], [3, 4, 5]]) |
4) random_integers(low[, high, size]),和上面的randint类似,区别在与取值范围是闭区间[low, high]。
5) random_sample([size]), 返回随机的浮点数,在半开区间 [0.0, 1.0)。如果是其他区间[a,b),可以加以转换(b - a) * random_sample([size]) + a
例如: (5-2)*np.random.random_sample(3)+2 返回[2,5)之间的3个随机数。
|
1
|
array([ 2.87037573, 4.33790491, 2.1662832 ]) |
2. scikit-learn随机数据生成API介绍
scikit-learn生成随机数据的API都在datasets类之中,和numpy比起来,可以用来生成适合特定机器学习模型的数据。常用的API有:
1) 用make_regression 生成回归模型的数据
2) 用make_hastie_10_2,make_classification或者make_multilabel_classification生成分类模型数据
3) 用make_blobs生成聚类模型数据
4) 用make_gaussian_quantiles生成分组多维正态分布的数据
3. scikit-learn随机数据生成实例
3.1 回归模型随机数据
这里我们使用make_regression生成回归模型数据。几个关键参数有n_samples(生成样本数), n_features(样本特征数),noise(样本随机噪音)和coef(是否返回回归系数)。例子代码如下:
|
1
2
3
4
5
6
7
8
9
10
11
12
|
import numpy as npimport matplotlib.pyplot as plt%matplotlib inlinefrom sklearn.datasets.samples_generator import make_regression# X为样本特征,y为样本输出, coef为回归系数,共1000个样本,每个样本1个特征X, y, coef =make_regression(n_samples=1000, n_features=1,noise=10, coef=True)# 画图plt.scatter(X, y, color='black')plt.plot(X, X*coef, color='blue', linewidth=3)plt.xticks(())plt.yticks(())plt.show() |
输出的图如下:

3.2 分类模型随机数据
这里我们用make_classification生成三元分类模型数据。几个关键参数有n_samples(生成样本数), n_features(样本特征数), n_redundant(冗余特征数)和n_classes(输出的类别数),例子代码如下:
|
1
2
3
4
5
6
7
8
9
|
import numpy as npimport matplotlib.pyplot as plt%matplotlib inlinefrom sklearn.datasets.samples_generator import make_classification# X1为样本特征,Y1为样本类别输出, 共400个样本,每个样本2个特征,输出有3个类别,没有冗余特征,每个类别一个簇X1, Y1 = make_classification(n_samples=400, n_features=2, n_redundant=0, n_clusters_per_class=1, n_classes=3)plt.scatter(X1[:, 0], X1[:, 1], marker='o', c=Y1)plt.show() |













