无监督学习
分类是监督学习的代表任务:把样本分到离散类别。垃圾邮件、图片识别、疾病诊断都是分类。
常用分类算法
- 逻辑回归 LogisticRegression:线性可分的基线
- 决策树 DecisionTree:可解释性强
- 随机森林 RandomForest:多棵决策树投票
- SVM:小样本高维效果好
- KNN:按邻居投票
评估指标
准确率 accuracy、精确率 precision、召回率 recall、F1。类别不平衡时准确率会骗人,看 F1。
代码示例
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report
data = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
data.data, data.target, test_size=0.3, random_state=42)
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
print("准确率:", accuracy_score(y_test, y_pred))
print(classification_report(y_test, y_pred))
📚 Python 语法速查
常用条目速查,完整版见对应教程章节。可复制代码到在线运行中测试。
| 写法 / 语法 | 作用 |
|---|---|
print("hello") | 输出到控制台 |
name = "张三" | 变量赋值(无需声明类型) |
if x > 0: ... | 条件判断(注意冒号和缩进) |
for i in range(10): ... | 循环(缩进是语法的一部分) |
while x < 10: ... | 条件循环 |
def fn(a, b): return a + b | 定义函数 |
class Person: ... | 定义类 |
list = [1, 2, 3] | 列表(可改) |
tuple = (1, 2) | 元组(不可改) |
dict = {"key": "value"} | 字典(键值对) |
set = {1, 2, 3} | 集合(去重) |
len(obj) | 取长度 |
str(x) / int(x) / float(x) | 类型转换 |
s.split(",") | 字符串按分隔符拆分 |
" ".join(list) | 列表拼接成字符串 |
import os | 导入模块 |
from math import sqrt | 从模块导入指定函数 |
try: ... except Exception as e: ... | 异常捕获 |
with open("a.txt", "r") as f: ... | 文件读取(自动关闭) |
f"你好 {name}" | f-string 格式化 |
lambda x: x * 2 | 匿名函数 |
list(map(fn, arr)) | 函数式处理列表 |
range(start, stop, step) | 生成数字序列 |
if __name__ == "__main__": | 主入口判断 |
pip install 包名 | 安装第三方包(命令行) |