我有输入和目标数据表示为MatrixXd (N x M)和VectorXd (N)。目标是创建大小为K的小批量,由输入和目标数据的子集以相同的方式进行洗牌。然后,ML模型将在循环中处理这些小批量。你能推荐一下如何用尽可能少的复制(也许,用一个代码示例)来实现这一点吗?
我尝试实现这种批处理
#include <algorithm>
#include <numeric>
#include <random>
#include <Eigen/Dense>
using Eigen::MatrixXd;
using Eigen::Ref;
using Eigen::VectorXd;
struct Batch {
const Ref<const MatrixXd> input;
const Ref<const VectorXd> target;
};
std::vector<Batch> generate_batches(const Ref<const MatrixXd> input, const Ref<const VectorXd> target, unsigned batch_size)
{
unsigned num_samples = input.rows();
unsigned num_batches = ceil(num_samples / (float)batch_size);
static std::default_random_engine engine;
std::vector<unsigned> idxs(num_samples);
std::iota(idxs.begin(), idxs.end(), 0);
std::shuffle(idxs.begin(), idxs.end(), engine);
std::vector<Batch> batches;
batches.reserve(num_batches);
auto idxs_begin = std::make_move_iterator(idxs.begin());
for (unsigned idx = 0; idx < num_batches; ++idx) {
int start = idx * batch_size;
int end = std::min(start + batch_size, num_samples);
std::vector<unsigned> batch_idxs(std::next(idxs_begin, start), std::next(idxs_begin, end));
batches.push_back({ input(batch_idxs, Eigen::all), target(batch_idxs) });
}
return batches;
}
Eigen自带的换位类型就是这样做的。它通过交换行或列来就地工作。所以你可以不断地变换相同的矩阵。
#include <Eigen/Dense>
#include <algorithm>
// using std::min
#include <cassert>
#include <random>
// using std::default_random_engine, std::uniform_int_distribution
void shuffle_apply(Eigen::Ref<Eigen::MatrixXd> mat,
Eigen::Ref<Eigen::VectorXd> vec,
int generations, int batchsize)
{
// colwise is faster than rowwise
const Eigen::Index size = mat.cols();
assert(vec.size() == size);
using Transpositions = Eigen::Transpositions<
Eigen::Dynamic, Eigen::Dynamic, Eigen::Index>;
Transpositions transp(size);
Eigen::Index* transp_indices = transp.indices().data();
std::default_random_engine rng; // seed appropriately!
for(int gen = 0; gen < generations; ++gen) {
for(Eigen::Index i = 0; i < size; ++i) {
std::uniform_int_distribution<Eigen::Index> distr(i, size - 1);
transp_indices[i] = distr(rng);
}
mat = mat * transp; // operates in-place
vec = transp * vec; // transp on left side to shuffle rows, not cols
for(Eigen::Index start = 0; start < size; start += batchsize) {
const Eigen::Index curbatch = std::min<Eigen::Index>(
batchsize, size - start);
const auto mat_batch = mat.middleCols(start, curbatch);
const auto vec_batch = vec.segment(start, curbatch);
}
}
}
参见特征矩阵的排列和类似问题。
编辑:这个旧版本通过std::shuffle初始化索引,我认为这是错误的
这里是第二个版本,它可能提供一个更令人满意的界面。特别是,不需要复制就可以恢复原来的矩阵和向量。
class BatchShuffle
{
using Transpositions = Eigen::Transpositions<
Eigen::Dynamic, Eigen::Dynamic, Eigen::Index>;
using Permutations = Eigen::PermutationMatrix<
Eigen::Dynamic, Eigen::Dynamic, Eigen::Index>;
Eigen::MatrixXd mat_;
Eigen::VectorXd vec_;
Transpositions cur_transp;
Permutations aggregated_permut;
public:
BatchShuffle(Eigen::MatrixXd mat, Eigen::VectorXd vec)
: mat_(std::move(mat)),
vec_(std::move(vec)),
cur_transp(this->mat_.cols()),
aggregated_permut(this->mat_.cols())
{
assert(this->vec_.size() == this->mat_.cols());
aggregated_permut.setIdentity();
}
Eigen::Index totalsize() const noexcept
{ return mat_.cols(); }
const Eigen::MatrixXd& mat() const noexcept
{ return mat_; }
const Eigen::VectorXd& vec() const noexcept
{ return vec_; }
template<class RandomNumberEngine>
void shuffle(RandomNumberEngine& rng)
{
Eigen::Index* indices = cur_transp.indices().data();
for(Eigen::Index i = 0, n = totalsize(); i < n; ++i) {
std::uniform_int_distribution<Eigen::Index> distr(i, n - 1);
indices[i] = distr(rng);
}
Permutations::IndicesType& aggregated = aggregated_permut.indices();
aggregated = cur_transp * aggregated;
mat_ = mat_ * cur_transp;
vec_ = cur_transp * vec_;
}
void BatchShuffle::restore_original()
{
const auto& inverse = aggregated_permut.inverse().eval();
mat_ = mat_ * inverse;
vec_ = inverse * vec_;
aggregated_permut.setIdentity();
}
};
void apply(const Eigen::Ref<const Eigen::MatrixXd>& mat,
const Eigen::Ref<const Eigen::VectorXd>& vec);
int main()
{
int rows = 1000, cols = 10000, batchsize = 100;
BatchShuffle batch(Eigen::MatrixXd::Random(rows, cols),
Eigen::VectorXd::Random(cols));
std::default_random_engine rng;
for(int i = 0; i < 100; ++i) {
batch.shuffle(rng);
for(Eigen::Index j = 0; j < batch.totalsize(); j += batchsize) {
Eigen::Index cursize =
std::min<Eigen::Index>(batchsize, batch.totalsize() - j);
apply(batch.mat().middleCols(j, cursize),
batch.vec().segment(j, cursize));
}
}
batch.restore_original();
}
再次,我选择使用矩阵列,不像在你的代码尝试,你取行。Eigen以列主顺序(即Fortran顺序)存储其矩阵。采用行切片而不是列切片将显著降低对数据所做的几乎所有操作的速度。因此,如果可能的话,我强烈建议您相应地转换您的输入生成和矩阵使用。