python机器学习(keras) 第六章

日记目录

一. 单词级one-hot编码

将每个单词与一个唯一的整数索引相关联,然后将这个整数索引 i 转换为长度为 N 的二进制向量(N 是词表大小),这个向量只有第 i 个元素是 1,其余元素都为 0。

import numpy as np

samples = ['The cat sat on the mat.', 'The dog ate my homework.'] 
##构建索引
token_index = {}
for sample in samples:
##对样本分词,实际引用中需去除其他符号,如:.split("str",num),str默认所有空字符,num分几次,默认为-1,分割所有
	for word in sample.split(): 
 		if word not in token_index:
 			## 为每个唯一单词指定一个唯一索引,至少为1
 			token_index[word] = len(token_index) + 1 
max_length = 10 
## 借助numpy库建立0矩阵,3维,
results = np.zeros(shape=(len(samples),
					max_length,
 					max(token_index.values()) + 1)) 
 ##enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标
 for i, sample in enumerate(samples):
 	##(j索引,word字符串),[:max_length]前10个
 	for j, word in list(enumerate(sample.split()))[:max_length]:
 	index = token_index.get(word)
 	results[i, j, index] = 1.

二. 字符级的one-hot编码

import string

samples = ['The cat sat on the mat.', 'The dog ate my homework.']
##所有所有可打印的 ASCII 字符
characters = string.printable 
##建立字典
##zip(),将参数打包为元组,后返回其组成的列表
token_index = dict(zip(range(1, len(characters) + 1), characters))

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

三. 用keras实现单词级的one-hot编码

from keras.preprocessing.text import Tokenizer

samples = ['The cat sat on the mat.', 'The dog ate my homework.']
##分词器,只考虑前1000个常用单词
tokenizer = Tokenizer(num_words=1000) 
## 构建索引
tokenizer.fit_on_texts(samples) 
## 序列列表,返回为字符串转化为整数索引组成的列表
sequences = tokenizer.texts_to_sequences(samples) 
## 将字符串转化为二进制向量
one_hot_results = tokenizer.texts_to_matrix(samples, mode='binary') 
##单词索引
word_index = tokenizer.word_index 
print('Found %s unique tokens.' % len(word_index))

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

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

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]:
 		index = abs(hash(word)) % dimensionality 
 		results[i, j, index] = 1.

五. 循环神经网路

循环神经网络(RNN):它处理序列的方式是,遍历所有序列元素,并保存一个状态(state),其中包含与已查看内容相关的信息

简单RNN的Numpy实现

import numpy as np
##输入序列的时间步数
timesteps = 100 
##输入特征空间的维度
input_features = 32 
##输出特征空间的维度
output_features = 64 

##输入数据,随机随机噪声【100*32】
inputs = np.random.random((timesteps, input_features)) 

##初始全零向量
state_t = np.zeros((output_features,)) 

##随机权重矩阵
W = np.random.random((output_features, input_features)) 
U = np.random.random((output_features, output_features))
b = np.random.random((output_features,))
successive_outputs = []

##input_t为(32, )向量
for input_t in inputs: 
	##由输入和当前状态(前一个输出)计算得到当前输出
 	output_t = np.tanh(np.dot(W, input_t) + np.dot(U, state_t) + b) 
 	##将输出值存储于列表中
 	successive_outputs.append(output_t) 
 	##更新状态
 	state_t = output_t 
## 最终输出为形状为(100,64)的二维向量
final_output_sequence = np.stack(successive_outputs, axis=0)

六. IMDB电影评论与RNN

数据处理

from keras.datasets import imdb
from keras.preprocessing import sequence

max_features = 10000 
maxlen = 500 
batch_size = 32

print('Loading data...')

(input_train, y_train), (input_test, y_test) = imdb.load_data(
 num_words=max_features)
 
print(len(input_train), 'train sequences')
print(len(input_test), 'test sequences')
print('Pad sequences (samples x time)')
input_train = sequence.pad_sequences(input_train, maxlen=maxlen)
input_test = sequence.pad_sequences(input_test, maxlen=maxlen)
print('input_train shape:', input_train.shape)
print('input_test shape:', input_test.shape)

训练模型

from keras.layers import Dense
model = Sequential() 
model.add(Embedding(max_features, 32)) 
model.add(SimpleRNN(32)) 
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['acc'])
history = model.fit(input_train, y_train,
					epochs=10, 
					batch_size=128,
					validation_split=0.2)

绘制结果

import matplotlib.pyplot as plt
acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
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('Training and validation accuracy')
plt.legend()
plt.figure()
plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()
plt.show()
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值