# TensorFlow API 简介

## TensorFlow 相关函数理解

### tf.nn.conv2d

```conv2d(
input,
filter,
strides,
use_cudnn_on_gpu=True,
data_format='NHWC',
name=None
)```

input

tensor

filter

tensor

strides

string

use_cudnn_on_gpu

bool

data_format

string

name

string

#### 示例代码：

##### 示例代码：/home/ubuntu/conv2d.py
```import tensorflow as tf

a = tf.constant([1,1,1,0,0,0,1,1,1,0,0,0,1,1,1,0,0,1,1,0,0,1,1,0,0],dtype=tf.float32,shape=[1,5,5,1])
b = tf.constant([1,0,1,0,1,0,1,0,1],dtype=tf.float32,shape=[3,3,1,1])
c = tf.nn.conv2d(a,b,strides=[1, 2, 2, 1],padding='VALID')
d = tf.nn.conv2d(a,b,strides=[1, 2, 2, 1],padding='SAME')
with tf.Session() as sess:
print ("c shape:")
print (c.shape)
print ("c value:")
print (sess.run(c))
print ("d shape:")
print (d.shape)
print ("d value:")
print (sess.run(d))```

#### 然后执行:

```cd /home/ubuntu;
python conv2d.py```

#### 执行结果：

```c shape:
(1, 3, 3, 1)
c value:
[[[[ 4.]
[ 3.]
[ 4.]]

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

[[ 2.]
[ 3.]
[ 4.]]]]
d shape:
(1, 5, 5, 1)
d value:
[[[[ 2.]
[ 2.]
[ 3.]
[ 1.]
[ 1.]]

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

[[ 1.]
[ 2.]
[ 4.]
[ 3.]
[ 3.]]

[[ 1.]
[ 2.]
[ 3.]
[ 4.]
[ 1.]]

[[ 0.]
[ 2.]
[ 2.]
[ 1.]
[ 1.]]]]```

### tf.nn.relu

```relu(
features,
name=None
)```

features

tensor

name

string

#### 示例代码：

##### 示例代码：/home/ubuntu/relu.py
```import tensorflow as tf

a = tf.constant([1,-2,0,4,-5,6])
b = tf.nn.relu(a)
with tf.Session() as sess:
print (sess.run(b))```

#### 然后执行：

```cd /home/ubuntu;
python relu.py```

#### 执行结果：

`[1 0 0 4 0 6]`

### tf.nn.max_pool

```max_pool(
value,
ksize,
strides,
data_format='NHWC',
name=None
)```

#### 参数列表：

value

tensor

4 维的张量，即 [ batch, height, width, channels ]，数据类型为 tf.float32

ksize

strides

string

data_format

string

name

string

#### 示例代码：

##### 示例代码：/home/ubuntu/max_pool.py
```import tensorflow as tf

a = tf.constant([1,3,2,1,2,9,1,1,1,3,2,3,5,6,1,2],dtype=tf.float32,shape=[1,4,4,1])
b = tf.nn.max_pool(a,ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1],padding='VALID')
c = tf.nn.max_pool(a,ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1],padding='SAME')
with tf.Session() as sess:
print ("b shape:")
print (b.shape)
print ("b value:")
print (sess.run(b))
print ("c shape:")
print (c.shape)
print ("c value:")
print (sess.run(c))```

#### 然后执行：

```cd /home/ubuntu;
python max_pool.py```

#### 执行结果：

```b shape:
(1, 2, 2, 1)
b value:
[[[[ 9.]
[ 2.]]

[[ 6.]
[ 3.]]]]
c shape:
(1, 2, 2, 1)
c value:
[[[[ 9.]
[ 2.]]

[[ 6.]
[ 3.]]]]```

### tf.nn.dropout

```dropout(
x,
keep_prob,
noise_shape=None,
seed=None,
name=None
)```

#### 参数列表：

x

tensor

keep_prob

scalar Tensor

dropout 的概率，一般是占位符

noise_shape

tensor

seed

name

string

#### 示例代码：

##### 示例代码：/home/ubuntu/dropout.py
```import tensorflow as tf

a = tf.constant([1,2,3,4,5,6],shape=[2,3],dtype=tf.float32)
b = tf.placeholder(tf.float32)
c = tf.nn.dropout(a,b,[2,1],1)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print (sess.run(c,feed_dict={b:0.75}))```

#### 然后执行：

```cd /home/ubuntu;
python dropout.py```

#### 执行结果：

```[[ 0.          0.          0.        ]
[ 5.33333349  6.66666651  8.        ]]```

### tf.nn.sigmoid_cross_entropy_with_logits

```sigmoid_cross_entropy_with_logits(
_sentinel=None,
labels=None,
logits=None,
name=None
)```

#### 参数列表：

_sentinel

None

labels

Tensor

type, shape 与 logits相同

logits

Tensor

type 是 float32 或者 float64

name

string

#### 示例代码：

##### 示例代码：/home/ubuntu/sigmoid_cross_entropy_with_logits.py
```import tensorflow as tf
x = tf.constant([1,2,3,4,5,6,7],dtype=tf.float64)
y = tf.constant([1,1,1,0,0,1,0],dtype=tf.float64)
loss = tf.nn.sigmoid_cross_entropy_with_logits(labels = y,logits = x)
with tf.Session() as sess:
print (sess.run(loss))```

#### 然后执行：

```cd /home/ubuntu;
python sigmoid_cross_entropy_with_logits.py```

#### 执行结果：

```[  3.13261688e-01   1.26928011e-01   4.85873516e-02   4.01814993e+00
5.00671535e+00   2.47568514e-03   7.00091147e+00]```

### tf.truncated_normal

```truncated_normal(
shape,
mean=0.0,
stddev=1.0,
dtype=tf.float32,
seed=None,
name=None
)```

shape

1 维整形张量或 array

mean

0 维张量或数值

stddev

0 维张量或数值

dtype

dtype

seed

name

string

#### 示例代码：

##### 示例代码：/home/ubuntu/truncated_normal.py
```import tensorflow as tf
initial = tf.truncated_normal(shape=[3,3], mean=0, stddev=1)
print(tf.Session().run(initial))```

#### 然后执行:

`python /home/ubuntu/truncated_normal.py`

### tf.constant

```constant(
value,
dtype=None,
shape=None,
name='Const',
verify_shape=False
)```

value

dtype

dtype

shape

1 维整形张量或 array

name

string

verify_shape

Boolean

#### 示例代码：

##### 示例代码：/home/ubuntu/constant.py
```#!/usr/bin/python

import tensorflow as tf
import numpy as np
a = tf.constant([1,2,3,4,5,6],shape=[2,3])
b = tf.constant(-1,shape=[3,2])
c = tf.matmul(a,b)

e = tf.constant(np.arange(1,13,dtype=np.int32),shape=[2,2,3])
f = tf.constant(np.arange(13,25,dtype=np.int32),shape=[2,3,2])
g = tf.matmul(e,f)
with tf.Session() as sess:
print (sess.run(a))
print ("##################################")
print (sess.run(b))
print ("##################################")
print (sess.run(c))
print ("##################################")
print (sess.run(e))
print ("##################################")
print (sess.run(f))
print ("##################################")
print (sess.run(g))```

#### 然后执行:

`python /home/ubuntu/constant.py`

#### 执行结果：

```a: 2x3 维张量；
b: 3x2 维张量；
c: 2x2 维张量；
e: 2x2x3 维张量；
f: 2x3x2 维张量；
g: 2x2x2 维张量。```

### tf.placeholder

```placeholder(
dtype,
shape=None,
name=None
)```

dtype

dtype

shape

1 维整形张量或 array

name

string

#### 示例代码：

##### 示例代码：/home/ubuntu/placeholder.py
```#!/usr/bin/python

import tensorflow as tf
import numpy as np

x = tf.placeholder(tf.float32,[None,3])
y = tf.matmul(x,x)
with tf.Session() as sess:
rand_array = np.random.rand(3,3)
print(sess.run(y,feed_dict={x:rand_array}))```

#### 然后执行:

`python /home/ubuntu/placeholder.py`

#### 执行结果：

`输出一个 3x3 的张量`

```bias_add(
value,
bias,
data_format=None,
name=None
)```

value

bias

1 维张量

data_format

string

name

string

#### 示例代码：

```#!/usr/bin/python

import tensorflow as tf
import numpy as np

a = tf.constant([[1.0, 2.0],[1.0, 2.0],[1.0, 2.0]])
b = tf.constant([2.0,1.0])
c = tf.constant([1.0])
sess = tf.Session()
print ("##################################")
print ("##################################")

#### 然后执行:

`python /home/ubuntu/bias_add.py`

#### 执行结果：

3 个 3x2 维张量。您也可以尝试修改源代码看看输出结果有什么变化？

### tf.reduce_mean

```reduce_mean(
input_tensor,
axis=None,
keep_dims=False,
name=None,
reduction_indices=None
)```

#### 参数列表：

input_tensor

axis

None、0、1

None：全局求平均值；0：求每一列平均值；1：求每一行平均值

keep_dims

Boolean

name

string

reduction_indices

None

#### 示例代码：

##### 示例代码：/home/ubuntu/reduce_mean.py
```#!/usr/bin/python

import tensorflow as tf
import numpy as np

initial = [[1.,1.],[2.,2.]]
x = tf.Variable(initial,dtype=tf.float32)
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init_op)
print(sess.run(tf.reduce_mean(x)))
print(sess.run(tf.reduce_mean(x,0))) #Column
print(sess.run(tf.reduce_mean(x,1))) #row```

#### 然后执行:

`python /home/ubuntu/reduce_mean.py`

```1.5
[ 1.5  1.5]
[ 1.  2.]```

### tf.squared_difference

```squared_difference(
x,
y,
name=None
)```

x

y

name

string

#### 示例代码：

##### 示例代码：/home/ubuntu/squared_difference.py
```#!/usr/bin/python

import tensorflow as tf
import numpy as np

initial_x = [[1.,1.],[2.,2.]]
x = tf.Variable(initial_x,dtype=tf.float32)
initial_y = [[3.,3.],[4.,4.]]
y = tf.Variable(initial_y,dtype=tf.float32)
diff = tf.squared_difference(x,y)
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init_op)
print(sess.run(diff))```

#### 然后执行:

`python /home/ubuntu/squared_difference.py`

#### 执行结果：

```[[ 4.  4.]
[ 4.  4.]]```

### tf.square

```square(
x,
name=None
)```

x

name

string

#### 示例代码：

##### 示例代码：/home/ubuntu/square.py
```#!/usr/bin/python
import tensorflow as tf
import numpy as np

initial_x = [[1.,1.],[2.,2.]]
x = tf.Variable(initial_x,dtype=tf.float32)
x2 = tf.square(x)
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init_op)
print(sess.run(x2))```

#### 然后执行:

`python /home/ubuntu/square.py`

#### 执行结果：

```[[ 1.  1.]
[ 4.  4.]]```

## TensorFlow 相关类理解

### tf.Variable

```__init__(
initial_value=None,
trainable=True,
collections=None,
validate_shape=True,
caching_device=None,
name=None,
variable_def=None,
dtype=None,
expected_shape=None,
import_scope=None
)```

#### 参数列表：

initial_value

Variable 类的初始值，这个变量必须指定 shape 信息，否则后面 validate_shape 需设为 False

trainable

Boolean

collections

Graph collections

validate_shape

Boolean

caching_device

string

name

string

dtype

dtype

expected_shape

TensorShape

#### 示例代码：

##### 示例代码：/home/ubuntu/Variable.py
```#!/usr/bin/python

import tensorflow as tf
initial = tf.truncated_normal(shape=[10,10],mean=0,stddev=1)
W=tf.Variable(initial)
list = [[1.,1.],[2.,2.]]
X = tf.Variable(list,dtype=tf.float32)
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init_op)
print ("##################(1)################")
print (sess.run(W))
print ("##################(2)################")
print (sess.run(W[:2,:2]))
op = W[:2,:2].assign(22.*tf.ones((2,2)))
print ("###################(3)###############")
print (sess.run(op))
print ("###################(4)###############")
print (W.eval(sess)) #computes and returns the value of this variable
print ("####################(5)##############")
print (W.eval())  #Usage with the default session
print ("#####################(6)#############")
print (W.dtype)
print (sess.run(W.initial_value))
print (sess.run(W.op))
print (W.shape)
print ("###################(7)###############")
print (sess.run(X))```

#### 然后执行：

`python /home/ubuntu/Variable.py`

19 篇文章169 人订阅

0 条评论

## 相关文章

### tensorflow学习笔记（二十七）：leaky relu

tensorflow leaky relu 在tensorflow 0.12.0及之前，都没有内置的leaky relu函数，那么我们如何实现leaky rel...

2838

### pytorch入门教程 | 第一章：Tensor

1 pytorch安装 安装pytorch之前，需要安装好python，还没安装过python的宝宝请先移步到廖雪峰的python教程，待安装熟悉完之后，再过来...

42110

### 洛谷P1313 计算系数【快速幂+dp】

P1313 计算系数 题目描述 给定一个多项式(by+ax)^k，请求出多项式展开后x^n*y^m 项的系数。 输入输出格式 输入格式： 输入文件名为facto...

2225

47610

### Python中的random模块用于生成随机数

Python中的random模块用于生成随机数。下面介绍一下random模块中最常用的几个函数。 random.random random.random(...

3577

4064

901

2732

1072