首页 最新 热门 推荐

  • 首页
  • 最新
  • 热门
  • 推荐

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

  • 24-03-04 23:02
  • 4651
  • 12817
blog.csdn.net

640?wx_fmt=jpeg


整理 | 非主流
出品 | 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')
[[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 ?")

 
 

<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'?']]
              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')

 
 

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')

 
 

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')

 
 

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 ?'.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"???", '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)


公开课预告

◆

报名中

◆


640?wx_fmt=png

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


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

直播时间:今晚8点

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


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

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

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


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

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

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


640?wx_fmt=png


推荐阅读

  • 自古英雄出少年,22岁中国小哥哥入选Nature十大人物

  • 凭什么老程序员被裁,应届生却能月薪 1.3 万?

  • 美团回应大规模裁员;ofo 戴威要为欠钱负责;高通要求禁售 iPhone X 系列

  • 6:1又怎样? 这20位区块链女神都是佼佼者, 她们也能撑起一片天!

  • “车联网”最强科普!据说它是未来五年5G兴衰的晴雨表?

  • 特斯拉加速“国产化”,上海工厂一期建设曝光

  • 让你崩溃无语的程序命名有哪些?


点击“阅读原文”,打开APP 阅读更顺畅。

注:本文转载自blog.csdn.net的AI科技大本营的文章"https://blog.csdn.net/dQCFKyQDXYm3F8rB0/article/details/85150227"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接
复制链接
相关推荐
发表评论
登录后才能发表评论和回复 注册

/ 登录

评论记录:

未查询到任何数据!
回复评论:

分类栏目

后端 (14832) 前端 (14280) 移动开发 (3760) 编程语言 (3851) Java (3904) Python (3298) 人工智能 (10119) AIGC (2810) 大数据 (3499) 数据库 (3945) 数据结构与算法 (3757) 音视频 (2669) 云原生 (3145) 云平台 (2965) 前沿技术 (2993) 开源 (2160) 小程序 (2860) 运维 (2533) 服务器 (2698) 操作系统 (2325) 硬件开发 (2492) 嵌入式 (2955) 微软技术 (2769) 软件工程 (2056) 测试 (2865) 网络空间安全 (2948) 网络与通信 (2797) 用户体验设计 (2592) 学习和成长 (2593) 搜索 (2744) 开发工具 (7108) 游戏 (2829) HarmonyOS (2935) 区块链 (2782) 数学 (3112) 3C硬件 (2759) 资讯 (2909) Android (4709) iOS (1850) 代码人生 (3043) 阅读 (2841)

热门文章

101
推荐
关于我们 隐私政策 免责声明 联系我们
Copyright © 2020-2025 蚁人论坛 (iYenn.com) All Rights Reserved.
Scroll to Top