- TensorFlow Machine Learning Projects
- Ankit Jain Armando Fandango Amita Kapoor
- 277字
- 2021-06-10 19:15:27
Tensors from Python objects
Tensors can be created from Python objects such as lists, NumPy arrays, and pandas DataFrames. To create tensors from Python objects, use the tf.convert_to_tensor() function with the following definition:
tf.convert_to_tensor(
value,
dtype=None,
name=None,
preferred_dtype=None
)
Let's practice doing this by creating some tensors and printing their definitions and values:
- Define a 0-D tensor:
tf_t=tf.convert_to_tensor(5.0,dtype=tf.float64)
print('tf_t : ',tf_t)
print('run(tf_t) : ',tfs.run(tf_t))
The output is as follows:
tf_t : Tensor("Const_1:0", shape=(), dtype=float64)
run(tf_t) : 5.0
- Define a 1-D tensor:
a1dim = np.array([1,2,3,4,5.99])
print("a1dim Shape : ",a1dim.shape)
tf_t=tf.convert_to_tensor(a1dim,dtype=tf.float64)
print('tf_t : ',tf_t)
print('tf_t[0] : ',tf_t[0])
print('tf_t[0] : ',tf_t[2])
print('run(tf_t) : \n',tfs.run(tf_t))
The output is as follows:
a1dim Shape : (5,)
tf_t : Tensor("Const_2:0", shape=(5,), dtype=float64)
tf_t[0] : Tensor("strided_slice:0", shape=(), dtype=float64)
tf_t[0] : Tensor("strided_slice_1:0", shape=(), dtype=float64)
run(tf_t) :
[ 1. 2. 3. 4. 5.99]
- Define a 2-D tensor:
a2dim = np.array([(1,2,3,4,5.99),
(2,3,4,5,6.99),
(3,4,5,6,7.99)
])
print("a2dim Shape : ",a2dim.shape)
tf_t=tf.convert_to_tensor(a2dim,dtype=tf.float64)
print('tf_t : ',tf_t)
print('tf_t[0][0] : ',tf_t[0][0])
print('tf_t[1][2] : ',tf_t[1][2])
print('run(tf_t) : \n',tfs.run(tf_t))
The output is as follows:
- Define a 3-D tensor:
a3dim = np.array([[[1,2],[3,4]],
[[5,6],[7,8]]
])
print("a3dim Shape : ",a3dim.shape)
tf_t=tf.convert_to_tensor(a3dim,dtype=tf.float64)
print('tf_t : ',tf_t)
print('tf_t[0][0][0] : ',tf_t[0][0][0])
print('tf_t[1][1][1] : ',tf_t[1][1][1])
print('run(tf_t) : \n',tfs.run(tf_t))
The output is as follows:
a3dim Shape : (2, 2, 2)
tf_t : Tensor("Const_4:0", shape=(2, 2, 2), dtype=float64)
tf_t[0][0][0] : Tensor("strided_slice_8:0", shape=(), dtype=float64)
tf_t[1][1][1] : Tensor("strided_slice_11:0", shape=(), dtype=float64)
run(tf_t) :
[[[ 1. 2.][ 3. 4.]]
[[ 5. 6.][ 7. 8.]]]
推薦閱讀
- Instant Raspberry Pi Gaming
- 大數(shù)據(jù)技術(shù)與應(yīng)用基礎(chǔ)
- 工業(yè)機(jī)器人產(chǎn)品應(yīng)用實(shí)戰(zhàn)
- 腦動(dòng)力:C語言函數(shù)速查效率手冊(cè)
- 3D Printing with RepRap Cookbook
- 大數(shù)據(jù)改變世界
- 流處理器研究與設(shè)計(jì)
- PHP開發(fā)手冊(cè)
- 大數(shù)據(jù)挑戰(zhàn)與NoSQL數(shù)據(jù)庫(kù)技術(shù)
- JBoss ESB Beginner’s Guide
- Lightning Fast Animation in Element 3D
- 學(xué)會(huì)VBA,菜鳥也高飛!
- Hadoop應(yīng)用開發(fā)基礎(chǔ)
- Drupal高手建站技術(shù)手冊(cè)
- 計(jì)算智能算法及其生產(chǎn)調(diào)度應(yīng)用