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

TensorFlow中如何将1D张量转为2D张量?转换后ndim仍为1求帮助

解决1D张量转2D张量后维度仍为1的问题

你的问题核心是TensorFlow的张量是不可变的,tf.reshape不会修改原张量,而是返回一个新的调整好形状的张量,你没有把这个新张量赋值回去,所以原张量还是1D的,自然ndim还是1。

修正后的代码如下:

import numpy as np
import tensorflow as tf

sample = np.array([-7.0,-4.0,-1.0,2.0,5.0,8.0,11.0,14.0,15.0])
sample = tf.convert_to_tensor(sample)
# 将reshape的结果重新赋值给sample
sample = tf.reshape(sample, shape=(3,3))
print(sample.ndim)  # 输出2

另外注意你代码里的X.ndim,这里的X应该是笔误,要改成你实际使用的变量名(比如sample),否则会报未定义的错误。

如果需要保留原张量,也可以赋值给新变量:

reshaped_sample = tf.reshape(sample, shape=(3,3))
print(reshaped_sample.ndim)  # 输出2
print(sample.ndim)  # 原张量还是1D,输出1

内容的提问来源于stack exchange,提问作者ZKS

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 20:51:20