TensorFlow 张量转 Numpy 数组方法


发布日期 : 2023-05-05 10:24:27 UTC

访问量: 10 次浏览

TensorFlow – 如何从张量中创建一个numpy ndarray

TensorFlow是谷歌设计的开源Python库,用于开发机器学习模型和深度学习神经网络。

为了从Tensor创建一个numpy数组,首先将Tensor转换为一个proto tensor。

使用的方法:

  • make\_ndarray :这个方法接受一个TensorProto作为输入,并返回一个与TensorProto内容相同的numpy数组。

示例 1:

# importing the library
import tensorflow as tf

# Initializing Input
value = tf.constant([1, 15, 10], dtype = tf.float64)

# Printing the Input
print("Value: ", value)

# Converting Tensor to TensorProto
proto = tf.make_tensor_proto(value)

# Generating numpy array
res = tf.make_ndarray(proto)

# Printing the resulting numpy array
print("Result: ", res)

输出:

Value: tf.Tensor([ 1. 15. 10.], shape=(3, ), dtype=float64)
Result: [ 1. 15. 10.]

例2:
这个例子使用了一个形状为(2, 2)的张量,所以产生的数组的形状将是(2, 2)。

# importing the library
import tensorflow as tf

# Initializing Input
value = tf.constant([[1, 2], [3, 4]], dtype = tf.float64)

# Printing the Input
print("Value: ", value)

# Converting Tensor to TensorProto
proto = tf.make_tensor_proto(value)

# Generating numpy array
res = tf.make_ndarray(proto)

# Printing the resulting numpy array
print("Result: ", res)

输出:

Value: tf.Tensor(
[[1. 2.]
[3. 4.]], shape=(2, 2), dtype=float64)
Result: [[1. 2.]
[3. 4.]]