前言

随着数据量的爆发式增长和算力的大幅提升,机器学习已广泛应用于图像、自然语言处理、金融风控等领域。Python 因其简洁易用、生态完善,一直是机器学习开发者的首选语言。本篇博客将带你系统梳理机器学习开发时所需的 Python 基础,从环境搭建到demo示例,助你快速上手。


一、环境搭建

  1. 安装 Python

    • 建议使用 Python 3.8 及以上版本。
    • 官网下载:https://www.python.org/downloads/
  2. 安装开发平台(anaconda)

    • 官网下载:https://www.anaconda.com/download
  3. 创建虚拟环境

    • 使用 venv(官方推荐,轻量)

      python -m venv ml_env
      source ml_env/bin/activate    # Mac/Linux
      .\ml_env\Scripts\activate     # Windows
      
    • 或使用 Anaconda/Miniconda(管理包更方便)

      conda create -n ml_env python=3.9
      conda activate ml_env
      
  4. 安装常用包

    
    pip install numpy pandas matplotlib seaborn scikit-learn jupyterlab
    

    或(conda 环境下):

    conda install numpy pandas matplotlib seaborn scikit-learn jupyterlab
    
  5. 启动 JupyterLab

    jupyter lab
    

    在浏览器中编辑、运行代码,交互式调试体验佳。


二、 Python 基础语法

a. 变量和数据类型 变量用于存储数据。Python 是动态类型语言,不需要显式声明变量类型。
常见数据类型:

  • 整数 (int) : 例如 10 , -3
  • 浮点数 (float) : 例如 3.14 , -0.5
  • 字符串 (str) : 例如 “你好” , ‘Python’
  • 布尔值 (bool) : True 或 False
# 变量赋值
age = 30
pi = 3.14159
name = "Trae AI"
is_learning = True

# 打印变量和类型
print(f"年龄: {age}, 类型: {type(age)}")
print(f"圆周率: {pi}, 类型: {type(pi)}")
print(f"名字: {name}, 类型: {type(name)}")
print(f"正在学习: {is_learning}, 类型: {type(is_learning)}")

# 基本运算
sum_val = 10 + 5
product_val = 10 * 5
print(f"10 + 5 = {sum_val}")
print(f"10 * 5 = {product_val}")

# 字符串操作
greeting = "Hello, " + "World!"
print(greeting)
print(f"字符串长度: {len(greeting)}")

b. 输入和输出 使用 input() 获取用户输入, print() 输出信息。

# 用户输入
user_name = input("请输入您的名字: ")
print(f"您好, {user_name}!")

# 格式化输出
score = 95.5
print("您的分数是: %.2f" % score) # 旧式格式化
print("您的分数是: {:.2f}".format(score)) # str.format()
print(f"您的分数是: {score:.2f}") # f-string (推荐)

三、 Python 数据结构

a. 列表 (List) 有序、可变序列,可以包含不同类型的元素。

# 创建列表
numbers = [1, 2, 3, 4, 5]
mixed_list = [1, "apple", 3.14, True]

# 访问元素 (索引从0开始)
print(f"第一个数字: {numbers[0]}")
print(f"最后一个数字: {numbers[-1]}")

# 切片
print(f"前三个数字: {numbers[0:3]}") # 或者 numbers[:3]
print(f"从第二个开始的所有数字: {numbers[1:]}")

# 修改列表
numbers[0] = 100
print(f"修改后的列表: {numbers}")

# 列表方法
numbers.append(6) # 末尾添加元素
print(f"添加元素后的列表: {numbers}")
numbers.insert(1, 200) # 在指定索引处插入元素
print(f"插入元素后的列表: {numbers}")
numbers.remove(3) # 删除第一个匹配的元素
print(f"删除元素后的列表: {numbers}")
print(f"列表长度: {len(numbers)}")

b. 元组 (Tuple) 有序、不可变序列。一旦创建,不能修改。

# 创建元组
point = (10, 20)
colors = ("red", "green", "blue")

# 访问元素
print(f"X 坐标: {point[0]}")

# 元组不可变性 (尝试修改会报错)
# point[0] = 15 # 这行会产生 TypeError

# 元组解包
x, y = point
print(f"x = {x}, y = {y}")

c. 字典 (Dictionary) 无序(在 Python 3.7+ 中是有序的)、可变的键值对集合。键必须是唯一的且不可变类型。

# 创建字典
student = {
    "name": "小明",
    "age": 18,
    "major": "计算机科学"
}

# 访问元素
print(f"学生姓名: {student['name']}")
print(f"学生年龄: {student.get('age')}") # 使用 get() 更安全,如果键不存在返回 None

# 修改和添加元素
student["age"] = 19 # 修改
student["grade"] = "大一" # 添加
print(f"更新后的学生信息: {student}")

# 遍历字典
print("\n学生信息:")
for key, value in student.items():
    print(f"{key}: {value}")

print("\n所有键:")
for key in student.keys():
    print(key)

print("\n所有值:")
for value in student.values():
    print(value)

d. 集合 (Set) 无序、不重复元素的集合。常用于去重和成员测试。

# 创建集合
unique_numbers = {1, 2, 2, 3, 4, 4, 4, 5}
print(f"去重后的数字: {unique_numbers}")

set1 = {1, 2, 3}
set2 = {3, 4, 5}

# 集合操作
print(f"并集: {set1.union(set2)}")
print(f"交集: {set1.intersection(set2)}")
print(f"差集 (set1 - set2): {set1.difference(set2)}")

四、控制流

a. 条件语句 ( if , elif , else )

score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "D"
print(f"分数 {score} 对应的等级是: {grade}")

b. 循环语句 ( for , while )

# for 循环遍历列表
fruits = ["apple", "banana", "cherry"]
print("\n水果列表:")
for fruit in fruits:
    print(fruit)

# for 循环使用 range()
print("\n数字序列:")
for i in range(5): # 0, 1, 2, 3, 4
    print(i)

print("\n指定范围的数字序列:")
for i in range(2, 6): # 2, 3, 4, 5
    print(i)

# while 循环
count = 0
print("\nWhile 循环计数:")
while count < 3:
    print(f"Count is {count}")
    count += 1

五、 函数 (Functions)

函数是可重用的代码块。

# 定义函数
def greet(name):
    """这是一个问候函数"""
    return f"你好, {name}!"

def add_numbers(a, b):
    """这个函数返回两个数的和"""
    return a + b

# 调用函数
message = greet("世界")
print(message)

sum_result = add_numbers(10, 25)
print(f"10 + 25 = {sum_result}")

# 带默认参数的函数
def power(base, exponent=2):
    return base ** exponent

print(f"3 的平方: {power(3)}")
print(f"2 的 3 次方: {power(2, 3)}")

# Lambda 函数 (匿名函数)
multiply = lambda x, y: x * y
print(f"5 * 6 = {multiply(5, 6)}")

六、 面向对象编程 (OOP) 基础

机器学习中虽然不总是直接编写复杂的类,但理解 OOP 概念有助于使用各种库。

class Dog:
    # 类属性
    species = "Canis familiaris"

    # 构造函数 (初始化方法)
    def __init__(self, name, age):
        # 实例属性
        self.name = name
        self.age = age

    # 实例方法
    def bark(self):
        return "汪汪!"

    def describe(self):
        return f"{self.name} is {self.age} years old."

# 创建对象 (类的实例)
my_dog = Dog("旺财", 3)
your_dog = Dog("小黑", 5)

# 访问属性和调用方法
print(f"{my_dog.name} 的品种是: {my_dog.species}")
print(my_dog.describe())
print(f"{my_dog.name} 叫: {my_dog.bark()}")

print(your_dog.describe())

七、 机器学习常用 Python 库

这些库是机器学习的基础:

  • NumPy : 用于科学计算,特别是多维数组和矩阵运算。

    import numpy as np
    
    # 创建 NumPy 数组
    arr1d = np.array([1, 2, 3, 4, 5])
    print(f"一维数组: {arr1d}")
    
    arr2d = np.array([[1, 2, 3], [4, 5, 6]])
    print(f"二维数组:\n{arr2d}")
    
    # 数组运算
    print(f"数组和: {arr1d + 5}")
    print(f"数组乘法: {arr1d * 2}")
    print(f"数组点积: {np.dot(arr1d, arr1d)}") # 1*1 + 2*2 + ...
    
    # 常用函数
    print(f"数组均值: {np.mean(arr1d)}")
    print(f"数组形状: {arr2d.shape}")
    
  • Pandas : 用于数据处理和分析,核心数据结构是 DataFrame 和 Series 。

    import pandas as pd
    
    # 创建 DataFrame
    data = {
        'Name': ['Alice', 'Bob', 'Charlie'],
        'Age': [25, 30, 22],
        'City': ['New York', 'Paris', 'London']
    }
    df = pd.DataFrame(data)
    print("DataFrame:\n", df)
    
    # 查看数据
    print("\n前两行:\n", df.head(2))
    print("\n基本统计信息:\n", df.describe()) # 对数值列
    print("\n年龄列:\n", df['Age'])
    
    # 假设有一个 data.csv 文件,内容如下:
    # Name,Age,City
    # Alice,25,New York
    # Bob,30,Paris
    # Charlie,22,London
    # David,35,Berlin
    # (你可以手动创建这个 c:\aa\data.csv 文件来运行下面的代码)
    # try:
    #     df_from_csv = pd.read_csv(r"c:\aa\data.csv")
    #     print("\n从 CSV 文件读取的 DataFrame:\n", df_from_csv)
    # except FileNotFoundError:
    #     print("\n未找到 data.csv 文件,跳过 CSV 读取示例。")
    

    注意 : 上述 pd.read_csv 部分需要在 c:\aa\ 目录下创建一个名为 data.csv 的文件。

  • Matplotlib / Seaborn : 用于数据可视化,绘制各种图表。

    import matplotlib.pyplot as plt
    import numpy as np # 通常与 matplotlib 一起使用
    
    # 简单的线图
    x = np.linspace(0, 10, 100) # 0到10之间100个点
    y = np.sin(x)
    
    plt.figure(figsize=(8, 4)) # 设置图形大小
    plt.plot(x, y)
    plt.title("Sine Wave")
    plt.xlabel("X-axis")
    plt.ylabel("Y-axis")
    plt.grid(True)
    # plt.show() # 在脚本中运行时,取消注释以显示图形
    plt.savefig(r"c:\aa\sine_wave.png") # 保存图形
    print(f"图形已保存到 c:\\aa\\sine_wave.png")
    

    注意 : plt.show() 在某些环境中(如 Jupyter Notebook)会自动显示图像,但在普通 Python 脚本中需要调用它才能看到弹出的图像窗口。 plt.savefig() 会将图像保存到文件。

  • Scikit-learn (sklearn) : 提供了大量的机器学习算法、预处理工具、模型评估方法等。

    from sklearn.model_selection import train_test_split
    from sklearn.linear_model import LogisticRegression
    from sklearn.datasets import load_iris # 一个经典的数据集
    import numpy as np
    
    # Scikit-learn 通常用于更复杂的任务,这里仅作概念性介绍
    # 1. 加载数据
    iris = load_iris()
    X, y = iris.data, iris.target # X 是特征, y 是标签
    
    # 2. 数据分割 (训练集和测试集)
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
    print(f"训练集大小: {X_train.shape}, 测试集大小: {X_test.shape}")
    
    # 3. 选择模型并训练
    # model = LogisticRegression(max_iter=200) # 增加 max_iter 以确保收敛
    # model.fit(X_train, y_train)
    
    # 4. 预测和评估 (这里不详细展开)
    # predictions = model.predict(X_test)
    # accuracy = np.mean(predictions == y_test)
    # print(f"模型准确率 (示例): {accuracy:.2f}") # 实际运行需要模型训练步骤
    
    print("Scikit-learn 示例演示了基本流程,实际应用中模型训练和评估会更复杂。")
    

    这是一个非常简化的流程,实际使用 sklearn 会涉及更多细节。


八、 文件操作

机器学习通常需要从文件中读取数据或将结果保存到文件。

# 写入文件
file_path = r"c:\aa\my_data.txt"
with open(file_path, "w", encoding="utf-8") as f:
    f.write("这是第一行数据。\n")
    f.write("这是第二行数据。\n")
print(f"数据已写入到 {file_path}")

# 读取文件
print(f"\n从 {file_path} 读取数据:")
with open(file_path, "r", encoding="utf-8") as f:
    # content = f.read() # 读取所有内容
    # print("全部内容:\n", content)

    # 逐行读取
    f.seek(0) # 回到文件开头
    for line in f:
        print(line.strip()) # strip() 去除行尾换行符

九、 错误和异常处理 (try-except)

编写的代码需要处理可能发生的错误。

try:
    numerator = 10
    denominator = 0
    result = numerator / denominator
    print(result)
except ZeroDivisionError:
    print("错误:不能除以零!")
except TypeError as e:
    print(f"类型错误: {e}")
except Exception as e: # 捕获其他所有类型的异常
    print(f"发生了一个未知错误: {e}")
finally:
    print("无论是否发生异常,finally 块总会执行。")

print("程序继续执行...")

十、数据可视化

  • Matplotlib
    • Matplotlib 是底层绘图库,灵活但写法较啰嗦。
import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y = [10, 15, 13, 17]

plt.plot(x, y, marker='o')
plt.xlabel("X 值")
plt.ylabel("Y 值")
plt.title("简单折线图")
plt.grid(True)
plt.show()
  • Seaborn

    • Seaborn 基于 Matplotlib,提供更简洁的统计图接口。
import seaborn as sns

# 直方图 + KDE
sns.histplot(df["feature"], kde=True)

# 散点图 + 回归线
sns.lmplot(x="feature1", y="feature2", data=df)

总结

掌握以上 Python 基础知识,将为您的机器学习之旅打下坚实的基础。最重要的还是多动手实践,通过编写代码来加深理解。随着学习的深入,您会接触到更多高级的 Python 特性和库的用法。接下来,建议你结合手头项目或公开数据集,动手实践、不断迭代,才能真正掌握机器学习技能。


参考链接

  • Python 官网:https://www.python.org/
  • NumPy 文档:https://numpy.org/doc/
  • Pandas 文档:https://pandas.pydata.org/docs/
  • Matplotlib 文档:https://matplotlib.org/stable/contents.html
  • Seaborn 文档:https://seaborn.pydata.org/
  • Scikit‑Learn 文档:https://scikit-learn.org/
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐