tensorflow2.0新特性

Tensorflow2.0相比于以往版本,有着极大的区别;最明显的区别可以用三字词来概括:更简单,更易用,更强大。

接下来让我们一起见证下不一样的地方吧!

一、使用tf.data加载数据

        使用tf.data创建的输入管道读取训练数据;支持从内存(Numpy)方便地输入数据;

二、使用tf.keras构建,训练和验证模型,或使用Premade来验证模型

        可以直接标准的打包模型(逻辑回归,随机森林),也可以直接使用(tf.estimator API)

        如果不想从头训练模型,可以使用迁移学习来训练一个使用TensorflowHub模块的Kerasa或Estimator模型。

三、取消了会话

例子:计算两个数乘积的平方根

2.0 前版本

 1 import tensorflow as tf
 2 
 3 #variables
 4 x=tf.placeholder(tf.float32)
 5 y=tf.placeholder(tf.float32)
 6 
 7 #graph
 8 mean=tf.sqrt(x*y)
 9 
10 #run the graph
11 with tf.Session() as sess:
12      res = sess.run(mean,feed_dict={x:2,y:8})
13      print(res)
View Code

2.0版本

1 import tensorflow as tf
2 
3 #define the inputs
4 x=2.0
5 y=8.0
6 
7 #define graph
8 mean=tf.sqrt(x*y)
9 tf.print(mean)
View Code

四、使用快速执行(Eager execution)运行和调试,然后使用tf.function

      定义一个全局函数

 1 import tensorflow as tf
 2 
 3 #define the inputs
 4 x=2.0
 5 y=8.0
 6 
 7 @tf.function
 8 def geometric_mean(x,y):
 9      mean=tf.sqrt(x*y)
10      return mean
11 
12 mean=geometric_mean(x,y)
13 tf.print(mean)
View Code

      整合了2.0之前的各种复杂的函数接口,统一了形形色色的编译语言,API满足Keras接口标准

 1 impot tensorflow as tf
 2 
 3 (train_images,train_labels),(test_images,test_labels) = tf.keras.datasets.mnist.load_data()
 4 
 5 model = tf.keras.Sequential([
 6           tf.keras.layers.Flatten(input_shape=(28,28)),
 7           tf.keras.layers.Dense(512,activation=tf.nn.relu),
 8           tf.keras.layers.Dense(10,activation=tf.nn.softmax)])
 9 
10 model.compile(optimizer='adam',
11                      loss='sparse_categorical_crossentropy',
12                      metrics=['accuracy'])
13 
14 model.fit(train_images,train_labels,epochs=5)
View Code

      支持与Tensorboard的调用交互

 1 import tensorflow as tf
 2 
 3 data_train,_ = tf.keras.datasets.mnist.load_data()
 4 dataset=tf.data.Dataset.from_tensor_slices(data_train)
 5 dataset=dataset.shuffle(buffer_size=60000)
 6 dataset=dataset.batch(32)
 7 
 8 model=tf.keras.Sequential([
 9            tf.keras.layers.Flatten(input_shape=(28,28)),
10            tf.keras.layers.Dense(512,activation=tf.nn.relu),
11            tf.keras.layers.Dense(10,activation=tf.nn.softmax)
12 ])
13 
14 model.compile(optimizer='adam',
15                       loss='sparse_categorical_crossentropy',
16                       metrics=['accuracy'])
17  
18 tb = tf.keras.callbacks.Tensorboard(log_dir='./checkpoints')
19 model.fit(dataset,epochs=5,callbacks=[tb])
View Code

五、使用分发策略进行分发训练

      大型ML训练任务,分发策略API可以在不更改定义的情况下,轻松在不同的硬件配置上分发和训练模型。TF支持一系列硬件加速器,GPU,TPU

六、导出到SavedModel

      Tensorflow将在SavedModel上作为Tensorflow服务,Tensorflow Lite,Tensorflow.js,Tensorflow Hub等交换格式进行标准化;

 

posted @ 2019-10-10 14:52  jimchen1218  阅读(2469)  评论(0编辑  收藏  举报