![]() | ![]() | ![]() | ![]() |
คู่มือนี้มีไว้สำหรับผู้ใช้ TensorFlow API ระดับต่ำ หากคุณใช้ API ระดับสูง ( tf.keras
) อาจมีการดำเนินการเพียงเล็กน้อยหรือไม่มีเลยที่คุณต้องดำเนินการเพื่อให้โค้ดของคุณเข้ากันได้กับ TensorFlow 2.x อย่างสมบูรณ์:
- ตรวจสอบ อัตราการเรียนรู้เริ่มต้นของเครื่องมือเพิ่มประสิทธิภาพของ คุณ
- โปรดทราบว่า "ชื่อ" ที่บันทึกเมตริกไว้ อาจมีการเปลี่ยนแปลง
ยังคงเป็นไปได้ที่จะเรียกใช้โค้ด 1.x โดยไม่ได้แก้ไข ( ยกเว้นการสนับสนุน ) ใน TensorFlow 2.x
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
อย่างไรก็ตามสิ่งนี้ไม่อนุญาตให้คุณใช้ประโยชน์จากการปรับปรุงมากมายที่เกิดขึ้นใน TensorFlow 2.x. คู่มือนี้จะช่วยให้คุณอัปเกรดโค้ดของคุณทำให้ง่ายขึ้นมีประสิทธิภาพมากขึ้นและดูแลรักษาง่ายขึ้น
สคริปต์การแปลงอัตโนมัติ
ขั้นตอนแรกก่อนที่จะพยายามใช้การเปลี่ยนแปลงที่อธิบายไว้ในคู่มือนี้คือการลองเรียกใช้ สคริปต์การอัพเกรด
การดำเนินการนี้จะเรียกใช้รหัสผ่านเริ่มต้นในการอัปเกรดโค้ดของคุณเป็น TensorFlow 2.x แต่ไม่สามารถทำให้รหัสของคุณเป็น v2 ได้ โค้ดของคุณอาจยังใช้ประโยชน์จากปลายทาง tf.compat.v1
เพื่อเข้าถึงตัวยึดเซสชันคอลเลกชันและฟังก์ชันรูปแบบ 1.x อื่น ๆ
การเปลี่ยนแปลงพฤติกรรมระดับบนสุด
หากโค้ดของคุณทำงานใน TensorFlow 2.x โดยใช้ tf.compat.v1.disable_v2_behavior
ยังคงมีการเปลี่ยนแปลงพฤติกรรมทั่วโลกที่คุณอาจต้องแก้ไข การเปลี่ยนแปลงที่สำคัญ ได้แก่
การดำเนินการอย่างกระตือรือร้น
v1.enable_eager_execution()
: โค้ดใด ๆ ที่ใช้tf.Graph
โดยปริยายจะล้มเหลว อย่าลืมรวมโค้ดนี้with tf.Graph().as_default()
ตัวแปรทรัพยากร
v1.enable_resource_variables()
: โค้ดบางตัวอาจขึ้นอยู่กับพฤติกรรมที่ไม่ใช่ปัจจัยที่เปิดใช้งานโดยตัวแปรอ้างอิง TensorFlow ตัวแปรทรัพยากรจะถูกล็อคในขณะที่เขียนถึงดังนั้นจึงให้การรับประกันความสอดคล้องที่ใช้งานง่ายมากขึ้น- สิ่งนี้อาจเปลี่ยนพฤติกรรมในกรณีขอบ
- ซึ่งอาจสร้างสำเนาเพิ่มเติมและสามารถใช้หน่วยความจำได้สูงขึ้น
- สามารถปิดใช้งานได้โดยส่ง
use_resource=False
ไปยังtf.Variable
constructor
รูปร่างของเทนเซอร์
v1.enable_v2_tensorshape()
: TensorFlow 2.x ช่วยลดความซับซ้อนของรูปทรงของเทนเซอร์ แทนt.shape[0].value
t.shape[0]
คุณสามารถพูดว่าt.shape[0]
การเปลี่ยนแปลงเหล่านี้ควรมีขนาดเล็กและควรแก้ไขทันที โปรดดูส่วน TensorShape สำหรับตัวอย่างโฟลว์การควบคุม
v1.enable_control_flow_v2()
: การนำโฟลว์การควบคุม TensorFlow 2.x ไปใช้งานได้ง่ายขึ้นและสร้างการแสดงกราฟที่แตกต่างกัน โปรดส่ง ข้อบกพร่อง สำหรับปัญหาใด ๆ
สร้างโค้ดสำหรับ TensorFlow 2.x
คู่มือนี้จะอธิบายถึงตัวอย่างต่างๆของการแปลงรหัส TensorFlow 1.x เป็น TensorFlow 2.x การเปลี่ยนแปลงเหล่านี้จะช่วยให้โค้ดของคุณใช้ประโยชน์จากการเพิ่มประสิทธิภาพและการเรียก API ที่ง่ายขึ้น
ในแต่ละกรณีรูปแบบคือ:
1. แทนที่การโทร v1.Session.run
ทุกการเรียก v1.Session.run
ควรถูกแทนที่ด้วยฟังก์ชัน Python
-
feed_dict
และv1.placeholder
กลายเป็นอาร์กิวเมนต์ของฟังก์ชัน - การ
fetches
จะกลายเป็นค่าส่งกลับของฟังก์ชัน - ในระหว่างการดำเนินการแปลงอย่างกระตือรือร้นช่วยให้สามารถแก้ไขจุดบกพร่องได้ง่ายด้วยเครื่องมือ Python มาตรฐานเช่น
pdb
หลังจากนั้นให้เพิ่มมัณฑนากร tf.function
เพื่อให้ทำงานได้อย่างมีประสิทธิภาพในกราฟ ดู คู่มือ Autograph สำหรับข้อมูลเพิ่มเติมเกี่ยวกับวิธีการทำงาน
โปรดทราบว่า:
ซึ่งแตกต่างจาก
v1.Session.run
tf.function
มีลายเซ็นส่งคืนคงที่และส่งคืนเอาต์พุตทั้งหมดเสมอ หากสิ่งนี้ทำให้เกิดปัญหาด้านประสิทธิภาพให้สร้างฟังก์ชันแยกกันสองฟังก์ชันไม่จำเป็นต้องมี
tf.control_dependencies
หรือการดำเนินการที่คล้ายกัน:tf.function
ทำงานเหมือนกับว่ามีการรันตามลำดับที่เขียนไว้tf.Variable
assignments และtf.assert
s เป็นต้นจะดำเนินการโดยอัตโนมัติ
ส่วนโมเดลการแปลง มีตัวอย่างการทำงานของกระบวนการแปลงนี้
2. ใช้วัตถุ Python เพื่อติดตามตัวแปรและการสูญเสีย
ไม่แนะนำให้ใช้การติดตามตัวแปรตามชื่อทั้งหมดใน TensorFlow 2.x ใช้วัตถุ Python เพื่อติดตามตัวแปร
ใช้ tf.Variable
แทน v1.get_variable
ทุก v1.variable_scope
ควรถูกแปลงเป็นวัตถุ Python โดยทั่วไปแล้วจะเป็นหนึ่งใน:
หากคุณต้องการรายชื่อรวมของตัวแปร (เช่น tf.Graph.get_collection(tf.GraphKeys.VARIABLES)
) ให้ใช้ .variables
และ .trainable_variables
แอตทริบิวต์ของ Layer
และ Model
วัตถุ
คลาส Layer
และ Model
เหล่านี้ใช้คุณสมบัติอื่น ๆ อีกมากมายที่ขจัดความจำเป็นในการรวบรวมส่วนกลาง คุณสมบัติ. .losses
ของพวกเขาสามารถทดแทนการใช้คอลเลกชัน tf.GraphKeys.LOSSES
ดู คู่มือ Keras สำหรับรายละเอียดเพิ่มเติม
3. อัปเกรดลูปการฝึกของคุณ
ใช้ API ระดับสูงสุดที่เหมาะกับกรณีการใช้งานของคุณ ชอบ tf.keras.Model.fit
มากกว่าสร้างลูปการฝึกของคุณเอง
ฟังก์ชันระดับสูงเหล่านี้จัดการรายละเอียดระดับต่ำจำนวนมากซึ่งอาจพลาดได้ง่ายหากคุณเขียนลูปการฝึกอบรมของคุณเอง ตัวอย่างเช่นพวกเขารวบรวมการสูญเสียการทำให้เป็นมาตรฐานโดยอัตโนมัติและตั้งค่าอาร์กิวเมนต์ training=True
เมื่อเรียกใช้โมเดล
4. อัพเกรดท่อป้อนข้อมูลของคุณ
ใช้ชุดข้อมูล tf.data
สำหรับการป้อนข้อมูล วัตถุเหล่านี้มีประสิทธิภาพแสดงออกและรวมเข้ากับเทนเซอร์โฟลว์ได้ดี
สามารถส่งผ่านไปยังเมธอด tf.keras.Model.fit
ได้โดยตรง
model.fit(dataset, epochs=5)
สามารถทำซ้ำผ่าน Python มาตรฐานโดยตรง:
for example_batch, label_batch in dataset:
break
5. ย้ายสัญลักษณ์ compat.v1
ออก
โมดูล tf.compat.v1
มี TensorFlow 1.x API ที่สมบูรณ์พร้อมความหมายดั้งเดิม
สคริปต์การอัปเกรด TensorFlow 2.x จะแปลงสัญลักษณ์ให้เทียบเท่า v2 หากการแปลงดังกล่าวปลอดภัยกล่าวคือหากสามารถระบุได้ว่าลักษณะการทำงานของเวอร์ชัน TensorFlow 2.x เทียบเท่ากันทุกประการ (ตัวอย่างเช่นจะเปลี่ยนชื่อ v1.arg_max
ถึง tf.argmax
เนื่องจากเป็นฟังก์ชันเดียวกัน)
หลังจากสคริปต์อัพเกรดเสร็จสิ้นด้วยโค้ดชิ้นหนึ่งมีแนวโน้มว่าจะมีการกล่าวถึง compat.v1
มากมาย มันคุ้มค่าที่จะผ่านรหัสและแปลงสิ่งเหล่านี้ด้วยตนเองให้เทียบเท่า v2 (ควรระบุไว้ในบันทึกหากมี)
การแปลงโมเดล
ตัวแปรระดับต่ำและการดำเนินการของตัวดำเนินการ
ตัวอย่างการใช้ API ระดับต่ำ ได้แก่ :
- การใช้ขอบเขตตัวแปรเพื่อควบคุมการใช้ซ้ำ
- การสร้างตัวแปรด้วย
v1.get_variable
- การเข้าถึงคอลเลกชันอย่างชัดเจน
การเข้าถึงคอลเลกชันโดยปริยายด้วยวิธีการเช่น:
การใช้
v1.placeholder
เพื่อตั้งค่าอินพุตกราฟการเรียกใช้กราฟด้วย
Session.run
การเริ่มต้นตัวแปรด้วยตนเอง
ก่อนที่จะแปลง
นี่คือลักษณะของรูปแบบเหล่านี้ในโค้ดโดยใช้ TensorFlow 1.x
import tensorflow as tf
import tensorflow.compat.v1 as v1
import tensorflow_datasets as tfds
g = v1.Graph()
with g.as_default():
in_a = v1.placeholder(dtype=v1.float32, shape=(2))
in_b = v1.placeholder(dtype=v1.float32, shape=(2))
def forward(x):
with v1.variable_scope("matmul", reuse=v1.AUTO_REUSE):
W = v1.get_variable("W", initializer=v1.ones(shape=(2,2)),
regularizer=lambda x:tf.reduce_mean(x**2))
b = v1.get_variable("b", initializer=v1.zeros(shape=(2)))
return W * x + b
out_a = forward(in_a)
out_b = forward(in_b)
reg_loss=v1.losses.get_regularization_loss(scope="matmul")
with v1.Session(graph=g) as sess:
sess.run(v1.global_variables_initializer())
outs = sess.run([out_a, out_b, reg_loss],
feed_dict={in_a: [1, 0], in_b: [0, 1]})
print(outs[0])
print()
print(outs[1])
print()
print(outs[2])
[[1. 0.] [1. 0.]] [[0. 1.] [0. 1.]] 1.0
หลังจากแปลง
ในรหัสที่แปลงแล้ว:
- ตัวแปรคือวัตถุ Python ในเครื่อง
- ฟังก์ชัน
forward
ยังคงกำหนดการคำนวณ - การเรียก
Session.run
จะถูกแทนที่ด้วยการโทรเพื่อforward
- สามารถเพิ่มมัณฑนากร
tf.function
เสริมเพื่อประสิทธิภาพ - การจัดลำดับจะคำนวณด้วยตนเองโดยไม่อ้างถึงคอลเล็กชันส่วนกลางใด ๆ
- ไม่มีการใช้งานเซสชันหรือตัวยึดตำแหน่ง
W = tf.Variable(tf.ones(shape=(2,2)), name="W")
b = tf.Variable(tf.zeros(shape=(2)), name="b")
@tf.function
def forward(x):
return W * x + b
out_a = forward([1,0])
print(out_a)
tf.Tensor( [[1. 0.] [1. 0.]], shape=(2, 2), dtype=float32)
out_b = forward([0,1])
regularizer = tf.keras.regularizers.l2(0.04)
reg_loss=regularizer(W)
โมเดลตาม tf.layers
โมดูล v1.layers
ใช้เพื่อบรรจุฟังก์ชันเลเยอร์ที่อาศัย v1.variable_scope
เพื่อกำหนดและนำตัวแปรกลับมาใช้ใหม่
ก่อนที่จะแปลง
def model(x, training, scope='model'):
with v1.variable_scope(scope, reuse=v1.AUTO_REUSE):
x = v1.layers.conv2d(x, 32, 3, activation=v1.nn.relu,
kernel_regularizer=lambda x:0.004*tf.reduce_mean(x**2))
x = v1.layers.max_pooling2d(x, (2, 2), 1)
x = v1.layers.flatten(x)
x = v1.layers.dropout(x, 0.1, training=training)
x = v1.layers.dense(x, 64, activation=v1.nn.relu)
x = v1.layers.batch_normalization(x, training=training)
x = v1.layers.dense(x, 10)
return x
train_data = tf.ones(shape=(1, 28, 28, 1))
test_data = tf.ones(shape=(1, 28, 28, 1))
train_out = model(train_data, training=True)
test_out = model(test_data, training=False)
print(train_out)
print()
print(test_out)
/tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/keras/legacy_tf_layers/convolutional.py:414: UserWarning: `tf.layers.conv2d` is deprecated and will be removed in a future version. Please Use `tf.keras.layers.Conv2D` instead. warnings.warn('`tf.layers.conv2d` is deprecated and ' /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/keras/engine/base_layer.py:2273: UserWarning: `layer.apply` is deprecated and will be removed in a future version. Please use `layer.__call__` method instead. warnings.warn('`layer.apply` is deprecated and ' tf.Tensor([[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]], shape=(1, 10), dtype=float32) tf.Tensor( [[ 0.379358 -0.55901194 0.48704922 0.11619566 0.23902717 0.01691487 0.07227738 0.14556988 0.2459927 0.2501198 ]], shape=(1, 10), dtype=float32) /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/keras/legacy_tf_layers/pooling.py:310: UserWarning: `tf.layers.max_pooling2d` is deprecated and will be removed in a future version. Please use `tf.keras.layers.MaxPooling2D` instead. warnings.warn('`tf.layers.max_pooling2d` is deprecated and ' /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/keras/legacy_tf_layers/core.py:329: UserWarning: `tf.layers.flatten` is deprecated and will be removed in a future version. Please use `tf.keras.layers.Flatten` instead. warnings.warn('`tf.layers.flatten` is deprecated and ' /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/keras/legacy_tf_layers/core.py:268: UserWarning: `tf.layers.dropout` is deprecated and will be removed in a future version. Please use `tf.keras.layers.Dropout` instead. warnings.warn('`tf.layers.dropout` is deprecated and ' /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/keras/legacy_tf_layers/core.py:171: UserWarning: `tf.layers.dense` is deprecated and will be removed in a future version. Please use `tf.keras.layers.Dense` instead. warnings.warn('`tf.layers.dense` is deprecated and ' /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/keras/legacy_tf_layers/normalization.py:308: UserWarning: `tf.layers.batch_normalization` is deprecated and will be removed in a future version. Please use `tf.keras.layers.BatchNormalization` instead. In particular, `tf.control_dependencies(tf.GraphKeys.UPDATE_OPS)` should not be used (consult the `tf.keras.layers.BatchNormalization` documentation). '`tf.layers.batch_normalization` is deprecated and '
หลังจากแปลง
- การเรียงซ้อนของเลเยอร์ที่เรียบง่ายเข้ากันได้ดีกับ
tf.keras.Sequential
ตามลำดับ (สำหรับโมเดลที่ซับซ้อนมากขึ้นโปรดดู เลเยอร์และโมเดลที่กำหนดเองและ คู่มือ API การทำงาน ) - แบบจำลองติดตามตัวแปรและการสูญเสียการทำให้เป็นมาตรฐาน
- การแปลงเป็นแบบ
v1.layers
เนื่องจากมีการแมปโดยตรงจากv1.layers
ไปยังtf.keras.layers
ข้อโต้แย้งส่วนใหญ่ยังคงเหมือนเดิม แต่สังเกตความแตกต่าง:
- อาร์กิวเมนต์
training
จะถูกส่งผ่านไปยังแต่ละเลเยอร์โดยโมเดลเมื่อรัน - อาร์กิวเมนต์แรกของฟังก์ชัน
model
ดั้งเดิม (อินพุตx
) หายไป เนื่องจากชั้นออบเจ็กต์แยกการสร้างโมเดลออกจากการเรียกโมเดล
โปรดทราบว่า:
- หากคุณใช้ Regularizers หรือ initializers จาก
tf.contrib
สิ่งเหล่านี้จะมีการเปลี่ยนแปลงอาร์กิวเมนต์มากกว่าตัวอื่น ๆ - โค้ดจะไม่เขียนลงในคอลเลกชันอีกต่อไปดังนั้นฟังก์ชันเช่น
v1.losses.get_regularization_loss
จะไม่ส่งคืนค่าเหล่านี้อีกต่อไปซึ่งอาจทำลายลูปการฝึกของคุณได้
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(32, 3, activation='relu',
kernel_regularizer=tf.keras.regularizers.l2(0.04),
input_shape=(28, 28, 1)),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Flatten(),
tf.keras.layers.Dropout(0.1),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.Dense(10)
])
train_data = tf.ones(shape=(1, 28, 28, 1))
test_data = tf.ones(shape=(1, 28, 28, 1))
train_out = model(train_data, training=True)
print(train_out)
tf.Tensor([[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]], shape=(1, 10), dtype=float32)
test_out = model(test_data, training=False)
print(test_out)
tf.Tensor( [[-0.2145557 -0.22979769 -0.14968733 0.01208701 -0.07569927 0.3475932 0.10718458 0.03482988 -0.04309493 -0.10469118]], shape=(1, 10), dtype=float32)
# Here are all the trainable variables
len(model.trainable_variables)
8
# Here is the regularization loss
model.losses
[<tf.Tensor: shape=(), dtype=float32, numpy=0.08174552>]
ตัวแปรผสม & v1.layers
โค้ดที่มีอยู่มักจะผสมตัวแปร TensorFlow 1.x ระดับล่างกับการดำเนินการกับ v1.layers
ระดับสูงกว่า
ก่อนที่จะแปลง
def model(x, training, scope='model'):
with v1.variable_scope(scope, reuse=v1.AUTO_REUSE):
W = v1.get_variable(
"W", dtype=v1.float32,
initializer=v1.ones(shape=x.shape),
regularizer=lambda x:0.004*tf.reduce_mean(x**2),
trainable=True)
if training:
x = x + W
else:
x = x + W * 0.5
x = v1.layers.conv2d(x, 32, 3, activation=tf.nn.relu)
x = v1.layers.max_pooling2d(x, (2, 2), 1)
x = v1.layers.flatten(x)
return x
train_out = model(train_data, training=True)
test_out = model(test_data, training=False)
หลังจากแปลง
ในการแปลงรหัสนี้ให้ทำตามรูปแบบของการแมปเลเยอร์เป็นเลเยอร์ดังตัวอย่างก่อนหน้านี้
รูปแบบทั่วไปคือ:
- รวบรวมพารามิเตอร์เลเยอร์ใน
__init__
- สร้างตัวแปรในการ
build
- ดำเนินการคำนวณในการ
call
และส่งคืนผลลัพธ์
v1.variable_scope
นั้นเป็นเลเยอร์ของตัวมันเอง ดังนั้นเขียนใหม่เป็น tf.keras.layers.Layer
ตรวจสอบการ สร้างเลเยอร์และโมเดลใหม่ผ่านคู่มือคลาสย่อย สำหรับรายละเอียด
# Create a custom layer for part of the model
class CustomLayer(tf.keras.layers.Layer):
def __init__(self, *args, **kwargs):
super(CustomLayer, self).__init__(*args, **kwargs)
def build(self, input_shape):
self.w = self.add_weight(
shape=input_shape[1:],
dtype=tf.float32,
initializer=tf.keras.initializers.ones(),
regularizer=tf.keras.regularizers.l2(0.02),
trainable=True)
# Call method will sometimes get used in graph mode,
# training will get turned into a tensor
@tf.function
def call(self, inputs, training=None):
if training:
return inputs + self.w
else:
return inputs + self.w * 0.5
custom_layer = CustomLayer()
print(custom_layer([1]).numpy())
print(custom_layer([1], training=True).numpy())
[1.5] [2.]
train_data = tf.ones(shape=(1, 28, 28, 1))
test_data = tf.ones(shape=(1, 28, 28, 1))
# Build the model including the custom layer
model = tf.keras.Sequential([
CustomLayer(input_shape=(28, 28, 1)),
tf.keras.layers.Conv2D(32, 3, activation='relu'),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Flatten(),
])
train_out = model(train_data, training=True)
test_out = model(test_data, training=False)
สิ่งที่ควรทราบ:
โมเดลและเลเยอร์ของ Keras ย่อยจำเป็นต้องทำงานในกราฟ v1 ทั้งสอง (ไม่มีการพึ่งพาการควบคุมอัตโนมัติ) และในโหมดกระตือรือร้น:
- ตัด
call
ในtf.function
เพื่อรับลายเซ็นและการพึ่งพาการควบคุมอัตโนมัติ
- ตัด
อย่าลืมยอมรับข้อโต้แย้ง
training
เพื่อcall
:- บางครั้งก็เป็น
tf.Tensor
- บางครั้งก็เป็นบูลีน Python
- บางครั้งก็เป็น
สร้างตัวแปรโมเดลในตัวสร้างหรือ
Model.build
โดยใช้ `self.add_weight:- ใน
Model.build
คุณสามารถเข้าถึงรูปร่างอินพุตได้ดังนั้นจึงสามารถสร้างน้ำหนักที่มีรูปร่างที่ตรงกันได้ - การใช้
tf.keras.layers.Layer.add_weight
ช่วยให้ Keras ติดตามตัวแปรและการสูญเสียการทำให้เป็นมาตรฐาน
- ใน
อย่าเก็บ
tf.Tensors
ไว้ในวัตถุของคุณ:- อาจถูกสร้างขึ้นใน
tf.function
หรือในบริบทที่กระตือรือร้นและเทนเซอร์เหล่านี้ทำงานแตกต่างกัน - ใช้
tf.Variable
s สำหรับสถานะซึ่งสามารถใช้งานได้จากทั้งสองบริบทเสมอ -
tf.Tensors
ใช้สำหรับค่ากลางเท่านั้น
- อาจถูกสร้างขึ้นใน
หมายเหตุเกี่ยวกับ Slim และ Contrib.layers
โค้ด TensorFlow 1.x รุ่นเก่าจำนวนมากใช้ไลบรารี Slim ซึ่งมาพร้อมกับ TensorFlow 1.x เป็น tf.contrib.layers
ในฐานะที่เป็น contrib
โมดูลนี้ไม่สามารถใช้ได้อีกใน TensorFlow 2.x แม้ใน tf.compat.v1
การแปลงโค้ดโดยใช้ Slim เป็น TensorFlow 2.x มีส่วนเกี่ยวข้องมากกว่าการแปลงที่เก็บที่ใช้ v1.layers
ในความเป็นจริงการแปลงรหัส Slim ของคุณเป็น v1.layers
ก่อนจากนั้นจึงเปลี่ยนเป็น Keras
- ลบ
arg_scopes
อาร์กิวเมนต์ทั้งหมดต้องชัดเจน - หากคุณใช้มันให้แบ่ง
normalizer_fn
และactivation_fn
ออกเป็นเลเยอร์ของตัวเอง - เลเยอร์ Conv ที่แยกออกได้จะจับคู่กับเลเยอร์ Keras ที่แตกต่างกันอย่างน้อยหนึ่งชั้น (เลเยอร์ Keras เชิงลึกชี้และแยกกันได้)
- Slim และ
v1.layers
มีชื่ออาร์กิวเมนต์และค่าเริ่มต้นที่แตกต่างกัน - บางอาร์กมีเกล็ดที่แตกต่างกัน
- หากคุณใช้โมเดลที่ผ่านการฝึกอบรมของ Slim ให้ลองใช้โมเดลสำเร็จรูปของ Keras จาก
tf.keras.applications
หรือ TensorFlow 2.x SavedModels ของ TF Hub ที่ ส่งออกจากโค้ด Slim ดั้งเดิม
เลเยอร์ tf.contrib
บางชั้นอาจไม่ได้ถูกย้ายไปยังแกน TensorFlow แต่ถูกย้ายไปที่ แพ็คเกจ TensorFlow Addons แทน
การฝึกอบรม
มีหลายวิธีในการป้อนข้อมูลไปยังโมเดล tf.keras
พวกเขาจะยอมรับตัวสร้าง Python และอาร์เรย์ Numpy เป็นอินพุต
วิธีที่แนะนำในการฟีดข้อมูลไปยังโมเดลคือการใช้แพ็กเกจ tf.data
ซึ่งมีคอลเล็กชันคลาสประสิทธิภาพสูงสำหรับจัดการข้อมูล
หากคุณยังคงใช้ tf.queue
สิ่งเหล่านี้ได้รับการสนับสนุนเป็นโครงสร้างข้อมูลเท่านั้นไม่ใช่เป็นไปป์ไลน์อินพุต
การใช้ TensorFlow Datasets
แพ็คเกจ TensorFlow Datasets ( tfds
) มียูทิลิตี้สำหรับการโหลดชุดข้อมูลที่กำหนดไว้ล่วงหน้าเป็นวัตถุtf.data.Dataset
สำหรับตัวอย่างนี้คุณสามารถโหลดชุดข้อมูล tfds
โดยใช้ tfds
:
datasets, info = tfds.load(name='mnist', with_info=True, as_supervised=True)
mnist_train, mnist_test = datasets['train'], datasets['test']
Downloading and preparing dataset mnist/3.0.1 (download: 11.06 MiB, generated: 21.00 MiB, total: 32.06 MiB) to /home/kbuilder/tensorflow_datasets/mnist/3.0.1... WARNING:absl:Dataset mnist is hosted on GCS. It will automatically be downloaded to your local data directory. If you'd instead prefer to read directly from our public GCS bucket (recommended if you're running on GCP), you can instead pass `try_gcs=True` to `tfds.load` or set `data_dir=gs://tfds-data/datasets`. Dataset mnist downloaded and prepared to /home/kbuilder/tensorflow_datasets/mnist/3.0.1. Subsequent calls will reuse this data.
จากนั้นเตรียมข้อมูลสำหรับการฝึกอบรม:
- ปรับขนาดแต่ละภาพใหม่
- สลับลำดับของตัวอย่าง
- รวบรวมชุดภาพและป้ายกำกับ
BUFFER_SIZE = 10 # Use a much larger value for real code
BATCH_SIZE = 64
NUM_EPOCHS = 5
def scale(image, label):
image = tf.cast(image, tf.float32)
image /= 255
return image, label
เพื่อให้ตัวอย่างสั้นให้ตัดชุดข้อมูลเพื่อส่งคืน 5 แบทช์เท่านั้น:
train_data = mnist_train.map(scale).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
test_data = mnist_test.map(scale).batch(BATCH_SIZE)
STEPS_PER_EPOCH = 5
train_data = train_data.take(STEPS_PER_EPOCH)
test_data = test_data.take(STEPS_PER_EPOCH)
image_batch, label_batch = next(iter(train_data))
ใช้ Keras training loops
หากคุณไม่ต้องการการควบคุมขั้นตอนการฝึกในระดับต่ำขอแนะนำให้ใช้วิธีการ fit
evaluate
และ predict
ในตัวของ Keras วิธีการเหล่านี้จัดเตรียมอินเทอร์เฟซที่เหมือนกันเพื่อฝึกโมเดลโดยไม่คำนึงถึงการนำไปใช้งาน (ตามลำดับฟังก์ชันหรือคลาสย่อย)
ข้อดีของวิธีการเหล่านี้ ได้แก่ :
- พวกเขายอมรับอาร์เรย์ Numpy ตัวสร้าง Python และ
tf.data.Datasets
- พวกเขาใช้การทำให้เป็นมาตรฐานและการสูญเสียการเปิดใช้งานโดยอัตโนมัติ
- สนับสนุน
tf.distribute
สำหรับการฝึกอบรมหลายอุปกรณ์ - พวกเขาสนับสนุนการโทรตามอำเภอใจเป็นการสูญเสียและตัวชี้วัด
- รองรับการโทรกลับเช่น
tf.keras.callbacks.TensorBoard
และการเรียกกลับที่กำหนดเอง - มีประสิทธิภาพโดยอัตโนมัติโดยใช้กราฟ TensorFlow
นี่คือตัวอย่างการฝึกโมเดลโดยใช้ Dataset
(สำหรับรายละเอียดเกี่ยวกับวิธีการทำงานโปรดดูส่วน บทช่วยสอน )
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(32, 3, activation='relu',
kernel_regularizer=tf.keras.regularizers.l2(0.02),
input_shape=(28, 28, 1)),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Flatten(),
tf.keras.layers.Dropout(0.1),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.Dense(10)
])
# Model is the full model w/o custom layers
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
model.fit(train_data, epochs=NUM_EPOCHS)
loss, acc = model.evaluate(test_data)
print("Loss {}, Accuracy {}".format(loss, acc))
Epoch 1/5 5/5 [==============================] - 1s 9ms/step - loss: 2.0191 - accuracy: 0.3608 Epoch 2/5 5/5 [==============================] - 0s 9ms/step - loss: 0.4736 - accuracy: 0.9059 Epoch 3/5 5/5 [==============================] - 0s 8ms/step - loss: 0.2973 - accuracy: 0.9626 Epoch 4/5 5/5 [==============================] - 0s 9ms/step - loss: 0.2108 - accuracy: 0.9911 Epoch 5/5 5/5 [==============================] - 0s 8ms/step - loss: 0.1791 - accuracy: 0.9874 5/5 [==============================] - 0s 6ms/step - loss: 1.5504 - accuracy: 0.7500 Loss 1.5504140853881836, Accuracy 0.75
เขียนวนซ้ำของคุณเอง
หากขั้นตอนการฝึกของโมเดล Keras เหมาะกับคุณ แต่คุณต้องการการควบคุมเพิ่มเติมนอกขั้นตอนนั้นให้พิจารณาใช้เมธอด tf.keras.Model.train_on_batch
ในการวนซ้ำข้อมูลของคุณเอง
ข้อควรจำ: หลายสิ่งสามารถนำไปใช้เป็น tf.keras.callbacks.Callback
วิธีนี้มีข้อดีหลายประการของวิธีการที่กล่าวถึงในหัวข้อก่อนหน้านี้ แต่ให้ผู้ใช้ควบคุมวงนอกได้
คุณยังสามารถใช้ tf.keras.Model.test_on_batch
หรือ tf.keras.Model.evaluate
เพื่อตรวจสอบประสิทธิภาพระหว่างการฝึก
หากต้องการฝึกโมเดลข้างต้นต่อไป:
# Model is the full model w/o custom layers
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
for epoch in range(NUM_EPOCHS):
# Reset the metric accumulators
model.reset_metrics()
for image_batch, label_batch in train_data:
result = model.train_on_batch(image_batch, label_batch)
metrics_names = model.metrics_names
print("train: ",
"{}: {:.3f}".format(metrics_names[0], result[0]),
"{}: {:.3f}".format(metrics_names[1], result[1]))
for image_batch, label_batch in test_data:
result = model.test_on_batch(image_batch, label_batch,
# Return accumulated metrics
reset_metrics=False)
metrics_names = model.metrics_names
print("\neval: ",
"{}: {:.3f}".format(metrics_names[0], result[0]),
"{}: {:.3f}".format(metrics_names[1], result[1]))
train: loss: 0.138 accuracy: 1.000 train: loss: 0.161 accuracy: 1.000 train: loss: 0.159 accuracy: 0.969 train: loss: 0.241 accuracy: 0.953 train: loss: 0.172 accuracy: 0.969 eval: loss: 1.550 accuracy: 0.800 train: loss: 0.086 accuracy: 1.000 train: loss: 0.094 accuracy: 1.000 train: loss: 0.090 accuracy: 1.000 train: loss: 0.119 accuracy: 0.984 train: loss: 0.099 accuracy: 1.000 eval: loss: 1.558 accuracy: 0.841 train: loss: 0.076 accuracy: 1.000 train: loss: 0.068 accuracy: 1.000 train: loss: 0.061 accuracy: 1.000 train: loss: 0.076 accuracy: 1.000 train: loss: 0.076 accuracy: 1.000 eval: loss: 1.536 accuracy: 0.841 train: loss: 0.059 accuracy: 1.000 train: loss: 0.056 accuracy: 1.000 train: loss: 0.058 accuracy: 1.000 train: loss: 0.054 accuracy: 1.000 train: loss: 0.055 accuracy: 1.000 eval: loss: 1.497 accuracy: 0.863 train: loss: 0.053 accuracy: 1.000 train: loss: 0.049 accuracy: 1.000 train: loss: 0.044 accuracy: 1.000 train: loss: 0.049 accuracy: 1.000 train: loss: 0.045 accuracy: 1.000 eval: loss: 1.463 accuracy: 0.878
ปรับแต่งขั้นตอนการฝึกอบรม
หากคุณต้องการความยืดหยุ่นและการควบคุมที่มากขึ้นคุณสามารถทำได้โดยใช้ห่วงการฝึกของคุณเอง มีสามขั้นตอน:
- ทำซ้ำบนตัวสร้าง Python หรือ
tf.data.Dataset
เพื่อรับชุดตัวอย่าง - ใช้
tf.GradientTape
เพื่อรวบรวมการไล่ระดับสี - ใช้
tf.keras.optimizers
ใดตัวหนึ่งเพื่อใช้การอัปเดตน้ำหนักกับตัวแปรของโมเดล
จำไว้ว่า:
- รวมอาร์กิวเมนต์
training
ไว้ในวิธีการcall
ของเลเยอร์และโมเดลย่อยเสมอ - ตรวจสอบให้แน่ใจว่าได้เรียกโมเดลด้วยอาร์กิวเมนต์
training
ตั้งไว้อย่างถูกต้อง - ตัวแปรของโมเดลอาจไม่มีอยู่จนกว่าโมเดลจะรันบนชุดข้อมูลทั้งนี้ขึ้นอยู่กับการใช้งาน
- คุณต้องจัดการสิ่งต่างๆด้วยตนเองเช่นการสูญเสียการทำให้เป็นมาตรฐานสำหรับโมเดล
สังเกตความเรียบง่ายที่สัมพันธ์กับ v1:
- ไม่จำเป็นต้องเรียกใช้ตัวเริ่มต้นตัวแปร ตัวแปรจะเริ่มต้นในการสร้าง
- ไม่จำเป็นต้องเพิ่มการพึ่งพาการควบคุมด้วยตนเอง แม้ในการทำงานของ
tf.function
ทำหน้าที่ในโหมดกระตือรือร้น
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(32, 3, activation='relu',
kernel_regularizer=tf.keras.regularizers.l2(0.02),
input_shape=(28, 28, 1)),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Flatten(),
tf.keras.layers.Dropout(0.1),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.Dense(10)
])
optimizer = tf.keras.optimizers.Adam(0.001)
loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
@tf.function
def train_step(inputs, labels):
with tf.GradientTape() as tape:
predictions = model(inputs, training=True)
regularization_loss=tf.math.add_n(model.losses)
pred_loss=loss_fn(labels, predictions)
total_loss=pred_loss + regularization_loss
gradients = tape.gradient(total_loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
for epoch in range(NUM_EPOCHS):
for inputs, labels in train_data:
train_step(inputs, labels)
print("Finished epoch", epoch)
Finished epoch 0 Finished epoch 1 Finished epoch 2 Finished epoch 3 Finished epoch 4
เมตริกและการสูญเสียรูปแบบใหม่
ใน TensorFlow 2.x เมตริกและการสูญเสียเป็นวัตถุ สิ่งเหล่านี้ทำงานได้ทั้งอย่างกระตือรือร้นและใน tf.function
s
ออบเจ็กต์การสูญเสียสามารถเรียกใช้ได้และคาดว่า (y_true, y_pred) เป็นอาร์กิวเมนต์:
cce = tf.keras.losses.CategoricalCrossentropy(from_logits=True)
cce([[1, 0]], [[-1.0,3.0]]).numpy()
4.01815
ออบเจ็กต์เมตริกมีวิธีการดังต่อไปนี้:
-
Metric.update_state()
: เพิ่มข้อสังเกตใหม่ -
Metric.result()
: รับผลลัพธ์ปัจจุบันของเมตริกโดยให้ค่าที่สังเกตได้ -
Metric.reset_states()
: ล้างการสังเกตทั้งหมด
วัตถุนั้นสามารถเรียกใช้ได้ การโทรจะอัปเดตสถานะด้วยการสังเกตใหม่เช่นเดียวกับ update_state
และส่งกลับผลลัพธ์ใหม่ของเมตริก
คุณไม่จำเป็นต้องเริ่มต้นตัวแปรของเมตริกด้วยตนเองและเนื่องจาก TensorFlow 2.x มีการพึ่งพาการควบคุมอัตโนมัติคุณจึงไม่จำเป็นต้องกังวลเกี่ยวกับตัวแปรเหล่านี้
โค้ดด้านล่างใช้เมตริกเพื่อติดตามการสูญเสียค่าเฉลี่ยที่สังเกตได้ภายในลูปการฝึกอบรมที่กำหนดเอง
# Create the metrics
loss_metric = tf.keras.metrics.Mean(name='train_loss')
accuracy_metric = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy')
@tf.function
def train_step(inputs, labels):
with tf.GradientTape() as tape:
predictions = model(inputs, training=True)
regularization_loss=tf.math.add_n(model.losses)
pred_loss=loss_fn(labels, predictions)
total_loss=pred_loss + regularization_loss
gradients = tape.gradient(total_loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
# Update the metrics
loss_metric.update_state(total_loss)
accuracy_metric.update_state(labels, predictions)
for epoch in range(NUM_EPOCHS):
# Reset the metrics
loss_metric.reset_states()
accuracy_metric.reset_states()
for inputs, labels in train_data:
train_step(inputs, labels)
# Get the metric results
mean_loss=loss_metric.result()
mean_accuracy = accuracy_metric.result()
print('Epoch: ', epoch)
print(' loss: {:.3f}'.format(mean_loss))
print(' accuracy: {:.3f}'.format(mean_accuracy))
Epoch: 0 loss: 0.139 accuracy: 0.997 Epoch: 1 loss: 0.116 accuracy: 1.000 Epoch: 2 loss: 0.105 accuracy: 0.997 Epoch: 3 loss: 0.089 accuracy: 1.000 Epoch: 4 loss: 0.078 accuracy: 1.000
ชื่อเมตริก Keras
ใน TensorFlow 2.x โมเดล Keras มีความสอดคล้องกันมากขึ้นเกี่ยวกับการจัดการชื่อเมตริก
ตอนนี้เมื่อคุณส่งสตริงในรายการเมตริกสตริง ที่แน่นอน นั้นจะถูกใช้เป็น name
ของเมตริก ชื่อเหล่านี้สามารถมองเห็นได้ในออบเจ็กต์ประวัติที่ส่งคืนโดย model.fit
และในบันทึกถูกส่งไปยัง keras.callbacks
ถูกตั้งค่าเป็นสตริงที่คุณส่งผ่านในรายการเมตริก
model.compile(
optimizer = tf.keras.optimizers.Adam(0.001),
loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics = ['acc', 'accuracy', tf.keras.metrics.SparseCategoricalAccuracy(name="my_accuracy")])
history = model.fit(train_data)
5/5 [==============================] - 1s 8ms/step - loss: 0.0901 - acc: 0.9923 - accuracy: 0.9923 - my_accuracy: 0.9923
history.history.keys()
dict_keys(['loss', 'acc', 'accuracy', 'my_accuracy'])
สิ่งนี้แตกต่างจากเวอร์ชันก่อนหน้าตรงที่การส่ง metrics=["accuracy"]
จะทำให้เกิดคำ dict_keys(['loss', 'acc'])
เครื่องมือเพิ่มประสิทธิภาพ Keras
เครื่องมือเพิ่มประสิทธิภาพใน v1.train
เช่น v1.train.AdamOptimizer
และ v1.train.GradientDescentOptimizer
มีค่าเทียบเท่าใน tf.keras.optimizers
แปลง v1.train
เป็น keras.optimizers
สิ่งที่ควรคำนึงถึงเมื่อแปลงเครื่องมือเพิ่มประสิทธิภาพของคุณมีดังนี้
- การอัปเกรดเครื่องมือเพิ่มประสิทธิภาพของคุณ อาจทำให้ด่านเก่าเข้ากันไม่ ได้
- ตอนนี้ epsilons ทั้งหมดมีค่าเริ่มต้นเป็น
1e-7
แทนที่จะเป็น1e-8
(ซึ่งน้อยมากในกรณีการใช้งานส่วนใหญ่) -
v1.train.GradientDescentOptimizer
สามารถแทนที่ได้โดยตรงโดยtf.keras.optimizers.SGD
-
v1.train.MomentumOptimizer
สามารถแทนที่ได้โดยตรงโดยเครื่องมือเพิ่มประสิทธิภาพSGD
โดยใช้อาร์กิวเมนต์โมเมนตัม:tf.keras.optimizers.SGD(..., momentum=...)
-
v1.train.AdamOptimizer
สามารถแปลงเป็นtf.keras.optimizers.Adam
อาร์กิวเมนต์beta1
และbeta2
ถูกเปลี่ยนชื่อเป็นbeta_1
และbeta_2
-
v1.train.RMSPropOptimizer
สามารถแปลงเป็นtf.keras.optimizers.RMSprop
อาร์กิวเมนต์การdecay
ถูกเปลี่ยนชื่อเป็นrho
-
v1.train.AdadeltaOptimizer
สามารถแปลงโดยตรงเป็นtf.keras.optimizers.Adadelta
-
tf.train.AdagradOptimizer
สามารถแปลงโดยตรงเป็นtf.keras.optimizers.Adagrad
-
tf.train.FtrlOptimizer
สามารถแปลงโดยตรงเป็นtf.keras.optimizers.Ftrl
accum_name
และlinear_name
ข้อโต้แย้งได้ถูกลบออก -
tf.contrib.AdamaxOptimizer
และtf.contrib.NadamOptimizer
สามารถแปลงโดยตรงเป็นtf.keras.optimizers.Adamax
และtf.keras.optimizers.Nadam
ตามลำดับ อาร์กิวเมนต์beta1
และbeta2
ถูกเปลี่ยนชื่อเป็นbeta_1
และbeta_2
ค่าเริ่มต้นใหม่สำหรับ tf.keras.optimizers
ไม่มีการเปลี่ยนแปลงสำหรับ optimizers.SGD
, optimizers.Adam
มหรือ optimizers.RMSprop
อัตราการเรียนรู้เริ่มต้นต่อไปนี้มีการเปลี่ยนแปลง:
-
optimizers.Adagrad
จาก 0.01 ถึง 0.001 -
optimizers.Adadelta
จาก 1.0 ถึง 0.001 -
optimizers.Adamax
Amax จาก 0.002 ถึง 0.001 -
optimizers.Nadam
Nadam จาก 0.002 ถึง 0.001
TensorBoard
TensorFlow 2.x มีการเปลี่ยนแปลงที่สำคัญกับ tf.summary
API ที่ใช้ในการเขียนข้อมูลสรุปสำหรับการแสดงภาพใน TensorBoard สำหรับคำแนะนำทั่วไปเกี่ยวกับ tf.summary
ใหม่มี บทช่วยสอนมากมาย ที่ใช้ TensorFlow 2.x API ซึ่งรวมถึง คู่มือการโยกย้าย TensorBoard TensorFlow 2.x
กำลังบันทึกและโหลด
ความเข้ากันได้ของจุดตรวจ
TensorFlow 2.x ใช้ จุดตรวจตามวัตถุ
ด่านตามชื่อแบบเก่ายังโหลดได้ถ้าคุณระวัง ขั้นตอนการแปลงรหัสอาจส่งผลให้เกิดการเปลี่ยนแปลงชื่อตัวแปร แต่มีวิธีแก้ปัญหาชั่วคราว
วิธีที่ง่ายที่สุดในการจัดเรียงชื่อของโมเดลใหม่ด้วยชื่อในจุดตรวจ:
- ตัวแปรยังคงมีอาร์กิวเมนต์
name
คุณสามารถตั้งค่าได้ - โมเดล Keras ยังใช้อาร์กิวเมนต์
name
ซึ่งตั้งเป็นคำนำหน้าสำหรับตัวแปร - ฟังก์ชัน
v1.name_scope
สามารถใช้เพื่อตั้งค่าคำนำหน้าชื่อตัวแปร ซึ่งแตกต่างจากtf.variable_scope
มาก มีผลกับชื่อเท่านั้นและไม่ติดตามตัวแปรและนำมาใช้ซ้ำ
หากไม่ได้ผลสำหรับกรณีการใช้งานของคุณให้ลองใช้ฟังก์ชัน v1.train.init_from_checkpoint
ใช้อาร์กิวเมนต์ assignment_map
ซึ่งระบุการแม็ปจากชื่อเก่าเป็นชื่อใหม่
ที่ เก็บ TensorFlow Estimator มี เครื่องมือการแปลง เพื่ออัพเกรดจุดตรวจสำหรับตัวประมาณค่าล่วงหน้าจาก TensorFlow 1.x เป็น 2.0 อาจใช้เป็นตัวอย่างวิธีการสร้างเครื่องมือสำหรับกรณีการใช้งานที่คล้ายกัน
ความเข้ากันได้ของโมเดลที่บันทึกไว้
ไม่มีข้อกังวลเกี่ยวกับความเข้ากันได้ที่สำคัญสำหรับรุ่นที่บันทึกไว้
- TensorFlow 1.x saved_models ทำงานใน TensorFlow 2.x.
- TensorFlow 2.x saved_models ทำงานใน TensorFlow 1.x หากรองรับการดำเนินการทั้งหมด
Graph.pb หรือ Graph.pbtxt
ไม่มีวิธีที่ตรงไปตรงมาในการอัปเกรดไฟล์ Graph.pb
ดิบเป็น TensorFlow 2.x ทางออกที่ดีที่สุดของคุณคืออัปเกรดโค้ดที่สร้างไฟล์
แต่ถ้าคุณมี "กราฟแช่แข็ง" (ก tf.Graph
ที่ตัวแปรที่ได้รับกลายเป็นค่าคงที่) จากนั้นก็เป็นไปได้ในการแปลงนี้ให้ concrete_function
ใช้ v1.wrap_function
:
def wrap_frozen_graph(graph_def, inputs, outputs):
def _imports_graph_def():
tf.compat.v1.import_graph_def(graph_def, name="")
wrapped_import = tf.compat.v1.wrap_function(_imports_graph_def, [])
import_graph = wrapped_import.graph
return wrapped_import.prune(
tf.nest.map_structure(import_graph.as_graph_element, inputs),
tf.nest.map_structure(import_graph.as_graph_element, outputs))
ตัวอย่างเช่นนี่คือกราฟแช่แข็งสำหรับ Inception v1 จากปี 2016:
path = tf.keras.utils.get_file(
'inception_v1_2016_08_28_frozen.pb',
'http://storage.googleapis.com/download.tensorflow.org/models/inception_v1_2016_08_28_frozen.pb.tar.gz',
untar=True)
Downloading data from http://storage.googleapis.com/download.tensorflow.org/models/inception_v1_2016_08_28_frozen.pb.tar.gz 24698880/24695710 [==============================] - 1s 0us/step
โหลด tf.GraphDef
:
graph_def = tf.compat.v1.GraphDef()
loaded = graph_def.ParseFromString(open(path,'rb').read())
ห่อเป็น concrete_function
:
inception_func = wrap_frozen_graph(
graph_def, inputs='input:0',
outputs='InceptionV1/InceptionV1/Mixed_3b/Branch_1/Conv2d_0a_1x1/Relu:0')
ส่งค่าเทนเซอร์เป็นอินพุต:
input_img = tf.ones([1,224,224,3], dtype=tf.float32)
inception_func(input_img).shape
TensorShape([1, 28, 28, 96])
ผู้ประมาณ
การฝึกอบรมกับผู้ประมาณ
เครื่องมือประมาณการได้รับการสนับสนุนใน TensorFlow 2.x
เมื่อคุณใช้ตัวประมาณค่าคุณสามารถใช้ input_fn
, tf.estimator.TrainSpec
และ tf.estimator.EvalSpec
จาก TensorFlow 1.x.
นี่คือตัวอย่างการใช้ input_fn
กับรถไฟและประเมินข้อกำหนด
การสร้างข้อมูลจำเพาะ input_fn และฝึกอบรม / ประเมิน
# Define the estimator's input_fn
def input_fn():
datasets, info = tfds.load(name='mnist', with_info=True, as_supervised=True)
mnist_train, mnist_test = datasets['train'], datasets['test']
BUFFER_SIZE = 10000
BATCH_SIZE = 64
def scale(image, label):
image = tf.cast(image, tf.float32)
image /= 255
return image, label[..., tf.newaxis]
train_data = mnist_train.map(scale).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
return train_data.repeat()
# Define train and eval specs
train_spec = tf.estimator.TrainSpec(input_fn=input_fn,
max_steps=STEPS_PER_EPOCH * NUM_EPOCHS)
eval_spec = tf.estimator.EvalSpec(input_fn=input_fn,
steps=STEPS_PER_EPOCH)
ใช้นิยามโมเดล Keras
มีความแตกต่างบางประการในการสร้างตัวประมาณของคุณใน TensorFlow 2.x
ขอแนะนำให้คุณกำหนดโมเดลของคุณโดยใช้ Keras จากนั้นใช้ยูทิลิตี้ tf.keras.estimator.model_to_estimator
เพื่อเปลี่ยนโมเดลของคุณให้เป็นตัวประมาณค่า โค้ดด้านล่างแสดงวิธีใช้ยูทิลิตี้นี้เมื่อสร้างและฝึกอบรมตัวประมาณค่า
def make_model():
return tf.keras.Sequential([
tf.keras.layers.Conv2D(32, 3, activation='relu',
kernel_regularizer=tf.keras.regularizers.l2(0.02),
input_shape=(28, 28, 1)),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Flatten(),
tf.keras.layers.Dropout(0.1),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.Dense(10)
])
model = make_model()
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
estimator = tf.keras.estimator.model_to_estimator(
keras_model = model
)
tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)
INFO:tensorflow:Using default config. INFO:tensorflow:Using default config. WARNING:tensorflow:Using temporary folder as model directory: /tmp/tmp0erq3im2 WARNING:tensorflow:Using temporary folder as model directory: /tmp/tmp0erq3im2 INFO:tensorflow:Using the Keras model provided. INFO:tensorflow:Using the Keras model provided. /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/keras/backend.py:434: UserWarning: `tf.keras.backend.set_learning_phase` is deprecated and will be removed after 2020-10-11. To update it, simply pass a True/False value to the `training` argument of the `__call__` method of your layer or model. warnings.warn('`tf.keras.backend.set_learning_phase` is deprecated and ' INFO:tensorflow:Using config: {'_model_dir': '/tmp/tmp0erq3im2', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': None, '_save_checkpoints_secs': 600, '_session_config': allow_soft_placement: true graph_options { rewrite_options { meta_optimizer_iterations: ONE } } , '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': 100, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_checkpoint_save_graph_def': True, '_service': None, '_cluster_spec': ClusterSpec({}), '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1} INFO:tensorflow:Using config: {'_model_dir': '/tmp/tmp0erq3im2', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': None, '_save_checkpoints_secs': 600, '_session_config': allow_soft_placement: true graph_options { rewrite_options { meta_optimizer_iterations: ONE } } , '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': 100, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_checkpoint_save_graph_def': True, '_service': None, '_cluster_spec': ClusterSpec({}), '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1} INFO:tensorflow:Not using Distribute Coordinator. INFO:tensorflow:Not using Distribute Coordinator. INFO:tensorflow:Running training and evaluation locally (non-distributed). INFO:tensorflow:Running training and evaluation locally (non-distributed). INFO:tensorflow:Start train and evaluate loop. The evaluate will happen after every checkpoint. Checkpoint frequency is determined based on RunConfig arguments: save_checkpoints_steps None or save_checkpoints_secs 600. INFO:tensorflow:Start train and evaluate loop. The evaluate will happen after every checkpoint. Checkpoint frequency is determined based on RunConfig arguments: save_checkpoints_steps None or save_checkpoints_secs 600. WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/training/training_util.py:236: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version. Instructions for updating: Use Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts. WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/training/training_util.py:236: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version. Instructions for updating: Use Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts. INFO:tensorflow:Calling model_fn. INFO:tensorflow:Calling model_fn. INFO:tensorflow:Done calling model_fn. INFO:tensorflow:Done calling model_fn. INFO:tensorflow:Warm-starting with WarmStartSettings: WarmStartSettings(ckpt_to_initialize_from='/tmp/tmp0erq3im2/keras/keras_model.ckpt', vars_to_warm_start='.*', var_name_to_vocab_info={}, var_name_to_prev_var_name={}) INFO:tensorflow:Warm-starting with WarmStartSettings: WarmStartSettings(ckpt_to_initialize_from='/tmp/tmp0erq3im2/keras/keras_model.ckpt', vars_to_warm_start='.*', var_name_to_vocab_info={}, var_name_to_prev_var_name={}) INFO:tensorflow:Warm-starting from: /tmp/tmp0erq3im2/keras/keras_model.ckpt INFO:tensorflow:Warm-starting from: /tmp/tmp0erq3im2/keras/keras_model.ckpt INFO:tensorflow:Warm-starting variables only in TRAINABLE_VARIABLES. INFO:tensorflow:Warm-starting variables only in TRAINABLE_VARIABLES. INFO:tensorflow:Warm-started 8 variables. INFO:tensorflow:Warm-started 8 variables. INFO:tensorflow:Create CheckpointSaverHook. INFO:tensorflow:Create CheckpointSaverHook. INFO:tensorflow:Graph was finalized. INFO:tensorflow:Graph was finalized. INFO:tensorflow:Running local_init_op. INFO:tensorflow:Running local_init_op. INFO:tensorflow:Done running local_init_op. INFO:tensorflow:Done running local_init_op. INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 0... INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 0... INFO:tensorflow:Saving checkpoints for 0 into /tmp/tmp0erq3im2/model.ckpt. INFO:tensorflow:Saving checkpoints for 0 into /tmp/tmp0erq3im2/model.ckpt. INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 0... INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 0... INFO:tensorflow:loss = 2.4717796, step = 0 INFO:tensorflow:loss = 2.4717796, step = 0 INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 25... INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 25... INFO:tensorflow:Saving checkpoints for 25 into /tmp/tmp0erq3im2/model.ckpt. INFO:tensorflow:Saving checkpoints for 25 into /tmp/tmp0erq3im2/model.ckpt. INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 25... INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 25... INFO:tensorflow:Calling model_fn. INFO:tensorflow:Calling model_fn. INFO:tensorflow:Done calling model_fn. /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py:2325: UserWarning: `Model.state_updates` will be removed in a future version. This property should not be used in TensorFlow 2.0, as `updates` are applied automatically. warnings.warn('`Model.state_updates` will be removed in a future version. ' INFO:tensorflow:Done calling model_fn. INFO:tensorflow:Starting evaluation at 2021-01-06T02:31:17Z INFO:tensorflow:Starting evaluation at 2021-01-06T02:31:17Z INFO:tensorflow:Graph was finalized. INFO:tensorflow:Graph was finalized. INFO:tensorflow:Restoring parameters from /tmp/tmp0erq3im2/model.ckpt-25 INFO:tensorflow:Restoring parameters from /tmp/tmp0erq3im2/model.ckpt-25 INFO:tensorflow:Running local_init_op. INFO:tensorflow:Running local_init_op. INFO:tensorflow:Done running local_init_op. INFO:tensorflow:Done running local_init_op. INFO:tensorflow:Evaluation [1/5] INFO:tensorflow:Evaluation [1/5] INFO:tensorflow:Evaluation [2/5] INFO:tensorflow:Evaluation [2/5] INFO:tensorflow:Evaluation [3/5] INFO:tensorflow:Evaluation [3/5] INFO:tensorflow:Evaluation [4/5] INFO:tensorflow:Evaluation [4/5] INFO:tensorflow:Evaluation [5/5] INFO:tensorflow:Evaluation [5/5] INFO:tensorflow:Inference Time : 0.86556s INFO:tensorflow:Inference Time : 0.86556s INFO:tensorflow:Finished evaluation at 2021-01-06-02:31:18 INFO:tensorflow:Finished evaluation at 2021-01-06-02:31:18 INFO:tensorflow:Saving dict for global step 25: accuracy = 0.6, global_step = 25, loss = 1.6160676 INFO:tensorflow:Saving dict for global step 25: accuracy = 0.6, global_step = 25, loss = 1.6160676 INFO:tensorflow:Saving 'checkpoint_path' summary for global step 25: /tmp/tmp0erq3im2/model.ckpt-25 INFO:tensorflow:Saving 'checkpoint_path' summary for global step 25: /tmp/tmp0erq3im2/model.ckpt-25 INFO:tensorflow:Loss for final step: 0.37597787. INFO:tensorflow:Loss for final step: 0.37597787. ({'accuracy': 0.6, 'loss': 1.6160676, 'global_step': 25}, [])
ใช้ model_fn
กำหนดเอง
หากคุณมี model_fn
ตัวประมาณแบบกำหนดเองที่คุณจำเป็นต้องดูแลคุณสามารถแปลง model_fn
ของคุณให้ใช้โมเดล Keras ได้
อย่างไรก็ตามด้วยเหตุผลด้านความเข้ากันได้ model_fn
กำหนดเองจะยังคงทำงานในโหมดกราฟสไตล์ 1.x ซึ่งหมายความว่าไม่มีการดำเนินการอย่างกระตือรือร้นและไม่มีการพึ่งพาการควบคุมอัตโนมัติ
model_fn ที่กำหนดเองโดยมีการเปลี่ยนแปลงน้อยที่สุด
เพื่อให้ model_fn
กำหนดเองของคุณทำงานใน TensorFlow 2.x หากคุณต้องการเปลี่ยนแปลงโค้ดที่มีอยู่เพียงเล็กน้อยสามารถใช้สัญลักษณ์ tf.compat.v1
เช่น optimizers
และ metrics
ได้
โดยใช้แบบจำลองใน Keras เอง model_fn
จะคล้ายกับการใช้มันในวงการฝึกอบรมที่กำหนดเอง:
- กำหนดขั้นตอน
training
เหมาะสมตามอาร์กิวเมนต์ของmode
- ส่งผ่าน
trainable_variables
ของโมเดลไปยังเครื่องมือเพิ่มประสิทธิภาพอย่างชัดเจน
แต่มีความแตกต่างที่สำคัญเมื่อเทียบกับ ลูปที่กำหนดเอง :
- แทนที่จะใช้
Model.losses
ให้แยกการสูญเสียโดยใช้Model.get_losses_for
- แตกการอัปเดตของโมเดลโดยใช้
Model.get_updates_for
โค้ดต่อไปนี้สร้างตัวประมาณค่าจาก model_fn
กำหนดเองซึ่งแสดงให้เห็นถึงข้อกังวลเหล่านี้ทั้งหมด
def my_model_fn(features, labels, mode):
model = make_model()
optimizer = tf.compat.v1.train.AdamOptimizer()
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
training = (mode == tf.estimator.ModeKeys.TRAIN)
predictions = model(features, training=training)
if mode == tf.estimator.ModeKeys.PREDICT:
return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)
reg_losses = model.get_losses_for(None) + model.get_losses_for(features)
total_loss=loss_fn(labels, predictions) + tf.math.add_n(reg_losses)
accuracy = tf.compat.v1.metrics.accuracy(labels=labels,
predictions=tf.math.argmax(predictions, axis=1),
name='acc_op')
update_ops = model.get_updates_for(None) + model.get_updates_for(features)
minimize_op = optimizer.minimize(
total_loss,
var_list=model.trainable_variables,
global_step=tf.compat.v1.train.get_or_create_global_step())
train_op = tf.group(minimize_op, update_ops)
return tf.estimator.EstimatorSpec(
mode=mode,
predictions=predictions,
loss=total_loss,
train_op=train_op, eval_metric_ops={'accuracy': accuracy})
# Create the Estimator & Train
estimator = tf.estimator.Estimator(model_fn=my_model_fn)
tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)
INFO:tensorflow:Using default config. INFO:tensorflow:Using default config. WARNING:tensorflow:Using temporary folder as model directory: /tmp/tmpifj8mysl WARNING:tensorflow:Using temporary folder as model directory: /tmp/tmpifj8mysl INFO:tensorflow:Using config: {'_model_dir': '/tmp/tmpifj8mysl', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': None, '_save_checkpoints_secs': 600, '_session_config': allow_soft_placement: true graph_options { rewrite_options { meta_optimizer_iterations: ONE } } , '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': 100, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_checkpoint_save_graph_def': True, '_service': None, '_cluster_spec': ClusterSpec({}), '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1} INFO:tensorflow:Using config: {'_model_dir': '/tmp/tmpifj8mysl', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': None, '_save_checkpoints_secs': 600, '_session_config': allow_soft_placement: true graph_options { rewrite_options { meta_optimizer_iterations: ONE } } , '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': 100, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_checkpoint_save_graph_def': True, '_service': None, '_cluster_spec': ClusterSpec({}), '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1} INFO:tensorflow:Not using Distribute Coordinator. INFO:tensorflow:Not using Distribute Coordinator. INFO:tensorflow:Running training and evaluation locally (non-distributed). INFO:tensorflow:Running training and evaluation locally (non-distributed). INFO:tensorflow:Start train and evaluate loop. The evaluate will happen after every checkpoint. Checkpoint frequency is determined based on RunConfig arguments: save_checkpoints_steps None or save_checkpoints_secs 600. INFO:tensorflow:Start train and evaluate loop. The evaluate will happen after every checkpoint. Checkpoint frequency is determined based on RunConfig arguments: save_checkpoints_steps None or save_checkpoints_secs 600. INFO:tensorflow:Calling model_fn. INFO:tensorflow:Calling model_fn. INFO:tensorflow:Done calling model_fn. INFO:tensorflow:Done calling model_fn. INFO:tensorflow:Create CheckpointSaverHook. INFO:tensorflow:Create CheckpointSaverHook. INFO:tensorflow:Graph was finalized. INFO:tensorflow:Graph was finalized. INFO:tensorflow:Running local_init_op. INFO:tensorflow:Running local_init_op. INFO:tensorflow:Done running local_init_op. INFO:tensorflow:Done running local_init_op. INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 0... INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 0... INFO:tensorflow:Saving checkpoints for 0 into /tmp/tmpifj8mysl/model.ckpt. INFO:tensorflow:Saving checkpoints for 0 into /tmp/tmpifj8mysl/model.ckpt. INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 0... INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 0... INFO:tensorflow:loss = 3.0136237, step = 0 INFO:tensorflow:loss = 3.0136237, step = 0 INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 25... INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 25... INFO:tensorflow:Saving checkpoints for 25 into /tmp/tmpifj8mysl/model.ckpt. INFO:tensorflow:Saving checkpoints for 25 into /tmp/tmpifj8mysl/model.ckpt. INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 25... INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 25... INFO:tensorflow:Calling model_fn. INFO:tensorflow:Calling model_fn. INFO:tensorflow:Done calling model_fn. INFO:tensorflow:Done calling model_fn. INFO:tensorflow:Starting evaluation at 2021-01-06T02:31:20Z INFO:tensorflow:Starting evaluation at 2021-01-06T02:31:20Z INFO:tensorflow:Graph was finalized. INFO:tensorflow:Graph was finalized. INFO:tensorflow:Restoring parameters from /tmp/tmpifj8mysl/model.ckpt-25 INFO:tensorflow:Restoring parameters from /tmp/tmpifj8mysl/model.ckpt-25 INFO:tensorflow:Running local_init_op. INFO:tensorflow:Running local_init_op. INFO:tensorflow:Done running local_init_op. INFO:tensorflow:Done running local_init_op. INFO:tensorflow:Evaluation [1/5] INFO:tensorflow:Evaluation [1/5] INFO:tensorflow:Evaluation [2/5] INFO:tensorflow:Evaluation [2/5] INFO:tensorflow:Evaluation [3/5] INFO:tensorflow:Evaluation [3/5] INFO:tensorflow:Evaluation [4/5] INFO:tensorflow:Evaluation [4/5] INFO:tensorflow:Evaluation [5/5] INFO:tensorflow:Evaluation [5/5] INFO:tensorflow:Inference Time : 0.97406s INFO:tensorflow:Inference Time : 0.97406s INFO:tensorflow:Finished evaluation at 2021-01-06-02:31:21 INFO:tensorflow:Finished evaluation at 2021-01-06-02:31:21 INFO:tensorflow:Saving dict for global step 25: accuracy = 0.59375, global_step = 25, loss = 1.6248872 INFO:tensorflow:Saving dict for global step 25: accuracy = 0.59375, global_step = 25, loss = 1.6248872 INFO:tensorflow:Saving 'checkpoint_path' summary for global step 25: /tmp/tmpifj8mysl/model.ckpt-25 INFO:tensorflow:Saving 'checkpoint_path' summary for global step 25: /tmp/tmpifj8mysl/model.ckpt-25 INFO:tensorflow:Loss for final step: 0.35726172. INFO:tensorflow:Loss for final step: 0.35726172. ({'accuracy': 0.59375, 'loss': 1.6248872, 'global_step': 25}, [])
model_fn
แบบกำหนดเองพร้อมสัญลักษณ์ TensorFlow 2.x
หากคุณต้องการกำจัดสัญลักษณ์ TensorFlow 1.x ทั้งหมดและอัปเกรด model_fn
แบบกำหนดเองของคุณเป็น TensorFlow 2.x คุณต้องอัปเดตเครื่องมือเพิ่มประสิทธิภาพและเมตริกเป็น tf.keras.optimizers
และ tf.keras.metrics
ใน model_fn
กำหนดเองนอกเหนือจากการ เปลี่ยนแปลง ข้างต้นจำเป็นต้องทำการอัพเกรดเพิ่มเติม:
- ใช้
tf.keras.optimizers
แทนv1.train.Optimizer
- อย่างชัดเจนผ่านรูปแบบของ
trainable_variables
ไปtf.keras.optimizers
- ในการคำนวณ
train_op/minimize_op
- ใช้
Optimizer.get_updates
หากการสูญเสียเป็นTensor
การสูญเสียสเกลาร์ (ไม่สามารถเรียกได้) องค์ประกอบแรกในรายการที่ส่งคืนคือtrain_op/minimize_op
ต้องการ - หากการสูญเสียเป็นสิ่งที่เรียกได้ (เช่นฟังก์ชัน) ให้ใช้
Optimizer.minimize
เพื่อรับtrain_op/minimize_op
- ใช้
- ใช้
tf.keras.metrics
แทนtf.compat.v1.metrics
สำหรับการประเมิน
สำหรับตัวอย่าง my_model_fn
ข้างต้นรหัสที่โอนย้ายด้วยสัญลักษณ์ TensorFlow 2.x จะแสดงเป็น:
def my_model_fn(features, labels, mode):
model = make_model()
training = (mode == tf.estimator.ModeKeys.TRAIN)
loss_obj = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
predictions = model(features, training=training)
# Get both the unconditional losses (the None part)
# and the input-conditional losses (the features part).
reg_losses = model.get_losses_for(None) + model.get_losses_for(features)
total_loss=loss_obj(labels, predictions) + tf.math.add_n(reg_losses)
# Upgrade to tf.keras.metrics.
accuracy_obj = tf.keras.metrics.Accuracy(name='acc_obj')
accuracy = accuracy_obj.update_state(
y_true=labels, y_pred=tf.math.argmax(predictions, axis=1))
train_op = None
if training:
# Upgrade to tf.keras.optimizers.
optimizer = tf.keras.optimizers.Adam()
# Manually assign tf.compat.v1.global_step variable to optimizer.iterations
# to make tf.compat.v1.train.global_step increased correctly.
# This assignment is a must for any `tf.train.SessionRunHook` specified in
# estimator, as SessionRunHooks rely on global step.
optimizer.iterations = tf.compat.v1.train.get_or_create_global_step()
# Get both the unconditional updates (the None part)
# and the input-conditional updates (the features part).
update_ops = model.get_updates_for(None) + model.get_updates_for(features)
# Compute the minimize_op.
minimize_op = optimizer.get_updates(
total_loss,
model.trainable_variables)[0]
train_op = tf.group(minimize_op, *update_ops)
return tf.estimator.EstimatorSpec(
mode=mode,
predictions=predictions,
loss=total_loss,
train_op=train_op,
eval_metric_ops={'Accuracy': accuracy_obj})
# Create the Estimator and train.
estimator = tf.estimator.Estimator(model_fn=my_model_fn)
tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)
INFO:tensorflow:Using default config. INFO:tensorflow:Using default config. WARNING:tensorflow:Using temporary folder as model directory: /tmp/tmpc93qfnv6 WARNING:tensorflow:Using temporary folder as model directory: /tmp/tmpc93qfnv6 INFO:tensorflow:Using config: {'_model_dir': '/tmp/tmpc93qfnv6', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': None, '_save_checkpoints_secs': 600, '_session_config': allow_soft_placement: true graph_options { rewrite_options { meta_optimizer_iterations: ONE } } , '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': 100, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_checkpoint_save_graph_def': True, '_service': None, '_cluster_spec': ClusterSpec({}), '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1} INFO:tensorflow:Using config: {'_model_dir': '/tmp/tmpc93qfnv6', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': None, '_save_checkpoints_secs': 600, '_session_config': allow_soft_placement: true graph_options { rewrite_options { meta_optimizer_iterations: ONE } } , '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': 100, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_checkpoint_save_graph_def': True, '_service': None, '_cluster_spec': ClusterSpec({}), '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1} INFO:tensorflow:Not using Distribute Coordinator. INFO:tensorflow:Not using Distribute Coordinator. INFO:tensorflow:Running training and evaluation locally (non-distributed). INFO:tensorflow:Running training and evaluation locally (non-distributed). INFO:tensorflow:Start train and evaluate loop. The evaluate will happen after every checkpoint. Checkpoint frequency is determined based on RunConfig arguments: save_checkpoints_steps None or save_checkpoints_secs 600. INFO:tensorflow:Start train and evaluate loop. The evaluate will happen after every checkpoint. Checkpoint frequency is determined based on RunConfig arguments: save_checkpoints_steps None or save_checkpoints_secs 600. INFO:tensorflow:Calling model_fn. INFO:tensorflow:Calling model_fn. INFO:tensorflow:Done calling model_fn. INFO:tensorflow:Done calling model_fn. INFO:tensorflow:Create CheckpointSaverHook. INFO:tensorflow:Create CheckpointSaverHook. INFO:tensorflow:Graph was finalized. INFO:tensorflow:Graph was finalized. INFO:tensorflow:Running local_init_op. INFO:tensorflow:Running local_init_op. INFO:tensorflow:Done running local_init_op. INFO:tensorflow:Done running local_init_op. INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 0... INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 0... INFO:tensorflow:Saving checkpoints for 0 into /tmp/tmpc93qfnv6/model.ckpt. INFO:tensorflow:Saving checkpoints for 0 into /tmp/tmpc93qfnv6/model.ckpt. INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 0... INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 0... INFO:tensorflow:loss = 2.5293791, step = 0 INFO:tensorflow:loss = 2.5293791, step = 0 INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 25... INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 25... INFO:tensorflow:Saving checkpoints for 25 into /tmp/tmpc93qfnv6/model.ckpt. INFO:tensorflow:Saving checkpoints for 25 into /tmp/tmpc93qfnv6/model.ckpt. INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 25... INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 25... INFO:tensorflow:Calling model_fn. INFO:tensorflow:Calling model_fn. INFO:tensorflow:Done calling model_fn. INFO:tensorflow:Done calling model_fn. INFO:tensorflow:Starting evaluation at 2021-01-06T02:31:24Z INFO:tensorflow:Starting evaluation at 2021-01-06T02:31:24Z INFO:tensorflow:Graph was finalized. INFO:tensorflow:Graph was finalized. INFO:tensorflow:Restoring parameters from /tmp/tmpc93qfnv6/model.ckpt-25 INFO:tensorflow:Restoring parameters from /tmp/tmpc93qfnv6/model.ckpt-25 INFO:tensorflow:Running local_init_op. INFO:tensorflow:Running local_init_op. INFO:tensorflow:Done running local_init_op. INFO:tensorflow:Done running local_init_op. INFO:tensorflow:Evaluation [1/5] INFO:tensorflow:Evaluation [1/5] INFO:tensorflow:Evaluation [2/5] INFO:tensorflow:Evaluation [2/5] INFO:tensorflow:Evaluation [3/5] INFO:tensorflow:Evaluation [3/5] INFO:tensorflow:Evaluation [4/5] INFO:tensorflow:Evaluation [4/5] INFO:tensorflow:Evaluation [5/5] INFO:tensorflow:Evaluation [5/5] INFO:tensorflow:Inference Time : 0.86534s INFO:tensorflow:Inference Time : 0.86534s INFO:tensorflow:Finished evaluation at 2021-01-06-02:31:25 INFO:tensorflow:Finished evaluation at 2021-01-06-02:31:25 INFO:tensorflow:Saving dict for global step 25: Accuracy = 0.59375, global_step = 25, loss = 1.7570661 INFO:tensorflow:Saving dict for global step 25: Accuracy = 0.59375, global_step = 25, loss = 1.7570661 INFO:tensorflow:Saving 'checkpoint_path' summary for global step 25: /tmp/tmpc93qfnv6/model.ckpt-25 INFO:tensorflow:Saving 'checkpoint_path' summary for global step 25: /tmp/tmpc93qfnv6/model.ckpt-25 INFO:tensorflow:Loss for final step: 0.47094986. INFO:tensorflow:Loss for final step: 0.47094986. ({'Accuracy': 0.59375, 'loss': 1.7570661, 'global_step': 25}, [])
เครื่องมือประมาณการล่วงหน้า
เครื่องมือประมาณการ tf.estimator.DNN*
ในตระกูล tf.estimator.DNN*
, tf.estimator.Linear*
และ tf.estimator.DNNLinearCombined*
ยังคงได้รับการสนับสนุนใน TensorFlow 2.x API อย่างไรก็ตามข้อโต้แย้งบางประการมีการเปลี่ยนแปลง:
-
input_layer_partitioner
: ลบออกใน v2 -
loss_reduction
: อัปเดตเป็นtf.keras.losses.Reduction
แทนtf.compat.v1.losses.Reduction
ค่าดีฟอลต์ยังเปลี่ยนเป็นtf.keras.losses.Reduction.SUM_OVER_BATCH_SIZE
จากtf.compat.v1.losses.Reduction.SUM
-
optimizer
dnn_optimizer
และlinear_optimizer
: อาร์กิวเมนต์นี้ได้รับการอัปเดตเป็นtf.keras.optimizers
แทนtf.compat.v1.train.Optimizer
ในการย้ายการเปลี่ยนแปลงข้างต้น:
- ไม่จำเป็นต้องย้ายข้อมูลสำหรับ
input_layer_partitioner
เนื่องจากDistribution Strategy
จะจัดการโดยอัตโนมัติใน TensorFlow 2.x - สำหรับ
loss_reduction
ให้ตรวจสอบtf.keras.losses.Reduction
สำหรับตัวเลือกที่รองรับ - สำหรับอาร์กิวเมนต์
optimizer
:- ถ้าคุณไม่ทำ: 1) ผ่านใน
optimizer
,dnn_optimizer
หรือlinear_optimizer
โต้แย้งหรือ 2) ระบุoptimizer
อาร์กิวเมนต์เป็นstring
ในรหัสของคุณแล้วคุณไม่จำเป็นต้องเปลี่ยนแปลงอะไรเพราะtf.keras.optimizers
ถูกนำมาใช้เป็นค่าเริ่มต้น . - มิฉะนั้นคุณต้องอัปเดตได้จาก
tf.compat.v1.train.Optimizer
จะสอดคล้องกันtf.keras.optimizers
- ถ้าคุณไม่ทำ: 1) ผ่านใน
Checkpoint Converter
การย้ายไปยัง keras.optimizers
จะทำลายจุดตรวจที่บันทึกไว้โดยใช้ TensorFlow 1.x เนื่องจาก tf.keras.optimizers
สร้างชุดตัวแปรที่แตกต่างกันเพื่อบันทึกในจุดตรวจ หากต้องการทำให้จุดตรวจเก่าสามารถนำกลับมาใช้ใหม่ได้หลังจากที่คุณย้ายไปยัง TensorFlow 2.x ให้ลองใช้ เครื่องมือแปลงจุดตรวจสอบ
curl -O https://raw.githubusercontent.com/tensorflow/estimator/master/tensorflow_estimator/python/estimator/tools/checkpoint_converter.py
% Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 15165 100 15165 0 0 40656 0 --:--:-- --:--:-- --:--:-- 40656
เครื่องมือนี้มีความช่วยเหลือในตัว:
python checkpoint_converter.py -h
2021-01-06 02:31:26.297951: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcudart.so.11.0 usage: checkpoint_converter.py [-h] {dnn,linear,combined} source_checkpoint source_graph target_checkpoint positional arguments: {dnn,linear,combined} The type of estimator to be converted. So far, the checkpoint converter only supports Canned Estimator. So the allowed types include linear, dnn and combined. source_checkpoint Path to source checkpoint file to be read in. source_graph Path to source graph file to be read in. target_checkpoint Path to checkpoint file to be written out. optional arguments: -h, --help show this help message and exit
TensorShape
คลาสนี้ถูกทำให้ง่ายขึ้นเพื่อเก็บ int
s แทนที่จะเป็นวัตถุ tf.compat.v1.Dimension
ดังนั้นจึงไม่จำเป็นต้องเรียก .value
เพื่อรับ int
tf.compat.v1.Dimension
แต่ละอ็อบเจ็กต์ยังคงสามารถเข้าถึงได้จาก tf.TensorShape.dims
ต่อไปนี้แสดงให้เห็นถึงความแตกต่างระหว่าง TensorFlow 1.x และ TensorFlow 2.x
# Create a shape and choose an index
i = 0
shape = tf.TensorShape([16, None, 256])
shape
TensorShape([16, None, 256])
หากคุณมีสิ่งนี้ใน TensorFlow 1.x:
value = shape[i].value
จากนั้นทำสิ่งนี้ใน TensorFlow 2.x:
value = shape[i]
value
16
หากคุณมีสิ่งนี้ใน TensorFlow 1.x:
for dim in shape:
value = dim.value
print(value)
จากนั้นทำสิ่งนี้ใน TensorFlow 2.x:
for value in shape:
print(value)
16 None 256
หากคุณมีสิ่งนี้ใน TensorFlow 1.x (หรือใช้วิธีการมิติข้อมูลอื่นใด):
dim = shape[i]
dim.assert_is_compatible_with(other_dim)
จากนั้นทำสิ่งนี้ใน TensorFlow 2.x:
other_dim = 16
Dimension = tf.compat.v1.Dimension
if shape.rank is None:
dim = Dimension(None)
else:
dim = shape.dims[i]
dim.is_compatible_with(other_dim) # or any other dimension method
True
shape = tf.TensorShape(None)
if shape:
dim = shape.dims[i]
dim.is_compatible_with(other_dim) # or any other dimension method
ค่าบูลีนของ tf.TensorShape
เป็น True
ถ้าทราบอันดับ False
อย่างอื่น
print(bool(tf.TensorShape([]))) # Scalar
print(bool(tf.TensorShape([0]))) # 0-length vector
print(bool(tf.TensorShape([1]))) # 1-length vector
print(bool(tf.TensorShape([None]))) # Unknown-length vector
print(bool(tf.TensorShape([1, 10, 100]))) # 3D tensor
print(bool(tf.TensorShape([None, None, None]))) # 3D tensor with no known dimensions
print()
print(bool(tf.TensorShape(None))) # A tensor with unknown rank.
True True True True True True False
การเปลี่ยนแปลงอื่น ๆ
ลบ
tf.colocate_with
: อัลกอริธึมการจัดวางอุปกรณ์ของ TensorFlow ได้รับการปรับปรุงอย่างมีนัยสำคัญ สิ่งนี้ไม่จำเป็นอีกต่อไป หากการลบออกทำให้ประสิทธิภาพลดลง โปรดแจ้งข้อบกพร่องแทนที่การใช้งาน
v1.ConfigProto
ด้วยฟังก์ชันเทียบเท่าจากtf.config
ข้อสรุป
กระบวนการโดยรวมคือ:
- เรียกใช้สคริปต์การอัพเกรด
- ลบสัญลักษณ์สนับสนุน
- เปลี่ยนโมเดลของคุณเป็นสไตล์เชิงวัตถุ (Keras)
- ใช้
tf.keras
หรือtf.estimator
การฝึกอบรมและลูปการประเมินผลที่คุณสามารถทำได้ - มิฉะนั้นให้ใช้การวนซ้ำที่กำหนดเอง แต่อย่าลืมหลีกเลี่ยงเซสชันและคอลเล็กชัน
การแปลงรหัสเป็น TensorFlow 2.x ใช้เวลาเล็กน้อย แต่การเปลี่ยนแปลงทุกครั้งส่งผลให้:
- โค้ดน้อยลง
- เพิ่มความชัดเจนและเรียบง่าย
- การดีบักที่ง่ายขึ้น