Ubuntu Python机器学习库使用指南
一 环境准备与基础安装
二 GPU加速配置
三 常用库安装与用途
| 库 | 主要用途 | 安装命令(CPU) | 备注 |
|---|---|---|---|
| NumPy | 数组与线性代数 | pip install numpy | 科学计算基础 |
| pandas | 数据处理与分析 | pip install pandas | DataFrame 高效操作 |
| SciPy | 科学算法与稀疏矩阵 | pip install scipy | 依赖 BLAS/LAPACK |
| scikit-learn | 传统机器学习 | pip install scikit-learn | 分类、回归、聚类、评估 |
| Matplotlib/Seaborn | 可视化 | pip install matplotlib seaborn | 绘图与统计图 |
| TensorFlow/Keras | 深度学习 | pip install tensorflow | tf.keras 高级 API |
| PyTorch | 深度学习 | pip install torch torchvision torchaudio | GPU 需匹配 CUDA |
| Jupyter | 交互式笔记本 | pip install notebook | 适合探索式分析 |
四 快速上手示例
python - <<‘PY’ import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error, r2_score import matplotlib.pyplot as plt
X = np.linspace(0, 10, 100).reshape(-1, 1) y = 3.5 * X.ravel() + np.random.normal(0, 2, X.size)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, random_state=42)
model = LinearRegression() model.fit(X_tr, y_tr)
y_pred = model.predict(X_te) print(“MSE:”, mean_squared_error(y_te, y_pred)) print(“R2:”, r2_score(y_te, y_pred))
plt.scatter(X_te, y_te, color=‘blue’, label=‘Actual’) plt.plot(X_te, y_pred, color=‘red’, label=‘Predicted’) plt.legend(); plt.show() PY
python - <<‘PY’ import tensorflow as tf from tensorflow.keras import Sequential from tensorflow.keras.layers import Dense, Flatten from tensorflow.keras.utils import to_categorical
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() x_train, x_test = x_train/255.0, x_test/255.0 y_train = to_categorical(y_train, 10)
model = Sequential([ Flatten(input_shape=(28, 28)), Dense(128, activation=‘relu’), Dense(10, activation=‘softmax’) ]) model.compile(optimizer=‘adam’, loss=‘categorical_crossentropy’, metrics=[‘accuracy’])
model.fit(x_train, y_train, epochs=3, batch_size=32, validation_split=0.1, verbose=2) loss, acc = model.evaluate(x_test, to_categorical(y_test, 10), verbose=0) print(f"Test accuracy: {acc:.4f}") PY
五 常见问题与排错