跳至主要内容

OpenAI o3-mini 教程:使用 o3-mini 构建机器学习项目

学习如何使用 o3-mini 模型构建端到端的岗位录用预测项目,从项目规划到模型部署。
· 11分钟 阅读

使用 AI 探索

在 DeepSeek R1 发布之后,OpenAI 随即推出了自家的最新推理模型 o3-mini。这个新模型比其前身 o1 更小、更快、更高效,同时在编码、STEM 以及逻辑问题求解等任务上表现出色。

OpenAI 已将该模型向所有用户免费开放,包括使用 ChatGPT 和其他平台的用户,使高级推理能力前所未有地触手可及。

关于 o3-mini 的更多细节,您可以参考博文 OpenAI’s O3: Features, O1 Comparison, Release Date & More。

ChatGPT user interface.

来源:ChatGPT

在本教程中,我们将探索 o3-mini 模型的技术能力。具体来说,我们将测试其处理复杂技术任务的能力、生成准确代码的能力,以及为构建、测试与部署规范的机器学习模型提供清晰指导的能力。最后,我们将评估 o3-mini 是否兑现其在技术与逻辑问题求解方面作为前沿推理模型的承诺。

Building Machine Learning Project with o3-mini feature Image

图片来源:作者

使用 o3-mini 开展机器学习项目

我们将请 o3-mini 使用 Placement Prediction 数据集,构建一个能够判断学生是否有资格被录用的机器学习应用。从规划到部署,我们将在 ChatGPT 上寻求 o3-mini 模型的协助。

1. 项目规划

在项目规划阶段,我们将向 o3-mini 模型提供所有必要信息并明确目标。我们会让它创建构建、训练和部署岗位预测应用所需的全部文件夹与文件。

具体而言,我们将:

  1. 提供清晰的项目目标。
  2. 分享关于数据集各列的全部信息,包括示例数据。
  3. 梳理项目结构,从数据分析与预处理开始,继而进行训练与实验跟踪,最后部署到云端。
  4. 同时给出明确的交付物。例如,我们希望它使用 bash 命令创建文件与文件夹,设置 MLflow 进行实验跟踪,并详细说明部署应用的步骤。

提示词如下: 

“I want to build a machine learning project to predict whether a student will be placed or not based on their academic and extracurricular data. The dataset contains the following columns:

- **StudentID**: Unique identifier for each student.

- **CGPA**: The overall grades achieved by the student.

- **Internships**: Number of internships a student has completed.

- **Projects**: Number of projects a student has completed.

- **Workshops/Certifications**: Indicates whether the student has attended workshops or completed certifications to upskill themselves.

- **AptitudeTestScore**: Score achieved in an aptitude test, which evaluates quantitative and logical thinking.

- **SoftSkillRating**: A rating of the student’s communication and interpersonal skills.

- **ExtraCurricularActivities**: Indicates whether the student is active in extracurricular activities (Yes/No).

- **PlacementTraining**: Indicates whether the student has undergone placement training (Yes/No).

- **SSC and HSC**: Senior Secondary and Higher Secondary marks.

- **PlacementStatus**: The target column, which has two classes: "Placed" and "Not Placed."

Here is a sample dataset row:  

StudentID,CGPA,Internships,Projects,Workshops/Certifications,AptitudeTestScore,SoftSkillsRating,ExtracurricularActivities,PlacementTraining,SSC_Marks,HSC_Marks,PlacementStatus

1,7.5,1,1,1,65,4.4,No,No,61,79,NotPlaced

I need help creating a structured project with the following components:

1. **Data Analysis**: Perform exploratory data analysis (EDA) to understand the dataset, visualize trends, and identify correlations between features and the target variable.

2. **Model Building**: Create a machine learning pipeline to preprocess the data and train a model to predict the placement status.

3. **Experiment Tracking**: Set up a system to track experiments, including model performance metrics, hyperparameters, and results.

4. **Model Training**: Train the model using appropriate algorithms and evaluate its performance using metrics like accuracy, precision, recall, and F1-score.

5. **Hyperparameter Tuning**: Optimize the model’s performance by tuning hyperparameters using techniques like grid search or random search.

6. **Model Inference Application**: Build an application (e.g., a web app or API) to allow users to input student data and get predictions on placement status.

7. **Dockerfile for Containerization**: Create a Dockerfile to containerize the application for easy deployment.

8. **Cloud Deployment**: Deploy the application on a cloud platform (e.g., AWS, Azure, or Google Cloud) to make it accessible online.

9. **Accessing the Model**: Provide a way to access the deployed model via an API or web interface.

Please provide the following:

- A folder structure for organizing the project files. (Also provide bash command for creating the folders and files.)

- Python scripts or code snippets for each of the above components.

- Suggestions for tools and libraries to use (e.g., pandas, scikit-learn, Flask, Docker, etc.).

- Guidance on setting up experiment tracking (using MLflow).

- Steps for deploying the model on a Hugging Face Space.”

作为回应,您将收到关于项目结构及如何从零构建一切的详细说明。

ChatGPT response generation

所提供的脚本将创建项目目录、文件夹以及所有必要文件:

mkdir -p student_placement_project/{data,notebooks,src,experiments,app/templates}
touch student_placement_project/data/dataset.csv \
      student_placement_project/notebooks/eda.ipynb \
      student_placement_project/src/{__init__.py,data_preprocessing.py,model_training.py,model_inference.py,utils.py} \
      student_placement_project/experiments/mlflow_tracking.py \
      student_placement_project/app/{app.py,requirements.txt} \
      student_placement_project/app/templates/index.html \
      student_placement_project/{Dockerfile,requirements.txt,README.md}

正如所见,这段脚本已为我们完成所有必要任务。

Project directory.

2. 数据分析

回复中给出了 Jupyter Notebook 文件的代码。您只需将代码逐段粘贴并运行即可查看输出。

# notebooks/eda.ipynb
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

# Load dataset
df = pd.read_csv('../data/dataset.csv')

# Basic info and descriptive statistics
print(df.info())
print(df.describe())

# Visualize distributions
sns.histplot(df['CGPA'], bins=20, kde=True)
plt.title('Distribution of CGPA')
plt.show()

# Correlation matrix
plt.figure(figsize=(10, 8))

# Compute correlation matrix only on numeric columns
numeric_df = df.select_dtypes(include=[np.number])
plt.figure(figsize=(10, 8))
corr = numeric_df.corr()
sns.heatmap(corr, annot=True, cmap="coolwarm")
plt.title("Feature Correlation Matrix")


# Count plot for PlacementStatus
sns.countplot(x='PlacementStatus', data=df)
plt.title('Placement Status Count')
plt.show()

效果如下所示。所有数据分析与图表集中在一个文件中,便于任何人审阅。

Jupyter Notebook in Cursor AI.

3. 数据预处理

接下来,我们将创建数据预处理文件。除少量小改动外,这段代码运行顺畅。

# src/data_preprocessing.py
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler


def load_and_preprocess_data(filepath):
    df = pd.read_csv(filepath)

    # Convert categorical columns
    df["ExtracurricularActivities"] = df["ExtracurricularActivities"].map(
        {"Yes": 1, "No": 0}
    )
    df["PlacementTraining"] = df["PlacementTraining"].map({"Yes": 1, "No": 0})
    df["Workshops/Certifications"] = df["Workshops/Certifications"].astype(
        int
    )  # assuming it's already 0/1

    # Convert target column to binary
    df["PlacementStatus"] = df["PlacementStatus"].map({"Placed": 1, "NotPlaced": 0})

    # Feature selection (excluding StudentID)
    X = df.drop(["StudentID", "PlacementStatus"], axis=1)
    y = df["PlacementStatus"]

    # Split dataset
    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.2, random_state=42
    )

    # Scaling numeric features (optional)
    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, scaler

4. 模型训练

训练脚本会导入数据处理函数,先处理数据,再训练随机森林模型。最后展示模型性能指标。

# src/model_training.py
import joblib
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from data_preprocessing import load_and_preprocess_data


def train_model(data_path):
    X_train, X_test, y_train, y_test, scaler = load_and_preprocess_data(data_path)

    # Initialize and train classifier
    clf = RandomForestClassifier(n_estimators=100, random_state=42)
    clf.fit(X_train, y_train)

    # Predictions and evaluation
    y_pred = clf.predict(X_test)
    metrics = {
        "accuracy": accuracy_score(y_test, y_pred),
        "precision": precision_score(y_test, y_pred),
        "recall": recall_score(y_test, y_pred),
        "f1_score": f1_score(y_test, y_pred),
    }
    print("Model Evaluation Metrics:", metrics)

    # Save model and scaler
    joblib.dump(clf, "model_rf.joblib")
    joblib.dump(scaler, "scaler.joblib")

    return clf, scaler, metrics


if __name__ == "__main__":
    train_model("data/dataset.csv")

78% 的准确率并不差。

$ python .\src\model_training.py        
                                                      
Model Evaluation Metrics: {'accuracy': 0.781, 'precision': 0.7462121212121212, 'recall': 0.7137681159420289, 'f1_score': 0.7296296296296296}

如果您还想进一步学习相关主题,不妨看看我们广受欢迎的 LLM 教程 Fine-Tuning DeepSeek R1 (Reasoning Model)。该教程介绍了如何在医学思维链数据集上微调全球首个开源推理模型,以期打造更优秀的未来 AI 医生。

5. 实验跟踪

我们不希望将 Python 脚本放在不同的文件夹内。我们会把 mlflow_tracking.py 文件移动到 src 文件夹,并删除 experiments 文件夹。请注意,您需要手动进行一些小调整,而不是让 o3-mini 模型来处理。

# src/mlflow_tracking.py
import mlflow
import mlflow.sklearn
from model_training import train_model


def run_experiment(data_path):
    mlflow.set_experiment("Student_Placement_Prediction")

    with mlflow.start_run():
        # Train the model
        clf, scaler, metrics = train_model(data_path)

        # Log parameters (example)
        mlflow.log_param("model_type", "RandomForest")
        mlflow.log_param("n_estimators", 100)

        # Log metrics
        mlflow.log_metric("accuracy", metrics["accuracy"])
        mlflow.log_metric("precision", metrics["precision"])
        mlflow.log_metric("recall", metrics["recall"])
        mlflow.log_metric("f1_score", metrics["f1_score"])

        # Log the model
        mlflow.sklearn.log_model(clf, "model")

        print("Experiment logged in MLflow.")


if __name__ == "__main__":
    run_experiment("data/dataset.csv")

该 Python 脚本运行顺利并生成了全部信息。

$ python .\src\mlflow_tracking.py                                                             
Model Evaluation Metrics: {'accuracy': 0.781, 'precision': 0.7462121212121212, 'recall': 0.7137681159420289, 'f1_score': 0.7296296296296296}
2025/02/17 00:03:34 WARNING mlflow.models.model: Model logged without a signature and input example. Please set `input_example` parameter when logging the model to auto infer the model signature.
Experiment logged in MLflow.

所有机器学习实验都会本地保存,您可以通过 MLflow UI 进行可视化。

MLflow MLruns in project.

6. 超参数调优

o3-mini 的回复还提供了一个可选步骤,您可以将其加入 model_training.py 脚本。我们已包含该步骤,以观察模型性能是否会提升。

# src/model_training.py
import joblib
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from data_preprocessing import load_and_preprocess_data
from sklearn.model_selection import GridSearchCV


def tune_model(X_train, y_train):
    param_grid = {"n_estimators": [50, 100, 150], "max_depth": [None, 5, 10]}
    clf = RandomForestClassifier(random_state=42)
    grid_search = GridSearchCV(clf, param_grid, cv=5, scoring="f1")
    grid_search.fit(X_train, y_train)
    print("Best parameters:", grid_search.best_params_)
    return grid_search.best_estimator_

def train_model(data_path):
    X_train, X_test, y_train, y_test, scaler = load_and_preprocess_data(data_path)

    # Initialize and train classifier
    clf = tune_model(X_train, y_train)

    # Predictions and evaluation
    y_pred = clf.predict(X_test)
    metrics = {
        "accuracy": accuracy_score(y_test, y_pred),
        "precision": precision_score(y_test, y_pred),
        "recall": recall_score(y_test, y_pred),
        "f1_score": f1_score(y_test, y_pred),
    }
    print("Model Evaluation Metrics:", metrics)

    # Save model and scaler
    joblib.dump(clf, "model_rf.joblib")
    joblib.dump(scaler, "scaler.joblib")

    return clf, scaler, metrics


if __name__ == "__main__":
    train_model("data/dataset.csv")

如您所见,通过超参数优化,我们的模型表现略有提升。

$ python .\src\model_training.py                                                              
Best parameters: {'max_depth': 5, 'n_estimators': 150}
Model Evaluation Metrics: {'accuracy': 0.791, 'precision': 0.7493917274939172, 'recall': 0.7439613526570048, 'f1_score': 0.7466666666666667}

7. 模型推理应用

现在是创建模型推理的时候了。我们将开发一个 Flask Web 应用。

首先需要加载模型和标准化器。之后,我们会处理用户输入并传给模型生成预测。这是一个相当简单的应用。

import joblib
import numpy as np

app = Flask(__name__)

# Load the trained model and scaler (update paths as necessary)
model = joblib.load("model_rf.joblib")
scaler = joblib.load("scaler.joblib")


@app.route("/")
def home():
    return render_template("index.html")


@app.route("/predict", methods=["POST"])
def predict():
    try:
        # Expecting form data from the HTML template
        CGPA = float(request.form.get("CGPA"))
        Internships = int(request.form.get("Internships"))
        Projects = int(request.form.get("Projects"))
        Workshops_Certifications = int(request.form.get("Workshops_Certifications"))
        AptitudeTestScore = float(request.form.get("AptitudeTestScore"))
        SoftSkillRating = float(request.form.get("SoftSkillRating"))
        ExtracurricularActivities = request.form.get("ExtracurricularActivities")
        PlacementTraining = request.form.get("PlacementTraining")
        SSC_Marks = float(request.form.get("SSC_Marks"))
        HSC_Marks = float(request.form.get("HSC_Marks"))

        # Convert categorical fields to numerical
        extra_act = 1 if ExtracurricularActivities.lower() == "yes" else 0
        placement_training = 1 if PlacementTraining.lower() == "yes" else 0

        # Construct feature vector
        features = [
            CGPA,
            Internships,
            Projects,
            Workshops_Certifications,
            AptitudeTestScore,
            SoftSkillRating,
            extra_act,
            placement_training,
            SSC_Marks,
            HSC_Marks,
        ]

        # Scale features and make prediction
        features_scaled = scaler.transform(np.array(features).reshape(1, -1))
        prediction = model.predict(features_scaled)
        result = "Placed" if prediction[0] == 1 else "Not Placed"

        return render_template("index.html", prediction=result)
    except Exception as e:
        return render_template("index.html", prediction=f"Error: {e}")


if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000, debug=True)

为创建应用的用户界面,我们已将 HTML 代码粘贴到 index.html 文件中。这些内容均由 o3-mini 模型提供。您甚至可以请 o3-mini 改进用户界面。

<!-- app/templates/index.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Student Placement Prediction</title>
</head>
<body>
    <h1>Student Placement Prediction</h1>
    <form action="/predict" method="post" id="predictForm">
        <!-- Create inputs for each feature. Example for CGPA: -->
        <label for="CGPA">CGPA:</label>
        <input type="number" step="0.1" id="CGPA" name="CGPA" required><br><br>
        <!-- Add more inputs as per features -->
        <button type="submit">Predict</button>
    </form>
    <div id="result"></div>
    <script>
      document.getElementById('predictForm').addEventListener('submit', async (e) => {
          e.preventDefault();
          const formData = new FormData(e.target);
          const data = Object.fromEntries(formData.entries());
          // Adjust keys to match what the API expects
          data.ExtracurricularActivities = data.ExtracurricularActivities || 'No';
          data.PlacementTraining = data.PlacementTraining || 'No';
         
          const response = await fetch('/predict', {
              method: 'POST',
              headers: {'Content-Type': 'application/json'},
              body: JSON.stringify(data)
          });
          const result = await response.json();
          document.getElementById('result').innerText = JSON.stringify(result);
      });
    </script>
</body>
</html>

一切设置完成后,运行应用并点击 Flask 生成的 URL。

$ python .\app\app.py                                                                         

 * Running on all addresses (0.0.0.0)
 * Running on http://127.0.0.1:5000
 * Running on http://192.168.100.41:5000

我们的 Web 应用运行流畅。

machine learning web application UI

8. 用于容器化的 Dockerfile

o3-mini 模型也为我们提供了 Dockerfile,我们只需在本地构建并测试,然后再部署到云端。

# Use an official Python runtime as a parent image
FROM python:3.12-slim

# Set the working directory in the container
WORKDIR /app

# Copy the requirements file and install dependencies
COPY requirements.txt ./
RUN pip install --upgrade pip && pip install -r requirements.txt

# Copy the entire project
COPY . .

# Expose port (adjust as necessary)
EXPOSE 5000

# Command to run the Flask app
CMD ["python", "app/app.py"]

使用以下命令构建 Docker 镜像。

$ docker build -t kingabzpro/student_placement . 

building the Docker image.

在本地运行该 Docker 镜像。

$ docker run -p 5000:5000 kingabzpro/student_placement

您可以看到我们的 Docker 运行良好。

machine learning web application UI

9. 云端部署

现在将我们的机器学习应用部署到 Hugging Face Cloud(Space)。

开始时,您可以先创建一个新的 Space。填写应用的必要信息,并选择 Docker 作为 SDK。

Creating the Hugging face Spaces using the Docker SDK.

之后,它会生成一个 URL,供您将应用克隆到本地。

$ git clone https://huggingface.co/spaces/kingabzpro/student_placement

接着,将模型、标准化器、app 文件夹、Dockerfile 和 requirements.txt 移动到该应用仓库中。

Local repository project directory.

您可以将 app.py 文件的最后一行更新为:

 app.run(host="0.0.0.0", port=7860, debug=True)

检查 Dockerfile 中暴露的端口。我们需要这样做以避免端口错误或其他问题:

# Expose port (adjust as necessary)
EXPOSE 7860

完成所有更改后,提交更新并推送到远程仓库:

$ cd .\student_placement\    
$ git add .
$ git commit -m "Initial commit of Dockerized student placement app"
$ git push

一旦您推送更改,系统将开始构建,并随后为您的应用部署用户界面。

Hugging face Space web application.

来源:Student Placement

从项目目录管理到成功将 Web 应用部署到云端,o3-mini 的表现可圈可点。

您也可以了解 Google 的前沿模型,并按照教程 Building Multimodal AI Application with Gemini 2.0 Pro 构建您自己的 AI 应用。

撰写高效 o3-mini 提示词的技巧

o3-mini 模型具有其独特性,这意味着在进行跟进请求与调试代码时需要格外谨慎。以下几点建议可帮助您更高效地与其协作:

1. 避免相互矛盾的指令

提供指令时要确保清晰一致。如果给出多条命令,o3-mini 会优先执行最新的指令。这意味着在一长串提示中,最后一条命令会占优,可能会覆盖较早的要求。

2. 可能需要手动调试

有些代码问题可能需要手动解决,而不要依赖模型修复。如果您让 o3-mini 修复代码的某一部分,它只会修改该部分;然而,这可能导致相关部分出现问题,因为模型并不总能顾及依赖关系或更广泛的上下文。

3. 提供完整上下文

在提示中包含所有相关细节,例如原始数据、清晰定义的行与列,以及其他补充背景。这将帮助模型更准确地理解您的需求并产出更优结果。

4. 明确交付物

清晰列出您希望模型返回的内容。例如,说明您需要文件夹、文件、Docker 命令,还是实施方案的分步指南。这样可以确保输出符合您的预期。

5. 打造强有力的基础提示词

先从覆盖 90% 需求的良好结构化基础提示词入手。在此基础上,您可以通过后续命令对流程进行细化、修复或补充步骤。

结论

与 GPT-4o 相比,o3-mini 脱颖而出:相较于 o1 具备更快的性能,并在 Python 与 HTML 编码等任务上表现优异。值得注意的是,o3-mini 生成的 Python 代码多数情况下都能顺利运行。它甚至可以改进 HTML 代码,帮助您优化用户界面并提升视觉效果。

在本教程中,我们在机器学习项目的背景下探索了 o3-mini 模型的实力。o3-mini 被证明是数据科学家、机器学习工程师和技术从业者的优秀工具。其高效处理复杂任务的能力,使其成为任何工作流程中的重要资产。

要获得最佳效果,您只需在初始提示中提供完整上下文,包括所有相关内容与交付物。当模型生成输出后,您即可转到代码编辑器开始运行脚本,并依据说明实现所提供的代码。

接下来,您需要学习如何在云端部署自有的前沿 LLM。相比依赖 OpenAI,这将让您全面掌控成本、准确率与数据可访问性。请参阅教程 How to Deploy LLMs with BentoML,全面掌握这一流程。

Abid Ali Awan

作者

Abid Ali Awan

作为一名持证的数据科学家,我热衷于利用前沿技术打造创新的机器学习应用。凭借在语音识别、数据分析与报告、MLOps、对话式人工智能以及自然语言处理方面的扎实背景,我不断打磨构建智能系统的能力,力求带来切实影响。除技术专长外,我也擅长沟通,能够将复杂概念提炼为清晰、简明的表述。因此,我成为数据科学领域备受关注的博主,与不断壮大的数据专业人士社区分享洞见与实践经验。目前,我专注于内容创作与编辑,借助大语言模型打造有力且吸引人的内容,帮助企业与个人更好地发挥数据价值。

主题