我有一个形式为:
的libsvm向量{I_1:V_1; I_2:V_2; ...; 1-N:v_n}
i_j:v_j 分别代表索引和值。如果该值为null,则不会给出任何索引。
我的目标是计算两个libsvm之间的欧氏距离 向量。为此,我必须将它们转换为相同的
vector<float>
尺寸。在下面的例子中,我将展示我用来将libsvm向量转换为vector<float>
的函数。
第一列的索引= 2648 ,值= 0.408734 ,这意味着它之前的所有值都是零。
LIBSVM VECTOR = 2648:0.408734; 4157:0.609588; 6087:0.593104; 26747:0.331008
#include <vector>
#include <string>
#include <chrono>
#include <boost/algorithm/string.hpp>
using namespace std;
using namespace chrono;
//convert libsvm vector to float vector in order to compute the similarity
vector<float> splitVector(const vector<string> &);
int main()
{
vector<string> libsvm {"2648:0.408734","4157:0.609588","6087:0.593104","26747:0.331008" };
high_resolution_clock::time_point t1 = high_resolution_clock::now();
vector<float> newVec = splitVector(libsvm);
high_resolution_clock::time_point t2 = high_resolution_clock::now();
auto duration = chrono::duration_cast<chrono::microseconds>( t2 - t1 ).count();
cout <<"construction time: " << duration << endl;
return 0;
}
vector<float> splitVector(const vector<string> & v)
{
int numberofterms = 266373;
vector<float> values;
vector<int> previous_idx;
for(int i = 0; i < v.size(); i++)
{
vector<string> tmpv;
boost::split(tmpv, v[i] , boost::is_any_of(":"));
//idx:value
int idx = atoi(tmpv[0].c_str());
float val = atof(tmpv[1].c_str());
//summation of previous indices
int sum = accumulate(previous_idx.begin(), previous_idx.end(), 0);
int n = idx - (sum + i + 1);
//fill vector with 0s
for(int k = 0; k < n; k++)
values.push_back(0.0);
//add value
values.push_back(val);
previous_idx.push_back(n);
}//end for
int paddingsize = numberofterms - values.size();
for(int i = 0; i < paddingsize;i++)
{
values.push_back(0.0);
}
return values;
}//end function
转换的时间大约是 0,00866 秒,当我有 1000 时,它会变慢。有没有更快的方法将libsvm向量转换为vector<float>
?
values.resize(266373,0.0);
void splitVector(const vector<string> & v, vector<float> & values)
{
vector<string> tmpv;
for(int i = 0; i < v.size(); i++)
{
boost::split(tmpv, v[i] , boost::is_any_of(":"));
//idx:value
int idx = atoi(tmpv[0].c_str());
float val = atof(tmpv[1].c_str());
tmpv.clear();
values[idx] = val;
}//end for
}//end function
答案 0 :(得分:1)
您可以通过重用vector
来减少内存分配的时间成本。
更具体地说,
tmpv
循环之前声明它并在每个循环开始时调用for
来重用tmpv.clear()
values
预先分配values.reserve()
;并按values.resize(266373, 0.0)
填充,而不是重复push_back()
。previous_idx
。这可能会对代码结构产生负面影响,从而对可维护性产生负面影响。