TensorFlow – 如何从张量创建一个 numpy ndarray
TensorFlow 是由 Google 设计的开源Python库,用于开发机器学习模型和深度学习神经网络。
为了从张量创建一个 numpy 数组,张量首先被转换为一个原型张量。
Method Used:
- make_ndarray: This method accepts a TensorProto as input and returns a numpy array with same content as TensorProto.
示例 1:
Python3
# 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)
Python3
# 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. 15. 10.], shape=(3, ), dtype=float64)
Result: [ 1. 15. 10.]
示例 2:此示例使用形状为 (2, 2) 的张量,因此结果数组的形状将为 (2, 2)。
Python3
# 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.]]