国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

????探索人工智能的世界:構(gòu)建智能問答系統(tǒng)之實(shí)戰(zhàn)篇

這篇具有很好參考價(jià)值的文章主要介紹了????探索人工智能的世界:構(gòu)建智能問答系統(tǒng)之實(shí)戰(zhàn)篇。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

引言

前面我們已經(jīng)做好了必要的準(zhǔn)備工作,包括對(duì)相關(guān)知識(shí)點(diǎn)的了解以及環(huán)境的安裝。今天我們將重點(diǎn)關(guān)注代碼方面的內(nèi)容。如果你已經(jīng)具備了Java編程基礎(chǔ),那么理解Python語法應(yīng)該不會(huì)成為問題,畢竟只是語法的差異而已。隨著時(shí)間的推移,你自然會(huì)逐漸熟悉和掌握這門語言?,F(xiàn)在讓我們開始吧!

環(huán)境安裝命令

在使用之前,我們需要先進(jìn)行一些必要的準(zhǔn)備工作,其中包括執(zhí)行一些命令。如果你已經(jīng)仔細(xì)閱讀了Milvus的官方文檔,你應(yīng)該已經(jīng)了解到了這一點(diǎn)。下面是需要執(zhí)行的一些命令示例:

pip3 install langchain

pip3 install openai

pip3 install protobuf==3.20.0

pip3 install grpcio-tools

python3 -m pip install pymilvus==2.3.2

python3 -c "from pymilvus import Collection"

快速入門

現(xiàn)在,我們來嘗試使用官方示例,看看在沒有集成LangChain的情況下,我們需要編寫多少代碼才能完成插入、查詢等操作。官方示例已經(jīng)在前面的注釋中詳細(xì)講解了所有的流程??傮w流程如下:

  1. 連接到數(shù)據(jù)庫
  2. 創(chuàng)建集合(這里還有分區(qū)的概念,我們不深入討論)
  3. 插入向量數(shù)據(jù)(我看官方文檔就簡單插入了一些數(shù)字...)
  4. 創(chuàng)建索引(根據(jù)官方文檔的說法,通常在一定數(shù)據(jù)量下是不會(huì)經(jīng)常創(chuàng)建索引的)
  5. 查詢數(shù)據(jù)
  6. 刪除數(shù)據(jù)
  7. 斷開與數(shù)據(jù)庫的連接

通過以上步驟,你會(huì)發(fā)現(xiàn)與連接MySQL數(shù)據(jù)庫的操作非常相似。

# hello_milvus.py demonstrates the basic operations of PyMilvus, a Python SDK of Milvus.
# 1. connect to Milvus
# 2. create collection
# 3. insert data
# 4. create index
# 5. search, query, and hybrid search on entities
# 6. delete entities by PK
# 7. drop collection
import time

import numpy as np
from pymilvus import (
    connections,
    utility,
    FieldSchema, CollectionSchema, DataType,
    Collection,
)

fmt = "\n=== {:30} ===\n"
search_latency_fmt = "search latency = {:.4f}s"
num_entities, dim = 3000, 8

#################################################################################
# 1. connect to Milvus
# Add a new connection alias `default` for Milvus server in `localhost:19530`
# Actually the "default" alias is a buildin in PyMilvus.
# If the address of Milvus is the same as `localhost:19530`, you can omit all
# parameters and call the method as: `connections.connect()`.
#
# Note: the `using` parameter of the following methods is default to "default".
print(fmt.format("start connecting to Milvus"))
connections.connect("default", host="localhost", port="19530")

has = utility.has_collection("hello_milvus")
print(f"Does collection hello_milvus exist in Milvus: {has}")

#################################################################################
# 2. create collection
# We're going to create a collection with 3 fields.
# +-+------------+------------+------------------+------------------------------+
# | | field name | field type | other attributes |       field description      |
# +-+------------+------------+------------------+------------------------------+
# |1|    "pk"    |   VarChar  |  is_primary=True |      "primary field"         |
# | |            |            |   auto_id=False  |                              |
# +-+------------+------------+------------------+------------------------------+
# |2|  "random"  |    Double  |                  |      "a double field"        |
# +-+------------+------------+------------------+------------------------------+
# |3|"embeddings"| FloatVector|     dim=8        |  "float vector with dim 8"   |
# +-+------------+------------+------------------+------------------------------+
fields = [
    FieldSchema(name="pk", dtype=DataType.VARCHAR, is_primary=True, auto_id=False, max_length=100),
    FieldSchema(name="random", dtype=DataType.DOUBLE),
    FieldSchema(name="embeddings", dtype=DataType.FLOAT_VECTOR, dim=dim)
]

schema = CollectionSchema(fields, "hello_milvus is the simplest demo to introduce the APIs")

print(fmt.format("Create collection `hello_milvus`"))
hello_milvus = Collection("hello_milvus", schema, consistency_level="Strong")

################################################################################
# 3. insert data
# We are going to insert 3000 rows of data into `hello_milvus`
# Data to be inserted must be organized in fields.
#
# The insert() method returns:
# - either automatically generated primary keys by Milvus if auto_id=True in the schema;
# - or the existing primary key field from the entities if auto_id=False in the schema.

print(fmt.format("Start inserting entities"))
rng = np.random.default_rng(seed=19530)
entities = [
    # provide the pk field because `auto_id` is set to False
    [str(i) for i in range(num_entities)],
    rng.random(num_entities).tolist(),  # field random, only supports list
    rng.random((num_entities, dim)),  # field embeddings, supports numpy.ndarray and list
]

insert_result = hello_milvus.insert(entities)

hello_milvus.flush()
print(f"Number of entities in Milvus: {hello_milvus.num_entities}")  # check the num_entities

################################################################################
# 4. create index
# We are going to create an IVF_FLAT index for hello_milvus collection.
# create_index() can only be applied to `FloatVector` and `BinaryVector` fields.
print(fmt.format("Start Creating index IVF_FLAT"))
index = {
    "index_type": "IVF_FLAT",
    "metric_type": "L2",
    "params": {"nlist": 128},
}

hello_milvus.create_index("embeddings", index)

################################################################################
# 5. search, query, and hybrid search
# After data were inserted into Milvus and indexed, you can perform:
# - search based on vector similarity
# - query based on scalar filtering(boolean, int, etc.)
# - hybrid search based on vector similarity and scalar filtering.
#

# Before conducting a search or a query, you need to load the data in `hello_milvus` into memory.
print(fmt.format("Start loading"))
hello_milvus.load()

# -----------------------------------------------------------------------------
# search based on vector similarity
print(fmt.format("Start searching based on vector similarity"))
vectors_to_search = entities[-1][-2:]
search_params = {
    "metric_type": "L2",
    "params": {"nprobe": 10},
}

start_time = time.time()
result = hello_milvus.search(vectors_to_search, "embeddings", search_params, limit=3, output_fields=["random"])
end_time = time.time()

for hits in result:
    for hit in hits:
        print(f"hit: {hit}, random field: {hit.entity.get('random')}")
print(search_latency_fmt.format(end_time - start_time))

# -----------------------------------------------------------------------------
# query based on scalar filtering(boolean, int, etc.)
print(fmt.format("Start querying with `random > 0.5`"))

start_time = time.time()
result = hello_milvus.query(expr="random > 0.5", output_fields=["random", "embeddings"])
end_time = time.time()

print(f"query result:\n-{result[0]}")
print(search_latency_fmt.format(end_time - start_time))

# -----------------------------------------------------------------------------
# pagination
r1 = hello_milvus.query(expr="random > 0.5", limit=4, output_fields=["random"])
r2 = hello_milvus.query(expr="random > 0.5", offset=1, limit=3, output_fields=["random"])
print(f"query pagination(limit=4):\n\t{r1}")
print(f"query pagination(offset=1, limit=3):\n\t{r2}")

# -----------------------------------------------------------------------------
# hybrid search
print(fmt.format("Start hybrid searching with `random > 0.5`"))

start_time = time.time()
result = hello_milvus.search(vectors_to_search, "embeddings", search_params, limit=3, expr="random > 0.5",
                             output_fields=["random"])
end_time = time.time()

for hits in result:
    for hit in hits:
        print(f"hit: {hit}, random field: {hit.entity.get('random')}")
print(search_latency_fmt.format(end_time - start_time))

###############################################################################
# 6. delete entities by PK
# You can delete entities by their PK values using boolean expressions.
ids = insert_result.primary_keys

expr = f'pk in ["{ids[0]}" , "{ids[1]}"]'
print(fmt.format(f"Start deleting with expr `{expr}`"))

result = hello_milvus.query(expr=expr, output_fields=["random", "embeddings"])
print(f"query before delete by expr=`{expr}` -> result: \n-{result[0]}\n-{result[1]}\n")

hello_milvus.delete(expr)

result = hello_milvus.query(expr=expr, output_fields=["random", "embeddings"])
print(f"query after delete by expr=`{expr}` -> result: {result}\n")

###############################################################################
# 7. drop collection
# Finally, drop the hello_milvus collection
print(fmt.format("Drop collection `hello_milvus`"))
utility.drop_collection("hello_milvus")

升級(jí)版

現(xiàn)在,讓我們來看一下使用LangChain版本的代碼。由于我們使用的是封裝好的Milvus,所以我們需要一個(gè)嵌入模型。在這里,我們選擇了HuggingFaceEmbeddings中的sensenova/piccolo-base-zh模型作為示例,當(dāng)然你也可以選擇其他模型,這里沒有限制。只要能將其作為一個(gè)變量傳遞給LangChain定義的函數(shù)調(diào)用即可。

下面是一個(gè)簡單的示例,包括數(shù)據(jù)庫連接、插入數(shù)據(jù)、查詢以及得分情況的定義:

from langchain.embeddings import HuggingFaceEmbeddings
from langchain.vectorstores import Milvus 


model_name = "sensenova/piccolo-base-zh"
embeddings = HuggingFaceEmbeddings(model_name=model_name) 

print("鏈接數(shù)據(jù)庫")
vector_db = Milvus(
    embeddings,
    connection_args={"host": "localhost", "port": "19530"},
    collection_name="hello_milvus",
) 
print("簡單傳入幾個(gè)值")
vector_db.add_texts(["12345678","789","努力的小雨是一個(gè)知名博主,其名下有公眾號(hào)【靈墨AI探索室】,博客:稀土掘金、博客園、51CTO及騰訊云等","你好啊","我不好"])

print("查詢前3個(gè)最相似的結(jié)果")
docs = vector_db.similarity_search_with_score("你好啊",3)

print("查看其得分情況,分值越低越接近")
for text in docs:
    print('文本:%s,得分:%s'%(text[0].page_content,text[1]))

????探索人工智能的世界:構(gòu)建智能問答系統(tǒng)之實(shí)戰(zhàn)篇

注意,以上代碼只是一個(gè)簡單示例,具體的實(shí)現(xiàn)可能會(huì)根據(jù)你的具體需求進(jìn)行調(diào)整和優(yōu)化。

在langchain版本的代碼中,如果你想要執(zhí)行除了自己需要開啟docker中的milvus容器之外的操作,還需要確保你擁有網(wǎng)絡(luò)代理。這里不多贅述,因?yàn)镠uggingFace社區(qū)并不在國內(nèi)。

個(gè)人定制版

接下來,我們將詳細(xì)了解如何調(diào)用openai模型來回答問題!

from dotenv import load_dotenv
from langchain.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate; 
from langchain import PromptTemplate
from langchain.chains import LLMChain 
from langchain.chat_models.openai import ChatOpenAI 
from langchain.schema import BaseOutputParser

# 加載env環(huán)境變量里的key值
load_dotenv()
# 格式化輸出
class CommaSeparatedListOutputParser(BaseOutputParser):
    """Parse the output of an LLM call to a comma-separated list."""

    def parse(self, text: str):
        """Parse the output of an LLM call."""
        return text.strip().split(", ")
# 先從數(shù)據(jù)庫查詢問題解
docs = vector_db.similarity_search("努力的小雨是誰?")
doc = docs[0].page_content

chat = ChatOpenAI(model_name='gpt-3.5-turbo', temperature=0)
template = "請根據(jù)我提供的資料回答問題,資料: {input_docs}"
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
human_template = "{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)

chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])

# chat_prompt.format_messages(input_docs=doc, text="努力的小雨是誰?")
chain = LLMChain(
    llm=chat,
    prompt=chat_prompt,
    output_parser=CommaSeparatedListOutputParser()
)
chain.run(input_docs=doc, text="努力的小雨是誰?") 

當(dāng)你成功運(yùn)行完代碼后,你將會(huì)得到你所期望的答案。如下圖所示,這些答案將會(huì)展示在你的屏幕上。不然,如果系統(tǒng)不知道這些問題的答案,那它又如何能夠給出正確的回答呢?

????探索人工智能的世界:構(gòu)建智能問答系統(tǒng)之實(shí)戰(zhàn)篇

總結(jié)

通過本系列文章的學(xué)習(xí),我們已經(jīng)對(duì)個(gè)人或企業(yè)知識(shí)庫有了一定的了解。盡管OpenAI已經(jīng)提供了私有知識(shí)庫的部署選項(xiàng),但是其高昂的成本對(duì)于一些企業(yè)來說可能是難以承受的。無論將來國內(nèi)企業(yè)是否會(huì)提供個(gè)人或企業(yè)知識(shí)庫的解決方案,我們都需要對(duì)其原理有一些了解。無論我們的預(yù)算多少,都可以找到適合自己的玩法,因?yàn)椴煌A(yù)算的玩法也會(huì)有所不同。文章來源地址http://www.zghlxwxcb.cn/news/detail-746340.html

到了這里,關(guān)于????探索人工智能的世界:構(gòu)建智能問答系統(tǒng)之實(shí)戰(zhàn)篇的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • 免費(fèi)的chartGPT 人工智能機(jī)器人問答展示

    免費(fèi)的chartGPT 人工智能機(jī)器人問答展示

    ??無意中發(fā)現(xiàn)一個(gè)特別好用的AI工具,試著問了幾個(gè)最近一直困擾我的小孩子的幼小銜接的問題,發(fā)現(xiàn)比度娘好用。給出的答案更加智能,還可以免費(fèi)試用。 對(duì)于日常的一些問題,回答更具針對(duì)性 ? ?日常寫代碼也能輕松搞定 ?人工智能是一種讓計(jì)算機(jī)系統(tǒng)具備智能的技術(shù)和

    2024年02月07日
    瀏覽(31)
  • 探索人工智能:深度學(xué)習(xí)、人工智能安全和人工智能編程(文末送書)

    探索人工智能:深度學(xué)習(xí)、人工智能安全和人工智能編程(文末送書)

    人工智能知識(shí)對(duì)于當(dāng)今的互聯(lián)網(wǎng)技術(shù)人來說已經(jīng)是剛需。但人工智能的概念、流派、技術(shù)紛繁復(fù)雜,選擇哪本書入門最適合呢? 這部被譽(yù)為人工智能“百科全書”的《人工智能(第3版)》,可以作為每個(gè)技術(shù)人進(jìn)入 AI 世界的第一本書。 購書鏈接,限時(shí)特惠5折 這本書是美國

    2024年02月03日
    瀏覽(53)
  • AI眼中的世界 ——人工智能繪畫入門

    AI眼中的世界 ——人工智能繪畫入門

    目錄 什么是Disco Diffusion? 如何使用Disco Diffusion? 正文 準(zhǔn)備工作 入門教程 開始行動(dòng)? 默認(rèn)跑一個(gè)默認(rèn)的描述A?beautiful?painting?of?a?singular?lighthouse,?shining?its?light?across?a?tumultuous?sea?of?blood?by?greg?rutkowski?and?thomas?kinkade,?Trending?on?artstation.?編輯 ?查看云端硬盤 ?編

    2023年04月16日
    瀏覽(23)
  • 從AI人工智能LLM大型語言模型到通用人工智能AGI “世界模型”的演進(jìn)路徑

    近年來,人工智能技術(shù)取得了飛速的發(fā)展,各種領(lǐng)域都出現(xiàn)了涉及人工智能的應(yīng)用。大型語言模型(Large Language Model, LLM)作為其中一種重要的技術(shù)手段,已成為當(dāng)前自然

    2024年02月08日
    瀏覽(111)
  • 世界人工智能三要素:數(shù)據(jù)、算力和算法

    世界人工智能三要素:數(shù)據(jù)、算力和算法

    隨著我國社會(huì)經(jīng)濟(jì)發(fā)展水平的提升,人工智能的技術(shù)運(yùn)用的越來越熟練,智能推送等應(yīng)用已經(jīng)悄無聲息的滲透到了我們的生活之中,今天我們就來聊一聊,人工智能的三大要素。 1.數(shù)據(jù) 實(shí)現(xiàn)人工智能的首要因素是數(shù)據(jù),數(shù)據(jù)是一切智慧物體的學(xué)習(xí)資源,沒有了數(shù)據(jù),任何智慧

    2024年02月13日
    瀏覽(18)
  • 人工智能圖——未來世界的指南針

    人工智能(Artificial Intelligence,AI)作為當(dāng)今科技領(lǐng)域的重要研究方向之一,正在成為社會(huì)、經(jīng)濟(jì)、安全和政治等多個(gè)領(lǐng)域的核心驅(qū)動(dòng)力。人工智能圖作為AI時(shí)代的新興產(chǎn)物,被認(rèn)為能夠成為未來世界的指南針。 一、人工智能圖的定義 人工智能圖(Artificial Intelligence Image,AII)是指

    2024年02月12日
    瀏覽(20)
  • 邁向多模態(tài)AGI之開放世界目標(biāo)檢測 | 人工智能

    邁向多模態(tài)AGI之開放世界目標(biāo)檢測 | 人工智能

    作者: 王斌 謝春宇 冷大煒 引言 目標(biāo)檢測是計(jì)算機(jī)視覺中的一個(gè)非常重要的基礎(chǔ)任務(wù),與常見的的圖像分類/識(shí)別任務(wù)不同,目標(biāo)檢測需要模型在給出目標(biāo)的類別之上,進(jìn)一步給出目標(biāo)的位置和大小信息,在CV三大任務(wù)(識(shí)別、檢測、分割)中處于承上啟下的關(guān)鍵地位。當(dāng)前

    2024年02月16日
    瀏覽(22)
  • 揭秘人工智能:探索智慧未來

    揭秘人工智能:探索智慧未來

    ??個(gè)人主頁: 聆風(fēng)吟 ??系列專欄: 數(shù)據(jù)結(jié)構(gòu)、網(wǎng)絡(luò)奇遇記 ??少年有夢不應(yīng)止于心動(dòng),更要付諸行動(dòng)。 人工智能是一種模擬人類智能的技術(shù),目的是讓計(jì)算機(jī)可以像人類一樣進(jìn)行學(xué)習(xí)、推理、感知、理解和創(chuàng)造等活動(dòng)。近年來,人工智能技術(shù)已經(jīng)在各個(gè)領(lǐng)域取得了顯著進(jìn)

    2024年02月03日
    瀏覽(94)
  • 【人工智能】大模型的本質(zhì)是這個(gè)世界抽象出來的函數(shù)

    【人工智能】大模型的本質(zhì)是這個(gè)世界抽象出來的函數(shù)

    模型是機(jī)器學(xué)習(xí)中的一個(gè)重要概念,它是指對(duì)數(shù)據(jù)進(jìn)行學(xué)習(xí)和預(yù)測的數(shù)學(xué)模型。在機(jī)器學(xué)習(xí)中,模型的本質(zhì)是函數(shù),本文將從函數(shù)的角度出發(fā),對(duì)模型的本質(zhì)進(jìn)行展開講解。

    2024年02月06日
    瀏覽(29)
  • 亞商投資顧問 早餐FM/07062023世界人工智能大會(huì)啟幕

    01/ 亞商投資顧問 早間導(dǎo)讀 1.2023世界人工智能大會(huì)今日在滬啟幕 2.工信部:加快大數(shù)據(jù)、人工智能、智能網(wǎng)聯(lián)汽車等戰(zhàn)略性新興產(chǎn)業(yè)創(chuàng)新發(fā)展 3.浙江:支持平臺(tái)企業(yè)科技創(chuàng)新 優(yōu)化人工智能算力平臺(tái)布局 02/ 亞商投資顧問 新聞早餐 // ?熱點(diǎn)聚焦 ?// 1.7月6日,2023世界人工智能大

    2024年02月12日
    瀏覽(16)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包