我有2个尺寸为6的向量。
a=c("HDa","2Pb","2","BxU","BuQ","Bve")
b=c("HCK","2Pb","2","09","F","G")
任何人都可以解释我应该做什么吗?
答案 0 :(得分:4)
使用lsa
包和此包的手册
# create some files
library('lsa')
td = tempfile()
dir.create(td)
write( c("HDa","2Pb","2","BxU","BuQ","Bve"), file=paste(td, "D1", sep="/"))
write( c("HCK","2Pb","2","09","F","G"), file=paste(td, "D2", sep="/"))
# read files into a document-term matrix
myMatrix = textmatrix(td, minWordLength=1)
编辑:显示mymatrix
对象
myMatrix
#myMatrix
# docs
# terms D1 D2
# 2 1 1
# 2pb 1 1
# buq 1 0
# bve 1 0
# bxu 1 0
# hda 1 0
# 09 0 1
# f 0 1
# g 0 1
# hck 0 1
# Calculate cosine similarity
res <- lsa::cosine(myMatrix[,1], myMatrix[,2])
res
#0.3333
答案 1 :(得分:1)
首先需要一个可能术语的字典,然后将你的矢量转换为二进制矢量,相应术语的位置为1,其他位置为0。如果您为新向量a2
和b2
命名,则可以使用cor(a2, b2)
类似地计算余弦,但请注意余弦类似于介于-1和1之间。您可以将其映射到[0 ,1]有这样的事情:0.5*cor(a2, b2) + 0.5
答案 2 :(得分:1)
CSString_vector <- c("Hi Hello","Hello");
corp <- tm::VCorpus(VectorSource(CSString_vector));
controlForMatrix <- list(removePunctuation = TRUE,wordLengths = c(1, Inf), weighting = weightTf)
dtm <- DocumentTermMatrix(corp,control = controlForMatrix);
matrix_of_vector = as.matrix(dtm);
res <- lsa::cosine(matrix_of_vector[1,], matrix_of_vector[2,]);
对于较大的数据集,可能是更好的数据集。
答案 3 :(得分:0)
高级形式的嵌入可能会帮助您获得更好的输出。请检查以下代码。 它是一种通用句子编码模型,使用基于转换器的架构生成句子嵌入。
from absl import logging
import tensorflow as tf
import tensorflow_hub as hub
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import re
import seaborn as sns
module_url = "https://tfhub.dev/google/universal-sentence-encoder/4"
model = hub.load(module_url)
print ("module %s loaded" % module_url)
def embed(input):
return model([input])
paragraph = [
"Universal Sentence Encoder embeddings also support short paragraphs. ",
"Universal Sentence Encoder support paragraphs"]
messages = [paragraph]
print(np.inner( embed(paragraph[0]) , embed(paragraph[1])))