1 Star 0 Fork 248

离留O/OPTIMAL_KNN_MNIST_QUESTION_1

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
optimal_knn_webapp_pinecone.py 1.27 KB
一键复制 编辑 原始数据 按行查看 历史
田玉汉 提交于 2024-09-22 17:54 +08:00 . added a file
import numpy as np
import joblib
import gradio as gr
from PIL import Image
import os
from pinecone import Pinecone
# 创建 Pinecone 实例
pc = Pinecone(api_key="e97e2b32-22d1-4eb0-bbd3-02d95c2484ce")
# 连接到已创建的索引
index_name = "mnist-index"
index = pc.Index(index_name)
# 加载保存的 KNN 模型
model = joblib.load('best_knn_model.pkl')
# 预处理图像
def preprocess_image(image):
image = Image.fromarray(image)
image = image.convert("L") # 转换为灰度图
image = image.resize((8, 8)) # 调整大小为 8x8
image = np.array(image).flatten() # 扁平化
image = image / 16.0 # 归一化
return image
# 定义使用 Pinecone 的预测函数
def predict_digit(image):
# 预处理输入图像
image = preprocess_image(image)
vector = image.flatten().tolist() # 将图像扁平化为列表
# 使用 Pinecone 获取预测结果
response = index.query(vector=vector, top_k=1) # 查询 Pinecone 获取最近邻
prediction = response['matches'][0]['id'] # 获取预测的数字 ID
return int(prediction)
iface = gr.Interface(fn=predict_digit,
inputs=gr.Sketchpad(shape=(28, 28), label="在此处手写数字"),
outputs='label')
# 启动 Gradio 接口
iface.launch(share=True)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/leaving-and-retaining-o/optimal_knn_mnist_question_1.git
git@gitee.com:leaving-and-retaining-o/optimal_knn_mnist_question_1.git
leaving-and-retaining-o
optimal_knn_mnist_question_1
OPTIMAL_KNN_MNIST_QUESTION_1
main

搜索帮助