tensorflow中数组与张量之间的相互转换

版权声明:站在巨人的肩膀上学习。 https://blog.csdn.net/zgcr654321/article/details/83651748

注意:

在tensorflow中,张量tensor是不能迭代的!

在tensorflow中,要对任何tensor进行操作,必须要先启动一个Session会话,否则,我们无法对一个tensor做操作,比如一个tensor常量重新赋值或是做一些判断,但是如果我们将tensor转化为numpy数组就可以直接处理了。

当我们在tensorflow模型中使用sess.run计算出某个变量的值(一般都是个数组或者多维矩阵的形式,但它的格式是张量,不能迭代),如果我们想对这个变量进行迭代时,就涉及到张量与数组的转换,因为张量只有转换成列表的形式才能够进行迭代。

数组与张量的相互转换:

主要是用tf.convert_to_tensor()函数和.eval()函数。

如:

import tensorflow as tf
import numpy as np

# 建立一个多维数组
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("建立的数组a为:\n", a)
with tf.Session() as sess:
	print("下面把数组a转化为张量:\n")
	tensor_a = tf.convert_to_tensor(a)
	print("转换成的张量为:\n", tensor_a)
	print("下面把张量tensor_a再转化数组:\n")
	a_convert = tensor_a.eval()
	print("转换成的数组为:\n", a_convert)

运行结果如下:

建立的数组a为:
 [[1 2 3]
 [4 5 6]
 [7 8 9]]
2018-11-02 10:54:14.329981: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
2018-11-02 10:54:14.558994: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1405] Found device 0 with properties: 
name: GeForce GTX 850M major: 5 minor: 0 memoryClockRate(GHz): 0.8625
pciBusID: 0000:01:00.0
totalMemory: 2.00GiB freeMemory: 1.91GiB
2018-11-02 10:54:14.558994: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1484] Adding visible gpu devices: 0
2018-11-02 10:54:15.620055: I tensorflow/core/common_runtime/gpu/gpu_device.cc:965] Device interconnect StreamExecutor with strength 1 edge matrix:
2018-11-02 10:54:15.620055: I tensorflow/core/common_runtime/gpu/gpu_device.cc:971]      0 
2018-11-02 10:54:15.620055: I tensorflow/core/common_runtime/gpu/gpu_device.cc:984] 0:   N 
2018-11-02 10:54:15.620055: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1097] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 1665 MB memory) -> physical GPU (device: 0, name: GeForce GTX 850M, pci bus id: 0000:01:00.0, compute capability: 5.0)
下面把数组a转化为张量:

转换成的张量为:
 Tensor("Const:0", shape=(3, 3), dtype=int32)
下面把张量tensor_a再转化数组:

转换成的数组为:
 [[1 2 3]
 [4 5 6]
 [7 8 9]]

Process finished with exit code 0

这样就实现了数组和张量的相互转换。

猜你喜欢

转载自blog.csdn.net/zgcr654321/article/details/83651748