当前位置: 首页 > news >正文

实现自学习系统,输入excel文件,能学习后进行相应回答

import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity
from sentence_transformers import SentenceTransformer'''
效果理想
'''class SelfLearningQASystem:def __init__(self, excel_path):# 读取Excel文件self.df = pd.read_excel(excel_path)# 假定有 'question' 和 'answer' 两列self.questions = self.df['question'].astype(str).tolist()self.answers = self.df['answer'].astype(str).tolist()# 使用预训练的多语言句子嵌入模型self.model = SentenceTransformer(r'D:\modelproject\paraphrase-multilingual-MiniLM-L12-v2')# 将所有问题向量化self.question_vectors = self.model.encode(self.questions)def ask(self, user_question):# 将用户问题向量化user_vector = self.model.encode(user_question)# 确保向量是二维的if len(user_vector.shape) == 1:user_vector = user_vector.reshape(1, -1)# 如果question_vectors是一维的,转换为二维question_vectors = self.question_vectorsif len(question_vectors.shape) == 1:question_vectors = question_vectors.reshape(1, -1)# 计算用户问题与所有已有问题的相似度similarities = cosine_similarity(user_vector, question_vectors)# print(similarities)# 找出最相似的问题的索引most_similar_idx = similarities.argmax()# print(most_similar_idx)max_similarity = similarities[0, most_similar_idx]print("问题相似度",max_similarity)# 可选择设置一个阈值,低于则认为没有匹配到threshold = 0.5  # 可调,根据实际情况调整if max_similarity < threshold:return "抱歉,我暂时无法回答这个问题。您可以更新我的知识库。"# 返回最相似问题对应的答案return self.answers[most_similar_idx]def add_qa_pair(self, new_question, new_answer, excel_path=None):# 自学习追加# 追加到内存self.questions.append(new_question)self.answers.append(new_answer)# 重新训练向量化self.question_vectors = self.model.encode(self.questions)# 可选:将新数据写入 Excelif excel_path:new_data = pd.DataFrame({'question': [new_question],'answer': [new_answer]})try:existing = pd.read_excel(excel_path)updated = pd.concat([existing, new_data], ignore_index=True)updated.to_excel(excel_path, index=False)except FileNotFoundError:new_data.to_excel(excel_path, index=False)if __name__ == "__main__":# 初始化问答系统,传入你的Excel路径inputfile = "input.xlsx"qa_system = SelfLearningQASystem(inputfile)qa_system.add_qa_pair("今天周几","星期三",inputfile)print("=== 欢迎使用自学习问答系统,输入 '退出' 结束对话 ===")while True:user_input = input("\n你:")if user_input.strip() in ['退出', 'exit', 'quit']:print("系统:再见!")breakanswer = qa_system.ask(user_input)print(f"系统:{answer}")
http://www.dtcms.com/a/337103.html

相关文章:

  • 香港服务器是否支持RAID磁盘阵列?
  • RTSP 播放器 vs RTMP 播放器:延迟对比与技术实践
  • HAProxy使用方法以及和LVS区别
  • 【数据库】Navicat 导入 Excel 数据乱码问题的解决方法
  • NY291NY297美光固态闪存NY298NY303
  • Jina Embeddings:高性能多模态向量模型的演进之路
  • Minitab AI 加持的头脑风暴法,破解企业改进难题
  • 驱动开发系列64 - glCompileShader实现之 GLSL normalize 精度优化
  • Linux 中断机制深度分析
  • SpatialLLM,SpatialReasoner,SpatialLM论文解读
  • 云原生事件驱动引擎(RocketMQ-EventBridge)应用场景与技术解析
  • 01数据结构-交换排序
  • 【EI会议征稿通知】第五届高性能计算、大数据与通信工程国际学术会议(ICHBC 2025)
  • 蓝桥杯算法之搜索章 - 6
  • LeetCode热题100--226. 翻转二叉树--简单
  • SSH 登录失败(publickey)问题总结
  • 【具身智能】2025:具身智能机器人量产元年——AI与物理世界的融合革命
  • UE TCP通信
  • FTP服务器
  • 【Python面试题】写一个用元类(metaclass)实现API接口自动注册的Demo。以及装饰器在项目中典型应用场景。
  • Unity进阶--C#补充知识点--【Unity跨平台的原理】Mono与IL2CPP
  • 继承中的向上转型、向下转型与动态绑定的深入解析
  • 【案例分享】AI使用分享|如何运用 GPT完成小任务并提升效率 —— Prompt 与案例整理
  • 跨平台笔记协作:cpolar 提升 Obsidian 知识库共享效率方案
  • 基于ssm jsp中学校园网站源码和答辩PPT论文
  • vue的双向数据绑定
  • 哪里找最新AI工具官网?如何快速对比ChatGPT替代品?AI工具导航指南 - AIbase
  • 基于Spring Boot+Vue的社区便民服务平台 智慧社区平台 志愿者服务管理
  • [矩阵置零]
  • 快速搭建项目(若依)