从0到1掌握机器学习核心概念:用Python亲手构建你的第一个AI模型(超多代码+可视化)

🧠 一、开始

真正动手实现一个完整的AI项目!从数据预处理、特征工程、模型训练,到评估与调优,一步步还原你在动画视频中看到的所有核心知识点。


📦 二、环境准备

建议使用 Python 3.8+,推荐工具:

shell 复制代码
pip install scikit-learn pandas matplotlib seaborn numpy

📊 三、案例背景:预测大学生能否被录取

我们将使用一个简化的数据集(模拟大学申请系统),包含:

GRE Score TOEFL Score GPA University Rating Research Admit
330 115 9.0 5 1 1
312 103 8.1 3 0 0
... ... ... ... ... ...

📥 四、加载数据与可视化探索

python 复制代码
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df = pd.read_csv('https://raw.githubusercontent.com/amankharwal/Website-data/master/Admission_Predict.csv')
df.columns = df.columns.str.strip()

# 简化目标变量
df['Admit'] = df['Chance of Admit '] > 0.75
df['Admit'] = df['Admit'].astype(int)

# 预览数据
print(df.head())

# 可视化相关性
sns.heatmap(df.corr(), annot=True, cmap='Blues')
plt.title('Correlation Matrix')
plt.show()

🧹 五、特征工程 & 数据预处理

python 复制代码
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

X = df.drop(['Chance of Admit ', 'Admit'], axis=1)
y = df['Admit']

# 标准化
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# 拆分训练集与测试集
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)

🤖 六、构建模型与训练

我们使用逻辑回归(Logistic Regression)作为分类模型,后续也会加入其他模型做对比。

python 复制代码
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, classification_report

model = LogisticRegression()
model.fit(X_train, y_train)

# 预测
y_pred = model.predict(X_test)
print(f'Accuracy: {accuracy_score(y_test, y_pred):.4f}')
print(classification_report(y_test, y_pred))

🔍 七、可视化决策边界(仅用于2D简化版)

python 复制代码
import numpy as np

# 降维为两个特征(仅用于可视化)
X2D = X_scaled[:, :2]
X_train2D, X_test2D, _, _ = train_test_split(X2D, y, test_size=0.2, random_state=42)

model2D = LogisticRegression()
model2D.fit(X_train2D, y_train)

# 生成边界图
x_min, x_max = X2D[:, 0].min() - 1, X2D[:, 0].max() + 1
y_min, y_max = X2D[:, 1].min() - 1, X2D[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1),
                     np.arange(y_min, y_max, 0.1))

Z = model2D.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)

plt.contourf(xx, yy, Z, alpha=0.4)
plt.scatter(X2D[:, 0], X2D[:, 1], c=y, s=20, edgecolor='k')
plt.title('Decision Boundary (2 Features)')
plt.xlabel('GRE Score')
plt.ylabel('TOEFL Score')
plt.show()

🧪 八、模型评估与过拟合检测

我们加入其他模型(随机森林)对比训练集与测试集效果,检测过拟合。

python 复制代码
from sklearn.ensemble import RandomForestClassifier

forest = RandomForestClassifier(n_estimators=100, random_state=42)
forest.fit(X_train, y_train)

train_score = forest.score(X_train, y_train)
test_score = forest.score(X_test, y_test)

print(f'RandomForest 训练集准确率: {train_score:.4f}')
print(f'RandomForest 测试集准确率: {test_score:.4f}')

训练集准确率远高于测试集 => 可能过拟合


✅ 九、正则化概念演示(L1, L2)

python 复制代码
from sklearn.linear_model import LogisticRegressionCV

lr_cv = LogisticRegressionCV(cv=5, penalty='l2', solver='liblinear')
lr_cv.fit(X_train, y_train)
print("最佳C值:", lr_cv.C_[0])

🧠 十、关键概念总结(边看边实践)

概念 示例代码 对应含义
特征工程 StandardScaler 统一数值尺度
模型训练 LogisticRegression().fit() 学习数据规律
过拟合 训练准确率高但测试低 模型记忆训练集
正则化 penalty='l2' 抑制复杂模型
模型选择 Logistic, RandomForest 尝试多个模型对比

🚀 Bonus:自动化训练多个模型对比性能

python 复制代码
from sklearn.model_selection import cross_val_score
from sklearn.svm import SVC
from sklearn.naive_bayes import GaussianNB

models = {
    'Logistic': LogisticRegression(),
    'RandomForest': RandomForestClassifier(),
    'SVM': SVC(),
    'NaiveBayes': GaussianNB()
}

for name, model in models.items():
    scores = cross_val_score(model, X_scaled, y, cv=5)
    print(f'{name}: 平均准确率 {scores.mean():.4f}')
相关推荐
九章云极AladdinEdu7 分钟前
GPU SIMT架构的极限压榨:PTX汇编指令级并行优化实践
汇编·人工智能·pytorch·python·深度学习·架构·gpu算力
数智大号8 分钟前
浪潮云边协同:赋能云计算变革的强力引擎
人工智能
胡玉洋1 小时前
从新手到高手:全面解析 AI 时代的「魔法咒语」——Prompt
人工智能·ai·prompt·transformer·协议
是店小二呀1 小时前
Trae 插件 Builder 模式:从 0 到 1 开发天气查询小程序,解锁 AI 编程新体验
人工智能·ai编程·trae
kyle~1 小时前
深度学习框架---TensorFlow概览
人工智能·深度学习·tensorflow
CodeJourney.1 小时前
ChemBlender:科研绘图创新解决方案
数据库·人工智能·信息可视化·excel
南部余额1 小时前
Python 类变量与实例变量完全指南:区别、使用场景及常见陷阱
开发语言·python
电鱼智能的电小鱼1 小时前
产线视觉检测设备技术方案:基于EFISH-SCB-RK3588/SAIL-RK3588的国产化替代赛扬N100/N150全场景技术解析
linux·人工智能·嵌入式硬件·计算机视觉·视觉检测·实时音视频
妄想成为master1 小时前
计算机视觉----基于锚点的车道线检测、从Line-CNN到CLRNet到CLRKDNet 本文所提算法Line-CNN 后续会更新以下全部算法
人工智能·计算机视觉·车道线检测
yunvwugua__2 小时前
Python训练营打卡 Day26
前端·javascript·python