生成数据,本应当在(1-1)sklearn库的 数据处理里面的内容,但由于现在不是我研究的重点,故单独摘出来备用
1.2 创建数据集
我们除了可以使用sklearn自带的数据集,还可以自己去创建训练样本,具体用法可以参考: https://scikit-learn.org/stable/datasets/



1.2.1 生成回归数据 make_regression()
from sklearn.datasets import make_regression
X, y, coef = make_regression(n_samples=200, n_features=1, n_informative=1, n_targets=1,
bias = 0, effective_rank=None, noise = 20,
tail_strength=0,random_state=0, coef = True)
- n_samples 样本数量
- n_features 特征数量
- n_informative 对回归有效的特征数量
(该项为对本次回归有用的特征数量,举个例子,我们想要预测房价,手上的特征有:房子面积、房龄、地段和房主的名字,显然前3项特征时有效特征,而房主的名字属于无效特征,改变其值并不影响回归效果。这里的n_informative就是3,总特征数为4.) - n_targets y的维度
- bias 底层线性模型中的偏差项。相当于y的中位数
- effective_rank 有效等级
- noise 设置高斯噪声的标准偏差加到数据上。(noise:其值是高斯分布的偏差值,其值越大数据越分散,其值越小数据越集中。)
- shuffle 是否洗牌(设置是否洗牌,如果为False,会按照顺序创建样本,一般设置为True。)
- coef 如果为真,则返回权重值
- random_state 设置随机种子
from sklearn.datasets import make_regression
from matplotlib import pyplot
X, y, coef = make_regression(n_samples=200, n_features=1, n_informative=1, n_targets=1,
bias = 0, effective_rank=None, noise = 20,
tail_strength=0,random_state=0, coef = True)
print(X[:10])#输出前十个
print(y[:10])#输出前十个
print(coef)
pyplot.scatter(X,y)
pyplot.show()



1.2.2 生成分类数据 make_classification()
from sklearn.datasets.samples_generator import make_classification
X, y = make_classification(n_samples=6, n_features=5, n_informative=2,
n_redundant=2, n_classes=2, n_clusters_per_class=2, scale=1.0,
random_state=20)
# n_samples:指定样本数
# n_features:指定特征数
#n_informative有意义的特征数,对本次分类有利的特征数
#n_redundant冗余信息
#n_repeated重复信息,随机提取n_informative和n_redundant 特征
# n_classes:指定几分类
#n_clusters_per_class某一个类别是由几个cluster构成的(子类别)
# random_state:随机种子,使得随机状可重
测试①:
>>> for x_,y_ in zip(X,y):
print(y_,end=': ')
print(x_)
0: [-0.6600737 -0.0558978 0.82286793 1.1003977 -0.93493796]
1: [ 0.4113583 0.06249216 -0.90760075 -1.41296696 2.059838 ]
1: [ 1.52452016 -0.01867812 0.20900899 1.34422289 -1.61299022]
0: [-1.25725859 0.02347952 -0.28764782 -1.32091378 -0.88549315]
0: [-3.28323172 0.03899168 -0.43251277 -2.86249859 -1.10457948]
1: [ 1.68841011 0.06754955 -1.02805579 -0.83132182 0.93286635]
测试②:
from sklearn.datasets import make_classification
import matplotlib.pyplot as plt
X, y = make_classification(n_samples=200, n_features=2, n_informative=2,n_redundant=0,
n_repeated=0, n_classes=2, n_clusters_per_class=1,random_state = 1)
print(X[:10])
print(y[:10])
plt.scatter(X[y == 0, 0], X[y == 0, 1], c = 'red', s = 100, label='0')
plt.scatter(X[y == 1, 0], X[y == 1, 1], c = 'blue', s = 100, label='1')
plt.scatter

本文深入探讨了使用Sklearn库生成各类数据集的方法,包括回归数据、分类数据、聚类数据及复杂数据形态的生成技巧。通过具体示例,详细介绍了make_regression、make_classification、make_blobs等函数的应用场景与参数配置,适用于初学者和进阶用户。
最低0.47元/天 解锁文章
526

被折叠的 条评论
为什么被折叠?



