python中怎么用url路径调用本地python训练好的模型
时间: 2024-12-13 14:28:21 浏览: 18
Python中调用本地训练好的模型通常涉及到序列化模型为可读文件(如pickle、onnx、h5等),然后通过HTTP或类似的协议发送请求。这里以假设你有一个训练好的模型文件(比如.onnx)为例:
1. 序列化模型[^1]:
```python
import pickle
model = YourTrainedModel() # 假设YourTrainedModel是你的模型类
with open('model.pkl', 'wb') as f:
pickle.dump(model, f)
```
2. 创建一个简单的服务器来接收请求并加载模型:
```python
from http.server import BaseHTTPRequestHandler, HTTPServer
class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/predict':
with open('model.pkl', 'rb') as f:
loaded_model = pickle.load(f)
# 这里模拟预测逻辑,实际替换为模型预测
prediction = loaded_model.predict_data()
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(bytes(str(prediction), "utf8"))
def run(server_class=HTTPServer, handler_class=RequestHandler, port=8000):
server_address = ('', port)
httpd = server_class(server_address, handler_class)
print(f'Starting server at {server_address[0]}:{server_address[1]}...')
httpd.serve_forever()
run()
```
3. 调用本地服务器:
```shell
# 在终端中运行
$ curl -X GET http://localhost:8000/predict
```
这会返回模型对输入的预测结果。注意,这只是一个基本示例,实际应用可能需要更复杂的设置,例如多线程、错误处理等。
阅读全文