Embeding编码方式

本文介绍了一种单词编码方法——Embedding,它能够利用低维向量表示单词,并保持单词之间的相关性。通过一个使用RNN预测字母序列的例子,展示了如何用Embedding替代独热码,并详细介绍了其编码过程及模型训练。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Embeding编码方式概述

独热码:数量大而且过于稀疏,映射之间是独立的,没有表现出关联性。

Embedding:是一种单词编码方法,用低维向量实现了编码,这种编码通过神经网络训练优化,能表达出单词间的相关性。

tf给出了Embedding实现编码的函数:

tf.keras.layers.Embedding(词汇表大小,编码维度)

编码维度就是用几个数字表达一个单词

例如想要表示1-100的编码,所以词汇表大小为100,我们可以对【4】编码为【0.25,0.1,0

.1】所以编码的维度就是3。则:tf.keras.layers.Embedding(100,3)

Embedding层对输入数据的维度也有要求,要求输入数据是二维的,第一维告知送入几个样本,第二维告知循环核时间展开步数。

案例分析:

用RNN实现输入一个字母预测下一个字母(用Embedding编码替换独热码)

import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Dense,SimpleRNN,Embedding
import matplotlib.pyplot as plt
import os
import PySide2

dirname = os.path.dirname(PySide2.__file__)
plugin_path = os.path.join(dirname, 'plugins', 'platforms')
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = plugin_path

input_word = "abcde"
w_to_id = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4}  # 单词隐射到数值id的词典

x_train = [w_to_id['a'], w_to_id['b'], w_to_id['c'], w_to_id['d'], w_to_id['e']]

y_train = [w_to_id['b'], w_to_id['c'], w_to_id['d'], w_to_id['e'], w_to_id['a']]

np.random.seed(7)
np.random.shuffle(x_train)
np.random.seed(7)
np.random.shuffle(y_train)
tf.random.set_seed(7)

# 使x_train符合SimpleRNN输入要求:【送入样本数,循环和时间展开步数, 每个时间步输入特征个数】
# 此处整个数据集送入数以送入,送入样本数为len(x_train);输入1个字母出结果,循环核时间展开步数为1
x_train = np.reshape(x_train, (len(x_train), 1))
y_train = np.array(y_train)

model = tf.keras.Sequential([
    Embedding(5, 2),  # 这一层会生成一个五行两列的可训练参数矩阵,实现编码可训练
    SimpleRNN(3),
    Dense(5, activation='softmax')
])

model.compile(optimizer=tf.keras.optimizers.Adam(0.01),
              loss=tf.losses.SparseCategoricalCrossentropy(from_logits=False),
              metrics=['sparse_categorical_accuracy'])

checkpoint_save_path = './checkpoint/mnist.ckpt'
if os.path.exists(checkpoint_save_path + '.index'):
    print('------------------------load the model---------------------')
    model.load_weights(checkpoint_save_path)


cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path,
                                                 save_weights_only=True,
                                                 save_best_only=True,
                                                 monitor='loss')  # 由于fit没有给出测试集,不计算测试集准确率,根据loss保存最有模型


history = model.fit(x_train, y_train, batch_size=32, epochs=50, callbacks=[cp_callback])
model.summary()

# print(model.trainable_variables)
file = open('./weights.txt', 'w')
for v in model.trainable_variables:
    file.write(str(v.name) + '\n')
    file.write(str(v.shape) + '\n')
    file.write(str(v.numpy()) + '\n')
file.close()

############################  show  #############################
# 显示训练集和验证集的acc和loss曲线
acc=history.history['sparse_categorical_accuracy']
loss = history.history['loss']

plt.subplot(1, 2, 1)
plt.plot(acc, label='Training Accuracy')
plt.title('Training Accuracy')
plt.legend()

plt.subplot(1, 2, 2)
plt.plot(loss, label='Training Loss')
plt.title('Training Loss')
plt.legend()
plt.show()

############################   predict    ######################
preNum = int(input("input the num of test alphabet:"))
for i in range(preNum):
    alphabet1 = input("input test alphabet1:")
    alphabet = [w_to_id[alphabet1]]
    # 使alphabet符合SimpleRNN输入要求:【送入样本数, 循环时间展开步数,每个时间步输入特征个数】
    # 此处验证效果送入了一个岩本,送入样本数为1;输入1个字母出结果,所哟循环核时间展开步数为1,表示为独热吗有5个输入特征,每个时间步输入特征个数为5
    alphabet = np.reshape(alphabet, (1, 1))
    result = model.predict([alphabet])
    pred = tf.argmax(result, axis=1)
    pred = int(pred)
    tf.print(alphabet1 + '->' + input_word[pred])

识别结果如下所示:

预测结果如下: 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI炮灰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值