您的位置:首页 >如何在Ubuntu用Python进行机器学习
发布于2026-04-24 阅读(0)
扫一扫,手机访问

想在 Ubuntu 系统上快速搭建一个稳定、高效的机器学习开发环境吗?这份指南将带你从零开始,一步步完成环境配置、框架安装,并运行你的第一个模型。整个过程清晰直接,力求避开常见的“坑”。
万事开头先打基础。首先,确保你的系统是最新的,并安装好 Python 和包管理工具 pip。
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 a vailable:', torch.cuda.is_a vailable())"python -c "import tensorflow as tf; print('TF version:', tf.__version__)"环境就绪,最好的验证方式就是跑通一个例子。下面两个经典示例,带你感受不同范式的建模流程。
ml_linear.py:
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.pytf_mnist.py:
import 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,浏览器会自动打开工作界面。机器学习离不开数据。如果你想涉足计算机视觉,OpenCV 是处理图像数据的瑞士军刀。
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 状态。torch.cuda.is_a vailable() 验证;TensorFlow 2.10+ 在 Linux 上通常已内置 GPU 支持,无需单独安装旧的 tensorflow-gpu 包。pip install -U pippython -m ipykernel install --user --name=ml_env(将 ml_env 替换为你的环境名)。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9