在本教程中,我們將從頭開始創建一個水質分類器應用程序,並使用Docker部署到雲中。
>我們將首先探索OpenAI O1模型並了解其功能。然後,我們將通過API和CHATGPT訪問該模型,並在開發構建水質分類器應用程序的有效提示之前,先嘗試O1-preiview和O1-Mini版本。
>輸出後,我們將通過本地執行Python代碼來將O1模型提供的代碼和文件添加到項目文件夾中,然後加載,預處理,訓練和評估。最後,我們將構建一個FastAPI應用程序,並使用Docker將其部署在擁抱面上。
>
如果您是AI的新手,那麼AI基礎知識技能軌道是一個不錯的起點。它將幫助您了解流行的AI主題,例如Chatgpt和大型語言模型。
>由作者 圖像
開始使用O1-preiview和O1-Mini在本節中,我們將學習如何使用它們來解決複雜的問題。
訪問O1模型
>要在Chatgpt上訪問它,您必須單擊“模型選擇”下拉選項,然後選擇“ O1-Preview”模型,如下所示。
from openai import OpenAI client = OpenAI() response = client.chat.completions.create( model="o1-preview", messages=[ { "role": "user", "content": "Create an SQL database from scratch, including guides on usage and code everything in Python." } ] ) print(response.choices[0].message.content)。
在chatgpt中使用o1-preview模型
我是西班牙的自由職業者,在美國一家公司工作。在過去的一年中,我賺了12萬美元,我需要計算我所欠的稅款。請考慮我8個月前搬到西班牙。
>響應花費了將近30秒,但響應詳細介紹了。它包括數學方程式,稅收信息以及所有必要的細節,以確定我們欠西班牙政府多少。
響應分為以下部分:
>不僅創建了一個適當的簡歷網站,而且還為我們提供了有關如何免費在Github頁面上發布的指南。 >
1。及時工程 >我們將在及時工程上花費更多的時間,因為我們要確保將所有項目指令都提供給模型。 提示:“我的項目經理已任務使用https://www.kaggle.com/datasets/adityakadiwal/water-potability提供的Kaggle數據集開發水質應用程序。請提供有關文件,Python軟件包和代碼的所有必要信息,以便我們可以構建一個高度準確的模型。
1。使用API從Kaggle加載數據集並將其解壓縮到數據文件夾中。
>
>
6。確保使用JINJA2模板添加用戶界面。 7。使用Docker選項將應用程序部署在擁抱麵線上。
>現在,我們將將所有代碼轉換為Python和HTML文件,使我們的生活更加輕鬆。 後續提示:“請將代碼轉換為Python文件。”
3。加載數據集 >我們將使用Kaggle API加載水質Kaggle數據集並將其解壓縮到數據文件夾中。 運行Python文件將下載數據集,解壓縮並刪除zip文件。 $ python .srcdownload_data.py 4。預處理數據並執行數據分析 >預處理python文件將加載數據,清潔,處理丟失的數據,縮放它,然後保存縮放器和預處理數據集。它還將執行數據分析並保存指標和數據可視化。
5。建築和培訓 >訓練腳本加載了預處理數據,並使用它來訓練隨機的森林分類器。然後,Skope用於保存模型,手動跟踪實驗,然後將模型元數據保存為JSON文件。
>
>總體準確性不是很好。但是,我們總是可以要求O1模型提高準確性。 指標文件夾包含所有保存的模型評估數字和指標。我們可以手動查看它以詳細了解模型性能。 為了為FastAPI應用程序創建用戶界面,我們需要創建索引和結果頁面。這可以通過在應用程序目錄中創建模板文件夾並添加兩個HTML文件來完成這一點:一個用於主頁,一個用於結果頁面。 >查看FastAPI教程:使用FastApi詳細了解FastAPI框架以及如何在項目中實現它的簡介。 如果您不熟悉HTML,請不要擔心。您只需要復制和粘貼代碼並信任O1模型即可。 > appTemplatesform.html: > appTemplatesResult.html: 主應用程序Python文件具有兩個Python函數:主頁和預測。 “主頁”功能顯示包含輸入框和一個按鈕的歡迎頁面。 “預測”函數會轉換用戶輸入,通過模型運行並顯示結果,指示水是否飲用。 > apptemplatesmain.py: >
注意:O1模型也提供了有關如何運行文件的所有信息。
> OpenAI O1模型已經生成了Docker代碼,指南和參考鏈接,以成功地學習如何在擁抱面前部署應用程序。
>
> dockerfile:
這是我們的應用存儲庫應該看起來的方式: 我們的模型是一個大文件(> 10MB),因此我們需要使用Git LFS跟踪它。安裝git lfs,並使用擴展名“ .skops”跟踪所有文件。 階段所有更改,使用消息提交,然後將其推向遠程服務器。 >在擁抱臉上轉到您的應用頁面,您會發現它正在構建容器並安裝所有必要的軟件包。 來源:水質分類器
來源:水質分類器 >
來源:水質分類器
>輸出: 所有項目文件,數據,模型和元數據都可以在KingAbzPro/Water-water-app github存儲庫上提供。
在本教程中,我們已經看到了OpenAI的O1推理模型的功能。我們建立了一個完整的機器學習項目,只需對代碼進行一些更改,它立即起作用。該模型完美地處理了每個命令,並產生了出色的結果,而無需進行後續說明。
>賺取頂級AI認證
審查摘要部分為我們提供了欠政府的大約稅款,這很有幫助。
在chatgpt
>提示:“
請使用Python框架為我的數據科學簡歷創建一個靜態網站。
如果您有興趣使用Chatgpt構建數據科學項目,請查看使用CHATGPT進行數據科學項目的指南。您將學習如何使用CHATGPT進行項目計劃,數據分析,數據預處理,模型選擇,超參數調整,開發Web應用程序並部署。
>閱讀chatgpt的初學者指南提示工程,以了解如何在chatgpt中編寫適當的提示並生成所需的結果。迅速的工程是一門藝術,隨著O1模型的引入,已經變得更加必要學習。
2。設置
O1模型提供了設置項目目錄所需的所有信息。我們只需要使用代碼編輯器在項目目錄中創建文件夾和文件。
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model="o1-preview",
messages=[
{
"role": "user",
"content": "Create an SQL database from scratch, including guides on usage and code everything in Python."
}
]
)
print(response.choices[0].message.content)
import os
# Ensure the data directory exists
os.makedirs("data", exist_ok=True)
# Download the dataset
os.system("kaggle datasets download -d adityakadiwal/water-potability -p data --unzip")
> datapreprocess_data.py:
Dataset URL: https://www.kaggle.com/datasets/adityakadiwal/water-potability
License(s): CC0-1.0
Downloading water-potability.zip to data
100%|████████████████████████████████████████████████████████████████████████████████| 251k/251k [00:00<00:00, 304kB/s]
100%|████████████████████████████████████████████████████████████████████████████████| 251k/251k [00:00<00:00, 303kB/s]
import os
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
import joblib
# Create directories if they don't exist
os.makedirs("metrics", exist_ok=True)
os.makedirs("models", exist_ok=True)
# Load the dataset
data = pd.read_csv("data/water_potability.csv")
# Check for missing values and save the summary
missing_values = data.isnull().sum()
missing_values.to_csv("metrics/missing_values.csv")
# Statistical summary
stats = data.describe()
stats.to_csv("metrics/data_statistics.csv")
# Pair plot
sns.pairplot(data, hue="Potability")
plt.savefig("metrics/pairplot.png")
# Correlation heatmap
plt.figure(figsize=(10, 8))
sns.heatmap(data.corr(), annot=True)
plt.savefig("metrics/correlation_heatmap.png")
# Handle missing values
imputer = SimpleImputer(strategy="mean")
data_imputed = pd.DataFrame(imputer.fit_transform(data), columns=data.columns)
# Feature scaling
scaler = StandardScaler()
features = data_imputed.drop("Potability", axis=1)
target = data_imputed["Potability"]
features_scaled = scaler.fit_transform(features)
# Save the scaler
joblib.dump(scaler, "models/scaler.joblib")
# Save preprocessed data
preprocessed_data = pd.DataFrame(features_scaled, columns=features.columns)
preprocessed_data["Potability"] = target
preprocessed_data.to_csv("metrics/preprocessed_data.csv", index=False)
$ python .\src\preprocess_data.py
import os
import json
import skops.io as sio
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
# Load preprocessed data
data = pd.read_csv("metrics/preprocessed_data.csv")
features = data.drop("Potability", axis=1)
target = data["Potability"]
# Split the data
X_train, X_test, y_train, y_test = train_test_split(
features, target, test_size=0.2, random_state=42, stratify=target
)
# Train the model
model = RandomForestClassifier(n_estimators=200, random_state=42)
model.fit(X_train, y_train)
# Save the model using skops
os.makedirs("models", exist_ok=True)
sio.dump(model, "models/water_quality_model.skops")
# Track experiments and save metadata
metadata = {
"model_name": "RandomForestClassifier",
"parameters": model.get_params(),
"training_score": model.score(X_train, y_train),
}
with open("models/metadata.json", "w") as f:
json.dump(metadata, f, indent=4)
6。模型評估> srcevaluate_model.py:
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model="o1-preview",
messages=[
{
"role": "user",
"content": "Create an SQL database from scratch, including guides on usage and code everything in Python."
}
]
)
print(response.choices[0].message.content)
import os
# Ensure the data directory exists
os.makedirs("data", exist_ok=True)
# Download the dataset
os.system("kaggle datasets download -d adityakadiwal/water-potability -p data --unzip")
Dataset URL: https://www.kaggle.com/datasets/adityakadiwal/water-potability
License(s): CC0-1.0
Downloading water-potability.zip to data
100%|████████████████████████████████████████████████████████████████████████████████| 251k/251k [00:00<00:00, 304kB/s]
100%|████████████████████████████████████████████████████████████████████████████████| 251k/251k [00:00<00:00, 303kB/s]
7。創建一個FastApi應用程序
import os
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
import joblib
# Create directories if they don't exist
os.makedirs("metrics", exist_ok=True)
os.makedirs("models", exist_ok=True)
# Load the dataset
data = pd.read_csv("data/water_potability.csv")
# Check for missing values and save the summary
missing_values = data.isnull().sum()
missing_values.to_csv("metrics/missing_values.csv")
# Statistical summary
stats = data.describe()
stats.to_csv("metrics/data_statistics.csv")
# Pair plot
sns.pairplot(data, hue="Potability")
plt.savefig("metrics/pairplot.png")
# Correlation heatmap
plt.figure(figsize=(10, 8))
sns.heatmap(data.corr(), annot=True)
plt.savefig("metrics/correlation_heatmap.png")
# Handle missing values
imputer = SimpleImputer(strategy="mean")
data_imputed = pd.DataFrame(imputer.fit_transform(data), columns=data.columns)
# Feature scaling
scaler = StandardScaler()
features = data_imputed.drop("Potability", axis=1)
target = data_imputed["Potability"]
features_scaled = scaler.fit_transform(features)
# Save the scaler
joblib.dump(scaler, "models/scaler.joblib")
# Save preprocessed data
preprocessed_data = pd.DataFrame(features_scaled, columns=features.columns)
preprocessed_data["Potability"] = target
preprocessed_data.to_csv("metrics/preprocessed_data.csv", index=False)
$ python .\src\preprocess_data.py
import os
import json
import skops.io as sio
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
# Load preprocessed data
data = pd.read_csv("metrics/preprocessed_data.csv")
features = data.drop("Potability", axis=1)
target = data["Potability"]
# Split the data
X_train, X_test, y_train, y_test = train_test_split(
features, target, test_size=0.2, random_state=42, stratify=target
)
# Train the model
model = RandomForestClassifier(n_estimators=200, random_state=42)
model.fit(X_train, y_train)
# Save the model using skops
os.makedirs("models", exist_ok=True)
sio.dump(model, "models/water_quality_model.skops")
# Track experiments and save metadata
metadata = {
"model_name": "RandomForestClassifier",
"parameters": model.get_params(),
"training_score": model.score(X_train, y_train),
}
with open("models/metadata.json", "w") as f:
json.dump(metadata, f, indent=4)
我們將首先在本地測試該應用程序,以驗證它是否正在運行。 $ python .\src\train_model.py
import os
import json
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.metrics import (
classification_report,
confusion_matrix,
roc_auc_score,
roc_curve,
)
import skops.io as sio
from sklearn.model_selection import train_test_split
# Load preprocessed data
data = pd.read_csv("metrics/preprocessed_data.csv")
features = data.drop("Potability", axis=1)
target = data["Potability"]
# Split the data
X_train, X_test, y_train, y_test = train_test_split(
features, target, test_size=0.2, random_state=42, stratify=target
)
# Load the model
model = sio.load("models/water_quality_model.skops")
# Predictions
y_pred = model.predict(X_test)
y_pred_proba = model.predict_proba(X_test)[:, 1]
# Classification report
report = classification_report(y_test, y_pred, output_dict=True)
with open("metrics/classification_report.json", "w") as f:
json.dump(report, f, indent=4)
# Confusion matrix
cm = confusion_matrix(y_test, y_pred)
sns.heatmap(cm, annot=True, fmt="d")
plt.title("Confusion Matrix")
plt.ylabel("Actual Label")
plt.xlabel("Predicted Label")
plt.savefig("metrics/confusion_matrix.png")
# ROC curve and AUC
fpr, tpr, _ = roc_curve(y_test, y_pred_proba)
roc_auc = roc_auc_score(y_test, y_pred_proba)
plt.figure()
plt.plot(fpr, tpr, label="AUC = %0.2f" % roc_auc)
plt.plot([0, 1], [0, 1], "k--")
plt.legend(loc="lower right")
plt.xlabel("False Positive Rate")
plt.ylabel("True Positive Rate")
plt.title("Receiver Operating Characteristic")
plt.savefig("metrics/roc_curve.png")
# Overall accuracy
accuracy = model.score(X_test, y_test)
print(f"Overall Accuracy: {accuracy * 100:.2f}%")
8。使用docker
部署該應用程序在擁抱臉部集線器上
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model="o1-preview",
messages=[
{
"role": "user",
"content": "Create an SQL database from scratch, including guides on usage and code everything in Python."
}
]
)
print(response.choices[0].message.content)
>
import os
# Ensure the data directory exists
os.makedirs("data", exist_ok=True)
# Download the dataset
os.system("kaggle datasets download -d adityakadiwal/water-potability -p data --unzip")
>要求.txt:Dataset URL: https://www.kaggle.com/datasets/adityakadiwal/water-potability
License(s): CC0-1.0
Downloading water-potability.zip to data
100%|████████████████████████████████████████████████████████████████████████████████| 251k/251k [00:00<00:00, 304kB/s]
100%|████████████████████████████████████████████████████████████████████████████████| 251k/251k [00:00<00:00, 303kB/s]
>
import os
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
import joblib
# Create directories if they don't exist
os.makedirs("metrics", exist_ok=True)
os.makedirs("models", exist_ok=True)
# Load the dataset
data = pd.read_csv("data/water_potability.csv")
# Check for missing values and save the summary
missing_values = data.isnull().sum()
missing_values.to_csv("metrics/missing_values.csv")
# Statistical summary
stats = data.describe()
stats.to_csv("metrics/data_statistics.csv")
# Pair plot
sns.pairplot(data, hue="Potability")
plt.savefig("metrics/pairplot.png")
# Correlation heatmap
plt.figure(figsize=(10, 8))
sns.heatmap(data.corr(), annot=True)
plt.savefig("metrics/correlation_heatmap.png")
# Handle missing values
imputer = SimpleImputer(strategy="mean")
data_imputed = pd.DataFrame(imputer.fit_transform(data), columns=data.columns)
# Feature scaling
scaler = StandardScaler()
features = data_imputed.drop("Potability", axis=1)
target = data_imputed["Potability"]
features_scaled = scaler.fit_transform(features)
# Save the scaler
joblib.dump(scaler, "models/scaler.joblib")
# Save preprocessed data
preprocessed_data = pd.DataFrame(features_scaled, columns=features.columns)
preprocessed_data["Potability"] = target
preprocessed_data.to_csv("metrics/preprocessed_data.csv", index=False)
$ python .\src\preprocess_data.py
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model="o1-preview",
messages=[
{
"role": "user",
"content": "Create an SQL database from scratch, including guides on usage and code everything in Python."
}
]
)
print(response.choices[0].message.content)
>結論
以上是Openai O1-preiview教程:構建機器學習項目的詳細內容。更多資訊請關注PHP中文網其他相關文章!