1. one-hot编码

# 字符集的one-hot编码
import string samples = ['zzh is a pig','he loves himself very much','pig pig han']
characters = string.printable
token_index = dict(zip(range(1,len(characters)+1),characters)) max_length =20
results = np.zeros((len(samples),max_length,max(token_index.keys()) + 1))
for i,sample in enumerate(sample):
for j,character in enumerate(sample):
index = token_index.get(character)
results[i,j,index] = 1
results

characters= '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVW

XYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'

# keras实现单词级的one-hot编码
from keras.preprocessing.text import Tokenizer
samples = ['zzh is a pig','he loves himself very much','pig pig han'] tokenizer = Tokenizer(num_words = 100)
#创建一个分词器(tokenizer),设置为只考虑前1000个最常见的单词
tokenizer.fit_on_texts(samples)#构建单词索引 sequences = tokenizer.texts_to_sequences(samples) one_hot_results = tokenizer.texts_to_matrix(samples,mode='binary') # one_hot_results.shape --> (3, 100) word_index = tokenizer.word_index
print('发现%s个unique标记',len(word_index))
sequences = [[2, 3, 4, 1], 
[5, 6, 7, 8, 9, 10],
[1, 1, 11]]
发现10个unique标记

word_index =
{'pig': 1, 'zzh': 2, 'is': 3, 'a': 4, 'he': 5, 
'loves': 6,'himself': 7, 'very': 8, 'much': 9,
'han': 10}

one-hot 编码的一种办法是 one-hot散列技巧(one-hot hashing trick)

如果词表中唯一标记的数量太大而无法直接处理,就可以使用这种技巧。

这种方法没有为每个单词显示的分配一个索引并将这些索引保存在一个字典中,而是将单词散列编码为固定长度的向量,通常用一个非常简单的散列函数来实现。

优点:节省内存并允许数据的在线编码(读取完所有数据之前,你就可以立刻生成标记向量)

缺点:可能会出现散列冲突

如果散列空间的维度远大于需要散列的唯一标记的个数,散列冲突的可能性会减小

import numpy as np

samples = ['the cat sat on the mat the cat sat on the mat the cat sat on the mat','the dog ate my homowork']
dimensionality = 1000#将单词保存为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]:
index = abs(hash(word)) % dimensionality
results[i,j,index] = 1
 

2. 词嵌入

获取词嵌入的两种方法:

  • 在完成主任务的同时学习词嵌入。在这种情况下,一开始是随机的词向量,然后对这些词向量进行学习,其学习方式与学习神经网络的权重相同。
  • 在不同于待解决的机器学习任务上预计算好词嵌入,然后将其加载到模型中。这些词嵌入叫作预训练词嵌入

实验数据:imdb电影评论,我们添加了以下限制,将训练数据限定为200个样本(打乱顺序)。

(1)使用embedding层学习词嵌入  
# 处理imdb原始数据的标签
# _*_ coding:utf-8 _*_
import os imdb_dir = 'imdb'
train_dir = os.path.join(imdb_dir,'train') labels = []
texts = [] for label_type in ['neg','pos']:
dir_name = os.path.join(train_dir,label_type)
for fname in os.listdir(dir_name):
if fname[-4:] == '.txt':
f = open(os.path.join(dir_name,fname),encoding='UTF-8')
texts.append(f.read())
f.close()
if label_type == 'neg':
labels.append(0)
else:
labels.append(1)

len(texts)=25000

len(labels)=25000

# 对imdb原始数据的文本进行分词
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences max_len = 100 #每句话最大长度不超过100个单词
training_samples = 200
validation_samples = 10000
max_words = 10000 #只考虑数据集中前10000个最常见的单词 tokenizer = Tokenizer(num_words=max_len)
tokenizer.fit_on_texts(texts)
sequences = tokenizer.texts_to_sequences(texts)
len(sequences)

sequence[0]

word_index = tokenizer.word_index

#88592个unique单词

word_index

data = pad_sequences(sequences,maxlen=max_len)

data.shape = (25000,100)

data[0]

labels = np.asarray(labels)

#asarray会跟着原labels的改变,算是浅拷贝吧,
没有新开一片内存 

indices = np.arange(data.shape[0])

np.random.shuffle(indices)

indices

array([ 2501, 4853, 2109, ..., 2357, 22166, 12397])

#将data,label打乱顺序
data = data[indices]
labels = labels[indices] x_train = data[:training_samples]
y_train = labels[:training_samples] x_val = data[training_samples:training_samples+validation_samples]
y_val = labels[training_samples:training_samples+validation_samples]

x_val.shape,y_val.shape
(10000, 100) (10000,)

#2014年英文维基百科的预计算嵌入:Glove词嵌入(包含400000个单词)
glove_dir = 'glove.6B'
embeddings_index = {} f = open(os.path.join(glove_dir,'glove.6B.100d.txt'),encoding='utf8')
for line in f:
values = line.split()
word = values[0]
coefs = np.asarray(values[1:],dtype='float32')
embeddings_index[word] = coefs
f.close()

len(embeddings_index) 400000
f.readline() #'the -0.038194 -0.24487 ...'
每个单词对应一个词向量

#准备glove词嵌入矩阵
embedding_dim = 100
# 每个单词都有编号,根据编号得到对应的矩阵
embedding_matrix = np.zeros((max_words,embedding_dim))
for word,i in word_index.items():
# print(word,i)--> the 1
if i < max_words:
embedding_vector = embeddings_index.get(word)
if embedding_vector is not None:
embedding_matrix[i] = embedding_vector # print(embedding_matrix[0])

把数据集里面的单词在glove中找到对应的词向量,组成embedding_matrix,

若在glove中不存在,那就为0向量

#定义模型
from keras.models import Sequential
from keras.layers import Embedding,Flatten,Dense model = Sequential() model.add(Embedding(max_words,embedding_dim,input_length=max_len)) model.add(Flatten())
model.add(Dense(32,activation='relu'))
model.add(Dense(1,activation='sigmoid')) model.summary() #将预训练的词嵌入加载到embedding层中,
model.layers[0].set_weights([embedding_matrix]) #embedding_matrix ==>(max_words,embedding_dim)
model.layers[0].trainable = False
 

model.compile(loss='binary_crossentropy',optimizer='rmsprop',metrics=['acc'])
history = model.fit(x_train,y_train,
epochs = 10,
batch_size = 32,
validation_data = (x_val,y_val))
model.save_weights('pre_trained_glove_model.h5')
 

import matplotlib.pyplot as plt

acc = history.history['acc']
loss = history.history['loss']
val_acc = history.history['val_acc']
val_loss = history.history['val_loss'] epochs = range(1,len(acc)+1) plt.plot(epochs,acc,'bo',label='Training acc')
plt.plot(epochs,val_acc,'b',label='Validation acc')
plt.title('Traning and validation acc')
plt.legend() plt.figure() plt.plot(epochs,loss,'bo',label='Training loss')
plt.plot(epochs,val_loss,'b',label='Validation loss')
plt.title('Traning and validation loss')
plt.legend() plt.show()
 

模型很快就开始过拟合,考虑到训练样本很少,这也很情有可原的

 
(2)下面在不使用预训练词嵌入的情况下,训练相同的模型  
#定义模型
from keras.models import Sequential
from keras.layers import Embedding,Flatten,Dense model = Sequential() model.add(Embedding(max_words,embedding_dim,input_length=max_len)) model.add(Flatten())
model.add(Dense(32,activation='relu'))
model.add(Dense(1,activation='sigmoid')) model.summary() model.compile(loss='binary_crossentropy',optimizer='rmsprop',metrics=['acc'])
history = model.fit(x_train,y_train,
epochs = 10,
batch_size = 32,
validation_data = (x_val,y_val))

import matplotlib.pyplot as plt

acc = history.history['acc']
loss = history.history['loss']
val_acc = history.history['val_acc']
val_loss = history.history['val_loss'] epochs = range(1,len(acc)+1) plt.plot(epochs,acc,'bo',label='Training acc')
plt.plot(epochs,val_acc,'b',label='Validation acc')
plt.title('Traning and validation acc')
plt.legend() plt.figure() plt.plot(epochs,loss,'bo',label='Training loss')
plt.plot(epochs,val_loss,'b',label='Validation loss')
plt.title('Traning and validation loss')
plt.legend() plt.show()
 

#在测试集上评估模型

test_dir = os.path.join(imdb_dir,'test')

labels = []
texts = [] for label_type in ['neg','pos']:
dir_name = os.path.join(test_dir,label_type)
for fname in os.listdir(dir_name):
if fname[-4:] == '.txt':
f = open(os.path.join(dir_name,fname),encoding='UTF-8')
texts.append(f.read())
f.close()
if label_type == 'neg':
labels.append(0)
else:
labels.append(1) sequence = tokenizer.texts_to_sequences(texts)
x_test = pad_sequences(sequences,maxlen = max_len)
y_test = np.asarray(labels)
 

model.load_weights('pre_trained_glove_model.h5')

model.evaluate(x=x_test,y=y_test)

 


 如果增加训练集样本的数量,可能使用词嵌入得到的效果会好很多。

2.keras实现-->字符级或单词级的one-hot编码 VS 词嵌入的更多相关文章

  1. 51nod图论题解(4级,5级算法题)

    51nod图论题解(4级,5级算法题) 1805 小树 基准时间限制:1.5 秒 空间限制:131072 KB 分值: 80 难度:5级算法题 她发现她的树的点上都有一个标号(从1到n),这些树都在空 ...

  2. Linux学习笔记(三):系统执行级与执行级的切换

    1.Linux系统与其它的操作系统不同,它设有执行级别.该执行级指定操作系统所处的状态.Linux系统在不论什么时候都执行于某个执行级上,且在不同的执行级上执行的程序和服务都不同,所要完毕的工作和所要 ...

  3. codewar代码练习1——8级晋升7级

    最近发现一个不错的代码练习网站codewar(http://www.codewars.com).注册了一个账号,花了几天的茶余饭后时间做题,把等级从8级升到了7级.本文的目的主要介绍使用感受及相应题目 ...

  4. [数据库事务与锁]详解五: MySQL中的行级锁,表级锁,页级锁

    注明: 本文转载自http://www.hollischuang.com/archives/914 在计算机科学中,锁是在执行多线程时用于强行限制资源访问的同步机制,即用于在并发控制中保证对互斥要求的 ...

  5. MySQL行级锁,表级锁,页级锁详解

    页级:引擎 BDB. 表级:引擎 MyISAM , 理解为锁住整个表,可以同时读,写不行 行级:引擎 INNODB , 单独的一行记录加锁 表级,直接锁定整张表,在你锁定期间,其它进程无法对该表进行写 ...

  6. 行为级和RTL级的区别(转)

    转自:http://hi.baidu.com/renmeman/item/5bd83496e3fc816bf14215db RTL级,registertransferlevel,指的是用寄存器这一级别 ...

  7. CSS 各类 块级元素 行级元素 水平 垂直 居中问题

    元素的居中问题是每个初学者碰到的第一个大问题,在此我总结了下各种块级 行级 水平 垂直 的居中方法,并尽量给出代码实例. 首先请先明白块级元素和行级元素的区别 行级元素 一块级元素 1 水平居中: ( ...

  8. 【数据库】数据库的锁机制,MySQL中的行级锁,表级锁,页级锁

    转载:http://www.hollischuang.com/archives/914 数据库的读现象浅析中介绍过,在并发访问情况下,可能会出现脏读.不可重复读和幻读等读现象,为了应对这些问题,主流数 ...

  9. MySQL中的行级锁,表级锁,页级锁

    在计算机科学中,锁是在执行多线程时用于强行限制资源访问的同步机制,即用于在并发控制中保证对互斥要求的满足. 在数据库的锁机制中介绍过,在DBMS中,可以按照锁的粒度把数据库锁分为行级锁(INNODB引 ...

随机推荐

  1. 【linux系列】Centos下安装mysql数据库

    前言 为了测试方便,通常我们会自己安装数据库,以下是在Centos上安装Mysql的操作. 一.检查自己是否安装了MySQL数据库 [root@s201 /home/mysql]#rpm -qa |g ...

  2. 【Spring Boot&&Spring Cloud系列】使用Intellij构建Spring Boot和Mybatis项目

    一.创建项目 1.File->New->Project->spring initializer 2.勾选Web SQL Template Engines 3.项目生成之后,点击add ...

  3. 原生js--键盘事件

    键盘事件知识点: 1.如果用户按键事件足够长,在keyup事件触发之前,会触发多次keydown事件 2.通过keyCode(charCode firefox)指定按下的是哪个键,采用unicode编 ...

  4. Rope整理(可持久化神器)

    rope是什么?STL的内置的可持久化的数组.其最为方便的就是可以O1复制原来的数组.事实上rope的内置实现也是平衡树,由于只需要复制根结点,O1可以做到复制历史版本. 然而这个东西常数特大,不开O ...

  5. 初始react

    很久就期待学习react了,惰性,一直都没有去翻阅react的资料,最近抽空,简单的了解了一下react,先记录一下,后续慢慢的学习. 一.ReactJS简介 React 起源于 Facebook 的 ...

  6. undefined类型

    undefined类型 只有一个特殊的值 undefined   在使用var声明变量但未对其加以初始化,这个变量的值就是undefined 值是undefined的情况: 1.显示声明并初始化变量值 ...

  7. jquery的$.each如何退出循环和退出本次循环

    https://api.jquery.com/jQuery.each/ We can break the $.each() loop at a particular iteration by maki ...

  8. libxml2简单的生成、解析操作

    3. 简单xml操作例子 link:http://www.blogjava.net/wxb_nudt/archive/2007/11/18/161340.html 了解以上基本知识之后,就可以进行一些 ...

  9. 170809、 把list集合中的数据按照一定数量分组

    /** * @Desc : 切分list位多个固定长度的list集合(我这是业务需要,直接是1w条数据切分) * @Author : RICK * @Params: [historyList] * @ ...

  10. pcl学习笔记(二):点云类型

    不同的点云类型 前面所说的,pcl::PointCloud包含一个域,它作为点的容器,这个域是PointT类型的,这个域是PointT类型的是pcl::PointCloud类的模板参数,定义了点云的存 ...