如何用Python从5万多个新特征中选择两个特征并通过散点图可视化分成两组
我有一个数据库(synthetic_feature_file
),里面有超过五万条特征,所有这些特征都是经过处理的,不是原始特征。这个文件里有43个样本。
我想看看能不能从这五万多条特征中找到两个新的特征,这两个特征可以把有肌肉减少症的样本和没有肌肉减少症的样本区分开来。我打算把这两个新特征作为x轴和y轴,然后用散点图来展示它们。
我希望分类的结果能像下面的图片那样,红色的样本形成一个聚类,蓝色的样本形成另一个聚类,两者之间没有重叠。例如:
下面是我写的代码。我应该怎么修改它呢?
(我不太确定怎么选择两个特征,所以我一直在反复运行代码,检查每次的结果。这效率很低。)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Read synthesized feature data
syn_data = pd.read_csv(synthetic_feature_file)
# labeled sample(people who suffer from Sarcopenia)
sample_indices = [1, 6, 7, 11, 14, 15, 27]
# Randomly pick two features as x and y axes
x_feature = np.random.choice(syn_data.columns[0:10000])
y_feature = np.random.choice(syn_data.columns[10001:20000])
# Clean feature names and remove illegal characters
x_feature = x_feature.strip().replace('\t', '')
y_feature = y_feature.strip().replace('\t', '')
plt.figure(figsize=(8, 6))
# Other samples(people who did not suffer from Sarcopenia)
other_samples = syn_data.drop(sample_indices)
plt.scatter(other_samples[x_feature], other_samples[y_feature], color='blue', label='Other Samples')
# Red sample
red_samples = syn_data.iloc[sample_indices]
plt.scatter(red_samples[x_feature], red_samples[y_feature], color='red', label='Sample Indices')
plt.xlabel(x_feature)
plt.ylabel(y_feature)
plt.title("Visualization")
plt.legend()
plt.show()
1 个回答
0
可以这样做:
x_feature, y_feature = np.random.choice(syn_data.columns, size=2, replace=False)
这里的 size=2
表示选择2个样本,而 replace=False
表示选择样本时不放回,也就是说每次选择后不会再把这个样本放回去。
正如我在评论中提到的,如果你想访问列,最好不要重命名或者清理它们。因为这样会让它们和原来的列名不同,之后就无法访问了。
其实效率低下的根本原因在于你试图删除行并创建一个副本。这个过程可以通过布尔掩码来完成。
sample_indices = syn_data.index.isin([1, 6, 7, 11, 14, 15, 27])
选择其他样本:
other_samples = syn_data.iloc[~sample_indices]
选择红色样本:
red_samples = syn_data.iloc[sample_indices]