生成EM算法python代码,并要求配有坐标图
时间: 2023-05-19 09:01:25 浏览: 107
EM算法+Python代码.zip
以下是一个简单的生成EM算法的Python代码,同时也包含了坐标图的绘制:
```python
import numpy as np
import matplotlib.pyplot as plt
# 生成数据
np.random.seed(0)
X = np.random.randn(100, 2)
# 初始化参数
K = 2
mu = np.random.randn(K, 2)
sigma = np.array([np.eye(2)] * K)
pi = np.ones(K) / K
# 定义高斯分布函数
def gaussian(x, mu, sigma):
d = x.shape[1]
det = np.linalg.det(sigma)
inv = np.linalg.inv(sigma)
norm = 1.0 / (np.power((2 * np.pi), d / 2) * np.power(det, 0.5))
exp = np.exp(-0.5 * np.sum(np.dot(x - mu, inv) * (x - mu), axis=1))
return norm * exp
# 定义E步骤
def E_step(X, mu, sigma, pi):
N = X.shape[0]
K = mu.shape[0]
gamma = np.zeros((N, K))
for k in range(K):
gamma[:, k] = pi[k] * gaussian(X, mu[k], sigma[k])
gamma /= np.sum(gamma, axis=1, keepdims=True)
return gamma
# 定义M步骤
def M_step(X, gamma):
N = X.shape[0]
K = gamma.shape[1]
mu = np.zeros((K, 2))
sigma = np.zeros((K, 2, 2))
pi = np.zeros(K)
for k in range(K):
Nk = np.sum(gamma[:, k])
mu[k] = np.sum(gamma[:, k].reshape(N, 1) * X, axis=0) / Nk
X_centered = X - mu[k]
sigma[k] = np.dot(X_centered.T, (X_centered * gamma[:, k].reshape(N, 1))) / Nk
pi[k] = Nk / N
return mu, sigma, pi
# 迭代EM算法
for i in range(10):
gamma = E_step(X, mu, sigma, pi)
mu, sigma, pi = M_step(X, gamma)
# 绘制坐标图
plt.scatter(X[:, 0], X[:, 1], c=np.argmax(gamma, axis=1))
plt.show()
```
希望这个代码能够帮助你理解EM算法的实现过程。
阅读全文