使用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.mzph.cn/news/681676.shtml

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

相关文章

浅谈Java常见设计模式及实例

前言 Java 中常用的设计模式有很多种,其实平常用到的还比较少,但是还是有必要了解一下,可以按照实际情况运用到我们的代码中。按照类型可以基本分解为,创建型模式、结构型模式和行为型模式。 创建型模式 (Creational Patterns) 1…

JS逆向进阶篇【去哪儿旅行登录】【上篇】

目标url: aHR0cHM6Ly91c2VyLnF1bmFyLmNvbS9wYXNzcG9ydC9sb2dpbi5qc3A 实现难点: 逆向滑块请求发送短信登录 目录 每篇前言:0、前置技术栈(1)JS实现页面滑动(2)JS实现记录滑动轨迹(3&#xff…

SAP MM学习笔记42 - 特殊调达流程 - 受托品(寄售)

上一章讲了 外注加工的知识。 详细可以参考如下链接。 SAP MM学习笔记41 - 特殊调达流程 - 外注加工-CSDN博客 咱们继续学习特殊调达流程。 本章主要讲受托品。 1,什么是受托品 (寄售) 仕入先提供的商品,商品是放在你公司了&a…

CSS定位装饰

网页常见布局方式 标准流 块级元素独占一行---垂直布局 行内元素/行内块元素一行显示多个----水平布局 浮动 可以让原本垂直布局的块级元素变成水平布局 定位 可以让元素自由的摆放在网页的任意位置 一般用于盒子之间的层叠情况 使用定位步骤 设置定位方式 属性名&am…

一周学会Django5 Python Web开发-Django5 Hello World编写

锋哥原创的Python Web开发 Django5视频教程: 2024版 Django5 Python web开发 视频教程(无废话版) 玩命更新中~_哔哩哔哩_bilibili2024版 Django5 Python web开发 视频教程(无废话版) 玩命更新中~共计14条视频,包括:2024版 Django5 Python we…

使用 C++23 从零实现 RISC-V 模拟器

👉🏻 文章汇总「从零实现模拟器、操作系统、数据库、编译器…」:https://okaitserrj.feishu.cn/docx/R4tCdkEbsoFGnuxbho4cgW2Yntc 使用 C23 从零实现 RISC-V 模拟器 使用 C23 从零实现的 RISC-V 模拟器,最终的模拟器可以运行 x…

java SSM新闻管理系统myeclipse开发mysql数据库springMVC模式java编程计算机网页设计

一、源码特点 java SSM新闻管理系统是一套完善的web设计系统(系统采用SSM框架进行设计开发,springspringMVCmybatis),对理解JSP java编程开发语言有帮助,系统具有完整的源代码和数据库,系统主要采用B/S…

《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…

智能汽车行业产业研究报告:4D成像毫米波雷达—自动驾驶最佳辅助

今天分享的是智能汽车系列深度研究报告:《智能汽车行业产业研究报告:4D成像毫米波雷达—自动驾驶最佳辅助》。 (报告出品方:开源证券) 报告共计:43页 视觉感知最佳辅助——4D 成像毫米波雷达 感知是自动…

【Python】window环境使用venv部署jupyter notebook

基础信息 执行winr,在输入框输入powershell: python版本:python -v 创建并激活虚拟环境 1、进入要创建虚拟环境的目录,操作示例如下: PS C:\Users\Administrator> cd D:\Python\weltest 2、创建虚拟环境,操作示…

BUGKU-WEB GET

题目描述 没有提示,就一个get,启动场景看看: 解题思路 显然是PHP语言解读分析代码吧写出你的payload 相关工具 略 解题步骤 进入场景分析代码 $what$_GET[what]; echo $what; if($whatflag) echo flag{****};前两句:使用get…

2024年最新指南:如何订阅Midjourney(详尽步骤解析)

前言: Midjourney是一个基于人工智能的图像生成工具,它使用高级算法来创建独特和复杂的图像。这个工具能够根据用户输入的文字描述生成对应的图片。Midjourney的特点在于它能够处理非常抽象或者具体的描述,生成高质量、富有创意的视觉内容。M…

Flaurm实现中文搜索

目录 摘要需求本文涉及环境情况如下解决方案最终效果文章其他链接: 摘要 Flarum本身对中文支持并不理想,但随着版本更新,逐渐加强了对中文的优化。然而在1.8.5版本,却还是不支持中文搜索网站文章内容。作者在检索了全网教程&#…

新概念英语第二册(64)

【New words and expressions】生词和短语(13) tunnel n. 隧道 port n. 港口 ventilate v. 通风 chimney n. 烟囱 sea level …

【2024年5月备考新增】《软考高项论文专题 (13)风险管理(合集)》

1 论文基础 1.1 写作要点 过程定义、作用写作要点、思路规划风险管理是定义如何实施项目风险管理活动的过程。作用:确保风险管理的水平、方法和可见度与项目风险程度相匹配,与对组织和其他干系人的重要程度相匹配。风险管理计划的内容、编写原则。结合风险管理计划其中2-3项内…

gorm day5

gorm day5 gorm更新 删除一条记录 删除一条记录时,删除对象需要指定主键,否则会出发批量Delete,例如 // Email 的 ID 是 10 db.Delete(&email) // DELETE from emails where id 10;// 带额外条件的删除 db.Where("name ?"…

数模.SI模型SI的四种扩展

一:最简单的考虑方式 二考虑某种使得参数beta降低的因素 三:增加人口自然出生率和死亡率,但不考虑疾病的死亡率 四:不考虑人口自然出生率和死亡率,只考虑疾病的死亡率 五:同时考虑人口自然出生率和死亡率和…

kali系统概述、nmap扫描应用、john破解密码、抓包概述、以太网帧结构、抓包应用、wireshark应用、nginx安全加固、Linux系统加固

目录 kali nmap扫描 使用john破解密码 抓包 封装与解封装 网络层数据包结构 TCP头部结构​编辑 UDP头部结构 实施抓包 安全加固 nginx安全 防止缓冲区溢出 Linux加固 kali 实际上它就是一个预安装了很多安全工具的Debian Linux [rootmyhost ~]# kali resetkali …

C#一维数组排序方法:选择排序法

目录 一、数组元素常见的排序法 1.选择排序法 二、实例1:选择排序法 1.源码 2.生成效果 一、数组元素常见的排序法 常见的排序法:选择排序法、冒泡排序法、快速排序法、直接插入法、希尔排序法、Array.Sort方法。 1.选择排序法 通过遍历实现排序&…

2024年华为OD机试真题-按身高和体重排队-Python-OD统一考试(C卷)

题目描述: :某学校举行运动会,学生们按编号(1、2、3…n)进行标识,现需要按照身高由低到高排列,对身高相同的人,按体重由轻到重排列;对于身高体重都相同的人,维持原有的编号顺序关系。请输出排列后的学生编号。 输入描述:两个序列,每个序列由n个正整数组成(0 < n …