ML、DL、CNN学习记录5



ML、DL、CNN学习记录4

Time/Spatial:
SimpleRNN
LSTM
GRU

RNN <—> Attention/Transformers

RNN

RNN类别

在这里插入图片描述

many to one:文本分类、股价预测
many to mary:语音识别(语音->文字)、语音合成(文字->语音)、翻译

Word 表示

  1. 分词(jieba、spacy、NLTK、HanLP)
  2. word -> token
  3. one-hot编码(并不是很好用,相似度度量的时候不好处理,过于稀疏)
  4. 相似度度量(欧式距离、夹角余弦…)

编码

one-hot编码

词嵌入(word Embedding):将词的向量 映射到 一个n维空间

Morkov model:
一阶Morlov: w i w_i wi只与 w i − 1 w_{i-1} wi1有关
二阶Morlov: w i w_i wi只与 w i − 1 w i − 2 w_{i-1}w_{i-2} wi1wi2有关

x阶Morlov: w i w_i wi只与 w i − 1 w i − 2 . . . w i − x + 1 w_{i-1}w_{i-2}...w_{i-x+1} wi1wi2...wix+1有关
w 1 w 2 w 2 w 3 w 4 . . . w m w_1w_2w_2w_3w_4...w_m w1w2w2w3w4...wm

skip-gram:
环境决定我:

w i − x + 1 w i − x + 2 . . . w i − 1 + w i + 1 w i + 2 . . . w i + x ⟶ w i w_{i-x+1}w_{i-x+2}...w_{i-1} + w_{i+1}w_{i+2}...w_{i+x} \longrightarrow w_i wix+1wix+2...wi1+wi+1wi+2...wi+xwi

CBOW(连续词带模型)

我决定环境(当前词预测周边词):

w i ⟶ w i − x + 1 w i − x + 2 . . . w i − 1 + w i + 1 w i + 2 . . . w i + x w_i \longrightarrow w_{i-x+1}w_{i-x+2}...w_{i-1} + w_{i+1}w_{i+2}...w_{i+x} wiwix+1wix+2...wi1+wi+1wi+2...wi+x

10000dim - 100dim

在这里插入图片描述

通过神经网络学习全连接矩阵W,可将word2vec添加到模型的某层

tf.nn.embedding_lookup(Params, ids, pertition_strategy='mod', max_norm=None)
# params:词向量矩阵;
# 按照找ids获取params中的行,ids为矩阵行号(index)
# max_norm允许使用L2范式缩放params中原向量:x*max_norm/norm(x)

在这里插入图片描述

note:一般使用缩放one-hot编码到 64-256的范围里

RNN基本运算

RNN基本运算:
在这里插入图片描述
Input/Output:
在这里插入图片描述
LSTM:
在这里插入图片描述



imdb

文本处理的重要数据集

流程:

# coding: utf-8

import keras
from keras.models import Sequential
from keras.layers import Embedding, SimpleRNN, LSTM, Dense
from keras.datasets import imdb
# 辅助函数(帮助)
from keras.preprocessing import sequence
import matplotlib.pyplot as plt
from time import time


t_start = time()
max_features = 10000  # number of words to consider as features
maxlen = 500  # cut texts after this number of words
batch_size = 32

# 获取imdb文本数据
# 限定文本的维度 为: max_features
(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(y_train.shape)
print(y_train[:100])
# 输出文本
# 首先需要构建文本的一个词典
# 每个词都有一个编号
word_index = imdb.get_word_index()
# 根据词来查找编号
reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])
# note that our indices were offset by 3 because 0, 1 and 2 are reserved indices for "padding", "start of sequence", and "unknown".
decoded_text = ' '.join([reverse_word_index.get(i - 3, '?') for i in input_train[0]])
print('第一个文本:\n', decoded_text)

print('Pad sequences (samples x time)')
# 做一个padding,进行数据的修正(多了删掉,少了填充)
# 文本长度可能不一样,所以需要这一步操作
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)

# 建立模型 使用Embedding,LSTM层
model = Sequential()
# Embedding,将max_features维度降到 32 维
model.add(Embedding(max_features, 32))
# LSTM
model.add(LSTM(64, return_sequences=True))
model.add(LSTM(32))  # SimpleRNN(32)
# 全连接层
# 多分类使用 softmax
# model.add(Dense(10, activation='softmax'))
# 单分类使用 sigmoid
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)
t_end = time()
print('耗时:%.3f秒。', (t_end - t_start))

acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']

epochs = range(len(acc))
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.savefig('acc.png')

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.savefig('loss.png')
plt.show()

模型一般就2、3、4层,并不需要太深。

文本生成模型


汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字


不同的文字集合生成字典
前面n个词(词:向量)预测第n+1个词

话说天下大势,分久必合,合久必分。周末七国分争,并入于秦。及秦灭之后,楚、汉分争,又并入于汉。汉朝自高祖斩白蛇而起义,一统天下,后来光武中兴,传至献帝,遂__
已知之前的一句话(n个词),预测第n+1个词。

模型示例

在这里插入图片描述

W_hh,W_hy,W_xh 是被复用的。
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SQLAlchemy 是一个 SQL 工具包和对象关系映射(ORM)库,用于 Python 编程语言。它提供了一个高级的 SQL 工具和对象关系映射工具,允许开发者以 Python 类和对象的形式操作数据库,而无需编写大量的 SQL 语句。SQLAlchemy 建立在 DBAPI 之上,支持多种数据库后端,如 SQLite, MySQL, PostgreSQL 等。 SQLAlchemy 的核心功能: 对象关系映射(ORM): SQLAlchemy 允许开发者使用 Python 类来表示数据库表,使用类的实例表示表中的行。 开发者可以定义类之间的关系(如一对多、多对多),SQLAlchemy 会自动处理这些关系在数据库中的映射。 通过 ORM,开发者可以像操作 Python 对象一样操作数据库,这大大简化了数据库操作的复杂性。 表达式语言: SQLAlchemy 提供了一个丰富的 SQL 表达式语言,允许开发者以 Python 表达式的方式编写复杂的 SQL 查询。 表达式语言提供了对 SQL 语句的灵活控制,同时保持了代码的可读性和可维护性。 数据库引擎和连接池: SQLAlchemy 支持多种数据库后端,并且为每种后端提供了对应的数据库引擎。 它还提供了连接池管理功能,以优化数据库连接的创建、使用和释放。 会话管理: SQLAlchemy 使用会话(Session)来管理对象的持久化状态。 会话提供了一个工作单元(unit of work)和身份映射(identity map)的概念,使得对象的状态管理和查询更加高效。 事件系统: SQLAlchemy 提供了一个事件系统,允许开发者在 ORM 的各个生命周期阶段插入自定义的钩子函数。 这使得开发者可以在对象加载、修改、删除等操作时执行额外的逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值