张量tensor的数据与numpy 数据之间的转化与打印

本文介绍如何在TensorFlow中打印Tensor变量的值,并演示如何将Tensor转换为NumPy数组,反之亦然。此外,还介绍了使用会话管理和评估函数来获取Tensor的实际数值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在tensorflow 中一般数据都是用tensor来表示,而在python 中一般是用numpy包,然而有时候需要打印变量的数据,所以下面可以代码:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data


def weight_variable(shape):
    initial=tf.truncated_normal(shape,stddev=0.1)
    return initial


if __name__=='__main__':
 '''
    mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
    x = tf.placeholder(tf.float32, [None, 784],'x')
    y_ = tf.placeholder(tf.float32, [None, 10],'y')
    x_image = tf.reshape(x, [-1, 28, 28, 1])
 '''
    W_conv1 = weight_variable([5, 5, 1, 32])

现在要打印W_conv1变量的值,首先看一下加入print(W_conv1)打印的效果

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data


def weight_variable(shape):
    initial=tf.truncated_normal(shape,stddev=0.1)
    return initial


if __name__=='__main__':

    '''mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
    x = tf.placeholder(tf.float32, [None, 784],'x')
    y_ = tf.placeholder(tf.float32, [None, 10],'y')
    x_image = tf.reshape(x, [-1, 28, 28, 1])'''

    W_conv1 = weight_variable([5, 5, 1, 32])
    print (W_conv1)
   # b_conv1 = bias_variable([32])

结果为:Tensor("truncated_normal:0", shape=(5, 5, 1, 32), dtype=float32),这是张量tensor,要打印这样的变量,需要在session 中,所以加入 with tf.Session() as sess 。程序如下:


import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data


def weight_variable(shape):
    initial=tf.truncated_normal(shape,stddev=0.1)
    return initial


if __name__=='__main__':

    '''mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
    x = tf.placeholder(tf.float32, [None, 784],'x')
    y_ = tf.placeholder(tf.float32, [None, 10],'y')
    x_image = tf.reshape(x, [-1, 28, 28, 1])'''

    W_conv1 = weight_variable([5, 5, 1, 32])
    with tf.Session() as sess:
            print (sess.run(W_conv1))
   # b_conv1 = bias_variable([32])
打印结果为5*5*1*32,所有复制了部分数据如下:

 [[-0.01138691 -0.06353019  0.12420362  0.14429896  0.01513781
    -0.1557924  -0.11008668 -0.05706662  0.04268187  0.02811845
     0.03623001 -0.15556422 -0.09083539  0.02959536 -0.00855448
     0.09642988 -0.09893788 -0.04005608 -0.02273898 -0.03150641
    -0.00355575  0.120373    0.03304343 -0.04112866  0.02824191
     0.04924054  0.07960307 -0.0673811   0.0637029  -0.10225315
     0.15535429 -0.01115945]]


  [[ 0.1377502  -0.13991357  0.05424013  0.15169595 -0.09851914
     0.0651127   0.05134506  0.0107875   0.01194856  0.00058991
     0.02181729 -0.09146625  0.04761747 -0.06609621  0.03090276
    -0.10576289 -0.00022165  0.06573081 -0.08087479 -0.06913969
     0.05346059 -0.06754622 -0.08353492  0.025491    0.06887309
     0.03608112  0.11575726  0.04321242  0.0215429  -0.07847684
    -0.06896582  0.00389415]]]

通过.eval函数可以把tensor转化为numpy类数据,程序如下:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data


def weight_variable(shape):
    initial=tf.truncated_normal(shape,stddev=0.1)
    return initial


if __name__=='__main__':

    '''mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
    x = tf.placeholder(tf.float32, [None, 784],'x')
    y_ = tf.placeholder(tf.float32, [None, 10],'y')
    x_image = tf.reshape(x, [-1, 28, 28, 1])'''
    sess=tf.Session()
    W_conv1 = weight_variable([5, 5, 1, 32])
    a=W_conv1.eval(session=sess)
    print (a)
   # b_conv1 = bias_variable([32])

通过tf.convert_to_tensor函数可以把numpy转化为tensor 类数据:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data


def weight_variable(shape):
    initial=tf.truncated_normal(shape,stddev=0.1)
    return initial


if __name__=='__main__':

    '''mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
    x = tf.placeholder(tf.float32, [None, 784],'x')
    y_ = tf.placeholder(tf.float32, [None, 10],'y')
    x_image = tf.reshape(x, [-1, 28, 28, 1])'''
    sess=tf.Session()
    W_conv1 = weight_variable([5, 5, 1, 32])
    a=W_conv1.eval(session=sess)
    b=tf.convert_to_tensor(a)
    print (b)
   # b_conv1 = bias_variable([32])





### 如何将 Tensor 张量转换为 NumPy 数组保存 在 TensorFlow 或其他框架中,可以通过特定方法实现张量NumPy 数组的转换。以下是具体操作: #### 转换过程 在 TensorFlow 中,可以使用 `.numpy()` 方法来完成这一目标。此方法适用于 Eager Execution 模式下的张量对象[^1]。如果当前环境未启用 Eager Execution,则需要通过会话(Session)运行张量以获取其数值表示。 对于初学者而言,在尝试 `.eval()` 时可能遇到错误是因为该方法依赖于活动会话的存在[^2]。因此推荐优先考虑 `.numpy()` 方法或 `tf.make_ndarray` 工具。 另外需要注意的是,在 PyTorch 中可以直接调用 `.numpy()` 来执行类似的转换[^3];然而这不完全适用 TensorFlow 的情况。 #### 实现代码示例 下面展示了一种标准方式用于将 TensorFlow 张量转化为 NumPy 数组,进一步将其存储至本地磁盘上作为二进制文件或其他格式的数据集成员之一: ```python import tensorflow as tf import numpy as np # 假设我们有一个随机初始化的张量 tensor = tf.random.uniform((3, 3)) # 使用 .numpy() 方法进行转换 (需确保启用了 eager execution) numpy_array = tensor.numpy() print("Converted Numpy Array:") print(numpy_array) # 接下来我们可以利用 NumPy 提供的功能保存数据到文件 np.save('my_tensor.npy', numpy_array) # 默认压缩形式 ``` 上述脚本首先创建了一个大小为 `(3x3)` 的均匀分布浮点数矩阵类型的张量实例,接着借助内置函数完成了向常规 Python 列表结构体过渡的过程^。最后一步演示了怎样采用高效机制持久化这些处理后的成果以便后续加载分析或者分享给他人使用[^4]. #### 注意事项 - 如果正在使用的版本较旧而无法支持某些特性,请确认已安装最新稳定发行版软件包。 - 对于非急切模式下工作的程序来说,记得设置好必要的上下文管理器比如显式的 Session 定义等才能顺利完成整个流程中的每一步骤动作。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值