[英]How to subtract an array from each row in matrix in PyOpenCL?
我想將尺寸為1xN
的相同數組減去尺寸為MxN
的矩陣的每一行。 即,當執行ab
時,執行numpy
相同的操作, ab
是前者為矩陣,而后者為數組。 例如:
import pyopencl as cl
import pyopencl.array as cl_array
import numpy as np
a = np.matrix('1 2 3; 4 5 6').astype(np.float32)
b = np.array([1,2,3]).astype(np.float32)
ctx = cl.create_some_context()
queue = cl.CommandQueue(ctx)
a_dev = cl_array.to_device(queue, a)
b_dev = cl_array.to_device(queue, b)
dest_dev = cl_array.empty_like(a_dev)
prg = cl.Program(ctx, """
__kernel void fun(
const unsigned int size,
__global const float *a,
__global const float *b,
__global float *c)
{
int i = get_global_id(0);
int j = get_global_id(1);
c[i + j*size] = a[i + j*size] - b[j];
}
""").build()
prg.fun(queue, a.shape, None, np.int32(len(a)), a_dev.data, b_dev.data, dest_dev.data)
print(dest_dev)
我以為這個內核會返回矩陣
[0 0 0 ; 3 3 3]
但實際上它返回
[0 1 1 ; 2 2 3]
錯誤在哪里?
您必須在內核中交換矩陣計算的行和列。 您可以從以下維度開始內核:
a.shape # returns tuple(rows, columns)
回報。 它返回(2, 3)
而不是(3, 2)
。 因此,將內核中的行更改為:
c[j + i*size] = a[j + i*size] - b[j];
在這種情況下, i
是行數, j
是列數。
將矩陣的size
提供給內核時,也會出錯。 代替
np.int32(len(a))
whitch返回2的行數(y軸)。 將內核啟動行更改為:
prg.fun(queue, a.shape, None, np.int32(a.shape[1]), a_dev.data, b_dev.data, dest_dev.data)
a.shape[1]
為您提供矩陣第二維的大小,即列數,在此示例中為3。
還可以使用Work-Item Built-In函數查詢內核本身中的列數:
unsigned int size = get_global_size(1); // size of the 2. dim of the kernel
在這種情況下,您不必將列數作為內核參數傳遞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.