我正在為我的 LSTM 訓練制作預處理代碼。我的 csv 包含 30 多個變數。在應用了一些 EDA 技術后,我發現可以洗掉一半的特征,并且它們對訓練沒有任何影響。
現在我正在使用pandas.
我想制作一個可以自動洗掉這些功能的代碼。我寫了一個代碼來以這種方式可視化熱圖和相關性:
#I am making a class so this part is from preprocessing.
# self.data is a Dataframe which contains all csv data
def calculateCorrelationByPearson(self):
columns = self.data.columns
plt.figure(figsize=(12, 8))
sns.heatmap(data=self.data.corr(method='pearson'), annot=True, fmt='.2f',
linewidths=0.5, cmap='Blues')
plt.show()
for column in columns:
corr = stats.spearmanr(self.data['total'], self.data[columns])
print(f'{column} - corr coefficient:{corr[0]}, p-value:{corr[1]}')
這讓我對自己的特征和彼此的關系有了一個完美的了解。
現在我想洗掉不重要的列。假設相關性小于 0.4。
如何將此邏輯應用于我的代碼?
uj5u.com熱心網友回復:
這是一種洗掉相關系數值低于某個閾值的變數的方法:
import pandas as pd
from scipy.stats import spearmanr
data = pd.DataFrame([{"A":1, "B":2, "C":3},{"A":2, "B":3, "C":1},{"A":3, "B":4, "C":0},{"A":4, "B":4, "C":1},{"A":5, "B":6, "C":2}])
targetVar = "A"
corr_threshold = 0.4
corr = spearmanr(data)
corrSeries = pd.Series(corr[0][:,0], index=data.columns) #Series with column names and their correlation coefficients
corrSeries = corrSeries[(corrSeries.index != targetVar) & (corrSeries > corr_threshold)] #apply the threshold
vars_to_keep = list(corrSeries.index.values) #list of variables to keep
vars_to_keep.append(targetVar) #add the target variable back in
data2 = data[vars_to_keep]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/402887.html
標籤:
下一篇:如何定義一系列動作空間?
