You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TensorFlow中如何创建每行仅含一个随机1元素的M*N全零张量

How to Create an M×N Tensor with One Random 1 per Row (Rest Zeros)

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:

  1. Generate random column indices for each of the M rows
  2. Create a zero tensor of shape (M, N)
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:12:56