在Python中对相关矩阵进行排序
先决条件:相关矩阵
相关矩阵同时调查多个变量之间的相关性。它显示了对称表格数据,其中每一行和每一列代表一个变量,对应的值是表示这两个变量之间关系强度的相关系数。相关系数有很多种(Pearson 系数、Kendall 系数、Spearman 系数等),它们是通过不同的相关分析方法计算出来的。相关系数值越接近1的变量表示强正相关,越接近-1表示强负相关,越接近0表示弱相关或无相关。
在数据分析中,相关矩阵对于总结和发现大量数据中的关系非常有用。它也是机器学习中探索性数据分析和特征选择的常用指标。
对于大数据,解释相关矩阵可能变得困难。有时对相关值进行排序有助于轻松查看各种变量对的依赖程度。在本文中,我们将看到如何在Python中对相关矩阵进行排序。
方法
- 导入模块
- 加载数据
- 使用上述数据创建相关矩阵
- 对数据进行排序。
- 显示排序数据
我们将使用 Python 的 Seaborn 包中的 Iris 数据集。该数据集包含 3 类鸢尾花,每类具有 50 个属性实例。请注意,相关矩阵会忽略数据中的任何非数字列。因此,首先使用标签编码将您想要包含在相关矩阵中的任何非数字数据更改为数字数据。
现在,要对相关矩阵进行排序,首先我们必须将矩阵转换为一维序列。 unstack()函数用于执行此操作。该系列将有多个索引。
使用 sort_values()函数进行排序。 sort_values()函数按传递的列的升序或降序对数据框进行排序。
Syntax: DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind=’quicksort’, na_position=’last’)
Parameters:
- by: Single/List of column names to sort Data Frame by.
- axis: 0 or ‘index’ for rows and 1 or ‘columns’ for Column
- ascending: Boolean value which sorts Data frame in ascending order if True
- inplace: Boolean value. Makes the changes in passed data frame itself if True.
- kind: String which can have three inputs(‘quicksort’, ‘mergesort’ or ‘heapsort’) of algorithm used to sort data frame.
- na_position: Takes two string input ‘last’ or ‘first’ to set position of Null values. Default is ‘last’.
Return type: Returns a sorted Data Frame with Same dimensions as of the function caller Data Frame.
使用中的数据框:
示例 1:
Python3
# Import required libraries
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder
# Load dataset
df = sns.load_dataset('iris')
# Convert categorical values to numeric
label_encoder = LabelEncoder()
df['species'] = label_encoder.fit_transform(df['species'])
# Create correlation matrix
corr_mat = df.corr(method='pearson')
# Convert correlation matrix to 1-D Series and sort
sorted_mat = corr_mat.unstack().sort_values()
print(sorted_mat)
Python3
# Import required libraries
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder
# Load dataset
df = sns.load_dataset('iris')
# Convert categorical values to numeric
label_encoder = LabelEncoder()
df['species'] = label_encoder.fit_transform(df['species'])
# Create correlation matrix
corr_mat = df.corr(method='pearson')
# Retain upper triangular values of correlation matrix and
# make Lower triangular values Null
upper_corr_mat = corr_mat.where(
np.triu(np.ones(corr_mat.shape), k=1).astype(np.bool))
# Convert to 1-D series and drop Null values
unique_corr_pairs = upper_corr_mat.unstack().dropna()
# Sort correlation pairs
sorted_mat = unique_corr_pairs.sort_values()
print(sorted_mat)
输出:
示例 2:对无重复项的相关矩阵进行排序
为了去除重复值和自相关值,在将相关矩阵转换为一维序列之前,先获取矩阵的上三角值或下三角值。为此,使用 triu()函数返回具有相关矩阵形状的上三角矩阵(主对角线上方的元素值为 1,其他元素值为 0)。 astype() 方法将矩阵值转换为布尔值。这是函数可以根据另一个条件数组选择数组的地方,因此我们得到的结果是一个矩阵,其具有相关矩阵的上三角值,其余值为空。
然后将相关矩阵转换为一维数组进行排序,如上例所示。下面给出实现:
蟒蛇3
# Import required libraries
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder
# Load dataset
df = sns.load_dataset('iris')
# Convert categorical values to numeric
label_encoder = LabelEncoder()
df['species'] = label_encoder.fit_transform(df['species'])
# Create correlation matrix
corr_mat = df.corr(method='pearson')
# Retain upper triangular values of correlation matrix and
# make Lower triangular values Null
upper_corr_mat = corr_mat.where(
np.triu(np.ones(corr_mat.shape), k=1).astype(np.bool))
# Convert to 1-D series and drop Null values
unique_corr_pairs = upper_corr_mat.unstack().dropna()
# Sort correlation pairs
sorted_mat = unique_corr_pairs.sort_values()
print(sorted_mat)
输出: