Skip to content

Instantly share code, notes, and snippets.

@KuRRe8
Last active May 9, 2025 02:06
Show Gist options
  • Save KuRRe8/36f63d23ef205a8e02b7b7ec009cc4e8 to your computer and use it in GitHub Desktop.
Save KuRRe8/36f63d23ef205a8e02b7b7ec009cc4e8 to your computer and use it in GitHub Desktop.
和Python使用有关的一些教程,按类别分为不同文件

Python教程

Python是一个新手友好的语言,并且现在机器学习社区深度依赖于Python,C++, Cuda C, R等语言,使得Python的热度稳居第一。本Gist提供Python相关的一些教程,可以直接在Jupyter Notebook中运行。

  1. 语言级教程,一般不涉及初级主题;
  2. 标准库教程,最常见的标准库基本用法;
  3. 第三方库教程,主要是常见的库如numpy,pytorch诸如此类,只涉及基本用法,不考虑新特性

其他内容就不往这个Gist里放了,注意Gist依旧由git进行版本控制,所以可以git clone 到本地,或者直接Google Colab\ Kaggle打开相应的ipynb文件

直接在网页浏览时,由于没有文件列表,可以按Ctrl + F来检索相应的目录,或者点击下面的超链接。

想要参与贡献的直接在评论区留言,有什么问题的也在评论区说 ^.^

目录-语言部分

目录-库部分

目录-具体业务库部分-本教程更多关注机器学习深度学习内容

Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Matplotlib - Python 数据可视化基础教程\n",
"\n",
"欢迎来到 Matplotlib 教程!Matplotlib 是 Python 中最基础、最广泛使用的数据可视化库。它提供了一个灵活的平台,可以创建各种静态、动态和交互式的图表。\n",
"\n",
"**为什么 Matplotlib 对 ML/DL/数据科学很重要?**\n",
"\n",
"1. **探索性数据分析 (EDA)**:可视化是理解数据分布、关系和模式的关键步骤。\n",
"2. **结果展示**:清晰地展示模型性能、比较结果或呈现发现。\n",
"3. **调试与监控**:绘制损失曲线、激活值分布等,有助于监控模型训练过程。\n",
"4. **生态系统基础**:许多其他高级可视化库(如 Seaborn, Pandas 的绘图功能)都构建在 Matplotlib 之上。\n",
"\n",
"**Matplotlib 的两种主要接口:**\n",
"\n",
"* **`pyplot` 接口**:基于状态机的接口(类似于 MATLAB)。它简单易用,适合快速绘图。\n",
"* **面向对象 (OO) 接口**:提供更多的控制和灵活性,特别适合创建复杂的图形和在 GUI 应用中嵌入图形。\n",
"\n",
"本教程将主要使用 `pyplot` 接口入门,并简要介绍 OO 接口。\n",
"\n",
"**本教程将涵盖:**\n",
"\n",
"1. 基本绘图 (`plot`)\n",
"2. 常用图表类型 (散点图, 条形图, 直方图)\n",
"3. 自定义图形元素 (标题, 标签, 图例, 颜色, 样式)\n",
"4. 子图 (Subplots)\n",
"5. 图像显示 (`imshow`)\n",
"6. 保存图形 (`savefig`)\n",
"7. 面向对象接口简介"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 准备工作:导入 Matplotlib 和 NumPy\n",
"\n",
"按照惯例,我们将 `matplotlib.pyplot` 导入为 `plt`。通常也需要 NumPy 来生成数据。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"\n",
"# 这行是 Jupyter Notebook 的魔法命令,通常确保图形在单元格内显示\n",
"%matplotlib inline\n",
"\n",
"print(\"Matplotlib and NumPy imported.\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1. 基本绘图 (`plot`)\n",
"\n",
"`plt.plot()` 是最基础的绘图函数,通常用于绘制线图。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 准备数据\n",
"x = np.linspace(0, 10, 100) # 0 到 10 之间生成 100 个点\n",
"y_sin = np.sin(x)\n",
"y_cos = np.cos(x)\n",
"\n",
"# 绘制简单的线图\n",
"plt.plot(x, y_sin)\n",
"plt.xlabel(\"x axis label\")\n",
"plt.ylabel(\"sin(x)\")\n",
"plt.title(\"Simple Sine Wave\")\n",
"plt.grid(True) # 添加网格线\n",
"plt.show() # 显示图形 (在脚本中必需,在Jupyter中通常可选)\n",
"\n",
"# 在同一张图上绘制多条线\n",
"plt.plot(x, y_sin, label='Sine') # 添加标签用于图例\n",
"plt.plot(x, y_cos, label='Cosine')\n",
"plt.xlabel(\"x\")\n",
"plt.ylabel(\"y\")\n",
"plt.title(\"Sine and Cosine Waves\")\n",
"plt.legend() # 显示图例\n",
"plt.grid(True)\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2. 常用图表类型\n",
"\n",
"除了线图,Matplotlib 还可以轻松创建其他常见图表。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# --- 散点图 (Scatter Plot) ---\n",
"x_scatter = np.random.rand(50) # 50个随机 x\n",
"y_scatter = np.random.rand(50) # 50个随机 y\n",
"colors = np.random.rand(50) # 随机颜色值\n",
"sizes = 100 * np.random.rand(50) # 随机大小\n",
"\n",
"plt.scatter(x_scatter, y_scatter, c=colors, s=sizes, alpha=0.7, cmap='viridis')\n",
"# c: 颜色, s: 大小, alpha: 透明度, cmap: 颜色映射\n",
"plt.xlabel(\"X value\")\n",
"plt.ylabel(\"Y value\")\n",
"plt.title(\"Scatter Plot Example\")\n",
"plt.colorbar() # 显示颜色条\n",
"plt.show()\n",
"\n",
"# --- 条形图 (Bar Chart) ---\n",
"categories = ['Category A', 'Category B', 'Category C']\n",
"values = [10, 25, 15]\n",
"\n",
"plt.bar(categories, values, color=['red', 'green', 'blue'])\n",
"plt.xlabel(\"Categories\")\n",
"plt.ylabel(\"Values\")\n",
"plt.title(\"Bar Chart Example\")\n",
"plt.show()\n",
"\n",
"# 水平条形图\n",
"plt.barh(categories, values, color='skyblue')\n",
"plt.xlabel(\"Values\")\n",
"plt.ylabel(\"Categories\")\n",
"plt.title(\"Horizontal Bar Chart Example\")\n",
"plt.show()\n",
"\n",
"# --- 直方图 (Histogram) ---\n",
"data_hist = np.random.randn(1000) # 1000个标准正态分布随机数\n",
"\n",
"plt.hist(data_hist, bins=30, color='purple', alpha=0.7, edgecolor='black')\n",
"# bins: 分箱数量\n",
"plt.xlabel(\"Value\")\n",
"plt.ylabel(\"Frequency\")\n",
"plt.title(\"Histogram Example\")\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3. 自定义图形元素\n",
"\n",
"Matplotlib 允许对图形的几乎所有方面进行详细定制。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x = np.linspace(0, 5, 20)\n",
"y1 = x**2\n",
"y2 = x**3\n",
"\n",
"plt.plot(x, y1,\n",
" color='blue', # 线条颜色\n",
" linestyle='--', # 线条样式 ('-', '--', '-.', ':')\n",
" linewidth=2, # 线条宽度\n",
" marker='o', # 数据点标记样式 ('o', 's', '^', '+', '*')\n",
" markersize=5, # 标记大小\n",
" label='y = x^2') # 图例标签\n",
"\n",
"plt.plot(x, y2,\n",
" color='#FF8C00', # 使用十六进制颜色码 (暗橙色)\n",
" linestyle=':', # 点线\n",
" linewidth=2,\n",
" marker='s', # 方块标记\n",
" markersize=6,\n",
" label='y = x^3')\n",
"\n",
"# 设置坐标轴范围\n",
"plt.xlim(0, 5)\n",
"plt.ylim(0, 130)\n",
"\n",
"# 添加标题和标签\n",
"plt.title(\"Customized Plot\", fontsize=16)\n",
"plt.xlabel(\"X Axis\", fontsize=12)\n",
"plt.ylabel(\"Y Axis\", fontsize=12)\n",
"\n",
"# 添加网格和图例\n",
"plt.grid(True, linestyle='-.', alpha=0.5)\n",
"plt.legend(loc='upper left', fontsize=10) # loc 指定图例位置\n",
"\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4. 子图 (Subplots)\n",
"\n",
"经常需要在同一个图形窗口 (Figure) 中绘制多个子图 (Axes)。有两种主要方式:\n",
"1. `plt.subplot()` (状态机方法)\n",
"2. `plt.subplots()` (面向对象方法 - 更推荐)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# --- 方法 1: plt.subplot() ---\n",
"plt.figure(figsize=(10, 4)) # 创建一个图形窗口, figsize 指定大小 (英寸)\n",
"\n",
"plt.subplot(1, 2, 1) # (nrows, ncols, index), index 从 1 开始\n",
"plt.plot(x, y_sin, 'r--') # 红色虚线\n",
"plt.title('Sine Wave (subplot 1)')\n",
"plt.grid(True)\n",
"\n",
"plt.subplot(1, 2, 2)\n",
"plt.plot(x, y_cos, 'g*-') # 绿色星号实线\n",
"plt.title('Cosine Wave (subplot 2)')\n",
"plt.grid(True)\n",
"\n",
"plt.suptitle(\"Using plt.subplot()\", fontsize=14) # 整个 Figure 的大标题\n",
"plt.tight_layout() # 自动调整子图参数以适应图形区域\n",
"plt.show()\n",
"\n",
"# --- 方法 2: plt.subplots() (更推荐) ---\n",
"# 它会创建一个 Figure 和一个包含 Axes 对象的 NumPy 数组\n",
"fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(10, 4)) # 返回 figure 和 axes 数组\n",
"\n",
"# axes 是一个 NumPy 数组,包含子图对象\n",
"# print(f\"Type of fig: {type(fig)}\")\n",
"# print(f\"Type of axes: {type(axes)}, shape: {axes.shape}\")\n",
"\n",
"# 在第一个子图 (axes[0]) 上绘制\n",
"axes[0].plot(x, y_sin, 'b-.') # 蓝色点划线\n",
"axes[0].set_title('Sine Wave (axes[0])')\n",
"axes[0].set_xlabel('x')\n",
"axes[0].set_ylabel('sin(x)')\n",
"axes[0].grid(True)\n",
"\n",
"# 在第二个子图 (axes[1]) 上绘制\n",
"axes[1].plot(x, y_cos, 'm:') # 洋红色点线\n",
"axes[1].set_title('Cosine Wave (axes[1])')\n",
"axes[1].set_xlabel('x')\n",
"axes[1].set_ylabel('cos(x)')\n",
"axes[1].grid(True)\n",
"\n",
"fig.suptitle(\"Using plt.subplots()\", fontsize=14)\n",
"plt.tight_layout()\n",
"plt.show()\n",
"\n",
"# 示例:2x2 子图\n",
"fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(8, 8))\n",
"axes[0, 0].plot(x, x, 'r')\n",
"axes[0, 0].set_title('y = x')\n",
"axes[0, 1].plot(x, x**2, 'g')\n",
"axes[0, 1].set_title('y = x^2')\n",
"axes[1, 0].plot(x, np.exp(x), 'b')\n",
"axes[1, 0].set_title('y = e^x')\n",
"axes[1, 1].plot(x, np.log1p(x), 'k') # log(1+x)\n",
"axes[1, 1].set_title('y = log(1+x)')\n",
"\n",
"for ax_row in axes:\n",
" for ax in ax_row:\n",
" ax.grid(True)\n",
"\n",
"plt.tight_layout()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 5. 图像显示 (`imshow`)\n",
"\n",
"`plt.imshow()` 用于将 NumPy 数组显示为图像。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 创建一个简单的灰度图像数据 (例如,一个棋盘格)\n",
"img_data = np.zeros((10, 10))\n",
"img_data[::2, ::2] = 1 # 偶数行偶数列设为1\n",
"img_data[1::2, 1::2] = 1 # 奇数行奇数列设为1\n",
"\n",
"plt.imshow(img_data, cmap='gray') # cmap='gray' 指定灰度颜色映射\n",
"plt.title(\"Simple Grayscale Image (Checkerboard)\")\n",
"plt.colorbar()\n",
"plt.show()\n",
"\n",
"# 创建一个随机彩色图像数据 (3通道 RGB)\n",
"img_color = np.random.rand(10, 10, 3) # 10x10 像素, 3个颜色通道 (RGB)\n",
"\n",
"plt.imshow(img_color)\n",
"plt.title(\"Random Color Image\")\n",
"# plt.axis('off') # 可以关闭坐标轴\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 6. 保存图形 (`savefig`)\n",
"\n",
"可以将绘制的图形保存到文件中。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"\n",
"x = np.linspace(0, 2 * np.pi, 50)\n",
"y = np.sin(x)\n",
"\n",
"plt.figure() # 创建一个新的图形\n",
"plt.plot(x, y)\n",
"plt.title(\"Plot to be Saved\")\n",
"plt.xlabel(\"Radians\")\n",
"plt.ylabel(\"sin(x)\")\n",
"plt.grid(True)\n",
"\n",
"output_filename = \"sine_wave_plot.png\"\n",
"plt.savefig(output_filename, dpi=150, bbox_inches='tight') \n",
"# dpi: 分辨率 (dots per inch)\n",
"# bbox_inches='tight': 尝试裁剪掉空白边缘\n",
"\n",
"print(f\"Plot saved to {output_filename}\")\n",
"plt.show() # 仍然可以在 notebook 中显示\n",
"\n",
"# 清理\n",
"if os.path.exists(output_filename):\n",
" os.remove(output_filename)\n",
" print(f\"Cleaned up {output_filename}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 7. 面向对象接口简介\n",
"\n",
"虽然 `pyplot` 接口方便快捷,但对于更复杂的图形或需要更多控制的情况,面向对象 (OO) 的接口通常更好。核心思想是显式地创建和操作 `Figure` 和 `Axes` 对象。\n",
"\n",
"* **`Figure`**: 整个图形窗口或画布。\n",
"* **`Axes`**: 图形中的一个子图区域,包含坐标轴、标签、数据点等。一个 Figure 可以包含多个 Axes。\n",
"\n",
"`plt.subplots()` 是创建 Figure 和 Axes 的常用方法。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# OO 风格示例\n",
"x_oo = np.linspace(0, 10, 100)\n",
"y_oo = np.sqrt(x_oo)\n",
"\n",
"# 1. 创建 Figure 和 Axes 对象\n",
"fig, ax = plt.subplots(figsize=(6, 4))\n",
"\n",
"# 2. 使用 Axes 对象的方法进行绘图和设置\n",
"ax.plot(x_oo, y_oo, color='purple', label='sqrt(x)')\n",
"ax.set_xlabel(\"X Value\")\n",
"ax.set_ylabel(\"Square Root\")\n",
"ax.set_title(\"Object-Oriented Plotting Example\")\n",
"ax.grid(True)\n",
"ax.legend()\n",
"\n",
"# 3. 显示图形 (pyplot 仍然可以用于显示)\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 总结\n",
"\n",
"Matplotlib 是 Python 数据可视化的基石。通过 `pyplot` 接口可以快速创建常见的图表,而面向对象的接口提供了更精细的控制。\n",
"\n",
"**关键要点:**\n",
"* 使用 `plt.plot()` 绘制线图,`plt.scatter()`, `plt.bar()`, `plt.hist()` 绘制其他常见图表。\n",
"* 使用 `plt.xlabel()`, `plt.ylabel()`, `plt.title()`, `plt.legend()` 等添加标签和图例。\n",
"* 可以通过颜色、线型、标记等参数自定义图形外观。\n",
"* 使用 `plt.subplots()` 创建包含多个子图的图形。\n",
"* 使用 `plt.imshow()` 显示图像数据。\n",
"* 使用 `plt.savefig()` 保存图形。\n",
"* 理解 `pyplot` 接口和面向对象接口的区别。\n",
"\n",
"Matplotlib 非常强大,有很多高级功能(3D绘图、动画、自定义样式等)值得探索。官方文档和示例库 (Gallery) 是非常好的学习资源。同时,Seaborn 库基于 Matplotlib 提供了更高级的统计可视化功能,通常与 Matplotlib 结合使用。"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.12"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 5
}
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
@KuRRe8
Copy link
Author

KuRRe8 commented May 8, 2025

返回顶部

有见解,有问题,或者单纯想盖楼灌水,都可以在这里发表!

因为文档比较多,有时候渲染不出来ipynb是浏览器性能的问题,刷新即可

或者git clone到本地来阅读

ChatGPT Image May 9, 2025, 04_45_04 AM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment