> 技术文档 > VSCode使用Jupyter完整指南配置机器学习环境

VSCode使用Jupyter完整指南配置机器学习环境

接下来开始机器学习部分
第一步配置环境

VSCode使用Jupyter完整指南

1. 安装必要的扩展

打开VSCode,按 Ctrl+Shift+X 打开扩展市场,搜索并安装以下扩展:

必装扩展:

  • Python (Microsoft官方) - Python语言支持
  • Jupyter (Microsoft官方) - Jupyter notebook支持
  • Pylance (Microsoft官方) - Python智能提示和语法检查

推荐扩展:

  • Python Docstring Generator - 自动生成函数文档
  • Python Environment Manager - Python环境管理
  • Jupyter Keymap - Jupyter快捷键支持

2. Python环境配置

# 方法1:使用Anaconda(推荐)conda create -n ai_learning python=3.9conda activate ai_learning# 安装Jupyter相关包conda install jupyter notebook ipykernel# 或使用pippip install jupyter notebook ipykernel# 安装AI学习必需的库pip install numpy pandas matplotlib seaborn scikit-learnpip install tensorflow keras torch torchvisionpip install plotly jupyter-widgets ipywidgets# 将环境注册到Jupyter内核python -m ipykernel install --user --name ai_learning --display-name \"AI Learning Python 3.9\"
# 方法2:使用虚拟环境python -m venv ai_env# Windows激活ai_env\\Scripts\\activate# macOS/Linux激活source ai_env/bin/activate# 安装相同的包pip install jupyter ipykernel numpy pandas matplotlib seaborn scikit-learnpython -m ipykernel install --user --name ai_env --display-name \"AI Environment\"

3. VSCode配置优化

Ctrl+, 打开设置,搜索相关设置或直接编辑 settings.json

{ // Python解释器路径 \"python.defaultInterpreterPath\": \"~/anaconda3/envs/ai_learning/bin/python\", // Jupyter设置 \"jupyter.askForKernelRestart\": false, \"jupyter.sendSelectionToInteractiveWindow\": false, \"jupyter.interactiveWindow.creationMode\": \"perFile\", \"jupyter.widgetScriptSources\": [\"jsdelivr.com\", \"unpkg.com\"], \"jupyter.runStartupCommands\": [\"%load_ext autoreload\", \"%autoreload 2\"], // Notebook设置 \"notebook.cellToolbarLocation\": { \"default\": \"right\", \"jupyter-notebook\": \"left\" }, \"notebook.output.textLineLimit\": 30, \"notebook.showCellStatusBar\": \"visible\", // Python设置 \"python.terminal.activateEnvironment\": true, \"python.linting.enabled\": true, \"python.linting.pylintEnabled\": true, // 字体和主题 \"editor.fontSize\": 14, \"editor.fontFamily\": \"\'Fira Code\', \'Consolas\', \'Courier New\', monospace\", \"editor.fontLigatures\": true, // 中文支持 \"files.autoGuessEncoding\": true}

4. 创建和使用Jupyter Notebook

方法1:通过命令面板

  1. Ctrl+Shift+P 打开命令面板
  2. 输入 “Jupyter: Create New Jupyter Notebook”
  3. 选择Python内核(选择我们创建的ai_learning环境)

方法2:直接创建文件

  1. 在文件资源管理器中右键点击
  2. 选择 “New File”
  3. 命名为 test.ipynb
  4. VSCode会自动识别为Jupyter文件

方法3:使用快捷键

  • Ctrl+Shift+P → “Python: Create Blank New Jupyter Notebook”

5. Jupyter Notebook基本操作

单元格操作:

  • Shift+Enter - 运行当前单元格并移到下一个
  • Ctrl+Enter - 运行当前单元格不移动
  • Alt+Enter - 运行当前单元格并在下方插入新单元格
  • A - 在当前单元格上方插入新单元格
  • B - 在当前单元格下方插入新单元格
  • DD - 删除当前单元格
  • M - 转换为Markdown单元格
  • Y - 转换为代码单元格

实用快捷键:

  • Ctrl+/ - 注释/取消注释
  • Tab - 自动补全
  • Shift+Tab - 查看函数文档
  • Ctrl+S - 保存
  • Ctrl+Z - 撤销

6. 环境切换和内核管理

切换Python环境:

  1. 点击右上角的内核选择器
  2. 选择 “Select Another Kernel”
  3. 选择 “Python Environments”
  4. 选择你创建的 “AI Learning Python 3.9”

查看可用内核:

jupyter kernelspec list

删除不需要的内核:

jupyter kernelspec uninstall unwanted_kernel_name

7. 实用技巧和最佳实践

7.1 魔法命令(Magic Commands)

# 在notebook中使用以下魔法命令%matplotlib inline # 图表内联显示%load_ext autoreload # 自动重载模块%autoreload 2 # 自动重载所有模块# 查看执行时间%time your_function()%timeit your_function()# 查看当前变量%who # 简单列表%whos # 详细信息# 执行shell命令!pip list!ls -la

7.2 调试技巧

# 在代码中设置断点import pdb; pdb.set_trace()# 或使用ipdb(需要安装:pip install ipdb)import ipdb; ipdb.set_trace()# 在VSCode中可以直接设置断点,点击行号左侧

7.3 输出优化

# 设置pandas显示选项import pandas as pdpd.set_option(\'display.max_columns\', None)pd.set_option(\'display.max_rows\', 100)pd.set_option(\'display.width\', None)# 设置numpy显示选项import numpy as npnp.set_printoptions(precision=3, suppress=True)# 设置matplotlib中文显示import matplotlib.pyplot as pltplt.rcParams[\'font.sans-serif\'] = [\'SimHei\'] # 中文字体plt.rcParams[\'axes.unicode_minus\'] = False # 负号显示

8. 测试配置

创建一个测试文件验证配置是否正确:

# 测试基本功能import sysprint(\"Python版本:\", sys.version)print(\"Python路径:\", sys.executable)plt.rcParams[\'font.sans-serif\'] = [\'SimHei\'] # 用来正常显示中文标签plt.rcParams[\'axes.unicode_minus\'] = False # 用来正常显示负号# 测试科学计算库import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsprint(\"NumPy版本:\", np.__version__)print(\"Pandas版本:\", pd.__version__)# 测试简单绘图x = np.linspace(0, 10, 100)y = np.sin(x)plt.figure(figsize=(10, 6))plt.plot(x, y, label=\'sin(x)\')plt.title(\'测试图表\')plt.xlabel(\'x\')plt.ylabel(\'y\')plt.legend()plt.grid(True)plt.show()# 测试数据处理df = pd.DataFrame({ \'A\': np.random.randn(5), \'B\': np.random.randn(5), \'C\': np.random.randn(5)})print(\"\\n测试DataFrame:\")print(df)# 测试机器学习库try: import sklearn print(f\"Scikit-learn版本: {sklearn.__version__}\") print(\"✅ 机器学习环境配置成功!\")except ImportError: print(\"❌ 需要安装scikit-learn\")try: import tensorflow as tf print(f\"TensorFlow版本: {tf.__version__}\") print(\"✅ 深度学习环境配置成功!\")except ImportError: print(\"❌ 需要安装TensorFlow\")

9. 常见问题解决

问题1:内核无法连接

# 重新安装ipykernelpip uninstall ipykernelpip install ipykernelpython -m ipykernel install --user

问题2:中文显示乱码

# 在notebook开头添加import matplotlibmatplotlib.rcParams[\'font.family\'] = [\'DejaVu Sans\']# 或下载中文字体文件

问题3:模块导入错误

# 检查当前Python路径import sysprint(sys.path)# 添加自定义路径sys.path.append(\'/path/to/your/modules\')

问题4:图表不显示

# 确保添加这行%matplotlib inline# 或者尝试%matplotlib widget

10. 推荐的工作流

  1. 项目结构
ai_learning_project/├── data/  # 数据文件├── notebooks/ # Jupyter notebooks├── src/  # Python源代码├── models/ # 保存的模型├── results/ # 结果和图表└── requirements.txt # 依赖列表
  1. 文件命名
  • 01_data_exploration.ipynb - 数据探索
  • 02_data_preprocessing.ipynb - 数据预处理
  • 03_model_training.ipynb - 模型训练
  • 04_model_evaluation.ipynb - 模型评估