使用Armadillo库计算Dunn指数时遇越界错误与NaN结果求助
问题:Armadillo库计算Dunn指数时出现索引越界与-nan(ind)输出
开发大型算法时,尝试用Armadillo库计算Dunn指数,运行代码后输出Dunn's index:-nan(ind),且触发索引越界错误。已确认数据格式合适、数据对齐正确,无空簇及缺失数据,但仍无法解决问题。
测试代码
#include <iostream> #include <armadillo> using namespace std; using namespace arma; double dunns(int clusters_number, const mat& distM, const uvec& ind) { // Determine the number of unique clusters int i = max(ind); vec denominator; for (int i2 = 1; i2 <= i; ++i2) { uvec indi = find(ind == i2); uvec indj = find(ind != i2); // Check if indi and indj are not empty if (!indi.is_empty() && !indj.is_empty()) { mat temp; // Check if indices are within bounds before submatrix extraction if (indi.max() < distM.n_rows && indj.max() < distM.n_cols) { temp = distM.submat(indi, indj); denominator = join_cols(denominator, vectorise(temp)); } else { // Debugging: Print indices that caused the error cout << "Error: Indices out of bounds for Cluster " << i2 << endl; } } } double num = 0.0; // Initialize num to 0.0 // Check if denominator is not empty before finding the minimum if (!denominator.is_empty()) { num = min(denominator); } mat neg_obs = zeros<mat>(distM.n_rows, distM.n_cols); for (int ix = 1; ix <= i; ++ix) { uvec indxs = find(ind == ix); // Check if indxs is not empty if (!indxs.is_empty()) { // Check if indices are within bounds before setting elements if (indxs.max() < distM.n_rows) { neg_obs.submat(indxs, indxs).fill(1.0); } } } // Print intermediate values cout << "Intermediate Values:" << endl; cout << "Denominator: " << denominator << endl; cout << "num: " << num << endl; mat dem = neg_obs % distM; double max_dem = max(max(dem)); // Print max_dem cout << "max_dem: " << max_dem << endl; double DI = num / max_dem; return DI; } int main() { // New inputs for testing int clusters_number = 2; // Modified dissimilarity matrix (4x4) mat distM(4, 4); distM << 0.0 << 1.0 << 2.0 << 3.0 << 1.0 << 0.0 << 1.0 << 2.0 << 2.0 << 1.0 << 0.0 << 1.0 << 3.0 << 2.0 << 1.0 << 0.0; // Modified cluster indices (4x1) arma::uvec ind; ind << 1 << 1 << 2 << 2; // Print the input dissimilarity matrix cout << "Dissimilarity Matrix:" << endl; cout << distM << endl; // Print the cluster indices cout << "Cluster Indices:" << endl; cout << ind << endl; double DI = dunns(clusters_number, distM, ind); cout << "Dunn's Index: " << DI << endl; return 0; }
已排查情况
- 使用double类型存储相异矩阵,arma::uvec存储簇索引,格式合理
- 数据点与簇索引对齐正确
- 无空簇及缺失数据
- 仍在子矩阵提取时触发越界错误
内容的提问来源于stack exchange,提问作者Duplic8e
相关产品推荐
相关产品推荐

