机器学习安装使用教程
一、机器学习简介
机器学习(Machine Learning)是一种通过算法让计算机从数据中学习并进行预测或决策的技术。常见应用包括分类、回归、聚类、图像识别、语音识别、自然语言处理等。
本教程以 Python 为基础,介绍主流机器学习工具包的安装与使用,包括 scikit-learn、XGBoost、LightGBM 等。
二、环境准备
2.1 安装 Python
建议使用 Python 3.8 或以上版本。可通过官网下载或使用 Anaconda:
- 官网下载:https://www.python.org/
- Anaconda:https://www.anaconda.com/
三、安装主流机器学习工具
3.1 安装 scikit-learn(最常用的机器学习库)
pip install scikit-learn
或通过 Anaconda:
conda install scikit-learn
3.2 安装 XGBoost(梯度提升框架)
pip install xgboost
3.3 安装 LightGBM(高性能 GBDT 库)
pip install lightgbm
3.4 安装 pandas、numpy(数据处理)
pip install pandas numpy
3.5 安装 matplotlib、seaborn(可视化)
pip install matplotlib seaborn
四、快速入门示例(使用 scikit-learn)
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score# 加载数据集
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2, random_state=42)# 模型训练
clf = RandomForestClassifier()
clf.fit(X_train, y_train)# 模型预测
y_pred = clf.predict(X_test)
print("准确率:", accuracy_score(y_test, y_pred))
五、使用 XGBoost 示例
import xgboost as xgb
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_scoredata = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.2, random_state=42)model = xgb.XGBClassifier()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)print("XGBoost 准确率:", accuracy_score(y_test, y_pred))
六、可视化模型结果
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import confusion_matrixconf_mat = confusion_matrix(y_test, y_pred)
sns.heatmap(conf_mat, annot=True, fmt="d", cmap="Blues")
plt.title("混淆矩阵")
plt.xlabel("预测")
plt.ylabel("实际")
plt.show()
七、常见问题
Q1: 安装失败?
- 确保网络正常,可使用国内镜像源:
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple scikit-learn
Q2: 模块未找到?
请确认运行代码的 Python 环境和 pip 安装路径一致(例如 venv 或 conda 环境)。
八、学习资源推荐
- scikit-learn 官方文档
- XGBoost 官方文档
- Kaggle 学习路径
- 《机器学习实战》、吴恩达《机器学习》课程
本文由“小奇Java面试”原创发布,转载请注明出处。
可以搜索【小奇JAVA面试】第一时间阅读,回复【资料】获取福利,回复【项目】获取项目源码,回复【简历模板】获取简历模板,回复【学习路线图】获取学习路线图。