使用word2vec+tensorflow自然语言处理NLP

目录

介绍: 

 搭建上下文或预测目标词来学习词向量

建模1:

建模2:

预测:

介绍: 

Word2Vec是一种用于将文本转换为向量表示的技术。它是由谷歌团队于2013年提出的一种神经网络模型。Word2Vec可以将单词表示为高维空间中的向量,使得具有相似含义的单词在向量空间中距离较近。这种向量表示可以用于各种自然语言处理任务,如语义相似度计算、文本分类和命名实体识别等。Word2Vec的核心思想是通过预测上下文或预测目标词来学习词向量。具体而言,它使用连续词袋(CBOW)和跳字模型(Skip-gram)来训练神经网络,从而得到单词的向量表示。这些向量可以捕捉到单词之间的语义和语法关系,使得它们在计算机中更容易处理和比较。Word2Vec已经成为自然语言处理领域中常用的工具,被广泛应用于各种文本分析和语义理解任务中。

import os
os.environ['KMP_DUPLICATE_LIB_OK']='True'#Dataset 10 sentences to create word vectorscorpus = ['king is a strong man', 'queen is a wise woman', 'boy is a young man','girl is a young woman','prince is a young king','princess is a young queen','man is strong', 'woman is pretty','prince is a boy will be king','princess is a girl will be queen']#Remove stop wordsdef remove_stop_words(corpus):stop_words = ['is', 'a', 'will', 'be']results = []for text in corpus:tmp = text.split(' ')for stop_word in stop_words:if stop_word in tmp:tmp.remove(stop_word)results.append(" ".join(tmp))return resultscorpus = remove_stop_words(corpus)corpus'''结果:
['king strong man','queen wise woman','boy young man','girl young woman','prince young king','princess young queen','man strong','woman pretty','prince boy king','princess girl queen']
'''

 搭建上下文或预测目标词来学习词向量

words = []
for text in corpus:for word in text.split(' '):words.append(word)words = set(words)word2int = {}for i,word in enumerate(words):word2int[word] = iprint(word2int)
'''结果:
{'strong': 0,'wise': 1,'man': 2,'boy': 3,'queen': 4,'king': 5,'princess': 6,'young': 7,'woman': 8,'pretty': 9,'prince': 10,'girl': 11}
'''sentences = []
for sentence in corpus:sentences.append(sentence.split())print(sentences)WINDOW_SIZE = 2#距离为2data = []
for sentence in sentences:for idx, word in enumerate(sentence):for neighbor in sentence[max(idx - WINDOW_SIZE, 0) : min(idx + WINDOW_SIZE, len(sentence)) + 1] : if neighbor != word:data.append([word, neighbor])print(data)data
'''结果:
[['king', 'strong'],['king', 'man'],['strong', 'king'],['strong', 'man'],['man', 'king'],['man', 'strong'],['queen', 'wise'],['queen', 'woman'],['wise', 'queen'],['wise', 'woman'],['woman', 'queen'],['woman', 'wise'],['boy', 'young'],['boy', 'man'],['young', 'boy'],['young', 'man'],['man', 'boy'],['man', 'young'],['girl', 'young'],['girl', 'woman'],['young', 'girl'],['young', 'woman'],['woman', 'girl'],['woman', 'young'],['prince', 'young'],['prince', 'king'],['young', 'prince'],['young', 'king'],['king', 'prince'],['king', 'young'],['princess', 'young'],['princess', 'queen'],['young', 'princess'],['young', 'queen'],['queen', 'princess'],['queen', 'young'],['man', 'strong'],['strong', 'man'],['woman', 'pretty'],['pretty', 'woman'],['prince', 'boy'],['prince', 'king'],['boy', 'prince'],['boy', 'king'],['king', 'prince'],['king', 'boy'],['princess', 'girl'],['princess', 'queen'],['girl', 'princess'],['girl', 'queen'],['queen', 'princess'],['queen', 'girl']]
'''

 搭建X,Y

import pandas as pd
for text in corpus:print(text)df = pd.DataFrame(data, columns = ['input', 'label'])word2int#Define Tensorflow Graph
import tensorflow as tf
import numpy as npONE_HOT_DIM = len(words)# function to convert numbers to one hot vectors
def to_one_hot_encoding(data_point_index):one_hot_encoding = np.zeros(ONE_HOT_DIM)one_hot_encoding[data_point_index] = 1return one_hot_encodingX = [] # input word
Y = [] # target wordfor x, y in zip(df['input'], df['label']):X.append(to_one_hot_encoding(word2int[ x ]))Y.append(to_one_hot_encoding(word2int[ y ]))# convert them to numpy arrays
X_train = np.asarray(X)
Y_train = np.asarray(Y)

建模1:

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()# making placeholders for X_train and Y_train
x = tf.placeholder(tf.float32, shape=(None, ONE_HOT_DIM))
y_label = tf.placeholder(tf.float32, shape=(None, ONE_HOT_DIM))# word embedding will be 2 dimension for 2d visualization
EMBEDDING_DIM = 2 # hidden layer: which represents word vector eventually
W1 = tf.Variable(tf.random_normal([ONE_HOT_DIM, EMBEDDING_DIM]))
b1 = tf.Variable(tf.random_normal([1])) #bias
hidden_layer = tf.add(tf.matmul(x,W1), b1)# output layer
W2 = tf.Variable(tf.random_normal([EMBEDDING_DIM, ONE_HOT_DIM]))
b2 = tf.Variable(tf.random_normal([1]))
prediction = tf.nn.softmax(tf.add( tf.matmul(hidden_layer, W2), b2))# loss function: cross entropy
loss = tf.reduce_mean(-tf.reduce_sum(y_label * tf.log(prediction), axis=[1]))# training operation
train_op = tf.train.GradientDescentOptimizer(0.05).minimize(loss)sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init) iteration = 20000
for i in range(iteration):# input is X_train which is one hot encoded word# label is Y_train which is one hot encoded neighbor wordsess.run(train_op, feed_dict={x: X_train, y_label: Y_train})if i % 3000 == 0:print('iteration '+str(i)+' loss is : ', sess.run(loss, feed_dict={x: X_train, y_label: Y_train}))# Now the hidden layer (W1 + b1) is actually the word look up table
vectors = sess.run(W1 + b1)
print(vectors)import matplotlib.pyplot as pltfig, ax = plt.subplots()for word, x1, x2 in zip(words, w2v_df['x1'], w2v_df['x2']):ax.annotate(word, (x1,x2 ))PADDING = 1.0
x_axis_min = np.amin(vectors, axis=0)[0] - PADDING
y_axis_min = np.amin(vectors, axis=0)[1] - PADDING
x_axis_max = np.amax(vectors, axis=0)[0] + PADDING
y_axis_max = np.amax(vectors, axis=0)[1] + PADDINGplt.xlim(x_axis_min,x_axis_max)
plt.ylim(y_axis_min,y_axis_max)
plt.rcParams["figure.figsize"] = (10,10)plt.show()

建模2:

# Deep learning: 
from tensorflow.python.keras.models import Input
from keras.models import  Model
from keras.layers import Dense# Defining the size of the embedding
embed_size = 2# Defining the neural network
#inp = Input(shape=(X.shape[1],))
#x = Dense(units=embed_size, activation='linear')(inp)
#x = Dense(units=Y.shape[1], activation='softmax')(x)
xx = Input(shape=(X_train.shape[1],))
yy = Dense(units=embed_size, activation='linear')(xx)
yy = Dense(units=Y_train.shape[1], activation='softmax')(yy)
model = Model(inputs=xx, outputs=yy)
model.compile(loss = 'categorical_crossentropy', optimizer = 'adam')# Optimizing the network weights
model.fit(x=X_train, y=Y_train, batch_size=256,epochs=1000)# Obtaining the weights from the neural network. 
# These are the so called word embeddings# The input layer 
weights = model.get_weights()[0]# Creating a dictionary to store the embeddings in. The key is a unique word and 
# the value is the numeric vector
embedding_dict = {}
for word in words: embedding_dict.update({word: weights[df.get(word)]})import matplotlib.pyplot as pltfig, ax = plt.subplots()#for word, x1, x2 in zip(words, w2v_df['x1'], w2v_df['x2']):
for word, x1, x2 in zip(words, weights[:,0], weights[:,1]):ax.annotate(word, (x1,x2 ))PADDING = 1.0
x_axis_min = np.amin(vectors, axis=0)[0] - PADDING
y_axis_min = np.amin(vectors, axis=0)[1] - PADDING
x_axis_max = np.amax(vectors, axis=0)[0] + PADDING
y_axis_max = np.amax(vectors, axis=0)[1] + PADDINGplt.xlim(x_axis_min,x_axis_max)
plt.ylim(y_axis_min,y_axis_max)
plt.rcParams["figure.figsize"] = (10,10)plt.show()

预测:

X_train[2]
#结果:array([1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) strongmodel.predict(X_train)[2]
'''结果:
array([0.07919139, 0.0019384 , 0.48794392, 0.05578128, 0.00650001,0.10083131, 0.02451131, 0.03198219, 0.04424168, 0.0013569 ,0.16189449, 0.00382716], dtype=float32) 预测结果:man
'''

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/467961.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

片上网络NoC(4)——直连拓扑

目录 一、前言 二、直连拓扑 三、总结 一、前言 本文中,我们将继续介绍片上网络中拓扑相关的内容,主要介绍直连拓扑,在此之前,我们已经介绍过了拓扑的指标,这将是继续阅读本文的基础,还没有了解相关内容…

OCP的operator——(1)概述

文章目录 概述了解Operator什么是Operator为何使用OperatorOperator FrameworkOperator成熟度模型 Operator Framework 打包格式Bundle格式Manifest注解依赖关于opm CLI 基于文件的目录RukPak Operator Framework常用术语表常见Operator Framework术语BundleBundle imageCatalo…

《Java 简易速速上手小册》第8章:Java 性能优化(2024 最新版)

文章目录 8.1 性能评估工具 - 你的性能探测仪8.1.1 基础知识8.1.2 重点案例:使用 VisualVM 监控应用性能8.1.3 拓展案例 1:使用 JProfiler 分析内存泄漏8.1.4 拓展案例 2:使用 Gatling 进行 Web 应用压力测试 8.2 JVM 调优 - 魔法引擎的调校8…

MQTT的学习与应用

文章目录 一、什么是MQTT二、MQTT协议特点三、MQTT应用领域四、安装Mosquitto五、如何学习 MQTT 一、什么是MQTT MQTT(Message Queuing Telemetry Transport)是一种轻量级的消息传输协议,设计用于在低带宽、不稳定的网络环境中进行高效的通信…

MYSQL学习笔记:MYSQL存储引擎

MYSQL学习笔记:MYSQL存储引擎 MYSQL是插件式的存储引擎 存储引擎影响数据的存储方式 存储引擎是用来干什么的,innodb和myisam的主要区别–数据存储方式----索引 mysql> show engines; ----------------------------------------------------------…

宠物空气净化器适合养猫家庭吗?除猫毛好的猫用空气净化器推荐

宠物掉毛是一个普遍存在的问题,尤其在脱毛季节,毛发似乎无处不在。这给家中的小孩和老人带来了很多麻烦,他们容易流鼻涕、过敏等不适。此外,宠物有时还会不规矩地拉扯和撒尿,这股气味实在是难以忍受。家人们对宠物的存…

耳机壳UV树脂制作私模定制耳塞需要哪些工具和材料呢?

制作私模定制耳塞需要使用到一些工具和材料,包括但不限于以下内容: UV树脂:用于制作耳塞的主体部分,具有高硬度、耐磨、耐高温、环保等优点。耳模材料:用于获取用户的耳型,通常是一些快速固化的材料&#…

编码、理解和实现LLM中的自注意力、多头注意力、交叉注意力和因果注意力

原文链接:understanding-and-coding-self-attention 2024年1月14日 自注意力是 LLM 的一大核心组件。对大模型及相关应用开发者来说,理解自注意力非常重要。近日,Ahead of AI 杂志运营者、机器学习和 AI 研究者 Sebastian Raschka 发布了一篇…

【小赛1】蓝桥杯双周赛第5场(小白)思路回顾

我的成绩:小白(5/6) 完稿时间:2024-2-13 比赛地址:https://www.lanqiao.cn/oj-contest/newbie-5/ 相关资料: 1、出题人题解:“蓝桥杯双周赛第5次强者挑战赛/小白入门赛”出题人题解 - 知乎 (zhihu.com) 2、矩阵快速幂&…

vue三种路由守卫详解

在 Vue 中,可以通过路由守卫来实现路由鉴权。Vue 提供了三种路由守卫:全局前置守卫、全局解析守卫和组件内的守卫。 全局前置守卫 通过 router.beforeEach() 方法实现,可以在路由跳转之前进行权限判断。在这个守卫中,可以根据用…

Decian 12.x基于LNMP安装phpIPAM(IP管理系统)

phpipam是一个开源Web IP地址管理应用程序(IPAM)。其目标是提供轻便,且有用的IP地址管理系统。它是基于PHP的应用程序,具有MySQL数据库后端,使用jQuery库,ajax和HTML5 / CSS3功能。 在Debian 12中&…

学生用的台灯哪种好?推荐央视公认好用的学生护眼台灯

随着太阳的落下,家家户户点亮了灯,孩子的案桌前也备上了台灯,让孩子在明亮的光线下更好学习写作业。但是家长们知道吗?其实孩子学习的台灯也是很有讲究的,不仅仅单看亮度是否充足,如果光线不适合是非常容易…