请给出一个SOM算法的示例,基于python
时间: 2023-05-24 22:01:49 浏览: 223
非常感谢您的提问。以下是一个基于Python的SOM算法示例:
```
import numpy as np
class SOM:
def __init__(self, input_dims, output_dims, learning_rate=0.1, radius=10, seed=None):
if seed:
np.random.seed(seed)
self.input_dims = input_dims
self.output_dims = output_dims
self.learning_rate = learning_rate
self.radius = radius
self.weights = np.random.normal(0, 1, size=(output_dims[0], output_dims[1], input_dims))
def get_bmu(self, x):
distances = np.sqrt(np.sum((self.weights - x) ** 2, axis=2))
return np.unravel_index(np.argmin(distances), distances.shape)
def update_weights(self, x, bmu):
for i in range(self.output_dims[0]):
for j in range(self.output_dims[1]):
d = np.sqrt((i - bmu[0]) ** 2 + (j - bmu[1]) ** 2)
if d <= self.radius:
h = np.exp(-(d ** 2) / (2 * self.radius ** 2))
self.weights[i, j] += self.learning_rate * h * (x - self.weights[i, j])
def train(self, X, epochs):
for epoch in range(epochs):
np.random.shuffle(X)
for x in X:
bmu = self.get_bmu(x)
self.update_weights(x, bmu)
self.radius *= 0.5
self.learning_rate *= 0.5
def predict(self, X):
y = np.zeros(len(X), dtype=np.uint8)
for i, x in enumerate(X):
bmu = self.get_bmu(x)
y[i] = bmu[0] * self.output_dims[1] + bmu[1]
return y
input_dims = 4
output_dims = (10, 10)
X = np.random.normal(0, 1, size=(1000, input_dims))
som = SOM(input_dims, output_dims)
som.train(X, 100)
y = som.predict(X)
print(y)
```
希望这个示例能够对您有所帮助。如果您还有其它问题,请随时向我提出。
阅读全文