TensorFlow支持Unicode,中文NLP终于省心了

栏目: 数据库 · 发布时间: 7年前

内容简介:整理 | 非主流终于,TensorFlow 增加了对 Unicode 的支持。

TensorFlow支持Unicode,中文NLP终于省心了

整理 | 非主流
出品 | AI科技大本营

终于,TensorFlow 增加了对 Unicode 的支持。

什么是 Unicode?Unicode 是计算机科学领域里的一项业界标准,包括字符集、编码方案等。Unicode 是为了解决传统的字符编码方案的局限而产生的,它为每种语言中的每个字符设定了统一并且唯一的二进制编码,以满足跨语言、跨平台进行文本转换、处理的要求。

在处理自然语言时,了解字符串中字符的编码方式非常重要。因为计算机只能处理数字,如果要处理文本,就必须先把文本转换为数字。最早的计算机在设计时采用 8 个比特(bit)作为一个字节(byte),所以一个字节能表示的最大的整数就是 255(二进制 11111111 = 十进制 255),0 - 255 被用来表示大小写英文字母、数字和一些符号,这个编码表被称为 ASCII 编码,比如大写字母 A 的编码是 65,小写字母 z 的编码是 122。

如果要表示中文,显然一个字节是不够的,至少需要两个字节,而且还不能和 ASCII 编码冲突,所以,中国制定了 GB2312 编码,用来把中文编进去。

类似的,日文和韩文等其他语言也有这个问题。为了统一所有文字的编码,Unicode 应运而生。Unicode 把所有语言都统一到一套编码里,这样就不会再有乱码问题了。

Unicode 几乎支持所有的语言,是字符编码最常用的标准。Unicode 规定,每个字符使用唯一的整数代码点(code point)表示,其值介于 0 和 0x10FFFF 之间。把代码点按顺序放置,就能得到一个 Unicode 字符串。

因此,TensorFlow 支持 Unicode 对中文 NLP 的研究人员来说绝对算得上是一大利好。与此同时,TensorFlow 社区也推出了新的 Unicode colab 教程,展示了如何在 TensorFlow 中表示 Unicode 字符串。

在使用 TensorFlow 时,有两种标准方式来表示 Unicode 字符串:

  • 作为整数向量,其中每个位置包含一个代码点。

  • 作为字符串,使用字符编码将代码点序列编码到字符串中,包括最常见的 UTF-8、UTF-16 等字符编码。

以下代码分别为使用代码点 UTF-8 和 UTF-16 显示字符串“语言处理”的编码。

# Unicode string, represented as a vector of code points.
text_chars = tf.constant([35821, 35328, 22788, 29702])

# Unicode string, represented as a UTF-8-encoded string scalar.
text_utf8 = tf.constant('\xe8\xaf\xad\xe8\xa8\x80\xe5\xa4\x84\xe7\x90\x86')

# Unicode string, represented as a UTF-16-BE-encoded string scalar.
text_utf16be = tf.constant('\x8b\xed\x8a\x00Y\x04t\x06')```

当然,你可能经常需要在不同的表示之间进行转换,而 TensorFlow 1.13 已添加了执行此操作的函数:

  • tf.strings.unicode_decode:将编码的字符串标量转换为代码点的向量。

  • tf.strings.unicode_encode:将代码点向量转换为编码的字符串标量。

  • tf.strings.unicode_transcode:将编码的字符串标量转换为不同的编码。

例如,如果要将上述示例中的 UTF-8 表示解码为代码点向量,则可以执行以下操作:

>>> tf.strings.unicode_decode(text_utf8, input_encoding='UTF-8')
tf.Tensor([35821 35328 22788 29702], shape=(4,), dtype=int32)

当对包含多个字符串的 Tensor 进行解码时,字符串可能具有不同的长度。unicode_decode 将结果作为 RaggedTensor 返回,其内部维度的长度根据每个字符串中的字符数而变化。

>>> hello = [b"Hello", b"你好", b"こんにちは", b"Bonjour"]
>>> tf.strings.unicode_decode(hello, input_encoding='UTF-8')
<tf.RaggedTensor [[72, 101, 108, 108, 111],                   [20320, 22909],                   [12371, 12435, 12395, 12385, 12399],                   [66, 111, 110, 106, 111, 117, 114]]>

以下是 Unicode 使用方法的详细介绍,希望对大家能有所帮助。

!pip install -q tf-nightly
from __future__ import absolute_import, division, print_function
import tensorflow as tf

tf.enable_eager_execution()

tf.string

通过基本的 TensorFlow tf.string dtype,你可以构建字节字符串的张量(tensor)。Unicode 字符串默认为 utf-8 编码。

tf.constant(u"Thanks :blush:")
<tf.Tensor: id=0, shape=(), dtype=string, numpy=b'Thanks \xf0\x9f\x98\x8a'>

tf.string 张量可以保存不同长度的字节串,因为字节串被视为原子单位。字符串长度不包括在张量尺寸中。

f.constant([u"You're", u"welcome!"]).shape
TensorShape([Dimension(2)])

Unicode 表示

在 TensorFlow 中有两种表示 Unicode 字符串的标准方法:

字符串标量,使用已知字符编码对代码点序列进行编码。
int32 vector,每个位置包含一个代码点。

例如,以下三个值都表示 Unicode 字符串“语言处理”。

# Unicode string, represented as a UTF-8 encoded string scalar.
text_utf8 = tf.constant(u"语言处理")
text_utf8
<tf.Tensor: id=3, shape=(), dtype=string, numpy=b'\xe8\xaf\xad\xe8\xa8\x80\xe5\xa4\x84\xe7\x90\x86'>
# Unicode string, represented as a UTF-16-BE encoded string scalar.
text_utf16be = tf.constant(u"语言处理".encode("UTF-16-BE"))
text_utf16be
<tf.Tensor: id=5, shape=(), dtype=string, numpy=b'\x8b\xed\x8a\x00Y\x04t\x06'>
# Unicode string, represented as a vector of Unicode code points.
text_chars = tf.constant([ord(char) for char in u"语言处理"])
text_chars
<tf.Tensor: id=7, shape=(4,), dtype=int32, numpy=array([35821, 35328, 22788, 29702], dtype=int32)>

表示之间的转换

TensorFlow 提供了在这些不同表示之间进行转换的操作:

  • tf.strings.unicode_decode:将编码的字符串标量转换为代码点的向量。

  • tf.strings.unicode_encode:将代码点向量转换为编码的字符串标量。

  • tf.strings.unicode_transcode:将编码的字符串标量转换为不同的编码。

tf.strings.unicode_decode(text_utf8,
                          input_encoding='UTF-8')
<tf.Tensor: id=12, shape=(4,), dtype=int32, numpy=array([35821, 35328, 22788, 29702], dtype=int32)>
tf.strings.unicode_encode(text_chars,
                          output_encoding='UTF-8')
<tf.Tensor: id=23, shape=(), dtype=string, numpy=b'\xe8\xaf\xad\xe8\xa8\x80\xe5\xa4\x84\xe7\x90\x86'>
tf.strings.unicode_transcode(text_utf8,
                             input_encoding='UTF8',
                             output_encoding='UTF-16-BE')
<tf.Tensor: id=25, shape=(), dtype=string, numpy=b'\x8b\xed\x8a\x00Y\x04t\x06'>

Batch dimensions

解码多个字符串时,每个字符串中的字符数可能不相等。 其返回结果是 tf.RaggedTensor,其中最里面的维度的长度根据每个字符串中的字符数而变化。

# A batch of Unicode strings, each represented as a UTF8-encoded string.
batch_utf8 = [s.encode('UTF-8') for s in
              [u'hÃllo',  u'What is the weather tomorrow', u'Göödnight', u':blush:']]
              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)
[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]

你既可以直接使用 tf.RaggedTensor,也可以用 tf.RaggedTensor.to_tensor 将其转换为有填充的密集 tf.Tensor,或者用 tf.RaggedTensor.to_sparse 将其转换为 tf.SparseTensor。

batch_chars_padded = batch_chars_ragged.to_tensor(default_value=-1)
print(batch_chars_padded.numpy())
[[   104    195    108    108    111     -1     -1     -1     -1                       -1   -1     -1     -1     -1     -1     -1     -1     -1     -1     -1  -1     -1     -1     -1     -1     -1     -1     -1]
 [    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     -1  -1     -1     -1     -1     -1     -1     -1     -1     -1     -1  -1     -1     -1     -1     -1     -1     -1     -1]
  [128522     -1     -1     -1     -1     -1     -1     -1     -1     -1   -1     -1     -1     -1     -1     -1     -1     -1     -1     -1  -1     -1     -1     -1     -1     -1     -1     -1]]
batch_chars_sparse = batch_chars_ragged.to_sparse()

编码多个相同长度的字符串时,可以使用 tf.Tensor 作为输入:

tf.strings.unicode_encode([[99, 97, 116], [100, 111, 103], [ 99, 111, 119]], output_encoding='UTF-8')
<tf.Tensor: id=129, shape=(3,), dtype=string, numpy=array([b'cat', b'dog', b'cow'], dtype=object)>

编码多个不同长度的字符串时,应使用 tf.RaggedTensor 作为输入:

tf.strings.unicode_encode(batch_chars_ragged, output_encoding='UTF-8')
<tf.Tensor: id=131, shape=(4,), dtype=string, numpy=array([b'h\xc3\x83llo', b'What is the weather tomorrow', b'G\xc3\xb6\xc3\xb6dnight', b'\xf0\x9f\x98\x8a'], dtype=object)>

如果你有一个带填充或稀疏格式的多个字符串的张量,那么在调用 unicode_encode 之前应将其转换为 tf.RaggedTensor:

tf.strings.unicode_encode(tf.RaggedTensor.from_sparse(batch_chars_sparse), output_encoding='UTF-8')
<tf.Tensor: id=214, shape=(4,), dtype=string, numpy=array([b'h\xc3\x83llo', b'What is the weather tomorrow', b'G\xc3\xb6\xc3\xb6dnight', b'\xf0\x9f\x98\x8a'], dtype=object)>
tf.strings.unicode_encode(tf.RaggedTensor.from_tensor(batch_chars_padded, padding=-1), output_encoding='UTF-8')
<tf.Tensor: id=288, shape=(4,), dtype=string, numpy=array([b'h\xc3\x83llo', b'What is the weather tomorrow', b'G\xc3\xb6\xc3\xb6dnight', b'\xf0\x9f\x98\x8a'], dtype=object)>

Unicode操作

字符长度

tf.strings.length 操作有一个参数单元,它指示应该如何计算长度。 unit 默认为“BYTE”,但可以设置为其他值,例如“UTF8_CHAR”或“UTF16_CHAR”,以确定每个编码字符串中的 Unicode代码点数。

# Note that the final character takes up 4 bytes in UTF8.
thanks = u'Thanks :blush:'.encode('UTF-8')
num_bytes = tf.strings.length(thanks).numpy()
num_chars = tf.strings.length(thanks, unit='UTF8_CHAR').numpy()
print('{} bytes; {} UTF-8 characters'.format(num_bytes, num_chars))
11 bytes; 8 UTF-8 characters

字符子串

类似地,tf.strings.substr 操作接受“unit”参数,并使用它来确定“pos”和“len”参数包含哪种偏移。

# default: unit='BYTE'. With len=1, we return a single byte.
tf.strings.substr(thanks, pos=7, len=1).numpy()
b'\xf0'
# Specifying unit='UTF8_CHAR', we return a single character, which in this case
# is 4 bytes.
print(tf.strings.substr(thanks, pos=7, len=1, unit='UTF8_CHAR').numpy())
b'\xf0\x9f\x98\x8a'

拆分 Unicode 字符串

tf.strings.unicode_split 操作将 unicode 字符串拆分为单个字符的子字符串:

tf.strings.unicode_split(thanks, 'UTF-8').numpy()
array([b'T', b'h', b'a', b'n', b'k', b's', b' ', b'\xf0\x9f\x98\x8a'], dtype=object)

字符的字节偏移量

要将 tf.strings.unicode_decode 生成的字符张量与原始字符串对齐,了解每个字符开始位置的偏移量很非常有用。除了会返回包含每个字符的起始偏移量的第二张量,方法 tf.strings.unicode_decode_with_offsets 与 unicode_decode 非常类似。

codepoints, offsets = tf.strings.unicode_decode_with_offsets(u":balloon::tada::confetti_ball:", 'UTF-8')
for (codepoint, offset) in zip(codepoints.numpy(), offsets.numpy()):
print("At byte offset {}: codepoint {}".format(offset, codepoint))
At byte offset 0: codepoint 127880
At byte offset 4: codepoint 127881
At byte offset 8: codepoint 127882

Unicode 脚本

每个 Unicode 代码点都属于一个称为脚本的代码点集合。字符的脚本有助于确定字符可能属于哪种语言。例如,我们知道'Б'是西里尔文字,那就表示包含该字符的现代文本可能来自斯拉夫语言,如俄语或乌克兰语。

TensorFlow 提供 tf.strings.unicode_script 操作以确定给定代码点使用哪个脚本。 脚本代码是对应于 International Components for Unicode(ICU)UScriptCode 值的 int32 值。

uscript = tf.strings.unicode_script([33464, 1041])  # ['芸', 'Б']

print(uscript.numpy())  # [17, 8] == [USCRIPT_HAN, USCRIPT_CYRILLIC]
[17  8]

tf.strings.unicode_script 操作也可以应用于代码点的多维 tf.Tensors 或 tf.RaggedTensors:

print(tf.strings.unicode_script(batch_chars_ragged))
<tf.RaggedTensor [[25, 25, 25, 25, 25], [25, 25, 25, 25, 0, 25, 25, 0, 25, 25, 25, 0, 25, 25, 25, 25, 25, 25, 25, 0, 25, 25, 25, 25, 25, 25, 25, 25], [25, 25, 25, 25, 25, 25, 25, 25, 25], [0]]>

参考链接:

https://medium.com/tensorflow/adding-unicode-support-in-tensorflow-6a04fb983b63

https://www.tensorflow.org/tutorials/representation/unicode

(*本文由AI科技大本营整理,转载请联系微信1092722531)

公开课预告

报名中

TensorFlow支持Unicode,中文NLP终于省心了

扫码报名,参加以下公开课

公开课一:《详解百度基于模板的文字识别(OCR)结果结构化处理技术

直播时间:今晚8点

本课程从百度自定义模板文字识别展开,从理论到案例,详细介绍OCR结构化的相关技术,并理清OCR和结构化之间的关系和适用场景。

公开课二:《达观数据个性化推荐系统实践》

直播时间:12月27日晚8点

本次分享带你揭开个性化推荐的神秘面纱,从推荐算法到大型系统架构进行全面剖析。

公开课三:《全双工语音对话以及在智能硬件上的应用》

直播 时间:1月17日晚8点

微软小冰全球首席架构师及研发总监周力博士将介绍微软小冰在全双工语音对话方面的最新成果,及其在智能硬件上的应用和未来将面临的更多技术产品挑战。

TensorFlow支持Unicode,中文NLP终于省心了

推荐阅读


以上所述就是小编给大家介绍的《TensorFlow支持Unicode,中文NLP终于省心了》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Learning jQuery

Learning jQuery

Jonathan Chaffer、Karl Swedberg / Packt Publishing / 2007-7-7 / GBP 24.99

jQuery is a powerful JavaScript library that can enhance your websites regardless of your background. In this book, creators of the popular jQuery learning resource, learningquery.com, share the......一起来看看 《Learning jQuery》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

随机密码生成器
随机密码生成器

多种字符组合密码

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具