百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程字典 > 正文

机器学习特征选择和降维实例

toyiye 2024-04-27 03:47 26 浏览 0 评论

“特征选择是选择用于模型构建的相关特征的子集的过程”,或者换句话说,选择最重要的特征。

在正常情况下,领域知识起着重要作用,我们可以选择我们认为最重要的特征。例如,在预测房价时,卧室和面积通常被认为是重要的。不幸的是,在Do not Overfit II竞赛(https://www.kaggle.com/c/dont-overfit-ii/data)中,领域知识的使用是不可能的,因为我们有一个二元目标和300个连续变量,这迫使我们尝试特征选择技术。

简介

通常,我们将特征选择和降维组合在一起使用。虽然这两种方法都用于减少数据集中的特征数量,但存在很大不同。

特征选择只是选择和排除给定的特征而不改变它们。

降维是将特征转换为较低维度。

在本文中,我们将探索以下特征选择和降维技术:

特征选择

  • 删除缺少值的特征
  • 删除方差较小的特征
  • 删除高度相关的特征
  • 单变量特征选择
  • 递归特征消除
  • 使用SelectFromModel选择特征

维度降低

  • PCA

加载数据

导入必须的Python库

import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier

设置默认绘图参数

%matplotlib inline
plt.rcParams['figure.figsize'] = [20.0, 7.0]
plt.rcParams.update({'font.size': 22,})
sns.set_palette('viridis')
sns.set_style('white')
sns.set_context('talk', font_scale=0.8)

加载机器学习数据集

train = pd.read_csv('../input/train.csv')
test = pd.read_csv('../input/test.csv')
print('Train Shape: ', train.shape)
print('Test Shape: ', test.shape)
train.head()

Train Shape: (250, 302)

Test Shape: (19750, 301)

使用seaborns countplot来显示机器学习数据集中问题的分布

fig, ax = plt.subplots()
g = sns.countplot(train.target, palette='viridis')
g.set_xticklabels(['0', '1'])
g.set_yticklabels([])
# function to show values on bars
def show_values_on_bars(axs):
 def _show_on_single_plot(ax): 
 for p in ax.patches:
 _x = p.get_x() + p.get_width() / 2
 _y = p.get_y() + p.get_height()
 value = '{:.0f}'.format(p.get_height())
 ax.text(_x, _y, value, ha="center") 
 if isinstance(axs, np.ndarray):
 for idx, ax in np.ndenumerate(axs):
 _show_on_single_plot(ax)
 else:
 _show_on_single_plot(axs)
show_values_on_bars(ax)
sns.despine(left=True, bottom=True)
plt.xlabel('')
plt.ylabel('')
plt.title('Distribution of Target', fontsize=30)
plt.tick_params(axis='x', which='major', labelsize=15)
plt.show()

基线模型

我们将使用逻辑回归作为基线模型。我们首先将数据分为测试集和训练集,并进行了缩放:

# prepare for modeling
X_train_df = train.drop(['id', 'target'], axis=1)
y_train = train['target']
X_test = test.drop(['id'], axis=1)
# scaling data
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train_df)
X_test = scaler.transform(X_test)
lr = LogisticRegression(solver='liblinear')
rfc = RandomForestClassifier(n_estimators=100)
lr_scores = cross_val_score(lr,
 X_train,
 y_train,
 cv=5,
 scoring='roc_auc')
rfc_scores = cross_val_score(rfc, X_train, y_train, cv=5, scoring='roc_auc')
print('LR Scores: ', lr_scores)
print('RFC Scores: ', rfc_scores)

LR Scores: [0.80729167 0.71875 0.734375 0.80034722 0.66319444]

RFC Scores: [0.66753472 0.61371528 0.69618056 0.63715278 0.65104167]

检查是最重要的特征

# checking which are the most important features
feature_importance = rfc.fit(X_train, y_train).feature_importances_
# Make importances relative to max importance.
feature_importance = 100.0 * (feature_importance / feature_importance.max())
sorted_idx = np.argsort(feature_importance)
sorted_idx = sorted_idx[-20:-1:1]
pos = np.arange(sorted_idx.shape[0]) + .5
plt.barh(pos, feature_importance[sorted_idx], align='center')
plt.yticks(pos, X_train_df.columns[sorted_idx])
plt.xlabel('Relative Importance')
plt.title('Feature Importance', fontsize=30)
plt.tick_params(axis='x', which='major', labelsize=15)
sns.despine(left=True, bottom=True)
plt.show()

从交叉验证分数的变化可以看出,模型存在过拟合现象。我们可以尝试通过特征选择来提高这些分数。

删除有缺失值的特征

检查缺失值是任何机器学习问题的第一步。然后我们可以删除超过我们定义的阈值的列。

train.isnull().any().any()

False

数据集没有缺失值,因此在此步骤中没有要删除的特征。

删除低方差的特征

在sklearn的特征选择模块中,我们可以找到VarianceThreshold。它删除方差不满足某个阈值的所有特征。默认情况下,它删除了方差为零的特征,或所有样本值相同的特征。

from sklearn import feature_selection
sel = feature_selection.VarianceThreshold()
train_variance = sel.fit_transform(train)
train_variance.shape

(250, 302)

我们可以从上面看到,所有列中都没有相同值的特征,因此我们没有要删除的特征。

删除高度相关的特征

高度相关或共线性的特征可能导致过度拟合。

当一对变量高度相关时,我们可以删除一个变量来减少维度,而不会损失太多信息。我们应该保留哪一个呢?与目标相关性更高的那个。

让我们来探索我们的特征之间的相关性:

# find correlations to target
corr_matrix = train.corr().abs()
print(corr_matrix['target'].sort_values(ascending=False).head(10))

这里我们看到了与目标变量高度相关的特性。特征33与目标相关性最高,但相关值仅为0.37,仅为弱相关。

我们还可以检查特征与其他特征之间的相关性。下面我们可以看到一个相关矩阵。看起来我们所有的特征都不是高度相关的。

# Select upper triangle of correlation matrix
matrix = corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(np.bool))
sns.heatmap(matrix)
plt.show;

相关矩阵

让我们尝试删除相关值大于0.5的特征:

# Find index of feature columns with high correlation
to_drop = [column for column in matrix.columns if any(matrix[column] > 0.50)]
print('Columns to drop: ' , (len(to_drop)))

Columns to drop: 0

从上面的相关矩阵可以看出,数据集中没有高度相关的特征。最高的相关性仅为0.37。

单变量特征选择

单变量特征选择是基于单变量统计检验选择最优特征。

我们可以使用sklearn的SelectKBest来选择一些要保留的特征。这种方法使用统计测试来选择与目标相关性最高的特征。这里我们将保留前100个特征。

# feature extraction
k_best = feature_selection.SelectKBest(score_func=feature_selection.f_classif, k=100)
# fit on train set
fit = k_best.fit(X_train, y_train)
# transform train set
univariate_features = fit.transform(X_train)
# checking which are the most important features
feature_importance = rfc.fit(univariate_features, y_train).feature_importances_
# Make importances relative to max importance.
feature_importance = 100.0 * (feature_importance / feature_importance.max())
sorted_idx = np.argsort(feature_importance)
sorted_idx = sorted_idx[-20:-1:1]
pos = np.arange(sorted_idx.shape[0]) + .5
plt.barh(pos, feature_importance[sorted_idx], align='center')
plt.yticks(pos, X_train_df.columns[sorted_idx])
plt.xlabel('Relative Importance')
plt.title('Feature Importance', fontsize=30)
plt.tick_params(axis='x', which='major', labelsize=15)
sns.despine(left=True, bottom=True)
plt.show()

交叉验证分数比上面的基线有所提高,但是我们仍然可以看到分数的变化,这表明过度拟合。

递归特性消除

递归特征选择通过消除最不重要的特征来实现。它进行递归,直到达到指定数量的特征为止。递归消除可以用于通过coef_或feature_importances_为特征分配权重的任何模型。

在这里,我们将使用随机森林选择100个最好的特征:

# feature extraction
rfe = feature_selection.RFE(lr, n_features_to_select=100)
# fit on train set
fit = rfe.fit(X_train, y_train)
# transform train set
recursive_features = fit.transform(X_train)
lr = LogisticRegression(solver='liblinear')
rfc = RandomForestClassifier(n_estimators=10)
lr_scores = cross_val_score(lr, recursive_features, y_train, cv=5, scoring='roc_auc')
rfc_scores = cross_val_score(rfc, recursive_features, y_train, cv=5, scoring='roc_auc')
print('LR Scores: ', lr_scores)
print('RFC Scores: ', rfc_scores)

LR Scores: [0.99826389 0.99652778 0.984375 1. 0.99652778]

RFC Scores: [0.63368056 0.72569444 0.66666667 0.77430556 0.59895833]

# checking which are the most important features
feature_importance = rfc.fit(recursive_features, y_train).feature_importances_
# Make importances relative to max importance.
feature_importance = 100.0 * (feature_importance / feature_importance.max())
sorted_idx = np.argsort(feature_importance)
sorted_idx = sorted_idx[-20:-1:1]
pos = np.arange(sorted_idx.shape[0]) + .5
plt.barh(pos, feature_importance[sorted_idx], align='center')
plt.yticks(pos, X_train_df.columns[sorted_idx])
plt.xlabel('Relative Importance')
plt.title('Feature Importance', fontsize=30)
plt.tick_params(axis='x', which='major', labelsize=15)
sns.despine(left=True, bottom=True)
plt.show()

使用SelectFromModel选择特征

与递归特征选择一样,sklearn的SelectFromModel与任何具有coef_或featureimportances属性的估计器一起使用。它删除低于设置阈值的特征。

# feature extraction
select_model = feature_selection.SelectFromModel(lr)
# fit on train set
fit = select_model.fit(X_train, y_train)
# transform train set
model_features = fit.transform(X_train)
lr = LogisticRegression(solver='liblinear')
rfc = RandomForestClassifier(n_estimators=100)
lr_scores = cross_val_score(lr, model_features, y_train, cv=5, scoring='roc_auc')
rfc_scores = cross_val_score(rfc, model_features, y_train, cv=5, scoring='roc_auc')
print('LR Scores: ', lr_scores)
print('RFC Scores: ', rfc_scores)

LR Scores: [0.984375 0.99479167 0.97222222 0.99305556 0.99305556]

RFC Scores: [0.70659722 0.80729167 0.76475694 0.84461806 0.77170139]

# checking which are the most important features
feature_importance = rfc.fit(model_features, y_train).feature_importances_
# Make importances relative to max importance.
feature_importance = 100.0 * (feature_importance / feature_importance.max())
sorted_idx = np.argsort(feature_importance)
sorted_idx = sorted_idx[-20:-1:1]
pos = np.arange(sorted_idx.shape[0]) + .5
plt.barh(pos, feature_importance[sorted_idx], align='center')
plt.yticks(pos, X_train_df.columns[sorted_idx])
plt.xlabel('Relative Importance')
plt.title('Feature Importance', fontsize=30)
plt.tick_params(axis='x', which='major', labelsize=15)
sns.despine(left=True, bottom=True)
plt.show()

PCA

主成分分析(PCA)是一种降维技术,它将数据投影到较低的维度空间。PCA在许多情况下都是有用的,但在多重共线性或预测函数需要解释的情况下,就不需要优先考虑了。

这里我们将使用PCA,保持90%的方差:

from sklearn.decomposition import PCA
# pca - keep 90% of variance
pca = PCA(0.90)
principal_components = pca.fit_transform(X_train)
principal_df = pd.DataFrame(data = principal_components)
principal_df.shape

(250, 139)

lr = LogisticRegression(solver='liblinear')
rfc = RandomForestClassifier(n_estimators=100)
lr_scores = cross_val_score(lr, principal_df, y_train, cv=5, scoring='roc_auc')
rfc_scores = cross_val_score(rfc, principal_df, y_train, cv=5, scoring='roc_auc')
print('LR Scores: ', lr_scores)
print('RFC Scores: ', rfc_scores)

LR Scores: [0.80902778 0.703125 0.734375 0.80555556 0.66145833]

RFC Scores: [0.60503472 0.703125 0.69878472 0.56597222 0.72916667]

# pca keep 75% of variance
pca = PCA(0.75)
principal_components = pca.fit_transform(X_train)
principal_df = pd.DataFrame(data = principal_components)
principal_df.shape

(250, 93)

lr = LogisticRegression(solver='liblinear')
rfc = RandomForestClassifier(n_estimators=100)
lr_scores = cross_val_score(lr, principal_df, y_train, cv=5, scoring='roc_auc')
rfc_scores = cross_val_score(rfc, principal_df, y_train, cv=5, scoring='roc_auc')
print('LR Scores: ', lr_scores)
print('RFC Scores: ', rfc_scores)

LR Scores: [0.72048611 0.60069444 0.68402778 0.71006944 0.61284722]

RFC Scores: [0.61545139 0.71440972 0.57465278 0.59722222 0.640625 ]

# checking which are the most important features
feature_importance = rfc.fit(principal_df, y_train).feature_importances_
# Make importances relative to max importance.
feature_importance = 100.0 * (feature_importance / feature_importance.max())
sorted_idx = np.argsort(feature_importance)
sorted_idx = sorted_idx[-20:-1:1]
pos = np.arange(sorted_idx.shape[0]) + .5
plt.barh(pos, feature_importance[sorted_idx], align='center')
plt.yticks(pos, X_train_df.columns[sorted_idx])
plt.xlabel('Relative Importance')
plt.title('Feature Importance', fontsize=30)
plt.tick_params(axis='x', which='major', labelsize=15)
sns.despine(left=True, bottom=True)
plt.show()

# feature extraction
rfe = feature_selection.RFE(lr, n_features_to_select=100)
# fit on train set
fit = rfe.fit(X_train, y_train)
# transform train set
recursive_X_train = fit.transform(X_train)
recursive_X_test = fit.transform(X_test)
lr = LogisticRegression(C=1, class_weight={1:0.6, 0:0.4}, penalty='l1', solver='liblinear')
lr_scores = cross_val_score(lr, recursive_X_train, y_train, cv=5, scoring='roc_auc')
lr_scores.mean()

0.9059027777777778

predictions = lr.fit(recursive_X_train, y_train).predict_proba(recursive_X_test)
submission = pd.read_csv('../input/sample_submission.csv')
submission['target'] = predictions
submission.to_csv('submission.csv', index=False)
submission.head()

结论

特征选择是任何机器学习过程的重要组成部分。在本文中,我们探索了几种有助于提高模型性能的特征选择和降维方法。

相关推荐

为何越来越多的编程语言使用JSON(为什么编程)

JSON是JavascriptObjectNotation的缩写,意思是Javascript对象表示法,是一种易于人类阅读和对编程友好的文本数据传递方法,是JavaScript语言规范定义的一个子...

何时在数据库中使用 JSON(数据库用json格式存储)

在本文中,您将了解何时应考虑将JSON数据类型添加到表中以及何时应避免使用它们。每天?分享?最新?软件?开发?,Devops,敏捷?,测试?以及?项目?管理?最新?,最热门?的?文章?,每天?花?...

MySQL 从零开始:05 数据类型(mysql数据类型有哪些,并举例)

前面的讲解中已经接触到了表的创建,表的创建是对字段的声明,比如:上述语句声明了字段的名称、类型、所占空间、默认值和是否可以为空等信息。其中的int、varchar、char和decimal都...

JSON对象花样进阶(json格式对象)

一、引言在现代Web开发中,JSON(JavaScriptObjectNotation)已经成为数据交换的标准格式。无论是从前端向后端发送数据,还是从后端接收数据,JSON都是不可或缺的一部分。...

深入理解 JSON 和 Form-data(json和formdata提交区别)

在讨论现代网络开发与API设计的语境下,理解客户端和服务器间如何有效且可靠地交换数据变得尤为关键。这里,特别值得关注的是两种主流数据格式:...

JSON 语法(json 语法 priority)

JSON语法是JavaScript语法的子集。JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔花括号保存对象方括号保存数组JS...

JSON语法详解(json的语法规则)

JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔大括号保存对象中括号保存数组注意:json的key是字符串,且必须是双引号,不能是单引号...

MySQL JSON数据类型操作(mysql的json)

概述mysql自5.7.8版本开始,就支持了json结构的数据存储和查询,这表明了mysql也在不断的学习和增加nosql数据库的有点。但mysql毕竟是关系型数据库,在处理json这种非结构化的数据...

JSON的数据模式(json数据格式示例)

像XML模式一样,JSON数据格式也有Schema,这是一个基于JSON格式的规范。JSON模式也以JSON格式编写。它用于验证JSON数据。JSON模式示例以下代码显示了基本的JSON模式。{"...

前端学习——JSON格式详解(后端json格式)

JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScriptProgrammingLa...

什么是 JSON:详解 JSON 及其优势(什么叫json)

现在程序员还有谁不知道JSON吗?无论对于前端还是后端,JSON都是一种常见的数据格式。那么JSON到底是什么呢?JSON的定义...

PostgreSQL JSON 类型:处理结构化数据

PostgreSQL提供JSON类型,以存储结构化数据。JSON是一种开放的数据格式,可用于存储各种类型的值。什么是JSON类型?JSON类型表示JSON(JavaScriptO...

JavaScript:JSON、三种包装类(javascript 包)

JOSN:我们希望可以将一个对象在不同的语言中进行传递,以达到通信的目的,最佳方式就是将一个对象转换为字符串的形式JSON(JavaScriptObjectNotation)-JS的对象表示法...

Python数据分析 只要1分钟 教你玩转JSON 全程干货

Json简介:Json,全名JavaScriptObjectNotation,JSON(JavaScriptObjectNotation(记号、标记))是一种轻量级的数据交换格式。它基于J...

比较一下JSON与XML两种数据格式?(json和xml哪个好)

JSON(JavaScriptObjectNotation)和XML(eXtensibleMarkupLanguage)是在日常开发中比较常用的两种数据格式,它们主要的作用就是用来进行数据的传...

取消回复欢迎 发表评论:

请填写验证码