在 Ubuntu 用 Python 进行机器学习的实操指南
一 环境准备与 Python 安装
sudo apt update && sudo apt upgrade -ysudo apt install python3 python3-pippython3 --version、pip3 --versionpython3 -m venv ~/ml_venvsource ~/ml_venv/bin/activatewget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh && bash Miniconda3-latest-Linux-x86_64.shconda create -n ml_env python=3.10conda activate ml_envpip install numpy pandas scikit-learn matplotlib seaborn jupyter二 安装机器学习与深度学习框架
pip install scikit-learnpip install tensorflowpip install torch torchvision torchaudioconda install pytorch torchvision torchaudio pytorch-cuda=11.8 -c pytorch -c nvidiaconda install pytorch torchvision torchaudio cpuonly -c pytorchpython -c "import torch; print('CUDA available:', torch.cuda.is_available())"python -c "import tensorflow as tf; print('TF version:', tf.__version__)"三 快速上手示例 传统机器学习与深度学习
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
X = np.random.rand(100, 1)
y = 2 + 3 * X + 0.1 * np.random.randn(100, 1)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
print("MSE:", mean_squared_error(y_test, y_pred))
python ml_linear.pyimport tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense, Flatten
(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
model = Sequential([
Flatten(input_shape=(28, 28)),
Dense(128, activation='relu'),
Dense(10, activation='softmax')
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5, batch_size=32, verbose=2)
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=0)
print(f"Test accuracy: {test_acc:.4f}")
python tf_mnist.pypip install notebook 或 conda install jupyterjupyter notebook(浏览器自动打开)四 数据处理与计算机视觉扩展
pip install opencv-pythonimport cv2
img = cv2.imread('image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
print(gray.shape)
五 常见问题与排错建议
--user 或将虚拟环境 bin 加入 PATH。nvidia-smi 检查驱动与 GPU 状态;PyTorch 可用 torch.cuda.is_available() 验证;TensorFlow 2.10+ 在 Linux 上通常内置 GPU 支持(无需单独安装 tensorflow-gpu 包)。pip install -U pippython -m ipykernel install --user --name=ml_env