极简TensorFlow学习教程-----TensorFow中Tensor与Numpy相互转换

1、Numpy转Tensor
TensorFlow 通过 convert_to_tensor() 函数将Numpy转换为Tensor,代码如下:

import tensorflow as tf
import numpy as np
# 创建ndarray
array = np.array([1, 2, 3, 4, 5], np.float32)
print(array) #[1. 2. 3. 4. 5.]
# 将ndarray转化为tensor
t = tf.convert_to_tensor(array, tf.float32, name='a')
# 打印输出
print(t) #Tensor("a:0", shape=(5,), dtype=float32)

2、Tensor转Numpy
TensorFlow 必须通过创建会话(session),才能将Tensor转化成Numpy的ndarray

import tensorflow as tf
# 创建张量
t = tf.constant([1, 2, 3, 4, 5], tf.int32)
print(t) #Tensor("Const:0", shape=(5,), dtype=int32)
# 创建会话
session = tf.Session()
# 张量转化为ndarray
array = session.run(t)
# 打印其数据类型与其值
print(type(array)) #<class 'numpy.ndarray'>
print(array) #[ 1.  2.  3.  4.]

猜你喜欢

转载自blog.csdn.net/qq_28057379/article/details/106378776