【发布时间】:2020-06-29 07:57:34
【问题描述】:
我正在尝试将大部分维度矩阵减少到仅二维,我正在使用二维数组的示例,它有效,但我需要为更高维度的散射做同样的事情。我有两个类,每个类都有 50x20 维特征空间的矩阵。
对于我的示例,我有这些 2D 数组:
rectangles = np.array([[1,1.5,1.7,1.45,1.1,1.6,1.8],[1.8,1.55,1.45,1.6,1.65,1.7,1.75]])
triangles = np.array([[0.1,0.5,0.25,0.4,0.3,0.6,0.35,0.15,0.4,0.5,0.48],[1.1,1.5,1.3,1.2,1.15,1.0,1.4,1.2,1.3,1.5,1.0]])
然后我找到了三角形和矩形类的平均值
# Calculate the mean vectors per class
mean_rectangles = np.mean(rectangles,axis=1).reshape(2,1)
mean_triangles = np.mean(triangles,axis=1).reshape(2,1)
通过矩形和三角形类给出的值,我用它们来计算散点:
scatter_triangles = np.dot((triangles-mean_triangles),(triangles-mean_triangles).T)
scatter_circles = np.dot((circles-mean_circles),(circles-mean_circles).T)
# Calculate the SW by adding the scatters within classes
SW = scatter_triangles+scatter_circles+scatter_rectangles
print(SW)
plt.show()
我想知道如何在类中找到散点并绘制它们,方法完全相同,但对于更大的数据,恰好是 50x20 矩阵?
为了重现性,这是我的代码:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use('fivethirtyeight')
# Create data
c_A_array = [[ 31, 25, 17, 62, 26, 23, 193, 143, 37, 29, 220, 216, 175, 195, 207, 198, 190, 222, 178, 214],
[ 31, 26, 19, 59, 25, 23, 193, 140, 37, 29, 220, 216, 174, 195, 207, 198, 190, 220, 178, 214],
[ 31, 23, 17, 67, 23, 22, 195, 147, 38, 31, 222, 215, 182, 195, 213, 198, 185, 221, 178, 207],
[ 31, 23, 19, 67, 23, 23, 194, 144, 37, 31, 222, 218, 179, 198, 216, 198, 186, 221, 179, 207],
[ 31, 28, 17, 65, 23, 22, 193, 142, 36, 31, 222, 217, 177, 195, 216, 196, 182, 220, 174, 207]]
c_B_array = [[ 16, 24, 33, 43, 43, 58, 163, 76, 57, 105, 205, 200, 193, 188, 186, 193, 182, 227, 193, 227],
[ 9, 13, 22, 36, 13, 49, 163, 39, 33, 105, 204, 200, 193, 191, 188, 193, 183, 224, 194, 227],
[ 23, 17, 10, 28, 21, 40, 166, 46, 28, 102, 208, 206, 196, 198, 195, 202, 190, 225, 196, 229],
[ 25, 19, 11, 30, 23, 39, 166, 46, 26, 99, 208, 206, 199, 196, 198, 201, 189, 227, 198, 231],
[ 25, 20, 12, 31, 25, 40, 169, 48, 27, 101, 211, 206, 198, 198, 196, 202, 190, 226, 198, 229]]
#Plot the data
fig = plt.figure(figsize=(10,10))
ax0 = fig.add_subplot(111)
ax0.scatter(c_A_array[0],c_A_array[1],marker='s',c='grey',edgecolor='black')
ax0.scatter(c_B_array[0],c_B_array[1],marker='o',c='blue',edgecolor='black')
# Calculate the mean vectors per class
c_A_array_mean = np.mean(c_A_array,axis=1)
c_B_array_mean = np.mean(c_A_array,axis=1)
# Calculate the scatter matrices for the SW (Scatter within) and sum the elements up
scatter_c_A_array = np.dot((c_A_array-c_A_array_mean),(c_A_array-c_A_array_mean).T)
scatter_c_B_array = np.dot((c_B_array-c_B_array_mean),(c_B_array-c_B_array_mean).T)
# Calculate the SW by adding the scatters within classes
SW = scatter_c_A_array+scatter_c_B_array
print(SW)
plt.show()
我收到以下错误:
ValueError:操作数无法与形状一起广播 (5,20) (5,)
【问题讨论】:
-
当您执行
c_A_array-c_A_array_mean时,您是否打算为 5 个列表中的每一个减去列表中每个项目的平均值? -
是的,每个列表都是一个簇,要找到每个类的内部散点图,我需要簇的平均值并从簇内的每个点中减去
标签: python python-3.x numpy matplotlib machine-learning