只需 10 个简单步骤即可使用 Python 构建数据科学应用程序
了解如何使用 Python、Scikit-Learn 和 FastAPI 一步一步构建数据科学应用程序。
希望进一步提高您的数据科学技能?构建数据科学应用程序是了解更多信息的好方法。
构建数据科学应用程序涉及多个步骤——从数据收集和预处理到模型训练和通过 API 提供预测。本分步教程将指导您完成创建简单的数据科学应用程序的过程。
我们将使用 Python、scikit-learn 和 FastAPI 来训练机器学习模型并构建 API 来服务其预测。为了简单起见,我们将使用 scikit-learn 的内置 wine 数据集。让我们开始吧!
▶️ 您可以在 GitHub 上找到代码。
第 1 步:设置环境
您应该安装最新版本的 Python。然后,安装构建机器学习模型所需的库和用于预测的 API:
$ pip3 install fastapi uvicorn scikit-learn pandas
注意:请务必在项目的虚拟环境中安装所需的库。
第 2 步:加载数据集
我们将使用 scikit-learn 的 wine 数据集。让我们加载数据集并将其转换为 pandas 数据框以便于操作:
# model_training.py
from sklearn.datasets import load_wine
import pandas as pd
def load_wine_data():
wine_data = load_wine()
df = pd.DataFrame(data=wine_data.data, columns=wine_data.feature_names)
df['target'] = wine_data.target # Adding the target (wine quality class)
return df
第 3 步:探索数据集
在我们继续之前,最好先探索一下数据集。
# model_training.py
if __name__ == "__main__":
df = load_wine_data()
print(df.head())
print(df.describe())
print(df['target'].value_counts()) # Distribution of wine quality classes
在这里,我们通过显示前几行、生成汇总统计数据并检查输出类的分布来对数据集进行初步探索。
第四步:数据预处理
接下来,我们将对数据集进行预处理。我们将数据集分为训练集和测试集,并缩放特征。
preprocess_data
函数就是这样做的:
# model_training.py
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
def preprocess_data(df):
X = df.drop('target', axis=1) # Features
y = df['target'] # Target (wine quality)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=27)
# Feature scaling
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
return X_train_scaled, X_test_scaled, y_train, y_test
使用 StandardScaler 进行特征缩放可确保所有特征对模型训练做出同等贡献。
第 5 步:训练逻辑回归模型
现在让我们在预处理的数据上训练 LogisticRegression 模型并将模型保存到 pickle 文件中。以下函数 train_model
可以执行此操作:
# model_training.py
from sklearn.linear_model import LogisticRegression
import pickle
def train_model(X_train, y_train):
model = LogisticRegression(random_state=42)
model.fit(X_train, y_train)
# Save the trained model using pickle
with open('classifier.pkl', 'wb') as f:
pickle.dump(model, f)
return model
第 6 步:评估模型
模型训练完成后,我们通过计算测试集的准确性来评估其性能。为此,我们定义函数evaluate_model
,如下所示:
# model_training.py
from sklearn.metrics import accuracy_score
def evaluate_model(model, X_test, y_test):
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy:.2f}")
if __name__ == "__main__":
df = load_wine_data()
X_train_scaled, X_test_scaled, y_train, y_test = preprocess_data(df)
model = train_model(X_train_scaled, y_train)
evaluate_model(model, X_test_scaled, y_test)
当您运行 Python 脚本时:数据被加载、预处理、模型被训练和评估。现在运行脚本给出:
Accuracy: 0.98
第 7 步:设置 FastAPI
现在,我们将设置一个基本的 FastAPI 应用程序,该应用程序将使用我们经过训练的模型进行预测。
# app.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "A Simple Prediction API"}
在此步骤中,我们设置了一个基本的 FastAPI 应用程序并定义了一个根端点。这将创建一个可以响应 HTTP 请求的简单 Web 服务器。
您可以使用以下命令运行 FastAPI 应用程序:
uvicorn app:app --reload
访问 http://127.0.0.1:8000 查看该消息。
第8步:在FastAPI中加载模型
我们将在 FastAPI 中加载预先训练的模型来进行预测。
让我们继续定义一个函数来在 FastAPI 应用程序中加载预先训练的 Logistic 回归模型。
# app.py
import pickle
def load_model():
with open('model/classifier.pkl', 'rb') as f:
model = pickle.load(f)
return model
这意味着我们的模型已准备好在收到请求时进行预测。
第9步:创建预测端点
我们将定义一个端点来接受葡萄酒特征作为输入并返回预测的葡萄酒质量等级。
定义输入数据模型
我们想要创建一个接受 JSON 格式的葡萄酒特征数据的预测端点。使用 Pydantic 定义的输入数据模型验证传入数据。
# app.py
from pydantic import BaseModel
class WineFeatures(BaseModel):
alcohol: float
malic_acid: float
ash: float
alcalinity_of_ash: float
magnesium: float
total_phenols: float
flavanoids: float
nonflavanoid_phenols: float
proanthocyanins: float
color_intensity: float
hue: float
od280_od315_of_diluted_wines: float
proline: float
预测端点
收到请求后,API 使用加载的模型根据提供的功能来预测葡萄酒类别。
# app.py
@app.post("/predict")
def predict_wine(features: WineFeatures):
model = load_model()
input_data = [[
features.alcohol, features.malic_acid, features.ash, features.alcalinity_of_ash,
features.magnesium, features.total_phenols, features.flavanoids,
features.nonflavanoid_phenols, features.proanthocyanins, features.color_intensity,
features.hue, features.od280_od315_of_diluted_wines, features.proline
]]
prediction = model.predict(input_data)
return {"prediction": int(prediction[0])}
步骤 10:本地测试应用程序
您可以通过运行以下命令重新运行该应用程序:
uvicorn app:app --reload
要测试应用程序,请使用 wine 功能数据向 /predict
端点发送 POST 请求:
curl -X POST "http://127.0.0.1:8000/predict" \
-H "Content-Type: application/json" \
-d '{
"alcohol": 13.0,
"malic_acid": 2.14,
"ash": 2.35,
"alcalinity_of_ash": 20.0,
"magnesium": 120,
"total_phenols": 3.1,
"flavanoids": 2.6,
"nonflavanoid_phenols": 0.29,
"proanthocyanins": 2.29,
"color_intensity": 5.64,
"hue": 1.04,
"od280_od315_of_diluted_wines": 3.92,
"proline": 1065
}'
本地测试对于确保 API 在任何部署之前按预期工作非常重要。因此,我们通过使用示例葡萄酒特征数据向预测端点发送 POST 请求来测试应用程序,并获取预测的类别。
{"prediction":0}
总结
我们构建了一个简单但实用的数据科学应用程序。
使用 scikit-learn 构建机器学习模型后,我们使用 FastAPI 创建一个接受用户输入并返回预测的 API。您可以尝试构建更复杂的模型、添加功能等等。
下一步,您可以探索不同的数据集、模型,甚至将应用程序部署到生产环境。阅读部署机器学习模型实用指南以了解更多信息。