【Python学习】 - sklearn学习 - 自带数据集sklearn.datasets.x
sklearn 的數據集有好多個種
- 自帶的小數據集(packaged dataset):sklearn.datasets.load_
- 可在線下載的數據集(Downloaded Dataset):sklearn.datasets.fetch_
- 計算機生成的數據集(Generated Dataset):sklearn.datasets.make_
- svmlight/libsvm格式的數據集:sklearn.datasets.load_svmlight_file(…)
- 從買了data.org在線下載獲取的數據集:sklearn.datasets.fetch_mldata(…)
①自帶的數據集
其中的自帶的小的數據集為:sklearn.datasets.load_
sklearn包含一些不許要下載的toy數據集,見下表:
| load_boston() | 加載和返回一個boston房屋價格的數據集 | 回歸 | 506*13 |
| load_iris([return_X_y]) | 加載和返回一個鳶尾花數據集 | 分類 | 150*4 |
| load_diabetes() | 加載和返回一個糖尿病數據集 | 回歸 | 442*10 |
| load_digits([n_class]) | 加載和返回一個手寫字數據集 | 分類 | 1797*64 |
| load_linnerud() | 加載和返回健身數據集 | 多分類 | 20 |
這些數據集都可以在官網上查到,以鳶尾花為例,可以在官網上找到demo,http://scikit-learn.org/stable/auto_examples/datasets/plot_iris_dataset.html
from sklearn.datasets import load_iris #加載數據集 iris=load_iris() iris.keys() #dict_keys(['target', 'DESCR', 'data', 'target_names', 'feature_names']) #數據的條數和維數 n_samples,n_features=iris.data.shape print("Number of sample:",n_samples) #Number of sample: 150 print("Number of feature",n_features) #Number of feature 4 #第一個樣例 print(iris.data[0]) #[ 5.1 3.5 1.4 0.2] print(iris.data.shape) #(150, 4) print(iris.target.shape) #(150,) print(iris.target) """[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 22 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 22 2]""" import numpy as np print(iris.target_names) #['setosa' 'versicolor' 'virginica'] np.bincount(iris.target) #[50 50 50]import matplotlib.pyplot as plt #以第3個索引為劃分依據,x_index的值可以為0,1,2,3 x_index=3 color=['blue','red','green'] for label,color in zip(range(len(iris.target_names)),color):plt.hist(iris.data[iris.target==label,x_index],label=iris.target_names[label],color=color)plt.xlabel(iris.feature_names[x_index]) plt.legend(loc="Upper right") plt.show()#畫散點圖,第一維的數據作為x軸和第二維的數據作為y軸 x_index=0 y_index=1 colors=['blue','red','green'] for label,color in zip(range(len(iris.target_names)),colors):plt.scatter(iris.data[iris.target==label,x_index],iris.data[iris.target==label,y_index],label=iris.target_names[label],c=color) plt.xlabel(iris.feature_names[x_index]) plt.ylabel(iris.feature_names[y_index]) plt.legend(loc='upper left') plt.show()手寫數字數據集load_digits():用于多分類任務的數據集
from sklearn.datasets import load_digits digits=load_digits() print(digits.data.shape) import matplotlib.pyplot as plt plt.gray() plt.matshow(digits.images[0]) plt.show()from sklearn.datasets import load_digits digits=load_digits() digits.keys() n_samples,n_features=digits.data.shape print((n_samples,n_features))print(digits.data.shape) print(digits.images.shape)import numpy as np print(np.all(digits.images.reshape((1797,64))==digits.data))fig=plt.figure(figsize=(6,6)) fig.subplots_adjust(left=0,right=1,bottom=0,top=1,hspace=0.05,wspace=0.05) #繪制數字:每張圖像8*8像素點 for i in range(64):ax=fig.add_subplot(8,8,i+1,xticks=[],yticks=[])ax.imshow(digits.images[i],cmap=plt.cm.binary,interpolation='nearest')#用目標值標記圖像ax.text(0,7,str(digits.target[i])) plt.show()乳腺癌數據集load-barest-cancer():簡單經典的用于二分類任務的數據集
糖尿病數據集:load-diabetes():經典的用于回歸認為的數據集,值得注意的是,這10個特征中的每個特征都已經被處理成0均值,方差歸一化的特征值,
波士頓房價數據集:load-boston():經典的用于回歸任務的數據集
體能訓練數據集:load-linnerud():經典的用于多變量回歸任務的數據集,其內部包含兩個小數據集:Excise是對3個訓練變量的20次觀測(體重,腰圍,脈搏),physiological是對3個生理學變量的20次觀測(引體向上,仰臥起坐,立定跳遠)
svmlight/libsvm的每一行樣本的存放格式:
: : …
這種格式比較適合用來存放稀疏數據,在sklearn中,用scipy sparse CSR矩陣來存放X,用numpy數組來存放Y
from sklearn.datasets import load_svmlight_file x_train,y_train=load_svmlight_file("/path/to/train_dataset.txt","")#如果要加在多個數據的時候,可以用逗號隔開Sample images
sklearn 帶有一組JPEG格式的圖片,可用與測試需要2D數據的算法和流程
| load_sample_images() | 導入樣本圖片,用于加載自帶的2個圖片 |
| load_sample_image(image_name) | 導入單個圖片,返回numpy數組,用于加載外部圖片 |
②生成數據集
生成數據集:可以用來分類任務,可以用來回歸任務,可以用來聚類任務,用于流形學習的,用于因子分解任務的
用于分類任務和聚類任務的:這些函數產生樣本特征向量矩陣以及對應的類別標簽集合
make_blobs:多類單標簽數據集,為每個類分配一個或多個正太分布的點集
make_classification:多類單標簽數據集,為每個類分配一個或多個正太分布的點集,提供了為數據添加噪聲的方式,包括維度相關性,無效特征以及冗余特征等
make_gaussian-quantiles:將一個單高斯分布的點集劃分為兩個數量均等的點集,作為兩類
make_hastie-10-2:產生一個相似的二元分類數據集,有10個維度
make_circle和make_moom產生二維二元分類數據集來測試某些算法的性能,可以為數據集添加噪聲,可以為二元分類器產生一些球形判決界面的數據
#生成多類單標簽數據集 import numpy as np import matplotlib.pyplot as plt from sklearn.datasets.samples_generator import make_blobs center=[[1,1],[-1,-1],[1,-1]] cluster_std=0.3 X,labels=make_blobs(n_samples=200,centers=center,n_features=2,cluster_std=cluster_std,random_state=0) print('X.shape',X.shape) print("labels",set(labels))unique_lables=set(labels) colors=plt.cm.Spectral(np.linspace(0,1,len(unique_lables))) for k,col in zip(unique_lables,colors):x_k=X[labels==k]plt.plot(x_k[:,0],x_k[:,1],'o',markerfacecolor=col,markeredgecolor="k",markersize=14) plt.title('data by make_blob()') plt.show()#生成用于分類的數據集 from sklearn.datasets.samples_generator import make_classification X,labels=make_classification(n_samples=200,n_features=2,n_redundant=0,n_informative=2,random_state=1,n_clusters_per_class=2) rng=np.random.RandomState(2) X+=2*rng.uniform(size=X.shape)unique_lables=set(labels) colors=plt.cm.Spectral(np.linspace(0,1,len(unique_lables))) for k,col in zip(unique_lables,colors):x_k=X[labels==k]plt.plot(x_k[:,0],x_k[:,1],'o',markerfacecolor=col,markeredgecolor="k",markersize=14) plt.title('data by make_classification()') plt.show()#生成球形判決界面的數據 from sklearn.datasets.samples_generator import make_circles X,labels=make_circles(n_samples=200,noise=0.2,factor=0.2,random_state=1) print("X.shape:",X.shape) print("labels:",set(labels))unique_lables=set(labels) colors=plt.cm.Spectral(np.linspace(0,1,len(unique_lables))) for k,col in zip(unique_lables,colors):x_k=X[labels==k]plt.plot(x_k[:,0],x_k[:,1],'o',markerfacecolor=col,markeredgecolor="k",markersize=14) plt.title('data by make_moons()') plt.show()單標簽
make_blobs 產生多類數據集,對每個類的中心和標準差有很好的控制
輸入參數:
sklearn.datasets.samples_generator.make_blobs(n_samples=100, n_features=2, centers=3, cluster_std=1.0, center_box=(-10.0, 10.0), shuffle=True, random_state=None)
| n_samples | int類型 | 可選參數 (default=100) | 總的點數,平均的分到每個clusters中。 |
| n_features | int類型 | 可選參數 (default=2) | 每個樣本的特征維度。 |
| centers | int類型 or 聚類中心坐標元組構成的數組類型 | 可選參數(default=3) | 產生的中心點的數量, or 固定中心點位置。 |
| cluster_std | float or floats序列 | 可選參數 (default=1.0) | clusters的標準差。 |
| center_box | 一對floats (min, max) | 可選參數 (default=(-10.0, 10.0)) | 隨機產生數據的時候,每個cluster中心的邊界。 |
| shuffle | boolean | 可選參數 (default=True) | 打亂樣本。 |
| random_state | int, RandomState對象 or None | 可選參數 (default=None) | 如果是int,random_state作為隨機數產生器的seed; 如果是RandomState對象, random_state是隨機數產生器; 如果是None, RandomState 對象是隨機數產生器通過np.random. |
返回的是:
X:[n_samples,n_features]大小的特征矩陣 y: [n_samples]大小的標簽數據矩陣,對應特征矩陣的每一行 例子:
- 例子:
產生兩類樣本點,兩個聚類中心,坐標是(-3, -3)和(3, 3); 方差是0.5和0.7; 樣本點有1000個,每個點維度是2維
from sklearn.datasets.samples_generator import make_blobs centers = [(-3, -3),(3, 3)] cluster_std = [0.5,0.7] X,y = make_blobs(n_samples=1000, centers=centers,n_features=2, random_state=0, cluster_std=cluster_std)%matplotlib inline import matplotlib import matplotlib.pyplot as plt plt.style.use('ggplot') plt.figure(figsize=(20,5)); plt.subplot(1, 2, 1 ); plt.scatter(X[:,0] , X[:,1], c = y, alpha = 0.7); plt.subplot(1, 2, 2); plt.hist(y) plt.show()產生3類樣本點,3個距離中心,方差分別是0.5,0.7,0.5,樣本點2000個
from sklearn.datasets.samples_generator import make_blobs centers = [(-3, -3),(0,0),(3, 3)] cluster_std = [0.5,0.7,0.5] X,y = make_blobs(n_samples=2000, centers=centers,n_features=2, random_state=0, cluster_std=cluster_std)%matplotlib inline import matplotlib import matplotlib.pyplot as plt plt.style.use('ggplot') plt.figure(figsize=(20,5)); plt.subplot(1, 2, 1 ); plt.scatter(X[:,0] , X[:,1], c = y, alpha = 0.7); plt.subplot(1, 2, 2); plt.hist(y) plt.show()make_classification:可以在模擬數據中添加噪聲
輸入參數:
sklearn.datasets.samples_generator.make_classification(n_samples=100, n_features=20, n_informative=2, n_redundant=2, n_repeated=0, n_classes=2, n_clusters_per_class=2, weights=None, flip_y=0.01, class_sep=1.0, hypercube=True, shift=0.0, scale=1.0, shuffle=True, random_state=None)
| n_samples | int類型 | 可選 (default=100) | 樣本數量. |
| n_features | int | 可選 (default=20) | 總的特征數量,是從有信息的數據點,冗余數據點,重復數據點,和特征點-有信息的點-冗余的點-重復點中隨機選擇的。 |
| n_informative | int | optional (default=2) | informative features數量 |
| n_redundant | int | optional (default=2) | redundant features數量 |
| n_repeated | int | optional (default=0) | duplicated features數量 |
| n_classes | int | optional (default=2) | 類別或者標簽數量 |
| n_clusters_per_class | int | optional (default=2) | 每個class中cluster數量 |
| weights | floats列表 or None | (default=None) | 每個類的權重,用于分配樣本點 |
| flip_y | float | optional (default=0.01) | 隨機交換樣本的一段 |
| class_sep | float | optional (default=1.0) | The factor multiplying the hypercube dimension. |
| hypercube | boolean | optional (default=True) | If True the clusters are put on the vertices of a hypercube. If False,the clusters are put on the vertices of a random polytope. |
| shift | float,array of shape [n_features] or None | optional (default=0.0) | Shift features by the specified value. If None,then features are shifted by a random value drawn in [-class_sep,class_sep]. |
| scale | float array of shape [n_features] or None | optional (default=1.0) | Multiply features by the specified value. If None,then features are scaled by a random value drawn in [1,100]. Note that scaling happens after shifting. |
| shuffle | boolean | optional (default=True) | Shuffle the samples and the features. |
| random_state | int,RandomState instance or None | optional (default=None) | If int,random_state is the seed used by the random number generator; If RandomState instance,random_state is the random number generator; If None,the random number generator is the RandomState instance used by np.random. |
返回的是:
X : array of shape [n_samples, n_features]; 特征矩陣 y : array of shape [n_samples]:矩陣每一行的整數類型標簽
例子:
from sklearn.datasets.samples_generator import make_classification X,y = make_classification(n_samples=2000, n_features=10, n_informative=4, n_classes=4, random_state=0)%matplotlib inline import matplotlib import matplotlib.pyplot as plt plt.style.use('ggplot') plt.figure(figsize=(20,5)); plt.subplot(1, 2, 1 ); plt.scatter(X[:,0] , X[:,1], c = y, alpha = 0.7); plt.subplot(1, 2, 2); plt.hist(y) plt.show()make_gaussian_quantiles 產生高斯分布
輸入參數:
sklearn.datasets.samples_generator.make_gaussian_quantiles(mean=None, cov=1.0, n_samples=100, n_features=2, n_classes=3, shuffle=True, random_state=None)
| mean | array of shape [n_features] | optional (default=None) | The mean of the multi-dimensional normal distribution. If None then use the origin (0, 0, …). |
| cov | float | optional (default=1.) | The covariance matrix will be this value times the unit matrix. This dataset only produces symmetric normal distributions. |
| n_samples | int | optional (default=100) | The total number of points equally divided among classes. |
| n_features | int | optional (default=2) | The number of features for each sample. |
| n_classes | int | optional (default=3) | The number of classes |
| shuffle | boolean | optional (default=True) | Shuffle the samples. |
| random_state | int, RandomState instance or None | optional (default=None) | If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random. |
make_hastie_10_2
產生用于二分類的數據。Hastie et al. 2009
輸入參數:
| n_samples | int | optional (default=12000) | The number of samples. |
| random_state | int, RandomState instance or None | optional (default=None) | If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random. |
輸出:
X : array of shape [n_samples, 10] 特征矩陣。 y : array of shape [n_samples],對應特征矩陣每一個行的真實值。
from sklearn.datasets.samples_generator import make_hastie_10_2 X,y = make_hastie_10_2(n_samples=1000, random_state=None)%matplotlib inline import matplotlib import matplotlib.pyplot as plt plt.style.use('ggplot') plt.figure(figsize=(20,5)); plt.subplot(1, 2, 1 ); plt.scatter(X[:,0] , X[:,1], c = y, alpha = 0.7); plt.subplot(1, 2, 2); plt.hist(y) plt.show()?
?
參考鏈接:https://www.cnblogs.com/nolonely/p/6980160.html
總結
以上是生活随笔為你收集整理的【Python学习】 - sklearn学习 - 自带数据集sklearn.datasets.x的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 信用卡审核没接到电话怎么办 信用卡回访电
- 下一篇: 2017年中信银行微信申请信用卡秒批方法