本項(xiàng)目使用到的數(shù)據(jù)集鏈接:
https://tianchi-media.oss-cn-beijing.aliyuncs.com/DSW/6tree/penguins_raw.csv
一、數(shù)據(jù)預(yù)處理
1 內(nèi)容和目標(biāo):
加載給定或者自行選定的數(shù)據(jù)集,對數(shù)據(jù)進(jìn)行查看和理解,例如樣本數(shù)量,各特征數(shù)據(jù)類型、分布、特征和標(biāo)簽所表達(dá)的含義等,然后對其進(jìn)行數(shù)據(jù)預(yù)處理工作,包括但不限于對敏感數(shù)據(jù)、缺失值、重復(fù)值、異常值等進(jìn)行統(tǒng)計(jì)和處理,對標(biāo)簽數(shù)據(jù)進(jìn)行編碼,對特征進(jìn)行標(biāo)準(zhǔn)化或歸一化等,最終獲得干凈整潔的數(shù)據(jù)集以便于后續(xù)的算法模型進(jìn)行處理。
2 加載和分析數(shù)據(jù)
2.1 導(dǎo)入基本庫和加載數(shù)據(jù)
# 基礎(chǔ)函數(shù)庫
import numpy as np
import pandas as pd
# 繪圖函數(shù)庫
import matplotlib.pyplot as plt
import seaborn as sns
我們利用pandas自帶的read_csv函數(shù)讀取并轉(zhuǎn)化為DataFrame格式
data = pd.read_csv('./penguins_raw.csv')
2.2 分析數(shù)據(jù)
①查看數(shù)據(jù)集大小
data.shape
## output: (344, 17) 該原始數(shù)據(jù)集包含344行(個(gè)),17列(特征)的數(shù)據(jù)。
②利用.info()查看數(shù)據(jù)的整體信息
data.info()
可以看出一共有17列,每一列的非空值個(gè)數(shù)以及值的類型。其中studyName、Species、Region、Island、Stage、Individual ID、Clutch Completion、Date Egg、Sex、Comments是分類指標(biāo)、Sampe Number為整數(shù)、其他為float64類型組成,數(shù)據(jù)集樣本數(shù)量為 340,數(shù)據(jù)不完整、包含缺失值。
③describe() 函數(shù)可以查看數(shù)值數(shù)據(jù)的基本情況
包括count 非空值數(shù)、mean 平均值、std 標(biāo)準(zhǔn)差、max 最大值、min 最小值、(25%、50%、75%)分位數(shù)
data.describe()
④查看前5行數(shù)據(jù) [.head() 頭部、 .tail()尾部]
data.head(5) # data.tail(5)
3 數(shù)據(jù)清洗
3.1 重復(fù)值處理
分析數(shù)據(jù)可知,’studyName’,‘Sample Number’,'Individual ID’三個(gè)屬性唯一確定一條數(shù)據(jù)。
data[data.duplicated(['studyName','Sample Number','Individual ID'])]
# data[data.duplicated()] 以全部屬性為標(biāo)準(zhǔn)的缺失值
# data.drop([339]) #若存在缺失值,根據(jù)所提示出的行索引刪除即可
3.2 數(shù)據(jù)脫敏—提取重要特征
為了方便我們僅選與企鵝本身關(guān)聯(lián)較大的特征,經(jīng)過查閱資料,我們將定量(喙長Culmen Length (mm)、喙深Culmen Depth (mm)、鰭長Flipper Length (mm)和身體質(zhì)量Body Mass (g))和定性(性別Sex)特征作為輸入,這些特征唯一地描述一個(gè)企鵝,輸出特征為Species,將企鵝進(jìn)行分類任務(wù)。
data = data[['Species', 'Culmen Length (mm)','Culmen Depth (mm)', 'Flipper Length (mm)','Body Mass (g)','Sex']]
3.3 缺失值處理
①查看數(shù)據(jù)缺失情況
data.isnull().sum()
②分析數(shù)據(jù)間的相關(guān)性
# 使用皮爾森計(jì)算特征相關(guān)矩陣
corr = data.corr(method='pearson')
# 熱力圖繪制相關(guān)性矩陣
sns.heatmap(data=corr, annot=True, cmap='coolwarm')
根據(jù)圖中數(shù)據(jù),可以看到缺失值特征與其它特性相關(guān)性均不大,因而通過其它特征進(jìn)行填充的方案不可行,結(jié)合數(shù)據(jù)理解部分的統(tǒng)計(jì)結(jié)果,故直接才用均值進(jìn)行填充可能更為簡單直接一些。
③處理缺失值
這里我們發(fā)現(xiàn)數(shù)據(jù)中存在缺失值,考慮到企鵝數(shù)據(jù)的實(shí)際意義,我們不能將缺失的數(shù)據(jù)刪除,故采用均值插補(bǔ)對連續(xù)的缺失值進(jìn)行處理,對于離散的分類數(shù)據(jù)值,我們采用MALE進(jìn)行填補(bǔ)。
data['Culmen Length (mm)']=data['Culmen Length (mm)'].fillna(data['Culmen Length (mm)'].mean())
data['Culmen Depth (mm)']=data['Culmen Depth (mm)'].fillna(data['Culmen Depth (mm)'].mean())
data['Flipper Length (mm)']=data['Flipper Length (mm)'].fillna(data['Flipper Length (mm)'].mean())
data['Body Mass (g)']=data['Body Mass (g)'].fillna(data['Body Mass (g)'].mean())
data['Sex']=data['Sex'].fillna(‘MALE’)
3.4 異常值處理
使用 3σ 法則識別異常值,并使用均值對其進(jìn)行填充處理。
list = ['Culmen Length (mm)','Culmen Depth (mm)','Flipper Length (mm)','Body Mass (g)']
for i in range(len(list)):
# 使用 3σ 法則識別異常值
col = data[list[i]]
condition = (col - col.mean()).abs() > 3 * col.std()
# 顯示找到的異常值
indices = np.arange(col.shape[0])[condition]
print(list[i])
print(col.loc[indices])
根據(jù)得出的行索引修改異常值
data.loc[[35,50],['Culmen Length (mm)']]=data['Culmen Length (mm)'].mean()
3.5 標(biāo)簽編碼或獨(dú)熱編碼
# 對目標(biāo)值進(jìn)行標(biāo)簽編碼
target = data[‘Species']
from sklearn.preprocessing import LabelEncoder
encoder = LabelEncoder()
data[‘Species'] = encoder.fit_transform(target) data[‘Species'].unique()
# 對Sex進(jìn)行標(biāo)簽編碼
target = data[‘Sex']
from sklearn.preprocessing import LabelEncoder
encoder = LabelEncoder()
data[‘Sex'] = encoder.fit_transform(target) data[‘Sex'].unique()
# output:array([0, 1, 2], dtype=int64)
4 其他處理
4.1 利用value_counts函數(shù)查看每個(gè)類別數(shù)量
pd.Series(data['Species']).value_counts()
可以看到,數(shù)據(jù)集中種類是Adelie Penguin (Pygoscelis adeliae)、Chinstrap penguin (Pygoscelis antarctica)、Gentoo penguin (Pygoscelis papua)的企鵝分別有152、124、68個(gè)。
4.2 特征與標(biāo)簽組合的散點(diǎn)可視化
sns.pairplot(data=data, diag_kind='hist', hue= 'Species')
plt.show()
二、機(jī)器學(xué)習(xí)算法
經(jīng)過數(shù)據(jù)預(yù)處理的數(shù)據(jù)比較完整可靠,下面我們將處理后的數(shù)據(jù)應(yīng)用到算法中。
1 數(shù)據(jù)歸一化和劃分
1.1 數(shù)據(jù)歸一化處理
for i in list(['Culmen Length (mm)','Culmen Depth (mm)','Flipper Length (mm)','Body Mass (g)']):
Max=np.max(data[i])
Min=np.min(data[i])
data[i]=(data[i]-Min)/(Max-Min)
1.2 數(shù)據(jù)集劃分
為了正確評估模型性能,將數(shù)據(jù)劃分為訓(xùn)練集和測試集,并在訓(xùn)練集上訓(xùn)練模型,在測試集上驗(yàn)證模型性能,我們將訓(xùn)練集和測試集劃分為4:1。
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(data[['Culmen Length (mm)','Culmen Depth (mm)', 'Flipper Length (mm)','Body Mass (g)', ‘Sex’]], data[['Species']], test_size = 0.2, random_state = 2022)
2 算法應(yīng)用
以決策樹為例,sklearn的tree模塊提供了 DecisionTreeClassifier 算法的具體實(shí)現(xiàn)。
2.1 算法實(shí)現(xiàn)
## 從sklearn中導(dǎo)入決策樹模型
from sklearn.tree import DecisionTreeClassifier
from sklearn import tree
from sklearn import metrics
## 定義 決策樹模型
clf = DecisionTreeClassifier()
# 在訓(xùn)練集上訓(xùn)練決策樹模型
clf.fit(x_train, y_train)
## 在訓(xùn)練集和測試集上分布利用訓(xùn)練好的模型進(jìn)行預(yù)測
train_predict = clf.predict(x_train)
test_predict = clf.predict(x_test)
print('The accuracy of the Logistic Regression is:',metrics.accuracy_score(y_train,train_predict))
print('The accuracy of the Logistic Regression is:',metrics.accuracy_score(y_test,test_predict))
## 由于決策樹模型是概率預(yù)測模型(前文介紹的 p = p(y=1|x,\theta)),所有我們可以利用 predict_proba 函數(shù)預(yù)測其概率
train_predict_proba = clf.predict_proba(x_train)
test_predict_proba = clf.predict_proba(x_test)
# print('The test predict Probability of each class:\n',test_predict_proba)
## 其中第一列代表預(yù)測為0類的概率,第二列代表預(yù)測為1類的概率,第三列代表預(yù)測為2類的概率。
## 利用accuracy(準(zhǔn)確度)【預(yù)測正確的樣本數(shù)目占總預(yù)測樣本數(shù)目的比例】評估模型效果
## 查看混淆矩陣
confusion_matrix_result = metrics.confusion_matrix(test_predict,y_test)
print('The confusion matrix result:\n',confusion_matrix_result)
# 利用熱力圖對于結(jié)果進(jìn)行可視化
plt.figure(figsize=(8, 6))
sns.heatmap(confusion_matrix_result, annot=True, cmap='Blues')
plt.xlabel('Predicted labels')
plt.ylabel('True labels')
plt.show()
2.2 算法評估與分析
2.2.1 模型特征重要性andPermutation Importance
注意!不是所有的模型都有feature_importances_屬性
from sklearn.inspection import permutation_importance
fearture_name=['Culmen Length (mm)','Culmen Depth (mm)', 'Flipper Length (mm)','Body Mass (g)']
feature_importance = clf.feature_importances_
sorted_idx = np.argsort(feature_importance)
pos = np.arange(sorted_idx.shape[0]) + 0.5
fig = plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.barh(pos, feature_importance[sorted_idx], align="center")
plt.yticks(pos, np.array(fearture_name)[sorted_idx])
plt.title("Feature Importance (MDI)")
result = permutation_importance(
clf, x_test, y_test, n_repeats=15, random_state=12, n_jobs=1
)
# print(result)
sorted_idx = result.importances_mean.argsort()
plt.subplot(1, 2, 2)
plt.boxplot(
result.importances[sorted_idx].T,
vert=False,
labels=np.array(fearture_name)[sorted_idx],
)
plt.title("Permutation Importance (test set)")
fig.tight_layout()
plt.show()
2.2.2 提取特征可視化
from matplotlib.colors import ListedColormap
# 使用兩個(gè)特征來預(yù)測,這樣方便繪制預(yù)測結(jié)果
x = data[['Culmen Length (mm)','Culmen Depth (mm)']]
y = data['Species']
clf =GradientBoostingClassifier()
clf.fit(x, y)
# 創(chuàng)建顏色組合
cmap_light = ListedColormap(['orange', 'cyan', 'cornflowerblue'])
cmap_bold = ['darkorange', 'c', 'darkblue']
# 繪制不同類別區(qū)域
x_min, x_max = x[ 'Culmen Length (mm)'].min() - 1, x['Culmen Length (mm)'].max() + 1
y_min, y_max = x['Culmen Depth (mm)'].min() - 1, x['Culmen Depth (mm)'].max() + 1
h = .02
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
z = z.reshape(xx.shape)
plt.contourf(xx, yy, z, cmap=cmap_light)
# 繪制數(shù)據(jù)點(diǎn)
sns.scatterplot(x=x['Culmen Length (mm)'], y=x['Culmen Depth (mm)'], hue=y,
palette=cmap_bold, alpha=1.0, edgecolor="black")
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.xlabel('Culmen Length (mm)')
plt.ylabel('Culmen Depth (mm)')
plt.title('GradientBoostingClassifier-liliangshuo-210217')
plt.show()
使用前兩個(gè)特征來預(yù)測,這樣方便繪制預(yù)測結(jié)果。可以看出,0和2分類的比較準(zhǔn)確,而1相對來說不準(zhǔn)確,符合我們的決策樹分類模型預(yù)測的結(jié)果。
3 其他常用機(jī)器學(xué)習(xí)算法的封裝(分類)
①邏輯回歸模型
from sklearn.linear_model import LogisticRegression
②支持向量機(jī)分類
from sklearn.svm import SVC()
③MLP分類
from sklearn.neural_network import MLPClassifier
④KNN分類
from sklearn.neighbors import KNeighborsClassifier
⑤決策樹分類
from sklearn.tree import DecisionTreeClassifier
⑥梯度提升決策樹分類文章來源:http://www.zghlxwxcb.cn/news/detail-499820.html
from sklearn.ensemble import GradientBoostingClassifier
⑦隨機(jī)森林分類文章來源地址http://www.zghlxwxcb.cn/news/detail-499820.html
from sklearn.ensemble import RandomForestClassifier
到了這里,關(guān)于《人工智能-機(jī)器學(xué)習(xí)》數(shù)據(jù)預(yù)處理和機(jī)器學(xué)習(xí)算法(以企鵝penguins數(shù)據(jù)集為例)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!