## Session execution

，然后通过 `tf.Session`

```g = tf.Graph()
with g.as_default():
a = tf.constant([[10,10],[11.,1.]])
x = tf.constant([[1.,0.],[0.,1.]])
b = tf.Variable(12.)
y = tf.matmul(a, x) + b
init_op = tf.global_variables_initializer()with tf.Session() as sess:
sess.run(init_op)
print(sess.run(y))```

Tensorflow变得像普通的Python代码一样简单．

```a = tf.constant([[10,10],[11.,1.]])
x = tf.constant([[1.,0.],[0.,1.]])
b = tf.Variable(12.)
y = tf.matmul(a, x) + b
print(y.numpy())```

## tf.function, not tf.Session

Tensorflow 2.0中一个主要的改变就是移除 `tf.Session`

## 懒人介绍tf.function

```tf.Operation
tf.control_dependencies```

```def f():
a = tf.constant([[10,10],[11.,1.]])
x = tf.constant([[1.,0.],[0.,1.]])
b = tf.Variable(12.)
y = tf.matmul(a, x) + b
return yprint(f().numpy())#执行结果
[[22. 22.]
[23. 13.]]```

## From eager to tf.function

```@tf.function
def f():
a = tf.constant([[10,10],[11.,1.]])
x = tf.constant([[1.,0.],[0.,1.]])
b = tf.Variable(12.)
y = tf.matmul(a, x) + b
print("PRINT: ", y)
tf.print("TF-PRINT: ", y)
return yf()#执行结果
ValueError: tf.function-decorated function tried to create variables on non-first call.```

，是在Graph中持续存在的．

1. 设计函数f时需要一些输入参数，这个输入参数可以是

`tf.Variable`

1. 或者其他任何类型．

1. 设计一个函数从parent scope继承Python variable，在函数中检查Variable是否已经定义过

`(if b != None)`

1. 将所有的内容写到一个class里，就好像Keras layer一样,所有的Variable都是class的内部参数

`(self._b)`

1. ，将class的

`__call__()`

1. 通过

`tf.function`

1. 装饰．

## 方案2 vs 方案3

```b = [email protected]
def f():
a = tf.constant([[10, 10], [11., 1.]])
x = tf.constant([[1., 0.], [0., 1.]])
global b
if b is None:
b = tf.Variable(12.)
y = tf.matmul(a, x) + b
print("PRINT: ", y)
tf.print("TF-PRINT: ", y)
return yf()```

```class F():
def __init__(self):
self._b = None @tf.function
def __call__(self):
a = tf.constant([[10, 10], [11., 1.]])
x = tf.constant([[1., 0.], [0., 1.]])
if self._b is None:
self._b = tf.Variable(12.)
y = tf.matmul(a, x) + self._b
print("PRINT: ", y)
tf.print("TF-PRINT: ", y)
return yf = F()
f()```

## 方案1举例

```@tf.function
def f(b):
a = tf.constant([[10,10],[11.,1.]])
x = tf.constant([[1.,0.],[0.,1.]])
y = tf.matmul(a, x) + b
print("PRINT: ", y)
tf.print("TF-PRINT: ", y)
return yb = tf.Variable(12.)
f(b)```

```@tf.function
def g(x):
return xa = tf.Variable(0)
print(g(a))
print(g(a))
print(g(a))#执行结果
tf.Tensor(1, shape=(), dtype=int32)
tf.Tensor(2, shape=(), dtype=int32)
tf.Tensor(3, shape=(), dtype=int32)```

## Conclusions

Dissecting tf function part 1 https://pgaleone.eu/tensorflow/tf.function/2019/03/21/dissecting-tf-function-part-1/