博主前期相關的博客可見下:
機器學習項目實戰(zhàn)-能源利用率 Part-1(數(shù)據(jù)清洗)
機器學習項目實戰(zhàn)-能源利用率 Part-2(探索性數(shù)據(jù)分析)
這部分進行的特征工程與特征篩選。
三 特征工程與特征篩選
一般情況下我們分兩步走:特征工程與特征篩選:
特征工程: 概括性來說就是盡可能的多在數(shù)據(jù)中提取特征,各種數(shù)值變換,特征組合,分解等各種手段齊上陣。
特征選擇: 就是找到最有價值的那些特征作為我們模型的輸入,但是之前做了那么多,可能有些是多余的,有些還沒被發(fā)現(xiàn),所以這倆階段都是一個反復在更新的過程。比如我在建模之后拿到了特征重要性,這就為特征選擇做了參考,有些不重要的我可以去掉,那些比較重要的,我還可以再想辦法讓其做更多變換和組合來促進我的模型。所以特征工程并不是一次性就能解決的,需要通過各種結果來反復斟酌。
3.1 特征變換 與 One-hot encode
有點像分析特征之間的相關性
features = data.copy()
numeric_subset = data.select_dtypes('number')
for col in numeric_subset.columns:
if col == 'score':
next
else:
numeric_subset['log_' + col] = np.log(abs(numeric_subset[col]) + 0.01)
categorical_subset = data[['Borough', 'Largest Property Use Type']]
categorical_subset = pd.get_dummies(categorical_subset)
features = pd.concat([numeric_subset, categorical_subset], axis = 1)
features.shape
這段代碼的目的是為了生成特征矩陣 features
,它包含了原始數(shù)據(jù) data
的數(shù)值特征和分類特征的處理結果。
首先,代碼復制了原始數(shù)據(jù) data
,并將其賦值給 features
。
接下來,通過 select_dtypes('number')
選擇了 data
中的數(shù)值類型的列,并將結果存儲在 numeric_subset
中。
然后,使用一個循環(huán)遍歷 numeric_subset
的列,對每一列進行處理。對于列名為 ‘score’ 的列,直接跳過(使用 next
)。對于其他列,將其絕對值加上一個很小的常數(shù)(0.01),然后取對數(shù),并將結果存儲在 numeric_subset
中以 ‘log_’ 開頭的列名中。
接著,從 data
中選擇了 ‘Borough’ 和 ‘Largest Property Use Type’ 兩列作為分類特征,并使用 pd.get_dummies
進行獨熱編碼(One-Hot Encoding)得到它們的編碼結果,并將結果存儲在 categorical_subset
中。
最后,使用 pd.concat
將 numeric_subset
和 categorical_subset
按列方向(axis=1)進行拼接,得到最終的特征矩陣 features
。
最后一行代碼輸出了 features
的形狀(行數(shù)和列數(shù))。
3.2 共線特征
在數(shù)據(jù)中Site EUI 和 Weather Norm EUI就是要考慮的目標,他倆描述的基本是同一個事
plot_data = data[['Weather Normalized Site EUI (kBtu/ft2)', 'Site EUI (kBtu/ft2)']].dropna()
plt.plot(plot_data['Site EUI (kBtu/ft2)'], plot_data['Weather Normalized Site EUI (kBtu/ft2)'], 'bo')
plt.xlabel('Site EUI'); plt.ylabel('Weather Norm EUI')
plt.title('Weather Norm EUI vs Site EUI, R = %.4f' % np.corrcoef(data[['Weather Normalized Site EUI (kBtu/ft2)', 'Site EUI (kBtu/ft2)']].dropna(), rowvar=False)[0][1])
3.3 剔除共線特征
def remove_collinear_features(x, threshold):
'''
Objective:
Remove collinear features in a dataframe with a correlation coefficient
greater than the threshold. Removing collinear features can help a model
to generalize and improves the interpretability of the model.
Inputs:
threshold: any features with correlations greater than this value are removed
Output:
dataframe that contains only the non-highly-collinear features
'''
y = x['score']
x = x.drop(columns = ['score'])
corr_matrix = x.corr()
iters = range(len(corr_matrix.columns) - 1)
drop_cols = []
for i in iters:
for j in range(i):
item = corr_matrix.iloc[j: (j+1), (i+1): (i+2)]
col = item.columns
row = item.index
val = abs(item.values)
if val >= threshold:
# print(col.values[0], "|", row.values[0], "|", round(val[0][0], 2))
drop_cols.append(col.values[0])
drops = set(drop_cols)
# print(drops)
x = x.drop(columns = drops)
x = x.drop(columns = ['Weather Normalized Site EUI (kBtu/ft2)',
'Water Use (All Water Sources) (kgal)',
'log_Water Use (All Water Sources) (kgal)',
'Largest Property Use Type - Gross Floor Area (ft2)'])
x['score'] = y
return x
features = remove_collinear_features(features, 0.6) # 閾值為0.6
features = features.dropna(axis = 1, how = 'all')
print(features.shape)
features.head()
這段代碼定義了一個名為 remove_collinear_features
的函數(shù),用于移除具有高相關性的特征。移除具有高相關性的特征可以幫助模型泛化并提高模型的解釋性。
函數(shù)的輸入?yún)?shù)為 x
(包含特征和目標變量的數(shù)據(jù)框)和 threshold
(相關系數(shù)的閾值),閾值以上的特征相關性會被移除。
首先,將目標變量 score
存儲在變量 y
中,并將其從 x
中移除。
接下來,計算特征之間的相關系數(shù)矩陣 corr_matrix
。
然后,使用兩個嵌套的循環(huán)遍歷相關系數(shù)矩陣中的元素。當相關系數(shù)的絕對值大于等于閾值時,將該特征的列名添加到 drop_cols
列表中。
完成循環(huán)后,將 drop_cols
轉換為集合 drops
,以去除重復的特征列名。
然后,從 x
中移除 drops
中的特征列,以及其他預定義的特征列。
接下來,將目標變量 y
添加回 x
中,并將結果返回。
最后,對更新后的特征矩陣 features
進行處理,移除所有包含缺失值的列,并輸出其形狀(行數(shù)和列數(shù)),并展示前幾行數(shù)據(jù)。
3.4 數(shù)據(jù)集劃分
no_score = features[features['score'].isna()]
score = features[features['score'].notnull()]
print('no_score.shape: ', no_score.shape)
print('score.shape', score.shape)
from sklearn.model_selection import train_test_split
features = score.drop(columns = 'score')
labels = pd.DataFrame(score['score'])
features = features.replace({np.inf: np.nan, -np.inf: np.nan})
X, X_test, y, y_test = train_test_split(features, labels, test_size = 0.3, random_state = 42)
print(X.shape)
print(X_test.shape)
print(y.shape)
print(y_test.shape)
這段代碼分為幾個步驟:
-
首先,將特征矩陣
features
分為兩部分:no_score
和score
。其中,no_score
是features
中目標變量score
為空的部分,而score
則是features
中目標變量score
不為空的部分。 -
輸出
no_score
和score
的形狀(行數(shù)和列數(shù)),分別使用no_score.shape
和score.shape
打印結果。 -
導入
sklearn.model_selection
模塊中的train_test_split
函數(shù)。 -
從
score
中移除目標變量score
列,得到特征矩陣features
。 -
創(chuàng)建標簽(目標變量)矩陣
labels
,其中只包含目標變量score
列。 -
使用
replace
方法將features
中的無窮大值替換為缺失值(NaN)。 -
使用
train_test_split
函數(shù)將特征矩陣features
和標簽矩陣labels
劃分為訓練集和測試集。參數(shù)test_size
設置測試集的比例為 0.3,random_state
設置隨機種子為 42。將劃分后的結果分別存儲在X
、X_test
、y
和y_test
中。 -
輸出訓練集
X
、測試集X_test
、訓練集標簽y
和測試集標簽y_test
的形狀(行數(shù)和列數(shù)),分別使用X.shape
、X_test.shape
、y.shape
和y_test.shape
打印結果。
這段代碼的目的是將數(shù)據(jù)集劃分為訓練集和測試集,并準備好用于訓練和評估模型的特征矩陣和標簽矩陣。
3.5 建立一個Baseline
在建模之前,我們得有一個最壞的打算,就是模型起碼得有點作用才行。
# 衡量標準: Mean Absolute Error
def mae(y_true, y_pred):
return np.mean(abs(y_true - y_pred))
baseline_guess = np.median(y)
print('The baseline guess is a score of %.2f' % baseline_guess)
print('Baseline Performance on the test set: MAE = %.4f' % mae(y_test, baseline_guess))
這段代碼定義了一個衡量標準函數(shù) mae
,并計算了一個基準預測結果。
-
mae
函數(shù)計算了預測值與真實值之間的平均絕對誤差(Mean Absolute Error)。它接受兩個參數(shù)y_true
和y_pred
,分別表示真實值和預測值。函數(shù)內部通過np.mean(abs(y_true - y_pred))
計算平均絕對誤差,并返回結果。 -
baseline_guess
是基準預測的結果,它被設置為標簽(目標變量)y
的中位數(shù)。這相當于一種簡單的基準方法,用中位數(shù)作為所有預測的固定值。 -
使用
print
函數(shù)打印基準預測結果的信息。'The baseline guess is a score of %.2f' % baseline_guess
會輸出基準預測結果的值,保留兩位小數(shù)。'Baseline Performance on the test set: MAE = %.4f' % mae(y_test, baseline_guess)
會輸出基準預測結果在測試集上的性能,即平均絕對誤差(MAE),保留四位小數(shù)。
這段代碼的目的是計算基準預測結果,并輸出基準預測結果的信息以及在測試集上的性能評估(使用平均絕對誤差作為衡量標準)。
3.6 保存數(shù)據(jù)
no_score.to_csv('data/no_score.csv', index = False)
X.to_csv('data/training_features.csv', index = False)
X_test.to_csv('data/testing_features.csv', index = False)
y.to_csv('data/training_labels.csv', index = False)
y_test.to_csv('data/testing_labels.csv', index = False)
Reference
機器學習項目實戰(zhàn)-能源利用率 Part-1(數(shù)據(jù)清洗)
機器學習項目實戰(zhàn)-能源利用率 Part-2(探索性數(shù)據(jù)分析)文章來源:http://www.zghlxwxcb.cn/news/detail-452057.html
機器學習項目實戰(zhàn)-能源利用率1-數(shù)據(jù)預處理文章來源地址http://www.zghlxwxcb.cn/news/detail-452057.html
到了這里,關于機器學習項目實戰(zhàn)-能源利用率 Part-3(特征工程與特征篩選)的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!