TensorFlow中如何创建每行仅含一个随机1元素的M*N全零张量
Got it! This is a common task often used for generating random one-hot labels or sampling random positions across rows. Let’s cover implementations in the most popular frameworks—PyTorch, TensorFlow, and NumPy—so you can pick what fits your workflow.
PyTorch Implementation
Here’s a straightforward, easy-to-read approach:
- Generate random column indices for each of the M rows
- Create a zero tensor of shape (M, N)
- Set the corresponding position in each row to 1
import torch # Define your desired dimensions M = 5 # Number of rows N = 3 # Number of columns # Step 1: Generate random column indices (one unique index per row) random_col_indices = torch.randint(low=0, high=N, size=(M,)) # Step 2: Initialize a tensor filled with zeros result_tensor = torch.zeros(M, N) # Step 3: Set the random position in each row to 1 result_tensor[torch.arange(M), random_col_indices] = 1 print(result_tensor)
Alternatively, you can use scatter_ for a more concise one-liner after generating indices:
result_tensor = torch.zeros(M, N).scatter_(1, random_col_indices.unsqueeze(1), 1)
TensorFlow Implementation
TensorFlow has a couple of intuitive ways to handle this, including a built-in function tailored for one-hot encoding:
Method 1: Using tf.one_hot (Simplest Option)
import tensorflow as tf M = 5 N = 3 # Generate random column indices random_col_indices = tf.random.uniform(shape=(M,), minval=0, maxval=N, dtype=tf.int32) # Directly create the one-hot tensor in one step result_tensor = tf.one_hot(random_col_indices, depth=N) print(result_tensor.numpy())
Method 2: Using tf.scatter_nd
Great if you need more control over the scatter operation:
import tensorflow as tf M = 5 N = 3 random_col_indices = tf.random.uniform(shape=(M,), minval=0, maxval=N, dtype=tf.int32) # Create (row, col) index pairs for the scatter operation scatter_indices = tf.stack([tf.range(M), random_col_indices], axis=1) result_tensor = tf.scatter_nd(scatter_indices, updates=tf.ones(M), shape=(M, N)) print(result_tensor.numpy())
NumPy Implementation
If you’re working with plain NumPy arrays instead of framework tensors:
import numpy as np M = 5 N = 3 # Generate random column indices random_col_indices = np.random.randint(0, N, size=M) # Initialize zero array and set positions to 1 result_tensor = np.zeros((M, N)) result_tensor[np.arange(M), random_col_indices] = 1 print(result_tensor)
All these methods will produce an M×N tensor where every row has exactly one 1 in a random column, with all other elements set to 0. If you’re using a less common framework, just let me know and I can adjust the code!
内容的提问来源于stack exchange,提问作者Mike Felan

