gpt4 book ai didi

normalization - 如何用推力标准化向量?

转载 作者:行者123 更新时间:2023-12-04 05:20:58 27 4
gpt4 key购买 nike

我现在正在学习推力。我有一个问题:如何用推力进行归一化?
我有一个有效的代码,但我想知道这是否是最佳方法。

struct square
{
__host__ __device__
float operator() (float x)
{
return x * x;
}
};




thrust::device_vector<float> d_x(2);
thrust::device_vector<float> d_y(2);
thrust::device_vector<float> d_z(2);
d_x[0] = 3;
d_x[1] = 4;
square<float> unary_op;
thrust::plus<float> binary_op;
float init = 0;

// compute norm
float norm = std::sqrt( thrust::transform_reduce(d_x.begin(), d_x.end(), unary_op, init, binary_op) );
thrust::fill(d_y.begin(), d_y.end(), 1/norm);
thrust::transform(d_x.begin(), d_x.end(), d_y.begin(), d_z.begin(), thrust::multiplies<float>());

最佳答案

这应该更有效,因为它不需要用于 d_y 的存储或带宽。或 d_z :

#include <thrust/device_vector.h>
#include <thrust/inner_product.h>
#include <thrust/transform.h>
#include <thrust/functional.h>
#include <cmath>

int main()
{
thrust::device_vector<float> d_x(2);
d_x[0] = 3;
d_x[1] = 4;

float norm = std::sqrt(thrust::inner_product(d_x.begin(), d_x.end()));

using namespace thrust::placeholders;
thrust::transform(d_x.begin(), d_x.end(), d_x.begin(), _1 /= norm);

return 0;
}

当然,您需要将问题规模扩大几个数量级。

关于normalization - 如何用推力标准化向量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13688307/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com