I am writing a C++ script using C++98 version (no upgrade possible). I need a function that generates polynomial combinations that works on my gcc version: I need this function in second degree, the input is 27 values and the output needs to be 405 values. Expected output for example : I call the function polyFeatures(input=[1,2,3],degree=2,interaction_only= False, include_bias= False) ==> Output=[1,2,3,1,2,3,4,6,9] ( that means input=[a,b,c] ,output=[a,b,c,a^2,ab,ac,b^2,bc,c^2]). I found this piece of code:
template <class T>
std::vector<T> polynomialFeatures( const std::vector<T>& input, unsigned int degree, bool interaction_only, bool include_bias )
{
std::vector<T> features = input;
std::vector<T> prev_chunk = input;
std::vector<size_t> indices( input.size() );
std::iota( indices.begin(), indices.end(), 0 );
for ( int d = 1 ; d < degree ; ++d )
{
// Create a new chunk of features for the degree d:
std::vector<T> new_chunk;
// Multiply each component with the products from the previous lower degree:
for ( size_t i = 0 ; i < input.size() - ( interaction_only ? d : 0 ) ; ++i )
{
// Store the index where to start multiplying with the current component at the next degree up:
size_t next_index = new_chunk.size();
for ( auto coef_it = prev_chunk.begin() + indices[i + ( interaction_only ? 1 : 0 )] ; coef_it != prev_chunk.end() ; ++coef_it )
{
new_chunk.push_back( input[i]**coef_it );
}
indices[i] = next_index;
}
// Extend the feature vector with the new chunk of features:
features.reserve( features.size() + std::distance( new_chunk.begin(), new_chunk.end() ) );
features.insert( features.end(), new_chunk.begin(), new_chunk.end() );
prev_chunk = new_chunk;
}
if ( include_bias )
features.insert( features.begin(), 1 );
return features;
}
I need a similar function that works with C++98. And in my case I don't need vectors but simple arrays with already known sizes.
Aucun commentaire:
Enregistrer un commentaire