生成每个类中心点(坐标为每个类内所有点的x与y坐标的均值的点)(在图中以单独的颜色表示)
时间: 2024-06-09 20:04:31 浏览: 13
好的,这个任务可以通过以下步骤来完成:
1. 对于每个类别,遍历该类别中的所有点,计算它们的x坐标和y坐标的平均值。
2. 使用平均值作为类别的中心点坐标。
3. 在图中以单独的颜色表示每个类别的中心点。
下面是一个示例代码实现:
```python
import matplotlib.pyplot as plt
import numpy as np
# 生成随机数据
np.random.seed(0)
num_points = 50
x1 = np.random.normal(loc=0.0, scale=0.5, size=num_points)
y1 = np.random.normal(loc=0.0, scale=0.5, size=num_points)
x2 = np.random.normal(loc=2.0, scale=0.5, size=num_points)
y2 = np.random.normal(loc=2.0, scale=0.5, size=num_points)
x3 = np.random.normal(loc=-2.0, scale=0.5, size=num_points)
y3 = np.random.normal(loc=2.0, scale=0.5, size=num_points)
# 绘制原始数据
fig, ax = plt.subplots(figsize=(8, 6))
ax.scatter(x1, y1, c='b', label='Class 1')
ax.scatter(x2, y2, c='g', label='Class 2')
ax.scatter(x3, y3, c='r', label='Class 3')
ax.set_title('Original Data')
ax.legend()
# 计算每个类别的中心点
centers = []
for data in [(x1, y1), (x2, y2), (x3, y3)]:
center_x = np.mean(data[0])
center_y = np.mean(data[1])
centers.append((center_x, center_y))
# 绘制类别中心点
for i, center in enumerate(centers):
ax.scatter(center[0], center[1], c=f'C{i}', marker='x', s=100, linewidth=2)
ax.set_title('Data with Class Centers')
plt.show()
```
运行上述代码,将得到一个带有类别中心点的图像。例如,这是一个使用随机数据生成的结果:
![class_centers](https://i.imgur.com/G1UJhPQ.png)
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)