当前位置:网站首页>钻石价格预测的ML全流程!从模型构建调优道部署应用!
钻石价格预测的ML全流程!从模型构建调优道部署应用!
2022-08-10 08:39:00 【ShowMeAI】
作者:韩信子@ShowMeAI 数据分析 ◉ 技能提升系列:http://www.showmeai.tech/tutorials/33 AI 面试题库系列:http://www.showmeai.tech/tutorials/48 本文地址:http://www.showmeai.tech/article-detail/302 声明:版权所有,转载请联系平台与作者并注明出处 收藏ShowMeAI查看更多精彩内容
我们经常会谈到工业界端到端的机器学习建模,所谓端到端,是指的把整个过程构建在一个完整的流程(比如pipeline管道)中,包括数据侧的处理、模型建模调优,及模型部署应用等环节,如我们之前所说,完整的机器学习开发流程如下:
在本篇内容中,ShowMeAI将给大家讲解到下述内容:
- 使用 PyCaret 构建端到端机器学习管道
- ML 模型部署 & FastAPI 开发实时预测
工具库
PyCaret
PyCaret 是一个开源的低代码机器学习库,内置Python端到端模型管理工具,被用于自动化机器学习工作流。因其易用性、简单性以及快速高效地构建和部署端到端 ML 原型的能力而广受欢迎。
更多有关 PyCaret 的信息,可以在官方 GitHub 查看。
我们先通过 pip 安装 pycaret 工具库:
pip install pycaretFastAPI
FastAPI 是一个快速(高性能)的Web框架,主要特点是:
- 快速 :非常高的性能,是目前可用的最快的 Python 框架之一 。
- 快速编码 :将开发速度提高2到3倍。
- 简单 :易于学习和使用。
更多有关 FastAPI 的信息,请查看官方 GitHub 。
我们也通过 pip 安装 fastapi:
pip install fastapi业务背景
本篇内容中涉及的案例来自达顿商学院(案例研究发表在 哈佛商学院),案例中收集了 6000 颗钻石的数据,包括它们的价格和切工、颜色、形状等属性。
数据
我们在本篇内容中,使用钻石的克拉重量、切工、颜色和其他特征等属性来预测钻石的价格。 数据集可从 此处下载。
# 加载数据
from pycaret.datasets import get_data
data = get_data('diamond')探索性数据分析
我们先做一些快速数据分析和可视化来评估数据字段属性(重量、切工、颜色、净度等)与目标变量/标签Price的关系。
# 绘制carat_weight和Price的散点图
import plotly.express as px
fig = px.scatter(x=data['Carat Weight'], y=data['Price'], facet_col = data['Cut'], opacity = 0.25, template = 'plotly_dark', trendline='ols', trendline_color_override = 'red', title = 'SARAH GETS A DIAMOND - A CASE STUDY')
fig.show()我们绘制并了解一下目标变量Price的分布。
# 绘制灰度图查看分布
fig = px.histogram(data, x=["Price"], template = 'plotly_dark', title = 'Histogram of Price')
fig.show()可以从上图看出Price是明显右偏分布的,对于有偏的分布,我们可以做一些数据变换以调整数据分布,比如对数变换,下面我们先用对数变换对Price进行处理。
import numpy as np
# 构建一份数据备份
data_copy = data.copy()
# log对数变换
data_copy['Log_Price'] = np.log(data['Price'])
# 绘制灰度图查看分布
fig = px.histogram(data_copy, x=["Log_Price"], title = 'Histgram of Log Price', template = 'plotly_dark')
fig.show()大家可以明显看到,经过log变换后的数据分布,更加接近正态分布。
数据准备
我们先导入PyCaret工具库,并做基本的设置。
# 初始化
from pycaret.regression import *
s = setup(data, target = 'Price', transform_target = True)注意上面的 transform_target = True,PyCaret会对Price字段使用 box-cox 变换,这个变换与对数转换是类似的,也能对有偏分布进行校正。
模型选择&训练&调优
数据准备完毕后,我们使用模型对其进行训练,pycaret中最简单的方式是使用 compare_models函数,它使用交叉验证来训练和评估模型库中可用的模型,它的返回值是具有平均交叉验证分数的评分网格。 这个过程只需要下列简单代码:
# 对所有可用模型进行实验和评估
best = compare_models()上图是最终的实验结果,我们可以看到,对所有模型使用平均绝对误差 (MAE) 评估,CatBoost Regressor模型有最好的效果。
# 训练模型的预估结果残差
plot_model(best, plot = 'residuals_interactive')# 输出特征重要度
plot_model(best, plot = 'feature')模型保存
我们把最优模型保存为 pickle 文件。
# 最佳模型
final_best = finalize_model(best)
# 存储模型
save_model(final_best, 'diamond-pipeline')模型部署
下面我们演示使用FastAPI框架快速构建模型服务,并提供实时预估的能力。
# 导入工具库
import pandas as pd
from pycaret.regression import load_model, predict_model
from fastapi import FastAPI
import uvicorn
# 构建app对象
app = FastAPI()
# 加载模型
model = load_model('diamond-pipeline')
# 定义预估函数
@app.post('/predict')
def predict(carat_weight, cut, color, clarity, polish, symmetry, report):
data = pd.DataFrame([[carat_weight, cut, color, clarity, polish, symmetry, report]])
data.columns = ['Carat Weight', 'Cut', 'Color', 'Clarity', 'Polish', 'Symmetry', 'Report']
predictions = predict_model(model, data=data)
return {'prediction': int(predictions['Label'][0])}
if __name__ == '__main__':
uvicorn.run(app, host='127.0.0.1', port=8000)接下来可以通过终端命令行运行以下命令来运行这个服务,大家确保运行命令的路径和上述python脚本和以及模型存储pickle文件在同一位置。
uvicorn main:app --reload命令执行完后,我们就在 localhost 上初始化 API 服务了,大家在浏览器上输入 http://localhost:8000/docs ,会显示如下内容:
点击页面中绿色的 POST 按钮,它将打开一个像这样的表单:
点击右上角的『Try it out』 ,在表单填入一些值,然后点击『Execute』,我们会看到以下响应:
我们可以使用 python 的 requests 库测试一下,远程发起请求是否可以得到结果,如下图所示:
大家可以看看,我们通过传参的方式对模型服务发起请求,并得到返回结果。
参考资料
- 点击 这里 获取本文 [13] 钻石价格预测的ML全流程!从模型构建调优道部署应用! 『 pycaret-master 数据集』
- ShowMeAI官方GitHub:https://github.com/ShowMeAI-Hub
- PyCaret GitHub:https://www.github.com/pycaret/pycaret
- FastAPI GitHub:https://github.com/tiangolo/fastapi
- 哈佛商学院 Sarah Gets a Diamond:https://hbsp.harvard.edu/product/UV0869-PDF-ENG
边栏推荐
- 爬虫-爬取某小说网站
- Uni-app develops WeChat applet using local images as background images
- Uni-app开发微信小程序使用本地图片做背景图
- DAY26:GetShell专题
- UGUI—事件,iTween插件
- Rust learning: 6.3_ Tuples of composite types
- Rust learning: 6.2_ Tuples of composite types
- Question brushing tool h
- [OAuth2] Nineteen, OpenID Connect dynamic client registration
- Rust学习:6.2_复合类型之元组
猜你喜欢
随机推荐
Class Notes (7) (1) - #647. Find the root and the child (root)
日期类(暑假每日一题 19)
2022-08-01 Advanced Network Engineering (24) STP Advanced Knowledge
iwemeta metaverse: a doll sells for 9999 yuan, and Bubble Mart thinks it is not expensive at all
Question brushing tool h
大佬们,请问一下,oraclecdc报错没有序列化,可是我看源码中的确是没有继承序列化的,是什么原因
Go-Excelize API source code reading (11) - GetActiveSheetIndex()
解决win10win7win8系统找不到指定的模块,注册不了大漠插件的问题
[OAuth2] Nineteen, OpenID Connect dynamic client registration
Rust learning: 6.5_Array of composite types
Rust learning: 6.4_ enumeration of composite types
[OAuth2] 20. OAuth2 Extended Protocol PKCE
DAY25:逻辑漏洞复现
The precise effect of network integration promotion outsourcing in the era of Internet of Things-Shenzhen Win-Win World News
2022-08-01 网工进阶(二十三) VLAN高级技术-VLAN聚合、MUX VLAN
Pieces of TensorFlow 2.9 (1)
A File Online Query Display and Download Function Realized by Delphi
Compilation failure:找不到符号
I don't want to do accounting anymore, Die changed to a new one, moved forward bravely, and finally successfully passed the career change test to double his monthly salary~
Ask next CDC mysql to Doris. Don't show the specific number of lines, how to do?








