C++ 代码:计算数据矩阵列之间的 MIC 系数并输出结果
这段代码看起来没有明显的错误,但是需要确保 cppmine.h 头文件已经正确包含并且定义了 MINE 类和 EST_MIC_APPROX 常量。此外,还需要确保数据文件'data.txt'存在,并且数据格式与代码中假设的格式一致。如果数据文件不存在或者格式不正确,代码可能会出现错误。
#include
// 2. 定义一个结构体来存储数据矩阵的行名和列名:
struct Matrix {
std::vectorstd::string row_names;
std::vectorstd::string col_names;
std::vector<std::vector
// 3. 定义一个函数来读取带有行名和列名的数据矩阵:
Matrix readMatrixFromFile(const std::string& filename) {
Matrix matrix;
std::ifstream file(filename);
std::string line;
if (file.is_open()) {
// 读取列名
if (std::getline(file, line)) {
std::istringstream iss(line);
std::string col_name;
while (iss >> col_name) {
matrix.col_names.push_back(col_name);
}
}
// 读取数据矩阵
while (std::getline(file, line)) {
std::istringstream iss(line);
double value;
std::vector
// 4. 修改main函数,使用读取的数据矩阵进行计算:
int main(int argc, char **argv) { // 读取数据矩阵 Matrix matrix = readMatrixFromFile('data.txt');
// 获取数据矩阵的大小 int n = matrix.data[0].size();
// 创建对称矩阵
std::vector<std::vector
// 创建MINE对象 MINE mine(0.6, 15, EST_MIC_APPROX);
// 计算每列两两之间的mic系数,并填充对称矩阵 for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { double x[n]; double y[n]; for (int k = 0; k < n; k++) { x[k] = matrix.data[k][i]; y[k] = matrix.data[k][j]; } mine.compute_score(x, y, n); symmetric_matrix[i][j] = mine.mic(); symmetric_matrix[j][i] = mine.mic(); } }
// 输出结果为txt文件的对称矩阵 std::ofstream output('output.txt'); if (output.is_open()) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { output << symmetric_matrix[i][j] << ' '; } output << '\n'; } output.close(); }
return 0;
原文地址: https://www.cveoy.top/t/topic/fUkd 著作权归作者所有。请勿转载和采集!