【问题标题】:Convert arrays and tensors to matrices then perform matrix operations将数组和张量转换为矩阵,然后执行矩阵运算
【发布时间】:2020-09-04 17:37:42
【问题描述】:

我有两个大小为 (128,) 的数组和第三个大小为 (784, 128) 的数组:

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

它们具有相同的数据类型,但 dtype() 输出不同:

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

它们属于不同的类:

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'>

我要执行以下矩阵运算:

(array1 - array2) * array3.T

其中T是array3的转置。

最后,输出矩阵(即 [784 * 1])需要重新整形为形状为 28 * 28 的 uint8 数组,这样我就可以在 plot 上输出 matplotlip

谁能帮我先把数组转换成矩阵。然后正确转置第三个数组。最后,将输出重塑为大小为 28 * 28 的 uint8 数组。

我正在 python 中使用 tensorflow 和 keras。

【问题讨论】:

    标签: python tensorflow matrix keras matrix-multiplication


    【解决方案1】:

    将 array1 转换为 np.asmatrix()

    array1 = np.asmatrix(array1)
    

    对于array2,将其更改为numpy数组拳头,然后将其转换为矩阵:

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

    对于array3,先将其更改为numpy数组,然后将其转换为矩阵。最后,转置该矩阵:

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

    最后,应用矩阵运算:

    result = (array1 - array2) * array3
    

    要绘制输出,请使用以下命令:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-21
      • 1970-01-01
      • 2019-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      相关资源
      最近更新 更多