简介:本文提供Python机器学习与深度学习核心代码速查指南,涵盖Scikit-learn、TensorFlow/PyTorch关键操作,包含数据预处理、模型构建、训练评估全流程代码示例,助力开发者快速实现AI项目落地。
数据清洗是机器学习的第一步,Pandas库提供了高效的数据处理工具:
import pandas as pdimport numpy as np# 缺失值处理df = pd.DataFrame({'A': [1,2,np.nan], 'B': [5,np.nan,np.nan]})df_filled = df.fillna(method='ffill') # 前向填充df_dropped = df.dropna(thresh=2) # 保留非空值≥2的行# 特征缩放from sklearn.preprocessing import StandardScaler, MinMaxScalerscaler = StandardScaler()X_scaled = scaler.fit_transform([[1,2], [3,4], [5,6]]) # 标准化mm_scaler = MinMaxScaler(feature_range=(0,1))X_mm = mm_scaler.fit_transform([[10,20], [30,40]]) # 归一化
特征转换直接影响模型性能:
from sklearn.preprocessing import OneHotEncoder, LabelEncoderfrom sklearn.feature_extraction.text import TfidfVectorizer# 类别编码le = LabelEncoder()y_encoded = le.fit_transform(['cat','dog','cat'])# 独热编码ohe = OneHotEncoder(sparse=False)X_ohe = ohe.fit_transform([[0], [1], [2]]) # 需先数值编码# 文本特征提取corpus = ['This is good', 'That is bad']tfidf = TfidfVectorizer()X_tfidf = tfidf.fit_transform(corpus).toarray()
Scikit-learn提供了标准化建模接口:
from sklearn.linear_model import LogisticRegressionfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import train_test_split# 数据划分X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)# 逻辑回归lr = LogisticRegression(penalty='l2', C=1.0)lr.fit(X_train, y_train)y_pred = lr.predict(X_test)# 随机森林rf = RandomForestClassifier(n_estimators=100, max_depth=5)rf.fit(X_train, y_train)print(rf.feature_importances_) # 特征重要性
TensorFlow 2.x的即时执行模式简化了开发流程:
import tensorflow as tffrom tensorflow.keras import layers, models# 张量操作a = tf.constant([[1,2], [3,4]])b = tf.constant([[5,6], [7,8]])c = tf.matmul(a, b) # 矩阵乘法# 模型构建model = models.Sequential([layers.Dense(64, activation='relu', input_shape=(784,)),layers.Dropout(0.2),layers.Dense(10, activation='softmax')])model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])# 自定义训练循环@tf.functiondef train_step(x, y):with tf.GradientTape() as tape:predictions = model(x)loss = loss_fn(y, predictions)gradients = tape.gradient(loss, model.trainable_variables)optimizer.apply_gradients(zip(gradients, model.trainable_variables))
PyTorch的动态计算图提供了更大灵活性:
import torchimport torch.nn as nnimport torch.optim as optim# 神经网络定义class Net(nn.Module):def __init__(self):super(Net, self).__init__()self.fc1 = nn.Linear(784, 128)self.fc2 = nn.Linear(128, 10)def forward(self, x):x = torch.relu(self.fc1(x))x = self.fc2(x)return x# 数据加载from torch.utils.data import DataLoader, TensorDatasetdataset = TensorDataset(torch.randn(100,784), torch.randint(0,10,(100,)))loader = DataLoader(dataset, batch_size=32, shuffle=True)# 训练过程model = Net()criterion = nn.CrossEntropyLoss()optimizer = optim.Adam(model.parameters(), lr=0.001)for epoch in range(10):for inputs, labels in loader:optimizer.zero_grad()outputs = model(inputs)loss = criterion(outputs, labels)loss.backward()optimizer.step()
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV# 网格搜索param_grid = {'C': [0.1, 1, 10],'penalty': ['l1', 'l2']}grid_search = GridSearchCV(LogisticRegression(), param_grid, cv=5)grid_search.fit(X_train, y_train)# 随机搜索from scipy.stats import uniformparam_dist = {'n_estimators': range(50,200),'max_depth': [3,5,7,None],'learning_rate': uniform(0.01, 0.2)}random_search = RandomizedSearchCV(RandomForestClassifier(), param_distributions=param_dist, n_iter=20)
# TensorFlow模型保存model.save('my_model.h5') # 完整模型保存converter = tf.lite.TFLiteConverter.from_keras_model(model)tflite_model = converter.convert() # 转换为TFLite格式# PyTorch模型保存torch.save(model.state_dict(), 'model_weights.pth') # 仅保存参数loaded_model = Net()loaded_model.load_state_dict(torch.load('model_weights.pth'))# ONNX格式转换dummy_input = torch.randn(1, 784)torch.onnx.export(model, dummy_input, "model.onnx")
数据可视化:Matplotlib/Seaborn进行特征分布分析
import seaborn as snssns.pairplot(df[['feature1','feature2','target']], hue='target')
模型解释:SHAP值解释预测结果
import shapexplainer = shap.TreeExplainer(rf)shap_values = explainer.shap_values(X_test)shap.summary_plot(shap_values, X_test)
自动化机器学习:PyCaret快速原型开发
from pycaret.classification import *clf = setup(data=df, target='target')best_model = compare_models()
版本控制:使用MLflow跟踪实验参数和结果
import mlflowmlflow.start_run()mlflow.log_param("learning_rate", 0.01)mlflow.log_metric("accuracy", 0.95)
性能优化:
调试技巧:
torch.autograd.set_detect_anomaly(True)捕获梯度异常check_estimator验证自定义模型本速查表覆盖了从数据预处理到模型部署的全流程核心代码,建议开发者:
通过系统化整理和实战演练,这些代码模式将显著提升AI开发效率,帮助开发者更专注于业务逻辑的实现而非底层技术细节。