项目设计集合(人工智能方向):助力新人快速实战掌握技能、自主完成项目设计升级,提升自身的硬实力(不仅限NLP、知识图谱、计算机视觉等领域):汇总有意义的项目设计集合,助力新人快速实战掌握技能,助力用户更好利用 CSDN 平台,自主完成项目设计升级,提升自身的硬实力。

专栏订阅:项目大全提升自身的硬实力 [专栏详细介绍:项目设计集合(人工智能方向):助力新人快速实战掌握技能、自主完成项目设计升级,提升自身的硬实力(不仅限NLP、知识图谱、计算机视觉等领域)

基于知识图谱的电影知识问答系统:训练TF-IDF 向量算法和朴素贝叶斯分类器、在 Neo4j 中查询

1.项目介绍

训练 TF-IDF 向量算法和朴素贝叶斯分类器,预测用户文本所属的问题类别使用分词库解析用户文本词性,提取关键词结合关键词与问题类别,在 Neo4j 中查询问题的答案通过 Flask 对外提供 RESTful API前端交互与答案展示

2.项目实操教学

2.1 数据集简介

{

"introduction_by_movie": [

"nm简介",

"nm剧情简介",

"nm的内容是什么",

"nm讲了什么",

"nm讲了什么故事",

"nm演了什么",

"nm的故事梗概是什么",

"nm的剧情简介是什么",

"nm的内容简介是什么",

"nm的剧情介绍是什么",

"nm的情节是什么",

"nm的主要情节是什么"

],

"rating_by_movie": [

"nm的评分是多少",

"nm得了多少分",

"nm的评分有多少",

"nm的评分",

"nm得分是多少",

"nm的分数是",

"nm电影分数是多少",

"nm电影评分",

"nm评分",

"nm的分数是多少",

"nm这部电影的评分是多少"

],

"release_date_by_movie": [

"nm上映时间",

"nm定档时间",

"nm的上映时间是什么时候",

"nm的首映时间是什么时候",

"nm什么时候上映",

"nm什么时候首映",

"最早什么时候能看到nm",

"nm什么时候在影院上线",

"什么时候可以在影院看到nm",

"nm什么时候在影院放映",

"nm什么时候首播"

],

2.2 用户词典

Forrest Gump nm

Kill Bill: Vol. 1 nm

英雄 nm

Miami Vice nm

Indiana Jones and the Temple of Doom nm

卧虎藏龙 nm

Pirates of the Caribbean: At World's End nm

Kill Bill: Vol. 2 nm

The Matrix Reloaded nm

The Matrix Revolutions nm

Harry Potter and the Chamber of Secrets nm

Harry Potter and the Prisoner of Azkaban nm

Harry Potter and the Goblet of Fire nm

Harry Potter and the Order of the Phoenix nm

The Last Emperor nm

Harry Potter and the Half-Blood Prince nm

花样年华 nm

2046 nm

Lethal Weapon 4 nm

Hannibal Rising nm

TMNT nm

무사 nm

Anna and the King nm

满城尽带黄金甲 nm

2.3 环境依赖

jieba

neo4j

python-dotenv

scikit-learn

flask

flask-cors

gunicorn

2.4 部分代码展示

import os

from neo4j import GraphDatabase

class Database:

"""

Neo4j 数据库访问层。

管理数据库连接的生命周期,并提供查询接口。

"""

def __init__(self):

uri = os.environ["DATABASE_URI"]

user = os.environ["DATABASE_USER"]

password = os.environ["DATABASE_PASSWORD"]

try:

self._driver = GraphDatabase.driver(uri, auth=(user, password))

self._session = self._driver.session()

except Exception as e:

raise Exception("数据库连接失败") from e

def close(self):

try:

self._session.close()

self._driver.close()

except Exception as e:

raise Exception("数据库断开失败") from e

def find_one(self, query: str, **parameters):

result = self._session.run(query, parameters).single()

return result.value() if result else None

def find_many(self, query: str, **parameters):

return self._session.run(query, parameters).value()

if __name__ == "__main__":

import dotenv

dotenv.load_dotenv()

database = Database()

genres = database.find_many(

"""

MATCH (m:Movie)-[BELONGS_TO]->(g:Genre)

WHERE m.name = $movie_name

RETURN g.name

""",

movie_name="卧虎藏龙",

)

database.close()

print(genres)

import json

import os

import jieba

from sklearn.feature_extraction.text import TfidfVectorizer

from sklearn.naive_bayes import MultinomialNB

TRAIN_DATASET_PATH = os.path.join("data", "train.json")

jieba.setLogLevel("ERROR")

def normalize(sentence: str):

return " ".join(jieba.cut(sentence))

class BaseClassifier:

"""

底层分类器。

使用 TF-IDF 向量化文本,然后使用朴素贝叶斯预测标签。

"""

def __init__(self):

self._vectorizer = TfidfVectorizer()

self._classifier = MultinomialNB(alpha=0.01)

def _train(self, x: list, y: list):

X = self._vectorizer.fit_transform(x).toarray()

self._classifier.fit(X, y)

def _predict(self, x: list):

X = self._vectorizer.transform(x).toarray()

return self._classifier.predict(X)

class Classifier(BaseClassifier):

"""

问题分类器。

根据问题中出现的关键词,将问题归于某一已知类别下。

"""

def __init__(self):

BaseClassifier.__init__(self)

questions, labels = Classifier._read_train_dataset()

self._train(questions, labels)

def classify(self, sentence: str):

question = normalize(sentence)

return self._predict([question])[0]

@staticmethod

def _read_train_dataset():

with open(TRAIN_DATASET_PATH, "r", encoding="utf-8") as fr:

train_dataset: dict[str, list[str]] = json.load(fr)

questions = []

labels = []

for label, sentences in train_dataset.items():

questions.extend([normalize(sentence) for sentence in sentences])

labels.extend([label for _ in sentences])

return questions, labels

if __name__ == "__main__":

classifier = Classifier()

while True:

sentence = input("请输入问题:").strip()

label = classifier.classify(sentence)

print(f"问题分类:{label}")

2.5 运行项目

在 backend 目录下添加环境变量文件 .env。

# Neo4j 数据库地址

DATABASE_URI=

# Neo4j 用户名

DATABASE_USER=

# Neo4j 密码

DATABASE_PASSWORD=

启动后端服务。

cd backend

gunicorn app:app

在 frontend 目录下添加环境变量文件 .env。

# 后端服务地址

VITE_API_BASE_URL=

启动前端服务。

cd frontend

npm build

npm preview

3.技术栈

3.1数据库

Neo4j

3.2核心 QA 模块

Python Scikit-learn Jieba

3.3后端

Python Flask Render

3.4前端

TypeScript Preact Tailwind CSS pnpm Vite ESLint Prettier

项目码源见文章顶部or文末

https://download.csdn.net/download/sinat_39620217/87990788

相关文章

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: