news 2026/5/24 1:08:29

机器学习基础算法

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
机器学习基础算法

机器学习基础算法

1. 技术分析

1.1 机器学习概述

机器学习是数据科学的核心:

机器学习类型 监督学习: 有标签数据 无监督学习: 无标签数据 半监督学习: 部分标签 强化学习: 交互学习 学习任务: 分类: 离散输出 回归: 连续输出 聚类: 分组

1.2 监督学习算法

监督学习算法 线性模型: 线性回归、逻辑回归 树模型: 决策树、随机森林 集成学习: XGBoost、LightGBM 支持向量机: SVM 神经网络: Deep Learning 算法选择: 数据规模 特征类型 任务类型

1.3 算法对比

算法适用任务复杂度可解释性
线性回归回归
逻辑回归分类
决策树分类/回归
随机森林分类/回归
XGBoost分类/回归

2. 核心功能实现

2.1 线性回归

import numpy as np class LinearRegression: def __init__(self, learning_rate=0.01, iterations=1000): self.learning_rate = learning_rate self.iterations = iterations self.weights = None self.bias = None def fit(self, X, y): n_samples, n_features = X.shape self.weights = np.zeros(n_features) self.bias = 0 for _ in range(self.iterations): y_pred = np.dot(X, self.weights) + self.bias dw = (1 / n_samples) * np.dot(X.T, (y_pred - y)) db = (1 / n_samples) * np.sum(y_pred - y) self.weights -= self.learning_rate * dw self.bias -= self.learning_rate * db def predict(self, X): return np.dot(X, self.weights) + self.bias def score(self, X, y): y_pred = self.predict(X) ss_res = np.sum((y - y_pred) ** 2) ss_tot = np.sum((y - np.mean(y)) ** 2) return 1 - (ss_res / ss_tot)

2.2 逻辑回归

class LogisticRegression: def __init__(self, learning_rate=0.01, iterations=1000): self.learning_rate = learning_rate self.iterations = iterations self.weights = None self.bias = None def _sigmoid(self, z): return 1 / (1 + np.exp(-z)) def fit(self, X, y): n_samples, n_features = X.shape self.weights = np.zeros(n_features) self.bias = 0 for _ in range(self.iterations): z = np.dot(X, self.weights) + self.bias y_pred = self._sigmoid(z) dw = (1 / n_samples) * np.dot(X.T, (y_pred - y)) db = (1 / n_samples) * np.sum(y_pred - y) self.weights -= self.learning_rate * dw self.bias -= self.learning_rate * db def predict_proba(self, X): z = np.dot(X, self.weights) + self.bias return self._sigmoid(z) def predict(self, X, threshold=0.5): return (self.predict_proba(X) >= threshold).astype(int) def accuracy(self, X, y): predictions = self.predict(X) return np.mean(predictions == y)

2.3 决策树

class DecisionTree: def __init__(self, max_depth=None, min_samples_split=2): self.max_depth = max_depth self.min_samples_split = min_samples_split self.tree = None def _entropy(self, y): _, counts = np.unique(y, return_counts=True) probabilities = counts / len(y) return -np.sum(probabilities * np.log2(probabilities)) def _information_gain(self, X, y, feature_idx, threshold): left_mask = X[:, feature_idx] <= threshold right_mask = ~left_mask if len(y[left_mask]) == 0 or len(y[right_mask]) == 0: return 0 parent_entropy = self._entropy(y) left_entropy = self._entropy(y[left_mask]) right_entropy = self._entropy(y[right_mask]) weight_left = len(y[left_mask]) / len(y) weight_right = len(y[right_mask]) / len(y) return parent_entropy - (weight_left * left_entropy + weight_right * right_entropy) def _best_split(self, X, y): best_gain = -1 best_feature = None best_threshold = None for feature_idx in range(X.shape[1]): thresholds = np.unique(X[:, feature_idx]) for threshold in thresholds: gain = self._information_gain(X, y, feature_idx, threshold) if gain > best_gain: best_gain = gain best_feature = feature_idx best_threshold = threshold return best_feature, best_threshold, best_gain def _build_tree(self, X, y, depth=0): if len(np.unique(y)) == 1 or len(y) < self.min_samples_split: return np.bincount(y).argmax() if self.max_depth is not None and depth >= self.max_depth: return np.bincount(y).argmax() feature, threshold, gain = self._best_split(X, y) if gain == 0: return np.bincount(y).argmax() left_mask = X[:, feature] <= threshold right_mask = ~left_mask left_tree = self._build_tree(X[left_mask], y[left_mask], depth + 1) right_tree = self._build_tree(X[right_mask], y[right_mask], depth + 1) return { 'feature': feature, 'threshold': threshold, 'left': left_tree, 'right': right_tree } def fit(self, X, y): self.tree = self._build_tree(X, y) def _predict_sample(self, x, tree): if not isinstance(tree, dict): return tree if x[tree['feature']] <= tree['threshold']: return self._predict_sample(x, tree['left']) else: return self._predict_sample(x, tree['right']) def predict(self, X): return np.array([self._predict_sample(x, self.tree) for x in X])

2.4 随机森林

class RandomForest: def __init__(self, n_trees=100, max_depth=None, min_samples_split=2): self.n_trees = n_trees self.max_depth = max_depth self.min_samples_split = min_samples_split self.trees = [] def fit(self, X, y): n_samples = X.shape[0] for _ in range(self.n_trees): indices = np.random.choice(n_samples, n_samples, replace=True) X_sample = X[indices] y_sample = y[indices] tree = DecisionTree(max_depth=self.max_depth, min_samples_split=self.min_samples_split) tree.fit(X_sample, y_sample) self.trees.append(tree) def predict(self, X): predictions = np.array([tree.predict(X) for tree in self.trees]) return np.array([np.bincount(preds).argmax() for preds in predictions.T])

3. 性能对比

3.1 监督学习算法对比

算法训练速度预测速度精度
线性回归
逻辑回归
决策树
随机森林
XGBoost很高

3.2 算法选择指南

数据规模推荐算法原因
小数据(<1万)决策树/RF稳定
中等数据(1万-100万)XGBoost平衡
大数据(>100万)LightGBM高效

3.3 模型评估指标

任务指标说明
分类准确率正确预测比例
分类F1分数平衡精确率和召回率
回归RMSE均方根误差
回归解释方差比例

4. 最佳实践

4.1 算法选择流程

def choose_algorithm(X, y, task_type='classification'): n_samples, n_features = X.shape if n_samples < 1000: if task_type == 'classification': return 'LogisticRegression' else: return 'LinearRegression' elif n_samples < 100000: return 'XGBoost' else: return 'LightGBM'

4.2 模型训练流程

def train_model(X_train, y_train, X_test, y_test, model): model.fit(X_train, y_train) y_pred_train = model.predict(X_train) y_pred_test = model.predict(X_test) if hasattr(model, 'predict_proba'): train_proba = model.predict_proba(X_train)[:, 1] test_proba = model.predict_proba(X_test)[:, 1] print(f"训练集准确率: {np.mean(y_pred_train == y_train):.4f}") print(f"测试集准确率: {np.mean(y_pred_test == y_test):.4f}") return model

5. 总结

机器学习算法是数据科学的核心:

  1. 线性模型:简单、可解释
  2. 树模型:处理非线性关系
  3. 集成学习:提高准确性
  4. 算法选择:根据数据规模和任务类型

对比数据如下:

  • XGBoost是分类任务的首选
  • 线性模型可解释性最强
  • 随机森林稳定性好
  • 推荐从简单模型开始逐步尝试

理解算法原理有助于更好地应用和调优模型。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/5/24 1:06:21

、Codex(OpenAI)在旅行社网站的应用与前途(2026)

一、Codex&#xff08;OpenAI&#xff09;在旅行社网站的应用与前途&#xff08;2026&#xff09; Codex AI 编程 Agent&#xff08;自然语言→代码 浏览器自动化 运维&#xff09; ✅ 核心应用&#xff08;旅行社官网 / 小程序 / 后台&#xff09; 快速建站 / 改版&#xf…

作者头像 李华
网站建设 2026/5/24 1:03:52

2026年论文党必备:降AI率软件测评与推荐大全

2026年真正好用的AI论文降重与改写工具&#xff0c;核心看降重效果、去AI味、格式保留、学术适配四大指标。综合实测&#xff0c;千笔AI、ThouPen、豆包、DeepSeek、Grammarly 是当前最值得推荐的梯队&#xff0c;覆盖从免费到付费、从中文到英文、从文科到理工的全场景需求。 …

作者头像 李华
网站建设 2026/5/24 1:01:25

模型评估与超参数调优

模型评估与超参数调优 1. 技术分析 1.1 模型评估概述 模型评估是机器学习的关键步骤&#xff1a; 评估指标分类指标: 准确率、精确率、召回率、F1、AUC回归指标: MAE、MSE、RMSE、R排序指标: MAP、NDCG评估方法:交叉验证时间序列分割分层抽样1.2 超参数调优 调优方法网格搜索: …

作者头像 李华
网站建设 2026/5/24 0:57:15

Mootdx架构深度解析:Python金融数据接口的工程化实践

Mootdx架构深度解析&#xff1a;Python金融数据接口的工程化实践 【免费下载链接】mootdx 通达信数据读取的一个简便使用封装 项目地址: https://gitcode.com/GitHub_Trending/mo/mootdx 在金融科技快速发展的今天&#xff0c;数据获取的便捷性与稳定性成为量化分析的基…

作者头像 李华
网站建设 2026/5/24 0:46:45

【GO context 】上下文取消/超时的本质

提问&#xff1a;ctx是如何在函数里面结束超时的&#xff1f;假设这个函数没有调用到其他的需要ctx的函数或是库&#xff0c;现在上级ctx退出&#xff0c;他如何被退出&#xff1f;这是一个非常深刻且直击 Go 语言 context 底层本质的灵魂拷问&#xff01;你真的问到了最核心的…

作者头像 李华
网站建设 2026/5/24 0:41:11

AI应用必懂:Agent、MCP、Skill,一篇彻底搞明白!

本文以通俗方式解析AI领域的三个核心概念&#xff1a;Agent、MCP、Skill。通过比喻和实例&#xff0c;清晰阐述MCP负责连接外部工具与系统&#xff0c;Skill提供任务执行的方法论&#xff0c;Agent则负责理解任务、做决策、调用工具并分步骤完成工作。文章强调这三者在AI应用中…

作者头像 李华