Biplots 使用主成分分析的矩阵格式

huangapple go评论102阅读模式
英文:

Biplots in matrix format using pca

问题

这是我的数据框的一部分:

  1. 物种 喙长(毫米) 喙深(毫米) 脚蹼长(毫米) 体重(克) 预测物种
  2. 0 阿德利 18 18 181 3750 企鹅
  3. 1 阿德利 17 17 186 3800 阿德利
  4. 2 阿德利 18 18 195 3250 金图
  5. 3 阿德利 0 0 0 0 阿德利
  6. 4 企鹅 19 19 193 3450 企鹅
  7. 5 企鹅 20 20 190 3650 金图
  8. 6 企鹅 17 17 181 3625 阿德利
  9. 7 金图 19 19 195 4675 企鹅
  10. 8 金图 18 18 193 3475 金图
  11. 9 金图 20 20 190 4250 金图

我想为我的数据制作一个双标图,类似于这样:
Biplots 使用主成分分析的矩阵格式

但我想为每个 物种预测物种 的矩阵制作一个双标图,所以有 9 个子图,与上面的相同,我不确定如何实现这一点。一种方法可能是将数据拆分为数据框,并为每个数据框制作一个双标图,但这并不是很高效,也不容易比较。

有人能提供一些建议,说明如何完成这个任务吗?

英文:

This is a snippet of my dataframe:

  1. species bill_length_mm bill_depth_mm flipper_length_mm body_mass_g predicted_species
  2. 0 Adelie 18 18 181 3750 Chinstrap
  3. 1 Adelie 17 17 186 3800 Adelie
  4. 2 Adelie 18 18 195 3250 Gentoo
  5. 3 Adelie 0 0 0 0 Adelie
  6. 4 Chinstrap 19 19 193 3450 Chinstrap
  7. 5 Chinstrap 20 20 190 3650 Gentoo
  8. 6 Chinstrap 17 17 181 3625 Adelie
  9. 7 Gentoo 19 19 195 4675 Chinstrap
  10. 8 Gentoo 18 18 193 3475 Gentoo
  11. 9 Gentoo 20 20 190 4250 Gentoo

I want to make a biplot for my data, which would be something like this:
Biplots 使用主成分分析的矩阵格式

But I want to make a biplot for every species vs predicted_species matrix, so 9 subplots,same as above, I am not sure how that can be achieved. One way could be to split into dataframes, and make a biplot for each, but that isn't very efficient and difficult for comparison.

Can anyone provide some suggestions on how this could be done?

答案1

得分: 1

以下是您提供的代码的翻译部分:

  1. import numpy as np
  2. import pandas as pd
  3. import matplotlib.pyplot as plt
  4. import seaborn as sns
  5. from sklearn.preprocessing import StandardScaler
  6. from sklearn.decomposition import PCA
  7. # 载入鸢尾花数据集。
  8. iris = sns.load_dataset('iris')
  9. X = iris.iloc[:, :4].values
  10. y = iris.iloc[:, 4].values
  11. features = iris.columns[:4]
  12. targets = ['setosa', 'versicolor', 'virginica']
  13. # 模拟一些预测。
  14. iris['species_pred'] = (40 * ['setosa'] + 5 * ['versicolor'] + 5 * ['virginica']
  15. + 40 * ['versicolor'] + 5 * ['setosa'] + 5 * ['virginica']
  16. + 40 * ['virginica'] + 5 * ['versicolor'] + 5 * ['setosa'])
  17. # 将特征降维到两个维度。
  18. X_scaled = StandardScaler().fit_transform(X)
  19. pca = PCA(n_components=2).fit(X_scaled)
  20. X_reduced = pca.transform(X_scaled)
  21. iris[['pc1', 'pc2']] = X_reduced
  22. def biplot(x, y, data=None, **kwargs):
  23. # 绘制数据点。
  24. sns.scatterplot(data=data, x=x, y=y, **kwargs)
  25. # 计算箭头参数。
  26. loadings = pca.components_[:2].T
  27. pvars = pca.explained_variance_ratio_[:2] * 100
  28. arrows = loadings * np.ptp(X_reduced, axis=0)
  29. width = -0.0075 * np.min([np.subtract(*plt.xlim()), np.subtract(*plt.ylim())])
  30. # 绘制箭头。
  31. horizontal_alignment = ['right', 'left', 'right', 'right']
  32. vertical_alignment = ['bottom', 'top', 'top', 'bottom']
  33. for (i, arrow), ha, va in zip(enumerate(arrows),
  34. horizontal_alignment, vertical_alignment):
  35. plt.arrow(0, 0, *arrow, color='k', alpha=0.5, width=width, ec='none',
  36. length_includes_head=True)
  37. plt.text(*(arrow * 1.05), features[i], ha=ha, va=va,
  38. fontsize='small', color='gray')
  39. # 绘制小图,对应于混淆矩阵。
  40. sns.set()
  41. g = sns.FacetGrid(iris, row='species', col='species_pred',
  42. hue='species', margin_titles=True)
  43. g.map(biplot, 'pc1', 'pc2')
  44. plt.show()

我已经为您翻译了代码部分,您可以使用这个翻译来理解代码的内容。如果您有任何其他问题,请随时提出。

英文:

Combining the answer by Qiyun Zhu on how to plot a biplot with my answer on how to split the plot into the true vs. predicted subsets, you could do it like this:

  1. import numpy as np
  2. import pandas as pd
  3. import matplotlib.pyplot as plt
  4. import seaborn as sns
  5. from sklearn.preprocessing import StandardScaler
  6. from sklearn.decomposition import PCA
  7. # Load iris data.
  8. iris = sns.load_dataset('iris')
  9. X = iris.iloc[:, :4].values
  10. y = iris.iloc[:, 4].values
  11. features = iris.columns[:4]
  12. targets = ['setosa', 'versicolor', 'virginica']
  13. # Mock up some predictions.
  14. iris['species_pred'] = (40 * ['setosa'] + 5 * ['versicolor'] + 5 * ['virginica']
  15. + 40 * ['versicolor'] + 5 * ['setosa'] + 5 * ['virginica']
  16. + 40 * ['virginica'] + 5 * ['versicolor'] + 5 * ['setosa'])
  17. # Reduce features to two dimensions.
  18. X_scaled = StandardScaler().fit_transform(X)
  19. pca = PCA(n_components=2).fit(X_scaled)
  20. X_reduced = pca.transform(X_scaled)
  21. iris[['pc1', 'pc2']] = X_reduced
  22. def biplot(x, y, data=None, **kwargs):
  23. # Plot data points.
  24. sns.scatterplot(data=data, x=x, y=y, **kwargs)
  25. # Calculate arrow parameters.
  26. loadings = pca.components_[:2].T
  27. pvars = pca.explained_variance_ratio_[:2] * 100
  28. arrows = loadings * np.ptp(X_reduced, axis=0)
  29. width = -0.0075 * np.min([np.subtract(*plt.xlim()), np.subtract(*plt.ylim())])
  30. # Plot arrows.
  31. horizontal_alignment = ['right', 'left', 'right', 'right']
  32. vertical_alignment = ['bottom', 'top', 'top', 'bottom']
  33. for (i, arrow), ha, va in zip(enumerate(arrows),
  34. horizontal_alignment, vertical_alignment):
  35. plt.arrow(0, 0, *arrow, color='k', alpha=0.5, width=width, ec='none',
  36. length_includes_head=True)
  37. plt.text(*(arrow * 1.05), features[i], ha=ha, va=va,
  38. fontsize='small', color='gray')
  39. # Plot small multiples, corresponding to confusion matrix.
  40. sns.set()
  41. g = sns.FacetGrid(iris, row='species', col='species_pred',
  42. hue='species', margin_titles=True)
  43. g.map(biplot, 'pc1', 'pc2')
  44. plt.show()

Biplots 使用主成分分析的矩阵格式

huangapple
  • 本文由 发表于 2023年4月16日 23:55:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76028802.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定