自组织映射(Self-Organizing Map, SOM)是一种无监督学习算法,用于将高维数据映射到低维空间(通常是二维),同时保留数据的拓扑结构
#include <iostream>
#include <vector>
#include <cmath>
#include <random>
class SOM {
public:
SOM(int input_dim, int map_size, int epochs, double learning_rate)
: input_dim_(input_dim), map_size_(map_size), epochs_(epochs), learning_rate_(learning_rate) {
weights_.resize(map_size_, std::vector<double>(input_dim, 0));
random_device rd;
gen_ = std::mt19937(rd());
}
void train(const std::vector<std::vector<double>>& data) {
for (int epoch = 0; epoch < epochs_; ++epoch) {
for (const auto& input : data) {
int best_map_idx = -1;
double min_distance = std::numeric_limits<double>::max();
for (int i = 0; i < map_size_; ++i) {
double distance = calculate_distance(input, weights_[i]);
if (distance < min_distance) {
min_distance = distance;
best_map_idx = i;
}
}
update_weights(input, best_map_idx);
}
}
}
std::vector<int> predict(const std::vector<double>& input) const {
int best_map_idx = -1;
double min_distance = std::numeric_limits<double>::max();
for (int i = 0; i < map_size_; ++i) {
double distance = calculate_distance(input, weights_[i]);
if (distance < min_distance) {
min_distance = distance;
best_map_idx = i;
}
}
return {best_map_idx};
}
private:
int input_dim_;
int map_size_;
int epochs_;
double learning_rate_;
std::vector<std::vector<double>> weights_;
std::mt19937 gen_;
double calculate_distance(const std::vector<double>& input, const std::vector<double>& weight) const {
double distance = 0;
for (int i = 0; i < input.size(); ++i) {
distance += pow(input[i] - weight[i], 2);
}
return sqrt(distance);
}
void update_weights(const std::vector<double>& input, int best_map_idx) {
double learning_rate = learning_rate_ * (1 - epoch_ / static_cast<double>(epochs_));
for (int i = 0; i < input.size(); ++i) {
weights_[best_map_idx][i] += learning_rate * (input[i] - weights_[best_map_idx][i]);
}
}
};
int main() {
std::vector<std::vector<double>> data = {
{1.0, 2.0},
{3.0, 4.0},
{5.0, 6.0},
{7.0, 8.0},
{9.0, 10.0}
};
SOM som(2, 5, 100, 0.5);
som.train(data);
std::vector<int> prediction = som.predict({3.0, 4.0});
std::cout << "Predicted map index: " << prediction[0] << std::endl;
return 0;
}
这个实现中,我们创建了一个名为SOM
的类,它包含了训练和预测的方法。train
方法用于训练模型,predict
方法用于预测新数据的映射。在main
函数中,我们创建了一个简单的二维数据集,并使用SOM
类对其进行训练和预测。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。