通过Python scikit-learn实战项目学习机器学习从数据处理到模型部署掌握全流程技能成为数据科学专家

引言
机器学习已经渗透到我们生活的方方面面,从推荐系统到自动驾驶,从语音识别到医疗诊断,它正在改变着世界。作为数据科学领域最受欢迎的编程语言之一,Python凭借其简洁的语法和强大的库生态系统,成为了机器学习的首选工具。而在Python的众多机器学习库中,scikit-learn以其统一的API设计、丰富的算法实现和完善的文档,成为了初学者和专业人员的首选。
本文将通过一个完整的实战项目,带您走过机器学习的全流程,从数据处理到模型部署,帮助您掌握成为数据科学专家所需的核心技能。我们将使用scikit-learn库,结合实际代码示例,详细解释每个步骤的原理和实现方法。
环境设置
在开始我们的机器学习之旅前,首先需要设置好开发环境。以下是必要的Python库和工具:
# 安装必要的库
!pip install numpy pandas matplotlib seaborn scikit-learn joblib flask

# 导入我们将要使用的库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.impute import SimpleImputer
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
import joblib
from flask import Flask, request, jsonify

# 设置可视化风格
sns.set(style=”whitegrid”)
plt.rcParams[“figure.figsize”] = (10, 6)
数据获取与理解
数据获取
机器学习项目的第一步是获取数据。数据可以来自多种来源,如CSV文件、数据库、API或网络爬虫。在本例中,我们将使用Kaggle上的泰坦尼克号数据集,这是一个经典的机器学习入门数据集。
# 从CSV文件加载数据
url = “https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv”
titanic_data = pd.read_csv(url)

# 显示数据的前几行
print(titanic_data.head())

# 显示数据的基本信息
print(titanic_data.info())
数据探索性分析(EDA)
在理解数据之前,我们需要进行探索性数据分析,以了解数据的分布、特征之间的关系以及缺失值情况。
# 查看数据的基本统计信息
print(titanic_data.describe())

# 检查缺失值
print(titanic_data.isnull().sum())

# 可视化生存情况
sns.countplot(x=’Survived’, data=titanic_data)
plt.title(‘Survival Count (0 = No, 1 = Yes)’)
plt.show()

# 按性别查看生存情况
sns.countplot(x=’Survived’, hue=’Sex’, data=titanic_data)
plt.title(‘Survival Count by Gender’)
plt.show()

# 按乘客等级查看生存情况
sns.countplot(x=’Survived’, hue=’Pclass’, data=titanic_data)
plt.title(‘Survival Count by Passenger Class’)
plt.show()

# 年龄分布
plt.hist(titanic_data[‘Age’].dropna(), bins=30, edgecolor=’black’)
plt.title(‘Age Distribution’)
plt.xlabel(‘Age’)
plt.ylabel(‘Count’)
plt.show()

# 年龄与生存率的关系
sns.boxplot(x=’Survived’, y=’Age’, data=titanic_data)
plt.title(‘Age vs Survival’)
plt.show()
通过这些可视化,我们可以初步了解数据的特点和特征之间的关系,为后续的特征工程和模型选择提供依据。
数据预处理
数据预处理是机器学习流程中至关重要的一步,它直接影响模型的性能。在这一阶段,我们需要处理缺失值、异常值,进行特征编码和特征缩放等。
处理缺失值
# 检查缺失值比例
missing_percentage = titanic_data.isnull().sum() / len(titanic_data) * 100
print(“Missing value percentages:”)
print(missing_percentage)

# 对于Cabin列,由于缺失值过多,我们可以选择删除它
titanic_data = titanic_data.drop(‘Cabin’, axis=1)

# 对于Age列,我们可以用中位数填充
age_median = titanic_data[‘Age’].median()
titanic_data[‘Age’].fillna(age_median, inplace=True)

# 对于Embarked列,我们可以用众数填充
embarked_mode = titanic_data[‘Embarked’].mode()[0]
titanic_data[‘Embarked’].fillna(embarked_mode, inplace=True)

# 再次检查缺失值
print(“Missing values after imputation:”)
print(titanic_data.isnull().sum())
特征工程
特征工程是机器学习中最具创造性的步骤之一,好的特征可以显著提高模型性能。
# 从Name列提取称呼
titanic_data[‘Title’] = titanic_data[‘Name’].str.extract(‘ ([A-Za-z]+)\.’, expand=False)

# 查看称呼的分布
print(titanic_data[‘Title’].value_counts())

# 将不常见的称呼归类为”Rare”
rare_titles = titanic_data[‘Title’].value_counts()[titanic_data[‘Title’].value_counts() < 10].index titanic_data['Title'] = titanic_data['Title'].replace(rare_titles, 'Rare') # 创建家庭大小特征 titanic_data['FamilySize'] = titanic_data['SibSp'] + titanic_data['Parch'] + 1 # 创建是否独自旅行的特征 titanic_data['IsAlone'] = (titanic_data['FamilySize'] == 1).astype(int) # 创建年龄分箱特征 titanic_data['AgeBin'] = pd.cut(titanic_data['Age'], bins=[0, 12, 20, 40, 60, 80], labels=['Child', 'Teenager', 'Adult', 'Middle Age', 'Senior']) # 查看处理后的数据 print(titanic_data.head()) 特征编码和缩放 机器学习模型通常需要数值型输入,因此我们需要将分类变量转换为数值形式,并对数值特征进行缩放。 # 选择我们将在模型中使用的特征 features = ['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked', 'Title', 'FamilySize', 'IsAlone', 'AgeBin'] X = titanic_data[features] y = titanic_data['Survived'] # 将数据分为训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # 定义数值型和分类型特征 numeric_features = ['Age', 'SibSp', 'Parch', 'Fare', 'FamilySize'] categorical_features = ['Pclass', 'Sex', 'Embarked', 'Title', 'IsAlone', 'AgeBin'] # 为数值型特征创建转换管道 numeric_transformer = Pipeline(steps=[ ('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler()) ]) # 为分类型特征创建转换管道 categorical_transformer = Pipeline(steps=[ ('imputer', SimpleImputer(strategy='most_frequent')), ('onehot', OneHotEncoder(handle_unknown='ignore')) ]) # 创建列转换器,将不同的转换应用到不同的列 preprocessor = ColumnTransformer( transformers=[ ('num', numeric_transformer, numeric_features), ('cat', categorical_transformer, categorical_features) ]) # 查看转换后的数据形状 X_train_preprocessed = preprocessor.fit_transform(X_train) print("Shape of preprocessed training data:", X_train_preprocessed.shape) 模型选择与训练 在数据预处理完成后,我们需要选择合适的机器学习模型并进行训练。scikit-learn提供了多种机器学习算法,我们可以根据问题的性质和数据的特点选择合适的模型。 模型选择 对于分类问题,我们可以考虑以下几种常用的算法: 逻辑回归(Logistic Regression) 决策树(Decision Tree) 随机森林(Random Forest) 支持向量机(Support Vector Machine) 梯度提升(Gradient Boosting) 让我们比较几种模型的性能: from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier from sklearn.svm import SVC # 定义模型 models = { "Logistic Regression": LogisticRegression(max_iter=1000, random_state=42), "Decision Tree": DecisionTreeClassifier(random_state=42), "Random Forest": RandomForestClassifier(random_state=42), "Gradient Boosting": GradientBoostingClassifier(random_state=42), "Support Vector Machine": SVC(random_state=42) } # 创建包含预处理和模型的完整管道 results = {} for name, model in models.items(): # 创建管道 pipeline = Pipeline(steps=[ ('preprocessor', preprocessor), ('classifier', model) ]) # 使用交叉验证评估模型 cv_scores = cross_val_score(pipeline, X_train, y_train, cv=5, scoring='accuracy') results[name] = cv_scores.mean() print(f"{name}: {cv_scores.mean():.4f} (±{cv_scores.std():.4f})") # 选择最佳模型 best_model_name = max(results, key=results.get) print(f"\nBest model: {best_model_name} with accuracy: {results[best_model_name]:.4f}") 模型训练 根据上述比较,我们选择随机森林作为我们的模型,因为它通常在分类任务中表现良好,并且对异常值和噪声具有较强的鲁棒性。 # 创建完整的管道,包括预处理和模型 pipeline = Pipeline(steps=[ ('preprocessor', preprocessor), ('classifier', RandomForestClassifier(random_state=42)) ]) # 训练模型 pipeline.fit(X_train, y_train) # 在测试集上进行预测 y_pred = pipeline.predict(X_test) # 计算准确率 accuracy = accuracy_score(y_test, y_pred) print(f"Test Accuracy: {accuracy:.4f}") # 显示分类报告 print("\nClassification Report:") print(classification_report(y_test, y_pred)) # 显示混淆矩阵 cm = confusion_matrix(y_test, y_pred) plt.figure(figsize=(8, 6)) sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=['Not Survived', 'Survived'], yticklabels=['Not Survived', 'Survived']) plt.xlabel('Predicted') plt.ylabel('Actual') plt.title('Confusion Matrix') plt.show() 模型评估 模型评估是机器学习流程中的关键步骤,它帮助我们了解模型的性能和局限性。除了准确率外,还有许多其他评估指标可以帮助我们全面评估模型。 评估指标 from sklearn.metrics import roc_curve, auc, precision_recall_curve, average_precision_score # 获取预测概率 y_prob = pipeline.predict_proba(X_test)[:, 1] # 计算ROC曲线和AUC fpr, tpr, thresholds = roc_curve(y_test, y_prob) roc_auc = auc(fpr, tpr) # 绘制ROC曲线 plt.figure(figsize=(8, 6)) plt.plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC curve (area = {roc_auc:.2f})') plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver Operating Characteristic (ROC) Curve') plt.legend(loc="lower right") plt.show() # 计算精确率-召回率曲线 precision, recall, _ = precision_recall_curve(y_test, y_prob) average_precision = average_precision_score(y_test, y_prob) # 绘制精确率-召回率曲线 plt.figure(figsize=(8, 6)) plt.plot(recall, precision, color='blue', lw=2, label=f'Precision-Recall curve (area = {average_precision:.2f})') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('Recall') plt.ylabel('Precision') plt.title('Precision-Recall Curve') plt.legend(loc="lower left") plt.show() # 特征重要性分析 # 获取随机森林模型的特征重要性 rf_model = pipeline.named_steps['classifier'] feature_names = numeric_features.copy() # 获取OneHotEncoder后的分类特征名称 categorical_encoder = pipeline.named_steps['preprocessor'].named_transformers_['cat'].named_steps['onehot'] encoded_features = categorical_encoder.get_feature_names_out(categorical_features) feature_names.extend(encoded_features) # 获取特征重要性 importances = rf_model.feature_importances_ # 创建DataFrame并排序 feature_importance_df = pd.DataFrame({ 'Feature': feature_names, 'Importance': importances }).sort_values(by='Importance', ascending=False) # 显示前10个最重要的特征 print("Top 10 Most Important Features:") print(feature_importance_df.head(10)) # 可视化特征重要性 plt.figure(figsize=(10, 8)) sns.barplot(x='Importance', y='Feature', data=feature_importance_df.head(10)) plt.title('Feature Importance') plt.tight_layout() plt.show() 模型优化 在初步评估模型后,我们可以通过调整超参数来进一步优化模型性能。scikit-learn提供了多种工具来帮助我们找到最佳的超参数组合。 超参数调优 # 定义要搜索的参数网格 param_grid = { 'classifier__n_estimators': [50, 100, 200], 'classifier__max_depth': [None, 10, 20, 30], 'classifier__min_samples_split': [2, 5, 10], 'classifier__min_samples_leaf': [1, 2, 4] } # 创建网格搜索对象 grid_search = GridSearchCV( pipeline, param_grid, cv=5, scoring='accuracy', n_jobs=-1, # 使用所有可用的CPU核心 verbose=1 ) # 执行网格搜索 print("Starting grid search...") grid_search.fit(X_train, y_train) # 显示最佳参数和对应的分数 print("\nBest parameters found:") print(grid_search.best_params_) print(f"\nBest cross-validation score: {grid_search.best_score_:.4f}") # 使用最佳模型进行预测 best_model = grid_search.best_estimator_ y_pred_best = best_model.predict(X_test) # 评估最佳模型 accuracy_best = accuracy_score(y_test, y_pred_best) print(f"\nTest Accuracy with best model: {accuracy_best:.4f}") # 显示分类报告 print("\nClassification Report with best model:") print(classification_report(y_test, y_pred_best)) 交叉验证 为了更可靠地评估模型性能,我们可以使用交叉验证技术。交叉验证将数据分成多个子集,轮流使用其中一个子集作为验证集,其余作为训练集。 # 使用交叉验证评估最佳模型 cv_scores = cross_val_score(best_model, X_train, y_train, cv=10, scoring='accuracy') print("Cross-Validation Scores:") print(cv_scores) print(f"\nMean CV Accuracy: {cv_scores.mean():.4f} (±{cv_scores.std():.4f})") # 可视化交叉验证结果 plt.figure(figsize=(8, 6)) plt.plot(range(1, len(cv_scores) + 1), cv_scores, marker='o', linestyle='--') plt.axhline(y=cv_scores.mean(), color='r', linestyle='-') plt.title('Cross-Validation Scores') plt.xlabel('Fold') plt.ylabel('Accuracy') plt.ylim([0.5, 1.0]) plt.show() 模型部署 模型训练和优化完成后,下一步是将模型部署到生产环境中,使其能够为实际应用提供服务。我们可以使用Flask框架创建一个简单的Web API来部署我们的模型。 保存模型 # 保存模型和预处理器 joblib.dump(best_model, 'titanic_model.pkl') # 保存特征列表 joblib.dump(features, 'model_features.pkl') print("Model and features saved successfully!") 创建Flask API # 创建Flask应用 app = Flask(__name__) # 加载模型和特征 model = joblib.load('titanic_model.pkl') model_features = joblib.load('model_features.pkl') @app.route('/predict', methods=['POST']) def predict(): # 获取JSON数据 data = request.json # 将数据转换为DataFrame input_data = pd.DataFrame([data]) # 确保所有必要的特征都存在 for feature in model_features: if feature not in input_data.columns: input_data[feature] = 0 # 或者使用其他适当的默认值 # 只使用模型训练时使用的特征 input_data = input_data[model_features] # 进行预测 prediction = model.predict(input_data)[0] probability = model.predict_proba(input_data)[0][1] # 返回预测结果 result = { 'prediction': int(prediction), 'survival_probability': float(probability) } return jsonify(result) @app.route('/') def home(): return "Titanic Survival Prediction API is running!" # 运行应用 if __name__ == '__main__': app.run(debug=True) 测试API import requests import json # 创建测试数据 test_passenger = { 'Pclass': 3, 'Sex': 'male', 'Age': 22, 'SibSp': 1, 'Parch': 0, 'Fare': 7.25, 'Embarked': 'S', 'Title': 'Mr', 'FamilySize': 2, 'IsAlone': 0, 'AgeBin': 'Adult' } # 发送POST请求到API url = 'http://localhost:5000/predict' headers = {'Content-Type': 'application/json'} response = requests.post(url, data=json.dumps(test_passenger), headers=headers) # 显示响应 print("API Response:") print(response.json()) 完整实战项目 现在,让我们通过一个更完整的实战项目来整合我们学到的所有知识。在这个项目中,我们将使用一个更复杂的数据集——银行营销数据集,来预测客户是否会订阅定期存款。 数据加载与探索 # 加载银行营销数据集 bank_url = "https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank-additional.zip" import requests, zipfile, io r = requests.get(bank_url) z = zipfile.ZipFile(io.BytesIO(r.content)) z.extractall() # 读取数据 bank_data = pd.read_csv('bank-additional/bank-additional-full.csv', sep=';') # 显示数据的前几行 print(bank_data.head()) # 显示数据的基本信息 print(bank_data.info()) # 检查缺失值 print(bank_data.isnull().sum()) # 查看目标变量的分布 sns.countplot(x='y', data=bank_data) plt.title('Subscription to Term Deposit (y)') plt.show() # 查看数值特征的分布 bank_data.hist(figsize=(12, 10)) plt.tight_layout() plt.show() # 查看分类特征的分布 categorical_features = bank_data.select_dtypes(include=['object']).columns for feature in categorical_features: if feature != 'y': plt.figure(figsize=(10, 6)) sns.countplot(y=feature, hue='y', data=bank_data) plt.title(f'{feature} vs Subscription') plt.tight_layout() plt.show() 数据预处理与特征工程 # 将目标变量转换为二进制 bank_data['y'] = bank_data['y'].map({'yes': 1, 'no': 0}) # 处理未知值(用mode替换) for col in bank_data.columns: if bank_data[col].dtype == 'object': mode_val = bank_data[col].mode()[0] bank_data[col] = bank_data[col].replace('unknown', mode_val) # 创建一些新特征 # 将年龄分组 bank_data['age_group'] = pd.cut(bank_data['age'], bins=[0, 30, 40, 50, 60, 100], labels=['<30', '30-40', '40-50', '50-60', '60+']) # 创建季节特征 bank_data['season'] = bank_data['month'].map({ 'mar': 'spring', 'apr': 'spring', 'may': 'spring', 'jun': 'summer', 'jul': 'summer', 'aug': 'summer', 'sep': 'autumn', 'oct': 'autumn', 'nov': 'autumn', 'dec': 'winter', 'jan': 'winter', 'feb': 'winter' }) # 创建工作日/周末特征 bank_data['day_of_week'] = bank_data['day_of_week'].map({ 'mon': 'weekday', 'tue': 'weekday', 'wed': 'weekday', 'thu': 'weekday', 'fri': 'weekday' }) # 创建联系次数分组 bank_data['campaign_group'] = pd.cut(bank_data['campaign'], bins=[0, 1, 3, 6, 100], labels=['1', '2-3', '4-6', '7+']) # 选择特征 features = ['age', 'job', 'marital', 'education', 'default', 'housing', 'loan', 'contact', 'month', 'day_of_week', 'duration', 'campaign', 'pdays', 'previous', 'poutcome', 'emp.var.rate', 'cons.price.idx', 'cons.conf.idx', 'euribor3m', 'nr.employed', 'age_group', 'season', 'campaign_group'] X = bank_data[features] y = bank_data['y'] # 将数据分为训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y) # 定义数值型和分类型特征 numeric_features = X.select_dtypes(include=['int64', 'float64']).columns categorical_features = X.select_dtypes(include=['object', 'category']).columns # 为数值型特征创建转换管道 numeric_transformer = Pipeline(steps=[ ('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler()) ]) # 为分类型特征创建转换管道 categorical_transformer = Pipeline(steps=[ ('imputer', SimpleImputer(strategy='most_frequent')), ('onehot', OneHotEncoder(handle_unknown='ignore')) ]) # 创建列转换器 preprocessor = ColumnTransformer( transformers=[ ('num', numeric_transformer, numeric_features), ('cat', categorical_transformer, categorical_features) ]) # 查看转换后的数据形状 X_train_preprocessed = preprocessor.fit_transform(X_train) print("Shape of preprocessed training data:", X_train_preprocessed.shape) 模型训练与评估 # 由于数据不平衡,我们将使用多种模型并比较它们的性能 from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier from sklearn.linear_model import LogisticRegression from sklearn.svm import SVC from sklearn.neural_network import MLPClassifier from sklearn.metrics import roc_auc_score, f1_score, precision_score, recall_score # 定义模型 models = { "Logistic Regression": LogisticRegression(max_iter=1000, random_state=42, class_weight='balanced'), "Random Forest": RandomForestClassifier(random_state=42, class_weight='balanced'), "Gradient Boosting": GradientBoostingClassifier(random_state=42), "SVM": SVC(random_state=42, class_weight='balanced', probability=True), "Neural Network": MLPClassifier(random_state=42, max_iter=1000) } # 创建包含预处理和模型的完整管道 results = {} for name, model in models.items(): # 创建管道 pipeline = Pipeline(steps=[ ('preprocessor', preprocessor), ('classifier', model) ]) # 训练模型 pipeline.fit(X_train, y_train) # 在测试集上进行预测 y_pred = pipeline.predict(X_test) y_prob = pipeline.predict_proba(X_test)[:, 1] # 计算评估指标 accuracy = accuracy_score(y_test, y_pred) f1 = f1_score(y_test, y_pred) precision = precision_score(y_test, y_pred) recall = recall_score(y_test, y_pred) roc_auc = roc_auc_score(y_test, y_prob) results[name] = { 'accuracy': accuracy, 'f1': f1, 'precision': precision, 'recall': recall, 'roc_auc': roc_auc } print(f"{name}:") print(f" Accuracy: {accuracy:.4f}") print(f" F1 Score: {f1:.4f}") print(f" Precision: {precision:.4f}") print(f" Recall: {recall:.4f}") print(f" ROC AUC: {roc_auc:.4f}") print() # 选择最佳模型(基于F1分数) best_model_name = max(results, key=lambda k: results[k]['f1']) print(f"Best model based on F1 score: {best_model_name}") print(f"F1 Score: {results[best_model_name]['f1']:.4f}") 模型优化 # 基于前面的结果,我们选择梯度提升模型进行优化 gb_pipeline = Pipeline(steps=[ ('preprocessor', preprocessor), ('classifier', GradientBoostingClassifier(random_state=42)) ]) # 定义参数网格 param_grid = { 'classifier__n_estimators': [100, 200, 300], 'classifier__learning_rate': [0.01, 0.1, 0.2], 'classifier__max_depth': [3, 5, 7], 'classifier__min_samples_split': [2, 5, 10], 'classifier__min_samples_leaf': [1, 2, 4] } # 创建随机搜索对象(比网格搜索更高效) from sklearn.model_selection import RandomizedSearchCV random_search = RandomizedSearchCV( gb_pipeline, param_distributions=param_grid, n_iter=20, # 尝试20个参数组合 cv=5, scoring='f1', n_jobs=-1, verbose=1, random_state=42 ) # 执行随机搜索 print("Starting random search...") random_search.fit(X_train, y_train) # 显示最佳参数和对应的分数 print("\nBest parameters found:") print(random_search.best_params_) print(f"\nBest cross-validation F1 score: {random_search.best_score_:.4f}") # 使用最佳模型进行预测 best_model = random_search.best_estimator_ y_pred_best = best_model.predict(X_test) y_prob_best = best_model.predict_proba(X_test)[:, 1] # 评估最佳模型 accuracy_best = accuracy_score(y_test, y_pred_best) f1_best = f1_score(y_test, y_pred_best) precision_best = precision_score(y_test, y_pred_best) recall_best = recall_score(y_test, y_pred_best) roc_auc_best = roc_auc_score(y_test, y_prob_best) print("\nBest Model Performance:") print(f"Accuracy: {accuracy_best:.4f}") print(f"F1 Score: {f1_best:.4f}") print(f"Precision: {precision_best:.4f}") print(f"Recall: {recall_best:.4f}") print(f"ROC AUC: {roc_auc_best:.4f}") # 显示分类报告 print("\nClassification Report:") print(classification_report(y_test, y_pred_best)) # 显示混淆矩阵 cm = confusion_matrix(y_test, y_pred_best) plt.figure(figsize=(8, 6)) sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=['No', 'Yes'], yticklabels=['No', 'Yes']) plt.xlabel('Predicted') plt.ylabel('Actual') plt.title('Confusion Matrix') plt.show() 模型部署 # 保存最佳模型 joblib.dump(best_model, 'bank_marketing_model.pkl') # 保存特征列表 joblib.dump(features, 'bank_model_features.pkl') print("Bank marketing model and features saved successfully!") # 创建Flask应用 app = Flask(__name__) # 加载模型和特征 model = joblib.load('bank_marketing_model.pkl') model_features = joblib.load('bank_model_features.pkl') @app.route('/predict', methods=['POST']) def predict(): # 获取JSON数据 data = request.json # 将数据转换为DataFrame input_data = pd.DataFrame([data]) # 确保所有必要的特征都存在 for feature in model_features: if feature not in input_data.columns: if feature in ['age_group', 'season', 'day_of_week', 'campaign_group']: # 对于分类特征,使用最常见的类别 if feature == 'age_group': input_data[feature] = '30-40' elif feature == 'season': input_data[feature] = 'spring' elif feature == 'day_of_week': input_data[feature] = 'weekday' elif feature == 'campaign_group': input_data[feature] = '1' else: # 对于数值特征,使用中位数 input_data[feature] = 0 # 只使用模型训练时使用的特征 input_data = input_data[model_features] # 进行预测 prediction = model.predict(input_data)[0] probability = model.predict_proba(input_data)[0][1] # 返回预测结果 result = { 'prediction': int(prediction), 'subscription_probability': float(probability), 'prediction_label': 'yes' if prediction == 1 else 'no' } return jsonify(result) @app.route('/') def home(): return "Bank Marketing Prediction API is running!" # 运行应用 if __name__ == '__main__': app.run(debug=True) 进阶学习路径 通过本文的学习,您已经掌握了使用scikit-learn进行机器学习项目的基本流程。但是,数据科学领域不断发展,要成为真正的专家,还需要不断学习和实践。以下是一些进阶学习的建议: 深入学习机器学习算法 深度学习 :学习使用TensorFlow、Keras或PyTorch构建神经网络模型。 集成学习 :深入研究XGBoost、LightGBM和CatBoost等高级集成算法。 强化学习 :了解强化学习的基本概念和算法,如Q-learning和策略梯度。 大数据处理技术 Spark MLlib :学习使用Apache Spark进行大规模机器学习。 Dask :了解如何使用Dask进行并行计算和大数据处理。 数据库技术 :学习SQL和NoSQL数据库,以及如何从数据库中高效获取数据。 模型部署与MLOps Docker :学习使用Docker容器化机器学习应用。 Kubernetes :了解如何使用Kubernetes编排和管理容器化应用。 CI/CD :学习持续集成和持续部署,实现模型的自动更新。 云服务 :了解AWS SageMaker、Google AI Platform或Azure Machine Learning等云机器学习服务。 领域专业知识 自然语言处理 :学习文本分析、情感分析、机器翻译等NLP技术。 计算机视觉 :学习图像识别、目标检测、图像分割等CV技术。 时间序列分析 :学习ARIMA、Prophet、LSTM等时间序列预测方法。 软件工程最佳实践 版本控制 :熟练使用Git进行代码管理。 测试 :学习编写单元测试和集成测试,确保代码质量。 文档 :学习编写清晰的文档和注释,使代码更易于维护。 参与开源项目和竞赛 Kaggle :参与Kaggle竞赛,与其他数据科学家竞争和学习。 GitHub :为开源机器学习项目做贡献,提高编程技能。 社区 :加入机器学习社区,如Stack Overflow、Reddit的r/MachineLearning等。 通过持续学习和实践,您将不断提升自己的技能,最终成为真正的数据科学专家。记住,数据科学是一个快速发展的领域,保持好奇心和学习热情是成功的关键。 结论 本文通过两个完整的实战项目,详细介绍了使用Python scikit-learn进行机器学习项目的全流程,从数据获取与理解、数据预处理、模型选择与训练、模型评估与优化,到最终的模型部署。通过学习这些内容,您已经掌握了成为数据科学专家所需的核心技能。 机器学习不仅是一门技术,更是一种思维方式。它要求我们以数据为中心,通过迭代实验和持续优化来解决复杂问题。希望本文能够为您的机器学习之旅提供坚实的起点,并激励您在这个充满挑战和机遇的领域不断探索和成长。 记住,真正的专家不仅是技术的掌握者,更是能够将技术应用于实际问题,并创造价值的人。祝您在数据科学的道路上取得成功!