如何将[N]维度张量转换为[N,D]维度矩阵(每列为原向量)?
Got it, let's walk through how to convert your [N]-dimensional tensor into an [N,D] matrix where every column is identical to the original vector. I'll cover the most common frameworks since implementation varies a bit depending on what you're using:
NumPy
If you're working with NumPy arrays, you've got a couple straightforward options:
- Using
np.tile(): First expand your original tensor to a [N,1] shape, then tile it across the column dimension:import numpy as np original_tensor = np.array([1, 2, 3]) # Shape (3,) D = 4 # Expand to (3,1) then tile 1 time along rows, D times along columns result = np.tile(original_tensor[:, np.newaxis], (1, D)) # Shape (3,4) - Using broadcasting (memory-efficient): Broadcasting avoids explicit memory duplication, which is great if D is large:
result = original_tensor[:, np.newaxis] * np.ones((1, D)) # Or using np.expand_dims + repeat result = np.expand_dims(original_tensor, axis=1).repeat(D, axis=1)
PyTorch
For PyTorch tensors, the approach is similar with framework-specific methods:
- Using
repeat():import torch original_tensor = torch.tensor([1, 2, 3]) # Shape (3,) D = 4 # Unsqueeze to add column dimension, then repeat result = original_tensor.unsqueeze(1).repeat(1, D) # Shape (3,4) - Using
torch.tile()(available in PyTorch 1.10+):result = torch.tile(original_tensor.unsqueeze(1), (1, D)) - Broadcasting trick: This creates a view without copying memory (until you modify it):
result = original_tensor.unsqueeze(1) + torch.zeros(1, D, device=original_tensor.device)
TensorFlow
In TensorFlow, you can use tf.tile or tf.repeat to achieve this:
- Using
tf.tile():import tensorflow as tf original_tensor = tf.constant([1, 2, 3]) # Shape (3,) D = 4 expanded = tf.expand_dims(original_tensor, axis=1) # Shape (3,1) result = tf.tile(expanded, [1, D]) # Shape (3,4) - Using
tf.repeat():result = tf.repeat(tf.expand_dims(original_tensor, 1), D, axis=1)
Quick Note
If you ever need to replicate the original vector across rows instead of columns, just adjust the axis you expand and repeat/tile along (e.g., unsqueeze(0) instead of unsqueeze(1)).
内容的提问来源于stack exchange,提问作者Pablo Sanchez

