Một tập hợp chuỗi Unicode có thể được biểu diễn dưới dạng chuỗi UTF-8 bằng phương thức encode().
Mã ví dụ
print("Tập chuỗi Unicode biểu diễn dưới dạng UTF-8")
batch_utf8 = [s.encode('UTF-8') for s in [u'hÃllo',
u'What is the weather tomorrow', u'Göödnight', u'😊']]
batch_chars_ragged = tf.strings.unicode_decode(batch_utf8, input_encoding='UTF-8')
for sentence_chars in batch_chars_ragged.to_list():
print(sentence_chars)
print("Dense tensor với padding")
batch_chars_padded = batch_chars_ragged.to_tensor(default_value=-1)
print(batch_chars_padded.numpy())
print("Chuyển sang ma trận thưa (sparse)")
batch_chars_sparse = batch_chars_ragged.to_sparse()
Nguồn mã: TensorFlow Unicode Tutorial
Đầu ra (rút gọn)
[104, 195, 108, 108, 111] [87, 104, 97, 116, 32, 105, 115, 32, 116, 104, 101, 32, 119, 101, 97, 116, 104, 101, 114, 32, 116, 111, 109, 111, 114, 114, 111, 119] [71, 246, 246, 100, 110, 105, 103, 104, 116] [128522] Dense tensor với padding (shape: 4 x max_len, pad=-1) [[104, 195, 108, 108, 111, -1, ...], [87, 104, 97, 116, 32, 105, ...], [71, 246, 246, 100, 110, 105, 103, 104, 116, -1, ...], [128522, -1, -1, ...]] Chuyển sang sparse matrix
Giải thích
- Khi giải mã nhiều chuỗi, số ký tự mỗi chuỗi thường khác nhau → kết quả là
tf.RaggedTensor(chiều trong cùng thay đổi). RaggedTensorcó thể dùng trực tiếp hoặc chuyển sang:tf.Tensordense với padding:to_tensor(default_value=-1)tf.SparseTensor:to_sparse()