# 2.1 张量与操作

### 张量

TensorFlow使用一种叫张量(tensor)的数据结构去定义所有的数据，我们可以把 tensor 看成是 n 维的 array 或者 list。在 TensorFlow 的各部分图形间流动传递的只能是tensor。

编写TensorFlow程序时，操纵并传递的主要对象是tf.Tensor:

* 一个数据类型（例如 float32，int32，或string）
* 以及shape

### array(numpy)和Tensor(Tensorflow)对比

| **Numpy**                                 | **TensorFlow**                            |
| ----------------------------------------- | ----------------------------------------- |
| a =  np.zeros((2,2));  b = np.ones((2,2)) | a =  tf.zeros((2,2));  b = tf.ones((2,2)) |
| np.sum(b,axis=1)                          | tf.reduce\_sum(a,axis=1)                  |
| a.shape                                   | a.get\_shape()                            |
| np.reshape(a,(1,4))                       | tf.reshape(a,(1,4))                       |
| b\*5+1                                    | b\*5+1                                    |
| np.dot(a,b)                               | tf.matmul(a,b)                            |
| a\[0,0];  a\[:,0]; a\[0,:]                | a\[0,0];  a\[:,0]; a\[0,:]                |

## 操作

* tf.strings (常用于**推荐算法场景、\*\***&#x4E;LP场景\*\*)
* tf.debugging
* tf.dtypes
* tf.math
* tf.random
* [tf.feature\_column](https://www.tensorflow.org/tutorials/structured_data/feature_columns) (常用于结构化数据特征处理)

#### tf.strings

```python
#字符切割
tf.strings.bytes_split('hello')
```

```python
#单词切割
tf.strings.split('hello world')
```

```python
#string hash
tf.strings.to_hash_bucket(['hello','world'], num_buckets=10)
```

#### tf.debugging

```python
#tf自带debug函数
a=tf.random.uniform((10,10))
tf.debugging.assert_equal(x=a.shape,y=(10,10))
```

```python
#错误示范
tf.debugging.assert_equal(x=a.shape,y=(20,10))
```

#### tf.random

```python
a = tf.random.uniform(shape=(10,5),minval=0,maxval=10)
```

#### tf.math

```python
a = tf.constant([[1,2],[3,4]])
b = tf.constant([[5,6],[7,8]])

tf.print(tf.math.add(a,b))
tf.print(tf.math.subtract(a,b))
tf.print(tf.math.multiply(a,b))
tf.print(tf.math.divide(a,b))
```

#### tf.dtypes

```python
x =tf.constant([1.8,2.2],dtype=tf.float32)

x1=tf.dtypes.cast(x,tf.int32)
```
