您好,登錄后才能下訂單哦!
自組織映射(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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。