#ifndef MATHUTIL_H #define MATHUTIL_H #include #include #include namespace Helper { static double minvec(const QVector &vec) { double val = std::numeric_limits::min(); for (int i = 0; i < vec.count(); ++i) { if (i == 0) { val = vec.at(i); } else if (val > vec.at(i)) { val = vec.at(i); } } return val; } static double maxvec(const QVector &vec) { double val = std::numeric_limits::max(); for (int i = 0; i < vec.count(); ++i) { if (i == 0) { val = vec.at(i); } else if (val < vec.at(i)) { val = vec.at(i); } } return val; } /// 均值 static double mean(const QVector &vec) { if (vec.count() == 0) { return 0; } double sum = 0; for (auto v : vec) { sum += v; } return sum / vec.count(); } /// 标准差 static double standardDeviation(const QVector &vec) { return qSqrt(standardDeviation(vec)); } static std::pair meanAndStandardDeviation(const QVector &vec) { if (vec.count() == 0) { return std::make_pair(0, 0); } double meanVal = mean(vec); double sum = 0; for (auto v : vec) { sum += qPow(v - meanVal, 2.0); } return std::make_pair(meanVal, sum / vec.count()); } /// 方差 static double variance(const QVector &vec) { if (vec.count() == 0) { return 0; } double meanVal = mean(vec); double sum = 0; for (auto v : vec) { sum += qPow(v - meanVal, 2.0); } return sum / vec.count(); } static void Standardization(QVector> &v) { double Avg, STD; for (int i = 0; i < v.size(); i++) { Avg = mean(v[i]); STD = standardDeviation(v[i]); for (int j = 0; j < v[i].size(); j++) { v[i][j] = (v[i][j] - Avg) / STD; } } } static double cov(QVector vA, QVector vB) { double total; for (int i = 0; i < vA.size(); i++) { total += vA[i] * vB[i]; } return (total / vA.size()); } static QVector> Covarience(QVector> features) { QVector> covMatrix; QVector temp; for (int i = 0; i < features.size(); i++) { for (int j = 0; j < features.size(); j++) { temp.push_back(cov(features[i], features[j])); } covMatrix.push_back(temp); temp.clear(); } return covMatrix; } } // namespace Helper #endif // MATHUTIL_H