数据挖掘二:相似文章推荐

文章目录

相似文章推荐

在用户阅读谋篇文章的时候,为用户推荐更多与在读文章内容相似的文章

概念

推荐
指介绍好的人或事物,希望被任用或接受。数据挖掘领域,推荐包括相似推荐以及协同过滤推荐
相似推荐
指当用户表现出对某人或者某物的兴趣时,为它推荐与之相类似的人或者物,核心定理:人以群分,物以类聚
协同过滤推荐
指利用已有的用户群过去的行为或意见,预测当前用户最可能喜欢哪些东西或对哪些东西感兴趣

余弦相似度

用向量空间中两个向量夹角的余弦值作为衡量两个个体间差异的大小。余弦值越接近1,就表示夹角越接近0度,也就是两个向量越相似,这个特征也叫“余弦相似性”

余弦相似度

案例
1. 文章A   放假我喜欢弹吉他,看书
2. 文章B   放假我不喜欢看书,喜欢打球
计算过程
1. 分词
    1. 文章A    放假 我 喜欢 弹 吉他 看书
    2. 文章B    放假 我 不 喜欢 看书 喜欢 打球
2. 语料库
            放假 我 喜欢 弹 吉他 看书 不 打球
3. 向量化(词频统计)
    文章A   [1   1  1    1  1    1    0  0]
    文章B   [1   1  2    0  0    1    1  1]
4. 计算余弦相似度

import codecs
import os
import jieba
import numpy
import pandas
import re
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics import pairwise_distances

# 导入停顿词
pause = pandas.read_csv("./file/StopwordsCN.txt")
# 中文正则
zh_pattern = re.compile(u'[\u4e00-\u9fa5]')

file_paths = []
file_contents = []
# 递归获取所有文章并分词
for root, dirs, files in os.walk("./file/2.1/SogouC.mini/Sample"):
    for file in files:
        # 文件路径
        file_path = os.path.join(root, file)
        # 文件流句柄
        f_handle = codecs.open(file_path, "r", "utf-8")
        # 文件内容
        file_content = f_handle.read()
        # 关闭文件
        f_handle.close()
        content = ''

        # 分词
        for segment in jieba.cut(file_content):
            if zh_pattern.search(segment) and segment not in pause.stopword.values and len(segment.strip().strip(b'\x00'.decode())) > 0:
                content = content + " " + segment

        file_paths.append(file_path)
        file_contents.append(content)

# 文章路径和文章内容分词拼接后的数据矿
file_data_frame = pandas.DataFrame({
    'file_path': file_paths,
    'file_content': file_contents
})

# TF-IDF矩阵
tfidf = CountVectorizer().fit_transform(file_data_frame['file_content'])

# 相似度
distance_matrix = pairwise_distances(
    tfidf,
    metric="cosine"
)

# 相似度数据矿,为了方便计算,相似度取反
distance_matrix_data_frame = 1 - pandas.DataFrame(distance_matrix)
distance_matrix_data_frame.columns = file_paths
distance_matrix_data_frame.index = file_paths

# 对相似度数据矿进行倒序,然后取前五列
TFIDFSorted = numpy.argsort(distance_matrix, axis=1)[:, 1:6]
# 取出每个相似度对应的文章路径
similarity5 = pandas.Index(file_paths)[TFIDFSorted].values
# 组成文章与其最为相似的五个文章路径的数据矿
similarityDF = pandas.DataFrame({
    'file_paths': file_paths,
    's1': similarity5[:, 0],
    's2': similarity5[:, 1],
    's3': similarity5[:, 2],
    's4': similarity5[:, 3],
    's5': similarity5[:, 4],
})
原文链接:,转发请注明来源!
评论已关闭。