Lecture 1
跳过一部分CMU软广和和有关数据重要性介绍的废话(
1.1 Introduction
1.1.1 The Data Pipeline
数据管道(Data Pipeline)是将原始数据转化为可操作洞察的系统化流程。理解数据管道是数据科学工作的基础。
Collection & Understand the Data — 收集并理解数据
Clean & Transform the Data — 清洗与转换数据
Explore & Visualize the Data — 探索与可视化数据
Establish Model & Test Hypotheses — 建立模型与检验假设
Establish Objectives(Business or Research) — 确定目标(业务或研究)
graph LR
A[数据收集] --> B[数据清洗]
B --> C[数据探索]
C --> D[建模与检验]
D --> E[目标达成]
style A fill:#e1f5fe
style B fill:#fff3e0
style C fill:#e8f5e9
style D fill:#fce4ec
style E fill:#f3e5f5
数据管道的核心原则
垃圾进,垃圾出(Garbage In, Garbage Out) 。数据管道中每一步的质量都直接影响最终结果。数据科学家约 80% 的时间花在数据收集和清洗上。
1.1.2 数据集的基本组成
一个标准的数据集由以下部分组成:
术语
含义
示例
样本(Sample)
数据集中的一条记录
一行用户数据
特征(Feature)
描述样本的属性
年龄、收入、城市
标签(Label)
预测目标
是否购买
维度(Dimension)
特征的数量
10 个特征 = 10 维
2. Python
Python 是数据科学领域最流行的编程语言,其生态系统提供了丰富的工具链。
2.1 NumPy — 数值计算基础
NumPy 是 Python 科学计算的基石,提供了高性能的多维数组对象 ndarray 和丰富的数学函数。
Python import numpy as np
# 创建数组
a = np . array ([ 1 , 2 , 3 ]) # 一维数组
b = np . array ([[ 1 , 2 , 3 ],
[ 4 , 5 , 6 ]]) # 二维数组(矩阵)
# 常用创建方法
np . zeros (( 3 , 4 )) # 全零矩阵
np . ones (( 2 , 3 )) # 全一矩阵
np . eye ( 4 ) # 4x4 单位矩阵
np . arange ( 0 , 10 , 2 ) # [0, 2, 4, 6, 8]
np . linspace ( 0 , 1 , 5 ) # [0.0, 0.25, 0.5, 0.75, 1.0]
NumPy 的核心优势在于 向量化运算 ,避免 Python 层面的显式循环,速度可提升数十到数百倍:
Python # 向量化 vs 循环
a = np . arange ( 1_000_000 )
b = np . arange ( 1_000_000 )
# 向量化(快)
c = a + b
# 循环(慢)
c = [ a [ i ] + b [ i ] for i in range ( len ( a ))]
广播机制(Broadcasting)
NumPy 支持不同形状数组之间的运算。当两个数组形状不匹配时,NumPy 会自动"广播"较小的数组以匹配较大的数组形状。例如 matrix + vector 会自动将 vector 沿行方向复制。
2.2 Pandas — 数据处理利器
Pandas 提供了 DataFrame 和 Series 两种核心数据结构,是数据清洗、转换和分析的主力工具。
Python import pandas as pd
# 从 CSV 加载数据
df = pd . read_csv ( 'data.csv' )
# 基本操作
df . head () # 查看前 5 行
df . describe () # 描述性统计
df . info () # 数据类型和非空计数
df . shape # (行数, 列数)
df . dtypes # 各列数据类型
# 数据选择
df [ 'age' ] # 选择单列
df [[ 'age' , 'income' ]] # 选择多列
df [ df [ 'age' ] > 30 ] # 条件过滤
df . loc [ 0 : 5 , 'age' : 'city' ] # 标签索引
df . iloc [ 0 : 5 , 0 : 3 ] # 位置索引
数据清洗 数据转换 数据导出
Python # 处理缺失值
df . dropna () # 删除含缺失值的行
df . fillna ( 0 ) # 用 0 填充
df [ 'age' ] . fillna ( df [ 'age' ] . median (), inplace = True ) # 用中位数填充
# 处理重复值
df . drop_duplicates ( inplace = True )
# 数据类型转换
df [ 'date' ] = pd . to_datetime ( df [ 'date' ])
df [ 'category' ] = df [ 'category' ] . astype ( 'category' )
Python # 列操作
df [ 'age_group' ] = pd . cut ( df [ 'age' ],
bins = [ 0 , 18 , 35 , 60 , 100 ],
labels = [ '少年' , '青年' , '中年' , '老年' ])
# 聚合
df . groupby ( 'city' )[ 'income' ] . agg ([ 'mean' , 'median' , 'count' ])
# 合并
pd . merge ( df1 , df2 , on = 'id' , how = 'left' )
pd . concat ([ df1 , df2 ], axis = 0 )
Python # 导出为各种格式
df . to_csv ( 'output.csv' , index = False )
df . to_excel ( 'output.xlsx' , index = False )
df . to_json ( 'output.json' , orient = 'records' )
# 写入 SQLite
import sqlite3
conn = sqlite3 . connect ( 'database.db' )
df . to_sql ( 'table_name' , conn , if_exists = 'replace' , index = False )
conn . close ()
2.3 Matplotlib & Seaborn — 数据可视化
Matplotlib 是 Python 最基础的绑图库,Seaborn 在其基础上提供了更美观的统计图表。
Python import matplotlib.pyplot as plt
import seaborn as sns
# Matplotlib 基础绘图
fig , axes = plt . subplots ( 1 , 2 , figsize = ( 12 , 5 ))
axes [ 0 ] . hist ( df [ 'age' ], bins = 20 , color = 'steelblue' , edgecolor = 'white' )
axes [ 0 ] . set_title ( 'Age Distribution' )
axes [ 0 ] . set_xlabel ( 'Age' )
axes [ 0 ] . set_ylabel ( 'Frequency' )
axes [ 1 ] . scatter ( df [ 'age' ], df [ 'income' ], alpha = 0.5 , c = 'coral' )
axes [ 1 ] . set_title ( 'Age vs Income' )
axes [ 1 ] . set_xlabel ( 'Age' )
axes [ 1 ] . set_ylabel ( 'Income' )
plt . tight_layout ()
plt . show ()
Python # Seaborn 统计图表
sns . heatmap ( df . corr (), annot = True , cmap = 'coolwarm' , center = 0 )
sns . pairplot ( df [[ 'age' , 'income' , 'spending' ]], hue = 'spending' )
sns . boxplot ( x = 'category' , y = 'value' , data = df )
2.4 Scikit-learn — 机器学习框架
Scikit-learn 是 Python 机器学习的标准库,提供了统一的 API 接口:
Python from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score , classification_report
# 标准的机器学习流程
X_train , X_test , y_train , y_test = train_test_split (
X , y , test_size = 0.2 , random_state = 42
)
scaler = StandardScaler ()
X_train_scaled = scaler . fit_transform ( X_train )
X_test_scaled = scaler . transform ( X_test ) # 注意:只用 transform
model = LogisticRegression ()
model . fit ( X_train_scaled , y_train )
y_pred = model . predict ( X_test_scaled )
print ( f "Accuracy: { accuracy_score ( y_test , y_pred ) : .4f } " )
fit_transform vs transform
对测试集只能使用 transform 而不是 fit_transform。fit_transform 会在测试集上重新计算统计量(如均值、标准差),导致 数据泄露(Data Leakage) ,使模型评估结果失真。
3. 数据加载与预处理
3.1 常见数据格式
格式
读取方法
适用场景
CSV
pd.read_csv()
通用表格数据
Excel
pd.read_excel()
电子表格
JSON
pd.read_json()
API 返回数据、嵌套结构
Parquet
pd.read_parquet()
大数据场景,列式存储
SQL
pd.read_sql()
关系型数据库
HDF5
pd.read_hdf()
大规模数值数据
3.2 数据预处理的基本步骤
graph TD
A[原始数据] --> B[数据类型检查]
B --> C[缺失值处理]
C --> D[异常值检测]
D --> E[数据转换]
E --> F[特征工程]
F --> G[可建模数据]
数据类型检查 :确保每列的数据类型正确(数值型不应存为字符串)
缺失值处理 :删除、填充(均值/中位数/众数/前后向填充)或标记
异常值检测 :使用 IQR 方法或 Z-score 识别离群点
数据转换 :标准化、归一化、编码分类变量
特征工程 :从原始数据中提取有意义的特征
完整的数据加载示例
Python import pandas as pd
import numpy as np
# 加载
df = pd . read_csv ( 'data.csv' )
# 快速了解数据
print ( df . shape )
print ( df . dtypes )
print ( df . isnull () . sum ())
# 清洗
df = df . drop_duplicates ()
df [ 'age' ] = df [ 'age' ] . fillna ( df [ 'age' ] . median ())
df = df [ df [ 'age' ] > 0 ] # 去除不合理的年龄
# 转换
df [ 'date' ] = pd . to_datetime ( df [ 'date' ])
df [ 'category' ] = df [ 'category' ] . astype ( 'category' )
print ( f "清洗后: { df . shape [ 0 ] } 行, { df . shape [ 1 ] } 列" )