简体   繁体   English

将数组和张量转换为矩阵,然后执行矩阵运算

[英]Convert arrays and tensors to matrices then perform matrix operations

I have two arrays of size (128,) and a third one of size (784, 128):我有两个大小为 (128,) 的数组和第三个大小为 (784, 128) 的数组:

array1.shape()
out: (128,)
array2.shape()
out: (128,)
array3.shape()
out: (784,128)

They have the same data type but the dtype() output is different:它们具有相同的数据类型,但dtype()输出不同:

array1.dtype
out: float32
array2.dtype
out: <dtype: 'float32'>
array2.dtype
out: <dtype: 'float32'>

And they belong to different classes:它们属于不同的类:

type(array1)
out: <class 'numpy.ndarray'>
type(array2)
out: <class 'tensorflow.python.ops.resource_variable_ops.ResourceVariable'>
type(array3)
out: <class 'tensorflow.python.ops.resource_variable_ops.ResourceVariable'>

I want to perform the following matrix operation:我想执行以下矩阵运算:

(array1 - array2) * array3.T

Where T is the transpose of array3.其中 T 是 array3 的转置。

Lastly, the output matrix (which is [784 * 1]) needs to be reshaped to become a uint8 array of shape 28 * 28 so I can plot that output on a matplotlip .最后,输出矩阵(即 [784 * 1])需要重新整形以成为形状为 28 * 28 的 uint8 数组,以便我可以在matplotlipplot该输出。

Can anyone help me to convert the arrays into matrices first.谁能帮我先把数组转换成矩阵。 Then Transpose the third array properly.然后正确转置第三个数组。 Finally, reshape the output to become an uint8 array of size 28 * 28.最后,将输出重塑为大小为 28 * 28 的 uint8 数组。

I am working with tensorflow and keras in python.我正在 python 中使用 tensorflow 和 keras。

Cast array1 as np.asmatrix()将 array1 转换为np.asmatrix()

array1 = np.asmatrix(array1)

For array2, change it to numpy array fist then cast it as a matrix:对于 array2,将其更改为 numpy array fist,然后将其转换为矩阵:

array2 = array2.numpy()
array2 = np.asmatrix(array2)

For array3, change it to numpy array first then cast it as a matrix.对于 array3,首先将其更改为 numpy 数组,然后将其转换为矩阵。 Lastly, transpose that matrix:最后,转置该矩阵:

array3 = array3.numpy()
array3 = np.asmatrix(array3)
array3 = np.transpose(array3)

Finally, apply the matrix operation:最后,应用矩阵运算:

result = (array1 - array2) * array3

To plot the output, use the following:要绘制输出,请使用以下命令:

result = np.array(result)
plt.imshow(result.reshape(28, 28), cmap='gray')
plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM