《Python 深度学习》6.1 One-hot 编码 (代码)_python one_hot(x, depth=2)-程序员宅基地

技术标签: python  深度学习  Keras  Python  

One-hot encoding of words or characters

单词和字符的 one-hot 编码

one-hot 编码是将标记转换为向量的最常用、最基本的方法。在第 3 章的 IMDB 和路透社两 个例子中,你已经用过这种方法(都是处理单词)。它将每个单词与一个唯一的整数索引相关联, 然后将这个整数索引 i 转换为长度为 N 的二进制向量(N 是词表大小),这个向量只有第 i 个元 素是 1,其余元素都为 0。

当然,也可以进行字符级的 one-hot 编码。为了让你完全理解什么是 one-hot 编码以及如何 实现 one-hot 编码,代码清单 6-1 和代码清单 6-2 给出了两个简单示例,一个是单词级的 one-hot 编码,另一个是字符级的 one-hot 编码。

 1. 单词级的 one-hot 编码(简单示例):

import numpy as np

# This is our initial data; one entry per "sample"
# (in this toy example, a "sample" is just a sentence, but
# it could be an entire document).
# 初始数据:每个样本是列表的一个元素(本例中的样本是一个句子,但也可以是一整篇文档)
samples = ['The cat sat on the mat.', 'The dog ate my homework.']

# First, build an index of all tokens in the data.
# 构建数据中所有标记的索引

token_index = {}
for sample in samples:
    # We simply tokenize the samples via the `split` method.
    # in real life, we would also strip punctuation and special characters
    # from the samples.
  # 利用 split 方法对样本进行分词。在实际应用中,还需要从样本中去掉标点和特殊字符

    for word in sample.split():
        if word not in token_index:
            # Assign a unique index to each unique word
            #为每个唯一单词指定一个唯一索引。
            token_index[word] = len(token_index) + 1
            # Note that we don't attribute index 0 to anything.
            #注意,没有为索引编号 0 指定单词
# Next, we vectorize our samples.
# We will only consider the first `max_length` words in each sample.
# 对样本进行分词。只考虑每个 样本前 max_length 个单词
max_length = 10

# This is where we store our results:(将结果保存在 results 中)
results = np.zeros((len(samples), max_length, max(token_index.values()) + 1))
for i, sample in enumerate(samples):
    for j, word in list(enumerate(sample.split()))[:max_length]:
        index = token_index.get(word)
        results[i, j, index] = 1.

  2. 字符级的 one-hot 编码(简单示例) 

import string

samples = ['The cat sat on the mat.', 'The dog ate my homework.']
characters = string.printable  # All printable ASCII characters.(所有可打印的 ASCII 字符)
token_index = dict(zip(characters, range(1, len(characters) + 1)))

max_length = 50
results = np.zeros((len(samples), max_length, max(token_index.values()) + 1))
for i, sample in enumerate(samples):
    for j, character in enumerate(sample[:max_length]):
        index = token_index.get(character)
        results[i, j, index] = 1.

 3. 用 Keras 实现单词级的 one-hot 编码:

from keras.preprocessing.text import Tokenizer

samples = ['The cat sat on the mat.', 'The dog ate my homework.']

# We create a tokenizer, configured to only take
# into account the top-1000 most common words
# 创建一个分词器(tokenizer),设置为只考虑前 1000 个最常见的单词
tokenizer = Tokenizer(num_words=1000)
# This builds the word index(构建单词索引)
tokenizer.fit_on_texts(samples)

# This turns strings into lists of integer indices.
# 将字符串转换为整数索引组成的列表
sequences = tokenizer.texts_to_sequences(samples)

# You could also directly get the one-hot binary representations.
# Note that other vectorization modes than one-hot encoding are supported!
# (也可以直接得到 one-hot 二进制表示。)这个分词器也支持除 one-hot 编码外的其他向量化模式

one_hot_results = tokenizer.texts_to_matrix(samples, mode='binary')

# This is how you can recover the word index that was computed(找回单词索引)

word_index = tokenizer.word_index
print('Found %s unique tokens.' % len(word_index))

        one-hot 编码的一种变体是所谓的 one-hot 散列技巧(one-hot hashing trick),如果词表中唯 一标记的数量太大而无法直接处理,就可以使用这种技巧。这种方法没有为每个单词显式分配 一个索引并将这些索引保存在一个字典中,而是将单词散列编码为固定长度的向量,通常用一个非常简单的散列函数来实现。这种方法的主要优点在于,它避免了维护一个显式的单词索引, 从而节省内存并允许数据的在线编码(在读取完所有数据之前,你就可以立刻生成标记向量)。 这种方法有一个缺点,就是可能会出现散列冲突(hash collision),即两个不同的单词可能具有相同的散列值,随后任何机器学习模型观察这些散列值,都无法区分它们所对应的单词。如果散列空间的维度远大于需要散列的唯一标记的个数,散列冲突的可能性会减小。

 4. 使用散列技巧的单词级的 one-hot 编码(简单示例):

samples = ['The cat sat on the mat.', 'The dog ate my homework.']

# We will store our words as vectors of size 1000.
# Note that if you have close to 1000 words (or more)
# you will start seeing many hash collisions, which
# will decrease the accuracy of this encoding method.
# 将单词保存为长度为 1000 的向量。如果单词数量接近 1000 个(或更多),
# 那么会遇到很多散列冲突,这会降低这种编码方法的准确性
dimensionality = 1000
max_length = 10

results = np.zeros((len(samples), max_length, dimensionality))
for i, sample in enumerate(samples):
    for j, word in list(enumerate(sample.split()))[:max_length]:
        # Hash the word into a "random" integer index
        # that is between 0 and 1000
        #将单词散列为 0~1000 范围内的一个随机整数索引

        index = abs(hash(word)) % dimensionality
        results[i, j, index] = 1.

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/baidu_30506559/article/details/121304224

智能推荐

jdk15安装_jdk15安装教程-程序员宅基地

文章浏览阅读319次。1.首先官网下载jdk包或者百度云找jdk包2.然后运行3.使用命令 bin\jlink.exe --module-path jmods --add-modules java.desktop --output jre 生成jre3.配置环境变量如图:1.配置JAVA_HOME2.配置path变量 bin 目录下和 jre/bin 下..._jdk15安装教程

elementUI多选组件的全部与单选选项互斥逻辑_el-select 默认选择【全部】;支持多选(【全部】与其他选项之间互斥)-程序员宅基地

文章浏览阅读1.8k次。使用多选下拉框组件,会出现选择‘全部’与选择某一项互斥的逻辑<template> <div> <div> <el-row :class="[this.isDataMore ? 'el-icon-arrow-down' : 'el-icon-arrow-up']" class="one-row"> <el-col :xs="20" :sm="20" :md="18_el-select 默认选择【全部】;支持多选(【全部】与其他选项之间互斥)

经纬度转换为三维坐标_经纬度转3d-程序员宅基地

文章浏览阅读6.1k次。// 经纬度转换为球坐标double torad(double deg){ return deg/180*acos(-1);}void get_coordinate(double R,double lat,double lng,double &x,double &y,double z){ lat = torad(lat); lng = torad(lng);_经纬度转3d

C#GPA计算_c#求学生的gpa-程序员宅基地

文章浏览阅读437次,点赞2次,收藏5次。using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace GPA计算{ class Program { class Student { int num; string name; Course[..._c#求学生的gpa

log4j2使用详解_long4j2 appenderref-程序员宅基地

文章浏览阅读405次。转载自 Blog of 天外的星星: http://www.cnblogs.com/leo-lsw/p/log4j2tutorial.html Log4j 2的好处就不和大家说了,如果你搜了2,说明你对他已经有一定的了解,并且想用它,所以这里直接就上手了。   1. 去官方下载log4j 2,导入jar包,基本上你只需要导入下面两个jar包就可以了(xx是乱七八糟的版本号):     log4_long4j2 appenderref

ERROR: pip‘s dependency resolver does not currently take into account all the packages that are inst_error: pip's dependency resolver does not currentl-程序员宅基地

文章浏览阅读1.5w次,点赞2次,收藏11次。安装包的时候出现报错:ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.distributed 1.21.8 requires msgpack, which is not installed.conda_error: pip's dependency resolver does not currently take into account all th

随便推点

在一个教务信息管理系统中 数据库服务器,教务信息管理系统设计和实现.doc-程序员宅基地

文章浏览阅读287次。分类号:TP315 U D C:D10621-408-(2007) 6227-0密 级:公 开 编 号:2003214014成都信息工程学院学位论文教务信息管理系统的设计与实现论文作者姓名:李黎申请学位专业:计算机科学与技术申请学位类别:工学学士指导教师姓名(职称):常征(副教授)论文提交日期:2007年06..._高校图书管理系统和教务系统共用一个数据库吗

Qt5.11.1 + VS2017环境搭建(Qt5.11在windows上的安装)_llvm_install_dir-程序员宅基地

文章浏览阅读6.4k次。安装视频:《Qt5.11在windows‘上的安装》---------------------------------------------------------------------------------------------------------------------------------------安装VisualStudio2017 VS2017安..._llvm_install_dir

webpack babel-loader一些配置属性_webpack配置babel-loader-程序员宅基地

文章浏览阅读231次。初始化项目npm init安装webpacknpm i webpack webpack-cli --save-d安装babel-loadernpm install [email protected] @babel/core @babel/preset-env webpack// 导入静态资源目录const path = require('path')module.exports = { // 指定开发环境 mode:"development",_webpack配置babel-loader

CSAPP期末复习(更新ing)-程序员宅基地

文章浏览阅读2.2k次,点赞8次,收藏54次。CSAPP期末快速复习(更新ing)本人有关CSAPP的博客链接:私人博客CSDN内容基本上差不多主要内容概论信息的表示机器级的表示链接I/O概论上下文:上下文是一个状态,包含运行进程所需的所有状态信息,进程切换通过切换上下文完成编译过程(链接中会再次提到):源程序 预处理-> 文本 编译->汇编程序 汇编->可重定位目标文件 链接->可执行文件指令集架构:每条机器代码的效果。微体系结构:处理器的具体实现存储器层次结构:从上至下,访问速度越来越慢,_csapp期末

(9月7日学习笔记) 宽高自适应、流式布局、bisiblity元素隐藏 伪对象选择器 代码实现三角形 常见的浏览器兼容问题 浏览器的内核_隐藏元素做三角形-程序员宅基地

文章浏览阅读155次。宽高自适应根据需求提出来的,在实际开发中,大家发现元素最外层宽度或者中间内容区域的高度如果写成固定形式,不方便内容增加或者更改提出了宽高自适应解决方案:宽度:自适应,块级元素,不设置宽度,或者宽度设置100% 或者width:auto;(区别:一个没有设置宽度,一个设置了宽度)高度:块级元素不设置高度,或者height:auto,不能设置为100%,否则会充满屏幕希望元素一开始就有高度,随着内容变化,增加,高度自适应提出最小高度的概念:min-height,满足上述需求其他的高度自适应m_隐藏元素做三角形

hrbust 1739 Sort Problem 模拟_zcmu1739-程序员宅基地

文章浏览阅读347次。Sort ProblemTime Limit: 1000 MSMemory Limit: 65535 KTotal Submit: 343(88 users)Total Accepted: 182(86 users)Rating: Special Judge: YesDescription_zcmu1739

推荐文章

热门文章

相关标签