以下是对这段代码的逐行注释:
#include <iostream>
// 包含输入输出流库,用于进行控制台的输入输出操作
#include <vector>
// 包含向量库,用于使用动态数组(std::vector)来表示矩阵
#include <cmath>
// 包含数学库,用于使用数学函数,如平方根函数 std::sqrt
// 定义特征矩阵
// 使用 typedef 为 std::vector<std::vector<double>> 定义一个别名 Matrix
// 这样可以更方便地表示二维矩阵
typedef std::vector<std::vector<double>> Matrix;
// 打印矩阵
// 该函数接受一个常量引用的 Matrix 类型参数 mat,用于打印矩阵的元素
void printMatrix(const Matrix &mat) {
// 遍历矩阵的每一行
for (const auto &row : mat) {
// 遍历当前行的每一个元素
for (double val : row) {
// 输出当前元素,并在元素之间添加一个空格
std::cout << val << " ";
}
// 每一行输出结束后换行
std::cout << std::endl;
}
}
// 计算两个矩阵的相似性(例如使用余弦相似度)
// 该函数接受两个常量引用的 Matrix 类型参数 A 和 B,返回它们的余弦相似度
double cosineSimilarity(const Matrix &A, const Matrix &B) {
// 初始化点积为 0
double dotProduct = 0.0;
// 初始化矩阵 A 的范数为 0
double normA = 0.0;
// 初始化矩阵 B 的范数为 0
double normB = 0.0;
// 遍历矩阵 A 的每一行
for (size_t i = 0; i < A.size(); ++i) {
// 遍历当前行的每一个元素
for (size_t j = 0; j < A[i].size(); ++j) {
// 计算点积,将 A[i][j] 和 B[i][j] 相乘并累加到 dotProduct 中
dotProduct += A[i][j] * B[i][j];
// 计算矩阵 A 的范数,将 A[i][j] 的平方累加到 normA 中
normA += A[i][j] * A[i][j];
// 计算矩阵 B 的范数,将 B[i][j] 的平方累加到 normB 中
normB += B[i][j] * B[i][j];
}
}
// 计算并返回余弦相似度,即点积除以两个矩阵范数的乘积
return dotProduct / (std::sqrt(normA) * std::sqrt(normB));
}
// 对齐函数:简单求平均作为对齐结果
// 该函数接受两个常量引用的 Matrix 类型参数 imageFeat 和 textFeat,返回对齐后的矩阵
Matrix alignMatrices(const Matrix &imageFeat, const Matrix &textFeat) {
// 初始化一个 3x3 的矩阵 aligned,所有元素初始值为 0.0
Matrix aligned(3, std::vector<double>(3, 0.0));
// 遍历对齐矩阵的每一行
for (size_t i = 0; i < aligned.size(); ++i) {
// 遍历当前行的每一个元素
for (size_t j = 0; j < aligned[i].size(); ++j) {
// 计算对齐矩阵的元素值,为 imageFeat 和 textFeat 对应元素的平均值
aligned[i][j] = (imageFeat[i][j] + textFeat[i][j]) / 2.0;
}
}
// 返回对齐后的矩阵
return aligned;
}
int main() {
// 模拟图像特征和文本特征矩阵
// 定义一个 3x3 的矩阵 imageFeat 表示图像特征
Matrix imageFeat = {
{0.2, 0.3, 0.4},
{0.4, 0.5, 0.6},
{0.6, 0.7, 0.8}
};
// 定义一个 3x3 的矩阵 textFeat 表示文本特征
Matrix textFeat = {
{0.1, 0.3, 0.5},
{0.5, 0.5, 0.7},
{0.7, 0.8, 0.9}
};
// 输出提示信息,表示接下来要输出图像特征矩阵
std::cout << "Image Features:" << std::endl;
// 调用 printMatrix 函数打印图像特征矩阵
printMatrix(imageFeat);
// 输出提示信息,表示接下来要输出文本特征矩阵
std::cout << "Text Features:" << std::endl;
// 调用 printMatrix 函数打印文本特征矩阵
printMatrix(textFeat);
// 对齐特征
// 调用 alignMatrices 函数对图像特征矩阵和文本特征矩阵进行对齐,并将结果存储在 alignedFeat 中
Matrix alignedFeat = alignMatrices(imageFeat, textFeat);
// 输出提示信息,表示接下来要输出对齐后的特征矩阵
std::cout << "Aligned Features:" << std::endl;
// 调用 printMatrix 函数打印对齐后的特征矩阵
printMatrix(alignedFeat);
// 计算对齐前后的相似性
// 调用 cosineSimilarity 函数计算图像特征矩阵和文本特征矩阵的余弦相似度
double similarity = cosineSimilarity(imageFeat, textFeat);
// 输出提示信息和对齐前的余弦相似度
std::cout << "Cosine Similarity Before Alignment: " << similarity << std::endl;
// 程序正常结束,返回 0
return 0;
}
这段代码的主要功能是模拟图像特征矩阵和文本特征矩阵,对它们进行简单的对齐操作(求对应元素的平均值),并计算对齐前两个矩阵的余弦相似度。


被折叠的 条评论
为什么被折叠?



