1. 程式人生 > >tensorflow中陣列與張量之間的相互轉換

tensorflow中陣列與張量之間的相互轉換

注意:

在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

這樣就實現了陣列和張量的相互轉換。