K-mean算法python代码
时间: 2023-03-28 13:04:30 浏览: 65
以下是K-mean算法的Python代码:
```python
import numpy as np
def k_means(X, k, max_iters=100):
m, n = X.shape
centroids = X[np.random.choice(m, k, replace=False), :]
for i in range(max_iters):
idx = np.argmin(np.sum((X - centroids[:, np.newaxis])**2, axis=2), axis=)
centroids = np.array([X[idx == j].mean(axis=) for j in range(k)])
return centroids, idx
```
希望对您有帮助!
相关问题
k-means算法 python实现
k-means算法是一种常用的聚类算法,它通过将样本点划分为K个不同的簇而被广泛应用。下面是用Python实现k-means算法的步骤:
1. 初始化:选择K个随机的中心点作为初始的聚类中心。
2. 分配:对于每个样本点,计算其与各个聚类中心的距离,并将样本点分配给距离最近的聚类中心。
3. 更新:对于每个聚类,计算其所有样本点的均值,将该均值作为新的聚类中心。
4. 重复步骤2和3,直到聚类中心不再发生变化或达到预定的迭代次数。
以下是Python代码实现k-means算法的伪代码:
```
1. 导入相关的库:
import numpy as np
2. 定义k-means函数:
def k_means(data, K, max_iter):
centroids = np.random.choice(data, K) # 随机选择K个聚类中心
for _ in range(max_iter):
clusters = [[] for _ in range(K)] # 初始化K个簇
for point in data:
distances = [np.linalg.norm(point - centroid) for centroid in centroids] # 计算样本点和各个聚类中心的距离
cluster_idx = np.argmin(distances) # 找到距离最近的聚类中心的索引
clusters[cluster_idx].append(point) # 将样本点分配给距离最近的簇
new_centroids = [np.mean(cluster, axis=0) for cluster in clusters] # 计算新的聚类中心
if np.all(centroids == new_centroids): # 判断是否收敛
break
centroids = new_centroids # 更新聚类中心
return clusters, centroids
3. 调用k-means函数:
clusters, centroids = k_means(data, K, max_iter)
```
其中,`data`是输入的样本数据,`K`是簇的个数,`max_iter`是最大迭代次数。返回的`clusters`是分配好的样本点簇的列表,`centroids`是最终得到的聚类中心点的坐标。
IPSO-GRU算法 python代码
我可以回答这个问题,以下是一个IPSO-GRU算法的Python代码示例:
```python
import numpy as np
import tensorflow as tf
# 定义IPSO-GRU模型
class IPSO_GRU(tf.keras.Model):
def __init__(self, input_dim, output_dim, hidden_dim, num_layers):
super(IPSO_GRU, self).__init__()
self.num_layers = num_layers
self.hidden_dim = hidden_dim
self.gru_layers = []
for i in range(num_layers):
self.gru_layers.append(tf.keras.layers.GRU(hidden_dim, return_sequences=True))
self.dense = tf.keras.layers.Dense(output_dim)
def call(self, inputs):
x = inputs
for i in range(self.num_layers):
x = self.gru_layers[i](x)
x = self.dense(x)
return x
# 定义IPSO-GRU算法
def IPSO_GRU_algorithm(X, y, input_dim, output_dim, hidden_dim, num_layers, population_size, max_iter):
# 初始化种群
population = []
for i in range(population_size):
model = IPSO_GRU(input_dim, output_dim, hidden_dim, num_layers)
model.build(input_shape=(None, None, input_dim))
population.append(model)
# 计算适应度函数
def fitness_function(model):
y_pred = model(X)
loss = tf.keras.losses.mean_squared_error(y, y_pred)
return 1 / (1 + loss)
# 迭代优化
for i in range(max_iter):
# 计算适应度值
fitness_values = []
for model in population:
fitness_values.append(fitness_function(model))
# 选择最优个体
best_model = population[np.argmax(fitness_values)]
# 更新种群
for j in range(population_size):
if population[j] != best_model:
# 交叉操作
new_model = IPSO_GRU(input_dim, output_dim, hidden_dim, num_layers)
new_model.build(input_shape=(None, None, input_dim))
for k in range(num_layers):
weights1 = best_model.gru_layers[k].get_weights()
weights2 = population[j].gru_layers[k].get_weights()
new_weights = []
for w1, w2 in zip(weights1, weights2):
mask = np.random.rand(*w1.shape) < 0.5
new_weights.append(np.where(mask, w1, w2))
new_model.gru_layers[k].set_weights(new_weights)
weights1 = best_model.dense.get_weights()
weights2 = population[j].dense.get_weights()
new_weights = []
for w1, w2 in zip(weights1, weights2):
mask = np.random.rand(*w1.shape) < 0.5
new_weights.append(np.where(mask, w1, w2))
new_model.dense.set_weights(new_weights)
# 变异操作
for k in range(num_layers):
weights = new_model.gru_layers[k].get_weights()
for w in weights:
mask = np.random.rand(*w.shape) < 0.1
w[mask] += np.random.normal(scale=0.1, size=w[mask].shape)
new_model.gru_layers[k].set_weights(weights)
weights = new_model.dense.get_weights()
for w in weights:
mask = np.random.rand(*w.shape) < 0.1
w[mask] += np.random.normal(scale=0.1, size=w[mask].shape)
new_model.dense.set_weights(weights)
# 替换原个体
population[j] = new_model
# 返回最优模型
return best_model
```
希望这个代码示例能够对你有所帮助!