使用python实现一种可以给各个特征设置权重的kmeans算法
时间: 2023-11-22 15:53:36 浏览: 33
以下是使用Python实现带权重的KMeans算法的代码:
```python
import numpy as np
from sklearn.cluster import KMeans
class WeightedKMeans:
def __init__(self, n_clusters=8, max_iter=300, weights=None):
self.n_clusters = n_clusters
self.max_iter = max_iter
self.weights = weights
def fit(self, X):
if self.weights is None:
self.weights = np.ones(X.shape[1])
# Normalize weights
self.weights = self.weights / np.sum(self.weights)
# Initialize centroids using weighted random sampling
indices = np.random.choice(X.shape[0], size=self.n_clusters, replace=False, p=None)
self.centroids = X[indices,:]
for i in range(self.max_iter):
# Find closest centroid for each data point
distances = np.sqrt(np.sum((X - self.centroids[:, np.newaxis])**2 * self.weights, axis=2))
labels = np.argmin(distances, axis=0)
# Update centroids
for j in range(self.n_clusters):
mask = labels == j
if np.sum(mask) > 0:
self.centroids[j,:] = np.average(X[mask,:], axis=0, weights=self.weights[mask])
def predict(self, X):
distances = np.sqrt(np.sum((X - self.centroids[:, np.newaxis])**2 * self.weights, axis=2))
return np.argmin(distances, axis=0)
```
在这个类中,我们首先初始化了KMeans算法所需的参数,包括簇的数量、最大迭代次数和特征权重。如果没有传入权重,则默认所有特征的权重相等。接着,在fit方法中,我们对传入的数据进行了归一化处理,并使用加权随机抽样初始化了簇的中心点。然后,我们开始进行迭代,首先计算每个数据点到所有簇中心的距离,并找到每个数据点最近的簇。接着,我们更新每个簇的中心点,使用加权平均值来计算新的中心点。在predict方法中,我们使用训练好的簇中心点来预测新的数据点所属的簇。
可以使用以下代码进行测试:
```python
import pandas as pd
# Load data
data = pd.read_csv('data.csv')
# Split features and labels
X = data.iloc[:, :-1].values
# Define feature weights
weights = np.array([0.4, 0.3, 0.2, 0.1])
# Initialize weighted KMeans algorithm
kmeans = WeightedKMeans(n_clusters=3, weights=weights)
# Fit data to algorithm
kmeans.fit(X)
# Predict clusters for new data
new_data = np.array([[5.1, 3.5, 1.4, 0.2], [6.2, 2.8, 4.8, 1.8], [7.3, 2.9, 6.3, 1.8]])
labels = kmeans.predict(new_data)
print(labels)
```
在这个例子中,我们首先加载了一个包含4个特征的数据集。然后,我们定义了一个包含4个特征权重的数组,并使用这些特征权重初始化了WeightedKMeans算法。接着,我们将数据拟合到算法中,并使用算法对新数据进行了预测,输出了每个新数据点所属的簇。