聲明:版權所有,轉載請聯系作者并注明出處 http://blog.csdn.net/u013719780?viewmode=contents
部落客簡介:風雪夜歸子(英文名: Allen),機器學習算法攻城獅,喜愛鑽研Machine Learning的黑科技,對Deep Learning和Artificial Intelligence充滿興趣,經常關注kaggle資料挖掘競賽平台,對資料、Machine Learning和Artificial Intelligence有興趣的各位童鞋可以一起探讨哦,個人CSDN部落格: http://blog.csdn.net/u013719780?viewmode=contents
建立試驗樣本資料
希望你在學習本書時用自己的資料來試驗,如果實在沒有資料,下面就介紹如何用scikit-learn建立一些試驗用的樣本資料(toy data)。
Getting ready
與前面擷取内置資料集,擷取新資料集的過程類似,建立樣本資料集,用
make_資料集名稱
函數。這些資料集都是人造的:
In [1]:
from sklearn import datasets
datasets.make_*?
datasets.make_biclusters
datasets.make_blobs
datasets.make_checkerboard
datasets.make_circles
datasets.make_classification
datasets.make_friedman1
datasets.make_friedman2
datasets.make_friedman3
datasets.make_gaussian_quantiles
datasets.make_hastie_10_2
datasets.make_low_rank_matrix
datasets.make_moons
datasets.make_multilabel_classification
datasets.make_regression
datasets.make_s_curve
datasets.make_sparse_coded_signal
datasets.make_sparse_spd_matrix
datasets.make_sparse_uncorrelated
datasets.make_spd_matrix
datasets.make_swiss_roll
為了簡便,下面我們用
d
表示
datasets
,
np
表示
numpy
:
In [1]:
import sklearn.datasets as d
import numpy as np
How to do it...
這一節将帶你建立幾個資料集;在後面的How it works...一節,我們會檢驗這些資料集的特性。除了樣本資料集,後面還會建立一些具有特定屬性的資料集來顯示算法的特點。
首先,我們建立回歸(regression)資料集:
In [2]:
reg_data = d.make_regression()
reg_data[0].shape,reg_data[1].shape
Out[2]:
((100, 100), (100,))
reg_data
預設是一個元組,第一個元素是 100×100 100×100的矩陣——100個樣本,每個樣本10個特征(自變量),第二個元素是1個因變量,對應自變量的樣本數量,也是100個樣本。然而,預設情況下,隻有10個特征與因變量的相關(參數
n_informative
預設值是10),其他90個特征都與。
可以自定義更複雜的資料集。比如,建立一個 1000×10 1000×10的矩陣,5個特征與因變量相關,誤差系數0.2,兩個因變量。代碼如下所示:
In [3]:
complex_reg_data = d.make_regression(1000, 10, 5, 2, 1.0)
complex_reg_data[0].shape,complex_reg_data[1].shape
Out[3]:
((1000, 10), (1000, 2))
分類資料集也很容易建立。很容易建立一個基本均衡分類集,但是這種情況現實中幾乎不可能發生——大多數使用者不會改變消費習慣,大多數交易都不是虛假的,等等。是以,建立一個非均衡資料集更有意義:
In [4]:
classification_set = d.make_classification(weights=[0.1])
np.bincount(classification_set[1])
Out[4]:
array([10, 90], dtype=int64)
聚類資料集也可以建立。有一些函數可以為不同聚類算法建立對應的資料集。例如,
blobs
函數可以輕松建立K-Means聚類資料集:
In [5]:
%matplotlib inline
import sklearn.datasets as d
from matplotlib import pyplot as plt
import numpy as np
blobs = d.make_blobs(200)
f = plt.figure(figsize=(8, 4))
ax = f.add_subplot(111)
ax.set_title("A blob with 3 centers")
colors = np.array(['r', 'g', 'b'])
ax.scatter(blobs[0][:, 0], blobs[0][:, 1], color=colors[blobs[1].astype(int)], alpha=0.75)
Out[5]:
<matplotlib.collections.PathCollection at 0x88e44e0>
How it works...
下面讓我們從源代碼看看scikit-learn是如何生成回歸資料集的。下面任何未重新定義的參數都使用
make_regression
函數的預設值。
其實非常簡單。首先,函數調用時生成一個指定次元的随機數組。
In [7]:
對于基本均衡資料集,其目标資料集生成方法是:
In [ ]:
ground_truth = np.zeroes((np_samples, n_target))
ground_truth[:n_informative, :] = 100*np.random.rand(n_informative,
n_targets)
然後
X
和
ground_truth
點積加上
bias
就得到了
y
:
In [ ]:
點積是一種基本的矩陣運算Am×n⋅Bn×s=Cm×s。是以,資料集裡面樣本數量是
y
,即資料集的行數,因變量數量是
n_samples
。
n_target
由于Numpy的傳播操作(broadcasting),
bias
雖然是标量,也會被增加到矩陣的每個元素上。增加噪聲和資料混洗都很簡單。這樣試驗用的回歸資料集就完美了。