• 微信公众号：美女很有趣。 工作之余，放松一下，关注即送10G+美女照片！

5天前 9次浏览

# 2-1,张量数据结构

TensorFlow程序 = 张量数据结构 + 计算图算法语言

Tensorflow的基本数据结构是张量Tensor。张量即多维数组。Tensorflow的张量和numpy中的array很类似。

### 一，常量张量

``````import numpy as np
import tensorflow as tf

i = tf.constant(1) # tf.int32 类型常量
l = tf.constant(1,dtype = tf.int64) # tf.int64 类型常量
f = tf.constant(1.23) #tf.float32 类型常量
d = tf.constant(3.14,dtype = tf.double) # tf.double 类型常量
s = tf.constant("hello world") # tf.string类型常量
b = tf.constant(True) #tf.bool类型常量

print(tf.int64 == np.int64)
print(tf.bool == np.bool)
print(tf.double == np.float64)
print(tf.string == np.unicode) # tf.string类型和np.unicode类型不等价

``````
``````True
True
True
False
``````

``````scalar = tf.constant(True)  #标量，0维张量

print(tf.rank(scalar))
print(scalar.numpy().ndim)  # tf.rank的作用和numpy的ndim方法相同
``````
``````tf.Tensor(0, shape=(), dtype=int32)
0
``````
``````vector = tf.constant([1.0,2.0,3.0,4.0]) #向量，1维张量

print(tf.rank(vector))
print(np.ndim(vector.numpy()))
``````
``````tf.Tensor(1, shape=(), dtype=int32)
1
``````
``````matrix = tf.constant([[1.0,2.0],[3.0,4.0]]) #矩阵, 2维张量

print(tf.rank(matrix).numpy())
print(np.ndim(matrix))
``````
``````2
2
``````
``````tensor3 = tf.constant([[[1.0,2.0],[3.0,4.0]],[[5.0,6.0],[7.0,8.0]]])  # 3维张量
print(tensor3)
print(tf.rank(tensor3))
``````
``````tf.Tensor(
[[[1. 2.]
[3. 4.]]

[[5. 6.]
[7. 8.]]], shape=(2, 2, 2), dtype=float32)
tf.Tensor(3, shape=(), dtype=int32)
``````
``````tensor4 = tf.constant([[[[1.0,1.0],[2.0,2.0]],[[3.0,3.0],[4.0,4.0]]],
[[[5.0,5.0],[6.0,6.0]],[[7.0,7.0],[8.0,8.0]]]])  # 4维张量
print(tensor4)
print(tf.rank(tensor4))
``````
``````tf.Tensor(
[[[[1. 1.]
[2. 2.]]

[[3. 3.]
[4. 4.]]]

[[[5. 5.]
[6. 6.]]

[[7. 7.]
[8. 8.]]]], shape=(2, 2, 2, 2), dtype=float32)
tf.Tensor(4, shape=(), dtype=int32)
``````

``````h = tf.constant([123,456],dtype = tf.int32)
f = tf.cast(h,tf.float32)
print(h.dtype, f.dtype)
``````
``````<dtype: 'int32'> <dtype: 'float32'>
``````
``````y = tf.constant([[1.0,2.0],[3.0,4.0]])
print(y.numpy()) #转换成np.array
print(y.shape)
``````
``````[[1. 2.]
[3. 4.]]
(2, 2)
``````
``````u = tf.constant(u"你好 世界")
print(u.numpy())
print(u.numpy().decode("utf-8"))
``````
``````b'xe4xbdxa0xe5xa5xbd xe4xb8x96xe7x95x8c'

``````
``````
``````

### 二，变量张量

``````# 常量值不可以改变，常量的重新赋值相当于创造新的内存空间
c = tf.constant([1.0,2.0])
print(c)
print(id(c))
c = c + tf.constant([1.0,1.0])
print(c)
print(id(c))
``````
``````tf.Tensor([1. 2.], shape=(2,), dtype=float32)
5276289568
tf.Tensor([2. 3.], shape=(2,), dtype=float32)
5276290240
``````
``````# 变量的值可以改变，可以通过assign, assign_add等方法给变量重新赋值
v = tf.Variable([1.0,2.0],name = "v")
print(v)
print(id(v))
``````<tf.Variable 'v:0' shape=(2,) dtype=float32, numpy=array([1., 2.], dtype=float32)>