This notebook has been translated from ImageJ Macro
It shows how to perform a matrix multiplication in the GPU.
import pyclesperanto_prototype as cle
from skimage.io import imread, imsave, imshow
import matplotlib
import numpy as np
# initialize GPU
cle.select_device("GTX")
print("Used GPU: " + cle.get_device().name)
Used GPU: Intel(R) Iris(R) Xe Graphics
array1 = np.asarray([[1, 2, 3, 4, 5]])
array2 = np.asarray([[6, 7, 8, 9, 10]])
vector1 = cle.push(array1)
vector2 = cle.push(array2)
Therefore, we transpose one of our vectors:
vector1_t = cle.transpose_xy(vector1)
print("Vector 1 (transposed): " + str(vector1_t))
print("Vector 2: " + str(vector2))
Vector 1 (transposed): [[1.] [2.] [3.] [4.] [5.]] Vector 2: [[ 6. 7. 8. 9. 10.]]
matrix = cle.create([vector1_t.shape[0], vector2.shape[1]])
cle.multiply_matrix(vector1_t, vector2, matrix)
print(matrix)
[[ 6. 7. 8. 9. 10.] [12. 14. 16. 18. 20.] [18. 21. 24. 27. 30.] [24. 28. 32. 36. 40.] [30. 35. 40. 45. 50.]]
cle.imshow(matrix)
# generate another matrix of the same size with random values
another_matrix = cle.push_zyx(np.random.random(matrix.shape))
# element by element multiplication
matrix_element_wise_multiplied = cle.multiply_images(matrix, another_matrix)
print(matrix_element_wise_multiplied)
cle.imshow(matrix_element_wise_multiplied)
[[ 3.514832 4.0798674 6.8832116 2.4485908 2.1087325] [11.203639 11.765139 12.340768 17.706673 19.63089 ] [13.040122 18.359781 5.621809 11.222803 26.120459 ] [ 7.7386 14.522078 21.716482 5.263441 5.4148645] [25.103271 18.912039 35.608345 41.090908 14.199609 ]]
elements_times_2 = cle.multiply_image_and_scalar(matrix, scalar=2)
print(elements_times_2)
[[ 12. 14. 16. 18. 20.] [ 24. 28. 32. 36. 40.] [ 36. 42. 48. 54. 60.] [ 48. 56. 64. 72. 80.] [ 60. 70. 80. 90. 100.]]