python機器學習基礎教程-監督學習


1. 分類與回歸

  分類:就是根據給定的標簽,把新的數據划分到這些標簽中的一個

  回歸:就是根據事物一些屬性,來判斷這個事物的另一個屬性在哪個區間范圍

    比如:根據一個人的受教育程度,年齡等,判斷這個人的收入在哪個范圍內

  區別: 分類的輸出是固定的,離散的,是一個點; 回歸的輸出是連續的,是區間.

2.泛化,過擬合與欠擬合

  泛化:一個模型能夠對沒見過的數據做出准確預測,就說模型能夠從訓練集泛化到測試集

  過擬合:構建的模型對於現有的數據來說過於復雜.即模型過分關注訓練集的細節,得到在訓練集上表現過好,但不能泛化到新數據上.

  欠擬合:模型在訓練集上的表現就很差,就是欠擬合

3.監督學習算法

3.1 一些樣本數據集

scikit-learn中數據集都是Bunch對象,包含了真實數據以及一些數據集信息(類似於字典)

3.1.1 forge數據集

導入必要的包

 

forge數據集有兩個特征

# 生成數據集
X, y = mglearn.datasets.make_forge()  # X和y是forge返回的兩個特征
print("X.shape: {}".format(X.shape))  # X.shape: (26, 2)
# 數據集繪圖
mglearn.discrete_scatter(X[:,0],X[:,1],y)  # 輸入X第0列和第1列作為x軸,將y作為y軸
plt.legend(["Class 0", "Class 1"], loc=4)  # 設置圖像的分類名稱
plt.xlabel("First feature")   # 設置圖像x軸的名稱
plt.ylabel("Second feature")  # 設置圖像的y軸的名稱

3.1.2 wave數據集

wave數據集只有一個輸入特征和一個連續的目標變量(x軸表示特征,y軸表示輸出)

X, y = mglearn.datasets.make_wave(n_samples=40) # 生成40個數據,X.shape是(40,1),y.shape是(40,)
plt.plot(X, y, 'o')  # 圖中的點使用圓點表示
plt.ylim(-3, 3)    #設置y軸的區間顯示范圍
plt.xlabel("Feature")
plt.ylabel("Target")

3.1.3 cancer數據集

cancer數據集記錄了乳腺癌腫瘤的臨床測量數據,將每個腫瘤標記為良性和惡性(即只有兩個標簽)

from sklearn.datasets import load_breast_cancer
cancer = load_breast_cancer()
print(cancer.keys())
>>>dict_keys(['data', 'target', 'target_names', 'DESCR', 'feature_names', 'filename'])

print(cancer.data.shape)
print(cancer.target.shape)
print(cancer.target_names)
print(cancer.feature_names)
>>>(569, 30)
>>>(569,)
>>>['malignant' 'benign']
>>>['mean radius' 'mean texture' 'mean perimeter' 'mean area' 'mean smoothness' 'mean compactness' 'mean concavity' 'mean concave points' 'mean symmetry' 'mean fractal dimension' 'radius error' 'texture error' 'perimeter error' 'area error' 'smoothness error' 'compactness error' 'concavity error' 'concave points error' 'symmetry error' 'fractal dimension error' 'worst radius' 'worst texture' 'worst perimeter' 'worst area' 'worst smoothness' 'worst compactness' 'worst concavity' 'worst concave points' 'worst symmetry' 'worst fractal dimension']
{n: v for n, v in zip(cancer.target_names, np.bincount(cancer.target))}
>>>{'malignant': 212, 'benign': 357}

np.bincount的功能:用於統計每個數字的出現次數

x = np.array([0, 1, 1, 3, 2, 1, 7])
a = np.bincount(x)
>>>array([1, 3, 1, 1, 0, 0, 0, 1])
# 如上例,x的范圍就是0-7,bincount生成一個np.max(x)+1的array:a
# 當a要生成第一個數時,此時要生成的數字索引為0,就在x中找0出現了多少次,本例為1次,append進來
# 然后a生成第二個數,此時要生成的數組索引是1,就在x中找1出現了多少次,本例為3
# 依次遍歷到7,即x

np.bincount的weights參數

w = np.array([0.3, 0.5, 0.2, 0.7, 1., -0.6])
# 我們可以看到x中最大的數為4,因此bin的數量為5,那么它的索引值為0->4
x = np.array([2, 1, 3, 4, 4, 3])
# 索引0 -> 0
# 索引1 -> w[1] = 0.5
# 索引2 -> w[0] = 0.3
# 索引3 -> w[2] + w[5] = 0.2 - 0.6 = -0.4
# 索引4 -> w[3] + w[4] = 0.7 + 1 = 1.7
np.bincount(x,  weights=w)
# 因此,輸出結果為:array([ 0. ,  0.5,  0.3, -0.4,  1.7])

 

3.1.4 波士頓房價數據集

這個數據集包含506個數據點,每個數據點有13個特征

from sklearn.datasets import load_boston
boston = load_boston()
print(boston.data.shape)
>>>(506, 13)

 

3.2 k近鄰

3.2.1 k近鄰分類,k-NN算法

取最近的鄰居的類別當做自己的類別

mglearn.plots.plot_knn_classification(n_neighbors=1)

取3個鄰居,並根據3個中類別包含最多個數的那個作為自己的類別

mglearn.plots.plot_knn_classification(n_neighbors=3)

 

3.2.2 應用k近鄰算法

導入數據集,並划分訓練集和測試集

from sklearn.model_selection import train_test_split
X, y = mglearn.datasets.make_forge()
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)

導入類並實例化knn算法,同時設置參數:鄰居的個數

from sklearn.neighbors import KNeighborsClassifier
clf = KNeighborsClassifier(n_neighbors=3)

利用訓練集對分類器進行擬合(對於knn就是保存訓練集的數據,以便predict的時候計算舉例)

clf.fit(X_train, y_train)
>>>KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski', metric_params=None, n_jobs=None, n_neighbors=3, p=2, weights='uniform')

調用predict方法進行預測

clf.predict(X_test)
>>>array([1, 0, 1, 0, 1, 0, 0])
clf.score(X_test, y_test)
>>>0.8571428571428571

3.2.3 分析KNeighborsClassifier

繪制決策邊界: 繪制1個,3個和9個鄰居的決策邊界

fig, axes = plt.subplots(1, 3, figsize=(10,3)) # 繪制一個1行3列的共3個子圖; fig是主圖,axes是子圖
for n_neighbors, ax in zip([1, 3, 9], axes):
    clf = KNeighborsClassifier(n_neighbors=n_neighbors).fit(X, y)
    mglearn.plots.plot_2d_separator(clf, X, fill=True, eps=0.5, ax=ax, alpha=.4)
    mglearn.discrete_scatter(X[:,0], X[:,1], y, ax=ax)
    ax.set_title("{} neighbor(s)".format(n_neighbors))
    ax.set_xlabel("feature 0")
    ax.set_ylabel("feature 1")
axes[0].legend(loc=3)    # loc標示legend的位置是左下角還是右下角,還是上邊

# # # 待更新


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM