logo

Python机器学习与深度学习开发必备:代码速查指南

作者:carzy2025.09.19 17:06浏览量:6

简介:本文为Python开发者提供机器学习与深度学习的核心代码速查表,涵盖数据预处理、模型构建、训练与评估全流程,结合scikit-learn、TensorFlow/Keras、PyTorch三大框架的实用代码示例,助力快速实现AI项目开发。

Python机器学习深度学习代码速查表:从基础到进阶的完整指南

在人工智能快速发展的今天,Python凭借其丰富的生态库(如scikit-learn、TensorFlowPyTorch)成为机器学习与深度学习的首选语言。然而,开发者在实际项目中常面临代码记忆困难、框架选择困惑等问题。本文整理了一份涵盖数据预处理、模型构建、训练与评估的全流程代码速查表,结合三大主流框架的对比与实用技巧,助力开发者高效实现AI项目。

一、数据预处理:构建模型的基础

数据质量直接影响模型性能,预处理步骤包括数据清洗、特征工程、标准化等。

1. 数据加载与探索

使用Pandas快速加载数据并初步分析:

  1. import pandas as pd
  2. data = pd.read_csv('dataset.csv')
  3. print(data.head()) # 查看前5行
  4. print(data.describe()) # 统计描述
  5. print(data.isnull().sum()) # 检查缺失值

关键点:通过describe()快速识别数值分布,isnull()定位缺失数据。

2. 特征工程

  • 数值特征标准化(Scikit-learn):
    1. from sklearn.preprocessing import StandardScaler
    2. scaler = StandardScaler()
    3. X_scaled = scaler.fit_transform(X_train) # 训练集拟合与转换
    4. X_test_scaled = scaler.transform(X_test) # 测试集仅转换
  • 类别特征编码
    1. from sklearn.preprocessing import OneHotEncoder
    2. encoder = OneHotEncoder(sparse_output=False)
    3. X_encoded = encoder.fit_transform(X_cat)
    对比StandardScaler适用于正态分布数据,MinMaxScaler适合非高斯分布;OneHotEncoder避免类别特征引入虚假顺序关系。

3. 数据分割与增强

  • 训练测试集划分
    1. from sklearn.model_selection import train_test_split
    2. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
  • 深度学习数据增强(TensorFlow):
    1. from tensorflow.keras.preprocessing.image import ImageDataGenerator
    2. datagen = ImageDataGenerator(rotation_range=20, horizontal_flip=True)
    3. train_generator = datagen.flow(X_train, y_train, batch_size=32)
    应用场景:图像分类中,旋转、翻转可扩充数据集,提升模型泛化能力。

二、模型构建:从传统到深度

根据任务类型(分类、回归)选择合适模型,并对比框架实现差异。

1. 传统机器学习模型(Scikit-learn)

  • 线性回归
    1. from sklearn.linear_model import LinearRegression
    2. model = LinearRegression()
    3. model.fit(X_train, y_train)
    4. print(model.coef_) # 输出权重
  • 随机森林
    1. from sklearn.ensemble import RandomForestClassifier
    2. rf = RandomForestClassifier(n_estimators=100, max_depth=5)
    3. rf.fit(X_train, y_train)
    4. print(rf.feature_importances_) # 特征重要性
    调参建议:通过GridSearchCV搜索最佳参数组合。

2. 深度学习模型(TensorFlow/Keras)

  • 全连接神经网络
    1. from tensorflow.keras.models import Sequential
    2. from tensorflow.keras.layers import Dense
    3. model = Sequential([
    4. Dense(64, activation='relu', input_shape=(n_features,)),
    5. Dense(32, activation='relu'),
    6. Dense(1, activation='sigmoid') # 二分类输出
    7. ])
    8. model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
    9. model.fit(X_train, y_train, epochs=50, batch_size=32, validation_split=0.2)
  • CNN图像分类(PyTorch对比):
    ```python

    TensorFlow/Keras实现

    from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten
    model = Sequential([
    Conv2D(32, (3,3), activation=’relu’, input_shape=(28,28,1)),
    MaxPooling2D((2,2)),
    Flatten(),
    Dense(10, activation=’softmax’)
    ])

PyTorch实现

import torch.nn as nn
class CNN(nn.Module):
def init(self):
super().init()
self.conv1 = nn.Conv2d(1, 32, 3)
self.pool = nn.MaxPool2d(2, 2)
self.fc1 = nn.Linear(32 13 13, 10)
def forward(self, x):
x = self.pool(torch.relu(self.conv1(x)))
x = x.view(-1, 32 13 13)
x = torch.softmax(self.fc1(x), dim=1)
return x

  1. **框架选择**:Keras适合快速原型开发,PyTorch提供更灵活的动态计算图。
  2. ### 3. 模型保存与加载
  3. - **Scikit-learn**:
  4. ```python
  5. import joblib
  6. joblib.dump(rf, 'random_forest.pkl') # 保存
  7. loaded_rf = joblib.load('random_forest.pkl') # 加载
  • TensorFlow/Keras
    1. model.save('my_model.h5') # 保存完整模型(结构+权重)
    2. loaded_model = tf.keras.models.load_model('my_model.h5')
  • PyTorch
    1. torch.save(model.state_dict(), 'model_weights.pth') # 仅保存权重
    2. model.load_state_dict(torch.load('model_weights.pth'))

三、模型评估与优化:提升性能的关键

通过指标计算与可视化工具诊断模型问题。

1. 评估指标

  • 分类任务
    1. from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
    2. y_pred = model.predict(X_test)
    3. print(accuracy_score(y_test, y_pred))
    4. print(classification_report(y_test, y_pred))
    5. print(confusion_matrix(y_test, y_pred))
  • 回归任务
    1. from sklearn.metrics import mean_squared_error, r2_score
    2. mse = mean_squared_error(y_test, y_pred)
    3. r2 = r2_score(y_test, y_pred)

2. 可视化工具

  • Matplotlib绘制损失曲线
    1. import matplotlib.pyplot as plt
    2. plt.plot(history.history['loss'], label='train_loss')
    3. plt.plot(history.history['val_loss'], label='val_loss')
    4. plt.legend()
    5. plt.show()
  • Seaborn热力图
    1. import seaborn as sns
    2. cm = confusion_matrix(y_test, y_pred)
    3. sns.heatmap(cm, annot=True, fmt='d')

3. 优化策略

  • 超参数调优(Scikit-learn):
    1. from sklearn.model_selection import GridSearchCV
    2. param_grid = {'n_estimators': [50, 100, 200], 'max_depth': [3, 5, 7]}
    3. grid_search = GridSearchCV(RandomForestClassifier(), param_grid, cv=5)
    4. grid_search.fit(X_train, y_train)
    5. print(grid_search.best_params_)
  • 深度学习正则化
    1. from tensorflow.keras import regularizers
    2. model.add(Dense(64, activation='relu', kernel_regularizer=regularizers.l2(0.01)))
    作用:L2正则化防止过拟合,Dropout层随机失活神经元增强泛化能力。

四、进阶技巧:提升开发效率

1. GPU加速

  • TensorFlow自动检测GPU
    1. import tensorflow as tf
    2. print(tf.config.list_physical_devices('GPU')) # 检查可用GPU
  • PyTorch CUDA配置
    1. device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    2. model.to(device)

2. 分布式训练

  • TensorFlow MultiWorkerMirroredStrategy
    1. strategy = tf.distribute.MultiWorkerMirroredStrategy()
    2. with strategy.scope():
    3. model = create_model() # 在策略范围内定义模型

3. 模型部署

  • TensorFlow Serving:将训练好的模型导出为SavedModel格式,通过gRPC或REST API部署。
  • Flask API封装(Scikit-learn示例):
    1. from flask import Flask, request, jsonify
    2. app = Flask(__name__)
    3. @app.route('/predict', methods=['POST'])
    4. def predict():
    5. data = request.json['data']
    6. prediction = loaded_rf.predict(data)
    7. return jsonify({'prediction': prediction.tolist()})

五、总结与建议

本文整理的代码速查表覆盖了从数据预处理到模型部署的全流程,开发者可根据任务需求选择合适框架:

  • 快速原型开发:优先使用Scikit-learn或Keras。
  • 复杂模型定制:选择PyTorch或TensorFlow低级API。
  • 生产环境部署:结合TensorFlow Serving或ONNX实现跨平台兼容。

实践建议

  1. 始终从简单模型开始,逐步增加复杂度。
  2. 使用交叉验证评估模型稳定性。
  3. 记录实验过程(如参数、指标),便于复现与优化。

通过掌握这些核心代码与技巧,开发者能够显著提升AI项目的开发效率与模型性能。

相关文章推荐

发表评论