python - 将张量重塑为矩阵并返回
问题描述
我有两种方法:一种将 4D 矩阵(张量)转换为矩阵,另一种将 2D 矩阵转换为 4D。
从 4D 到 2D 的重塑效果很好,但是当我再次尝试在张量中重新转换时,我没有达到相同的元素顺序。方法是:
# Method to convert the tensor in a matrix
def tensor2matrix(tensor):
# rows, columns, channels and filters
r, c, ch, f = tensor[0].shape
new_dim = [r*c*ch, f] # Inferer the new matrix dims
# Transpose is necesary because the columns are the channels weights
# flattened in columns
return np.reshape(np.transpose(tensor[0], [2,0,1,3]), new_dim)
# Method to convert the matrix in a tensor
def matrix2tensor(matrix, fs):
return np.reshape(matrix, fs, order="F")
我认为问题出在np.transpose
因为什么时候只有一个矩阵我可以逐行排列列......无论如何要从没有循环的矩阵中支持张量?
解决方案
考虑以下变化:
将两者替换为
tensor[0]
,tensor
以避免ValueError:没有足够的值来解包(预期 4,得到 3)
运行下面提供的示例时
确保两个
np.reshape
调用使用相同的order="F"
在内部使用另一个
np.transpose
调用matrix2tensor
来撤消np.transpose
fromtensor2matrix
更新的代码是
import numpy as np
# Method to convert the tensor in a matrix
def tensor2matrix(tensor):
# rows, columns, channels and filters
r, c, ch, f = tensor.shape
new_dim = [r*c*ch, f] # Inferer the new matrix dims
# Transpose is necesary because the columns are the channels weights
# flattened in columns
return np.reshape(np.transpose(tensor, [2,0,1,3]), new_dim, order="F")
# Method to convert the matrix in a tensor
def matrix2tensor(matrix, fs):
return np.transpose(np.reshape(matrix, fs, order="F"), [1,2,0,3])
它可以像这样测试:
x,y,z,t = 2,3,4,5
shape = (x,y,z,t)
m1 = np.arange(x*y*z*t).reshape((x*y*z, 5))
t1 = matrix2tensor(m1, shape)
m2 = tensor2matrix(t1)
assert (m1 == m2).all()
t2 = matrix2tensor(m2, shape)
assert (t1 == t2).all()
推荐阅读
- mysql - 更改生产服务器中的mysql表结构
- wso2 - 在 WSO2 3.0.0 APIM 中设置多个流量管理器
- sql-server - 如何在 SQL Server 中设置更新事件的时间戳?
- tensorflow - `tensorflowjs_converter` 导致浏览器中的模型无法检测到任何对象
- javascript - 如何同时置换和重新排列数组元素
- sharepoint-online - SPFX-图表-webpart-react-pnpcontrol
- c - 为什么代码显示空白而不是 C 中的字符串?
- python-3.x - 有没有临时变量之类的东西?
- docker - 在生产 VPS/VDS 上使用 Docker 容器有意义吗?
- python - 通过dict中的多个键对dict列表进行排序