Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

จะเข้ารหัสหลายสตริงที่มีความยาวเท่ากันโดยใช้ Tensorflow และ Python ได้อย่างไร


สามารถเข้ารหัสสตริงที่มีความยาวเท่ากันได้โดยใช้ 'tf.Tensor' เป็นค่าอินพุต เมื่อจำเป็นต้องเข้ารหัสสตริงหลายสตริงที่มีความยาวต่างกัน ควรใช้ tf.RaggedTensor เป็นอินพุต หากเทนเซอร์มีหลายสตริงในรูปแบบเบาะ/บาง จะต้องแปลงเป็น tf.RaggedTensor จากนั้น ควรเรียกใช้เมธอด unicode_encode

อ่านเพิ่มเติม: TensorFlow คืออะไรและ Keras ทำงานร่วมกับ TensorFlow เพื่อสร้าง Neural Networks อย่างไร

ให้เราเข้าใจวิธีการแสดงสตริง Unicode โดยใช้ Python และจัดการกับสตริงที่ใช้ Unicode ที่เทียบเท่ากัน ขั้นแรก เราแยกสตริง Unicode เป็นโทเค็นตามการตรวจจับสคริปต์โดยใช้ Unicode ที่เทียบเท่ากับ ops สตริงมาตรฐาน

เรากำลังใช้ Google Colaboratory เพื่อเรียกใช้โค้ดด้านล่าง Google Colab หรือ Colaboratory ช่วยเรียกใช้โค้ด Python บนเบราว์เซอร์และไม่ต้องมีการกำหนดค่าใดๆ และเข้าถึง GPU ได้ฟรี (หน่วยประมวลผลกราฟิก) Colaboratory สร้างขึ้นบน Jupyter Notebook

print("When encoding multiple strings of   same lengths, tf.Tensor is used as input")
tf.strings.unicode_encode([[99, 97, 116], [100, 111, 103], [ 99, 111, 119]],output_encoding='UTF-8')
print("When encoding multiple strings with varying length, a tf.RaggedTensor should be used as input:")
tf.strings.unicode_encode(batch_chars_ragged, output_encoding='UTF-8')
print("If there is a tensor with multiple strings in padded/sparse format, convert it to a tf.RaggedTensor before calling unicode_encode")
tf.strings.unicode_encode(
   tf.RaggedTensor.from_sparse(batch_chars_sparse),
   output_encoding='UTF-8')
tf.strings.unicode_encode(
   tf.RaggedTensor.from_tensor(batch_chars_padded, padding=-1),
   output_encoding='UTF-8')

เครดิตโค้ด:https://www.tensorflow.org/tutorials/load_data/unicode

ผลลัพธ์

When encoding multiple strings of   same lengths, tf.Tensor is used as input
When encoding multiple strings with varying length, a tf.RaggedTensor should be used as input:
If there is a tensor with multiple strings in padded/sparse format, convert it to a tf.RaggedTensor before calling unicode_encode

คำอธิบาย

  • เมื่อเข้ารหัสสตริงหลายสตริงที่มีความยาวเท่ากัน คุณสามารถใช้ tf.Tensor เป็นอินพุตได้
  • เมื่อเข้ารหัสสตริงหลายสตริงที่มีความยาวต่างกัน คุณสามารถใช้ tf.RaggedTensor เป็นอินพุตได้
  • เมื่อมีเทนเซอร์ที่มีหลายสตริงในรูปแบบเบาะ/บาง จะต้องแปลงเป็น tf.RaggedTensor ก่อนเรียกใช้ unicode_encode