[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"similar-JavierAntoran--Bayesian-Neural-Networks":3,"tool-JavierAntoran--Bayesian-Neural-Networks":61},[4,18,26,36,44,53],{"id":5,"name":6,"github_repo":7,"description_zh":8,"stars":9,"difficulty_score":10,"last_commit_at":11,"category_tags":12,"status":17},4358,"openclaw","openclaw\u002Fopenclaw","OpenClaw 是一款专为个人打造的本地化 AI 助手，旨在让你在自己的设备上拥有完全可控的智能伙伴。它打破了传统 AI 助手局限于特定网页或应用的束缚，能够直接接入你日常使用的各类通讯渠道，包括微信、WhatsApp、Telegram、Discord、iMessage 等数十种平台。无论你在哪个聊天软件中发送消息，OpenClaw 都能即时响应，甚至支持在 macOS、iOS 和 Android 设备上进行语音交互，并提供实时的画布渲染功能供你操控。\n\n这款工具主要解决了用户对数据隐私、响应速度以及“始终在线”体验的需求。通过将 AI 部署在本地，用户无需依赖云端服务即可享受快速、私密的智能辅助，真正实现了“你的数据，你做主”。其独特的技术亮点在于强大的网关架构，将控制平面与核心助手分离，确保跨平台通信的流畅性与扩展性。\n\nOpenClaw 非常适合希望构建个性化工作流的技术爱好者、开发者，以及注重隐私保护且不愿被单一生态绑定的普通用户。只要具备基础的终端操作能力（支持 macOS、Linux 及 Windows WSL2），即可通过简单的命令行引导完成部署。如果你渴望拥有一个懂你",349277,3,"2026-04-06T06:32:30",[13,14,15,16],"Agent","开发框架","图像","数据工具","ready",{"id":19,"name":20,"github_repo":21,"description_zh":22,"stars":23,"difficulty_score":10,"last_commit_at":24,"category_tags":25,"status":17},3808,"stable-diffusion-webui","AUTOMATIC1111\u002Fstable-diffusion-webui","stable-diffusion-webui 是一个基于 Gradio 构建的网页版操作界面，旨在让用户能够轻松地在本地运行和使用强大的 Stable Diffusion 图像生成模型。它解决了原始模型依赖命令行、操作门槛高且功能分散的痛点，将复杂的 AI 绘图流程整合进一个直观易用的图形化平台。\n\n无论是希望快速上手的普通创作者、需要精细控制画面细节的设计师，还是想要深入探索模型潜力的开发者与研究人员，都能从中获益。其核心亮点在于极高的功能丰富度：不仅支持文生图、图生图、局部重绘（Inpainting）和外绘（Outpainting）等基础模式，还独创了注意力机制调整、提示词矩阵、负向提示词以及“高清修复”等高级功能。此外，它内置了 GFPGAN 和 CodeFormer 等人脸修复工具，支持多种神经网络放大算法，并允许用户通过插件系统无限扩展能力。即使是显存有限的设备，stable-diffusion-webui 也提供了相应的优化选项，让高质量的 AI 艺术创作变得触手可及。",162132,"2026-04-05T11:01:52",[14,15,13],{"id":27,"name":28,"github_repo":29,"description_zh":30,"stars":31,"difficulty_score":32,"last_commit_at":33,"category_tags":34,"status":17},1381,"everything-claude-code","affaan-m\u002Feverything-claude-code","everything-claude-code 是一套专为 AI 编程助手（如 Claude Code、Codex、Cursor 等）打造的高性能优化系统。它不仅仅是一组配置文件，而是一个经过长期实战打磨的完整框架，旨在解决 AI 代理在实际开发中面临的效率低下、记忆丢失、安全隐患及缺乏持续学习能力等核心痛点。\n\n通过引入技能模块化、直觉增强、记忆持久化机制以及内置的安全扫描功能，everything-claude-code 能显著提升 AI 在复杂任务中的表现，帮助开发者构建更稳定、更智能的生产级 AI 代理。其独特的“研究优先”开发理念和针对 Token 消耗的优化策略，使得模型响应更快、成本更低，同时有效防御潜在的攻击向量。\n\n这套工具特别适合软件开发者、AI 研究人员以及希望深度定制 AI 工作流的技术团队使用。无论您是在构建大型代码库，还是需要 AI 协助进行安全审计与自动化测试，everything-claude-code 都能提供强大的底层支持。作为一个曾荣获 Anthropic 黑客大奖的开源项目，它融合了多语言支持与丰富的实战钩子（hooks），让 AI 真正成长为懂上",150037,2,"2026-04-10T23:33:47",[14,13,35],"语言模型",{"id":37,"name":38,"github_repo":39,"description_zh":40,"stars":41,"difficulty_score":32,"last_commit_at":42,"category_tags":43,"status":17},2271,"ComfyUI","Comfy-Org\u002FComfyUI","ComfyUI 是一款功能强大且高度模块化的视觉 AI 引擎，专为设计和执行复杂的 Stable Diffusion 图像生成流程而打造。它摒弃了传统的代码编写模式，采用直观的节点式流程图界面，让用户通过连接不同的功能模块即可构建个性化的生成管线。\n\n这一设计巧妙解决了高级 AI 绘图工作流配置复杂、灵活性不足的痛点。用户无需具备编程背景，也能自由组合模型、调整参数并实时预览效果，轻松实现从基础文生图到多步骤高清修复等各类复杂任务。ComfyUI 拥有极佳的兼容性，不仅支持 Windows、macOS 和 Linux 全平台，还广泛适配 NVIDIA、AMD、Intel 及苹果 Silicon 等多种硬件架构，并率先支持 SDXL、Flux、SD3 等前沿模型。\n\n无论是希望深入探索算法潜力的研究人员和开发者，还是追求极致创作自由度的设计师与资深 AI 绘画爱好者，ComfyUI 都能提供强大的支持。其独特的模块化架构允许社区不断扩展新功能，使其成为当前最灵活、生态最丰富的开源扩散模型工具之一，帮助用户将创意高效转化为现实。",108322,"2026-04-10T11:39:34",[14,15,13],{"id":45,"name":46,"github_repo":47,"description_zh":48,"stars":49,"difficulty_score":32,"last_commit_at":50,"category_tags":51,"status":17},6121,"gemini-cli","google-gemini\u002Fgemini-cli","gemini-cli 是一款由谷歌推出的开源 AI 命令行工具，它将强大的 Gemini 大模型能力直接集成到用户的终端环境中。对于习惯在命令行工作的开发者而言，它提供了一条从输入提示词到获取模型响应的最短路径，无需切换窗口即可享受智能辅助。\n\n这款工具主要解决了开发过程中频繁上下文切换的痛点，让用户能在熟悉的终端界面内直接完成代码理解、生成、调试以及自动化运维任务。无论是查询大型代码库、根据草图生成应用，还是执行复杂的 Git 操作，gemini-cli 都能通过自然语言指令高效处理。\n\n它特别适合广大软件工程师、DevOps 人员及技术研究人员使用。其核心亮点包括支持高达 100 万 token 的超长上下文窗口，具备出色的逻辑推理能力；内置 Google 搜索、文件操作及 Shell 命令执行等实用工具；更独特的是，它支持 MCP（模型上下文协议），允许用户灵活扩展自定义集成，连接如图像生成等外部能力。此外，个人谷歌账号即可享受免费的额度支持，且项目基于 Apache 2.0 协议完全开源，是提升终端工作效率的理想助手。",100752,"2026-04-10T01:20:03",[52,13,15,14],"插件",{"id":54,"name":55,"github_repo":56,"description_zh":57,"stars":58,"difficulty_score":32,"last_commit_at":59,"category_tags":60,"status":17},4721,"markitdown","microsoft\u002Fmarkitdown","MarkItDown 是一款由微软 AutoGen 团队打造的轻量级 Python 工具，专为将各类文件高效转换为 Markdown 格式而设计。它支持 PDF、Word、Excel、PPT、图片（含 OCR）、音频（含语音转录）、HTML 乃至 YouTube 链接等多种格式的解析，能够精准提取文档中的标题、列表、表格和链接等关键结构信息。\n\n在人工智能应用日益普及的今天，大语言模型（LLM）虽擅长处理文本，却难以直接读取复杂的二进制办公文档。MarkItDown 恰好解决了这一痛点，它将非结构化或半结构化的文件转化为模型“原生理解”且 Token 效率极高的 Markdown 格式，成为连接本地文件与 AI 分析 pipeline 的理想桥梁。此外，它还提供了 MCP（模型上下文协议）服务器，可无缝集成到 Claude Desktop 等 LLM 应用中。\n\n这款工具特别适合开发者、数据科学家及 AI 研究人员使用，尤其是那些需要构建文档检索增强生成（RAG）系统、进行批量文本分析或希望让 AI 助手直接“阅读”本地文件的用户。虽然生成的内容也具备一定可读性，但其核心优势在于为机器",93400,"2026-04-06T19:52:38",[52,14],{"id":62,"github_repo":63,"name":64,"description_en":65,"description_zh":66,"ai_summary_zh":66,"readme_en":67,"readme_zh":68,"quickstart_zh":69,"use_case_zh":70,"hero_image_url":71,"owner_login":72,"owner_name":73,"owner_avatar_url":74,"owner_bio":75,"owner_company":73,"owner_location":76,"owner_email":73,"owner_twitter":73,"owner_website":77,"owner_url":78,"languages":79,"stars":88,"forks":89,"last_commit_at":90,"license":91,"difficulty_score":32,"env_os":92,"env_gpu":93,"env_ram":94,"env_deps":95,"category_tags":102,"github_topics":104,"view_count":32,"oss_zip_url":73,"oss_zip_packed_at":73,"status":17,"created_at":125,"updated_at":126,"faqs":127,"releases":160},6407,"JavierAntoran\u002FBayesian-Neural-Networks","Bayesian-Neural-Networks","Pytorch implementations of Bayes By Backprop, MC Dropout, SGLD, the Local Reparametrization Trick, KF-Laplace, SG-HMC and more","Bayesian-Neural-Networks 是一个基于 PyTorch 的开源项目，专注于提供多种贝叶斯神经网络近似推断方法的代码实现。它旨在解决传统深度学习模型中常见的“过度自信”问题，通过量化预测不确定性，让模型不仅能给出预测结果，还能评估该结果的可靠程度，从而在医疗诊断、自动驾驶等高风险场景中提升决策安全性。\n\n该项目非常适合人工智能研究人员、算法工程师以及对概率深度学习感兴趣的学生使用。无论是希望复现经典论文实验，还是需要在回归分析或图像分类任务中引入不确定性估计，都能从中找到成熟的参考代码。\n\n其核心技术亮点在于集成了多种前沿算法，包括 Bayes by Backprop、MC Dropout、随机梯度朗之万动力学（SGLD）以及局部重参数化技巧等。特别是局部重参数化技巧，通过将采样对象从权重转换为激活值，显著降低了估计方差并加快了收敛速度。此外，项目还贴心地提供了针对 MNIST 分类和 UCI 回归数据集的完整实验脚本及 Google Colab 笔记本，用户无需复杂配置即可直接在云端 GPU 上运行和验证模型，极大地降低了贝叶斯深度学习的研究与开发门槛。","\n# Bayesian Neural Networks\n[![License: MIT](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FLicense-MIT-yellow.svg)](https:\u002F\u002Fgithub.com\u002FJavierAntoran\u002FBayesian-Neural-Networks\u002Fblob\u002Fmaster\u002FLICENSE) [![Python 2.7+](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fpython-2.7+-blue.svg)](https:\u002F\u002Fwww.python.org\u002Fdownloads\u002Frelease\u002Fpython-2716\u002F)\n[![Pytorch 1.0](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fpytorch-1.0.1-blue.svg)](https:\u002F\u002Fpytorch.org\u002F)\n\n\n\nPytorch implementations for the following approximate inference methods:\n\n* [Bayes by Backprop](#bayes-by-backprop-bbp)\n* [Bayes by Backprop + Local Reparametrisation Trick](#local-reparametrisation-trick)\n* [MC dropout](#mc-dropout)\n* [Stochastic Gradient Langevin Dynamics](#stochastic-gradient-langevin-dynamics-sgld)\n* [Preconditioned SGLD](#psgld)\n* [Kronecker-Factorised Laplace Approximation](#kronecker-factorised-laplace)\n* [Stochastic Gradient Hamiltonian Monte Carlo with Scale Adaption](#stochastic-gradient-hamiltonian-monte-carlo)\n\nWe also provide code for:\n* [Bootstrap MAP Ensemble](#bootstrap-map-ensemble)\n\n### Prerequisites\n* PyTorch\n* Numpy\n* Matplotlib\n\nThe project is written in python 2.7 and Pytorch 1.0.1. If CUDA is available, it will be\nused automatically. The models can also run on CPU as they are not excessively big.\n\n## Usage\n\n### Structure\n\n#### Regression experiments\n\n\nWe carried out homoscedastic and heteroscedastic regression\n  experiements on toy datasets, generated with [(Gaussian Process ground truth)](https:\u002F\u002Fcolab.research.google.com\u002Fdrive\u002F1t-OmK57w31ukbuftqk-1zAFzIgZhSMwG),\n    as well as on real data (six [UCI datasets](https:\u002F\u002Farchive.ics.uci.edu\u002Fml\u002Fdatasets.php)). \n    \n    \n*Notebooks\u002Fclassification\u002F(ModelName)_(ExperimentType).ipynb*: Contains experiments using (ModelName)\n on (ExperimentType), i.e. homoscedastic\u002Fheteroscedastic. The heteroscedastic\n  notebooks contain both toy and UCI dataset experiments for a given (ModelName).\n\nWe also provide [Google Colab](https:\u002F\u002Fcolab.research.google.com\u002F) notebooks. This means that\n  you can run on a GPU (for free!). No modifications required - all dependencies \n  and datasets are added from within the notebooks - except for selecting \n  Runtime -> Change runtime type -> Hardware accelerator -> GPU.\n\n\n\u003C!--* [Regression Results](#homoscedastic-regression)-->\n\n#### MNIST classification experiments\n\n*train_(ModelName)_(Dataset).py*: Trains (ModelName) on (Dataset). Training\nmetrics and model weights will be saved to the specified directories.\n\n*src\u002F*: General utilities and model definitions.\n\n*Notebooks\u002Fclassification*: An asortment of notebooks which allow for model training, evaluation and\nrunning of digit rotation uncertainty experiments. They also allow for weight\ndistribution plotting and weight pruning.  They allow for loading of pre-trained models\nfor experimentation.\n\n### Bayes by Backprop (BBP)\n(https:\u002F\u002Farxiv.org\u002Fabs\u002F1505.05424)\n\nColab notebooks with regression models: [BBP homoscedastic](https:\u002F\u002Fcolab.research.google.com\u002Fdrive\u002F1K1I_UNRFwPt9l6RRkp8IYg1504PR9q4L) \u002F [heteroscedastic](https:\u002F\u002Fcolab.research.google.com\u002Fdrive\u002F13oTnT6oKnB6NNBPVAczx8X-QEot2hfp9)\n\nTrain a model on MNIST:\n```bash\npython train_BayesByBackprop_MNIST.py [--model [MODEL]] [--prior_sig [PRIOR_SIG]] [--epochs [EPOCHS]] [--lr [LR]] [--n_samples [N_SAMPLES]] [--models_dir [MODELS_DIR]] [--results_dir [RESULTS_DIR]]\n```\nFor an explanation of the script's arguments:\n```bash\npython train_BayesByBackprop_MNIST.py -h\n```\n\nBest results are obtained with a Laplace prior.\n\n#### Local Reparametrisation Trick\n(https:\u002F\u002Farxiv.org\u002Fabs\u002F1506.02557)\n\nBayes By Backprop inference where the mean and variance of activations\n are calculated in closed form. Activations are sampled instead of\n weights. This makes the variance of the Monte Carlo ELBO estimator scale\n as 1\u002FM, where M is the minibatch size. Sampling weights scales (M-1)\u002FM.\n The KL divergence between gaussians can also be computed in closed form,\n further reducing variance. Computation of each epoch is faster and so is convergence.\n\nTrain a model on MNIST:\n```bash\npython train_BayesByBackprop_MNIST.py --model Local_Reparam [--prior_sig [PRIOR_SIG]] [--epochs [EPOCHS]] [--lr [LR]] [--n_samples [N_SAMPLES]] [--models_dir [MODELS_DIR]] [--results_dir [RESULTS_DIR]]\n```\n\n### MC Dropout\n(https:\u002F\u002Farxiv.org\u002Fabs\u002F1506.02142)\n\nA fixed dropout rate of 0.5 is set.\n\nColab notebooks with regression models: [MC Dropout homoscedastic](https:\u002F\u002Fcolab.research.google.com\u002Fdrive\u002F11knF0-7F7hK3Yhsj8VkG9fHbdB-LvtpQ) [heteroscedastic](https:\u002F\u002Fcolab.research.google.com\u002Fdrive\u002F11wYjIF9_mPTpJJ-M-TqLJ1X6sfeXtrOd)\n\nTrain a model on MNIST:\n```bash\npython train_MCDropout_MNIST.py [--weight_decay [WEIGHT_DECAY]] [--epochs [EPOCHS]] [--lr [LR]] [--models_dir [MODELS_DIR]] [--results_dir [RESULTS_DIR]]\n```\nFor an explanation of the script's arguments:\n```bash\npython train_MCDropout_MNIST.py -h\n```\n\n\n### Stochastic Gradient Langevin Dynamics (SGLD)\n(https:\u002F\u002Fwww.ics.uci.edu\u002F~welling\u002Fpublications\u002Fpapers\u002Fstoclangevin_v6.pdf)\n\nIn order to converge to the true posterior over w, the learning rate\nshould be annealed according to the [Robbins-Monro](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FStochastic_approximation)\n conditions. In practise, we use a fixed learning rate.\n \nColab notebooks with regression models: [SGLD homoscedastic](https:\u002F\u002Fcolab.research.google.com\u002Fdrive\u002F1vV5bsp7o6SyhAXErHwUC1FYxb-9Dc9SK) \u002F [heteroscedastic](https:\u002F\u002Fcolab.research.google.com\u002Fdrive\u002F1Qk-gGWLwVrYc6hn7-EKIbkIYeZoWBx4f)\n\nTrain a model on MNIST:\n```bash\npython train_SGLD_MNIST.py [--use_preconditioning [USE_PRECONDITIONING]] [--prior_sig [PRIOR_SIG]] [--epochs [EPOCHS]] [--lr [LR]] [--models_dir [MODELS_DIR]] [--results_dir [RESULTS_DIR]]\n```\nFor an explanation of the script's arguments:\n```bash\npython train_SGLD_MNIST.py -h\n```\n\n#### pSGLD\n(https:\u002F\u002Farxiv.org\u002Fabs\u002F1512.07666)\n\nSGLD with RMSprop preconditioning. A higher learning rate should be used\nthan for vanilla SGLD.\n\nTrain a model on MNIST:\n```bash\npython train_SGLD_MNIST.py --use_preconditioning True [--prior_sig [PRIOR_SIG]] [--epochs [EPOCHS]] [--lr [LR]] [--models_dir [MODELS_DIR]] [--results_dir [RESULTS_DIR]]\n```\n\n### Bootstrap MAP Ensemble\n\nMultiple networks are trained on subsamples of the dataset.\n\nColab notebooks with regression models: [MAP Ensemble homoscedastic](https:\u002F\u002Fcolab.research.google.com\u002Fdrive\u002F1iA3IUjaEHlb0XpLUF_WafbMS70UQnSaA) \u002F [heteroscedastic](https:\u002F\u002Fcolab.research.google.com\u002Fdrive\u002F1B14--H3mduShIDb7M-CPbDOG8lOu2jvK)\n\nTrain an ensemble on MNIST:\n```bash\npython train_Bootrap_Ensemble_MNIST.py [--weight_decay [WEIGHT_DECAY]] [--subsample [SUBSAMPLE]] [--n_nets [N_NETS]] [--epochs [EPOCHS]] [--lr [LR]] [--models_dir [MODELS_DIR]] [--results_dir [RESULTS_DIR]]\n```\nFor an explanation of the script's arguments:\n```bash\npython train_Bootrap_Ensemble_MNIST.py -h\n```\n\n## Kronecker-Factorised Laplace\n(https:\u002F\u002Fopenreview.net\u002Fpdf?id=Skdvd2xAZ)\n\nTrain a MAP network and then calculate a second order taylor series aproxiamtion\n to the curvature around a mode of the posterior. A block diagonal Hessian\n approximation is used, where only intra-layer dependencies are accounted\n for. The Hessian is further approximated as the kronecker product of the \n expectation of a single datapoint's Hessian factors. Approximating the Hessian\n can take a while. Fortunately it only needs to be done once. \n\nTrain a MAP network on MNIST and approximate Hessian:\n```bash\npython train_KFLaplace_MNIST.py [--weight_decay [WEIGHT_DECAY]] [--hessian_diag_sig [HESSIAN_DIAG_SIG]] [--epochs [EPOCHS]] [--lr [LR]] [--models_dir [MODELS_DIR]] [--results_dir [RESULTS_DIR]]\n```\n\nFor an explanation of the script's arguments:\n```bash\npython train_KFLaplace_MNIST.py -h\n```\n\nNote that we save the unscaled and uninverted Hessian factors. This will\nallow for computationally cheap changes to the prior at inference time as the\nHessian will not need to be re-computed. Inference will require inverting\n the approximated Hessian factors and sampling from a matrix normal distribution.\n This is shown in [notebooks\u002FKFAC_Laplace_MNIST.ipynb](https:\u002F\u002Fgithub.com\u002FJavierAntoran\u002FBayesian-Neural-Networks\u002Fblob\u002Fmaster\u002Fnotebooks\u002Fclassification\u002FKFAC_Laplace_MNIST.ipynb)\n\n## Stochastic Gradient Hamiltonian Monte Carlo\n(https:\u002F\u002Farxiv.org\u002Fabs\u002F1402.4102)\n\nWe implement the scale-adapted version of this algorithm, proposed [here](https:\u002F\u002Fpapers.nips.cc\u002Fpaper\u002F6117-bayesian-optimization-with-robust-bayesian-neural-networks.pdf)\nto find hyperparameters automatically during burn-in. We place a Gaussian prior\nover network weights and a Gamma hyperprior over the Gaussian's precision.\n\nRun SG-HMC-SA burn in and sampler, saving weights in specified file.\n```bash\npython train_SGHMC_MNIST.py [--epochs [EPOCHS]] [--sample_freq [SAMPLE_FREQ]] [--burn_in [BURN_IN]] [--lr [LR]] [--models_dir [MODELS_DIR]] [--results_dir [RESULTS_DIR]]\n```\n\nFor an explanation of the script's arguments:\n```bash\npython train_SGHMC_MNIST.py -h\n```\n \n\n## Approximate Inference in Neural Networks\n\nMap inference provides a point estimate of parameter values. When provided with\nout of distribution inputs, such as rotated digits, these models then to\nmake wrong predictions with high confidence.\n\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_849a208f65cc.png\" width=\"430\" height=\"270\"\u002F>\n\n### Uncertainty Decomposition\nWe can measure uncertainty in our models' predictions through predictive entropy.\nWe can decompose this term in order to distinguish between 2 types of uncertainty.\nUncertainty caused by noise in the data, or **Aleatoric uncertainty**, can be\n quantified as the expected entropy of model predictions. Model uncertainty\n or **Epistemic uncertainty** can be measured as the difference between total entropy\n and aleatoric entropy.\n\n## Results\n\n### Homoscedastic Regression\n\nToy homoscedastic regression task. Data is generated by a GP with a RBF\n kernel (l = 1, σn = 0.3). We use a single-output FC network with one hidden layer of\n  200 ReLU units to predict the regression mean μ(x). A fixed log σ is learnt separately.\n\u003Cp float=\"center\">\n  \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_7df14b74089e.png\" width=\"170\" \u002F>\n  \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_2586c808e97e.png\" width=\"150\" \u002F> \n  \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_c7ca7444e6b3.png\" width=\"150\" \u002F>\n  \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_b79aaabbc408.png\" width=\"150\" \u002F> \n  \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_7a9820cdf1ad.png\" width=\"150\" \u002F>\n\u003C\u002Fp>\n\n### Heteroscedastic Regression\nSame scenario as previous section but log σ(x) is predicted from the input.\n\u003Cp float=\"center\">\n  \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_3b3595dd6cbf.png\" width=\"170\" \u002F>\n  \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_cd7c90627bcb.png\" width=\"150\" \u002F> \n  \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_1c30ed91f7dd.png\" width=\"150\" \u002F>\n  \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_63c04b757afc.png\" width=\"150\" \u002F> \n  \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_093217b466d8.png\" width=\"150\" \u002F>\n\u003C\u002Fp>\n\nToy heteroscedastic regression task. Data is generated by a GP with a RBF\n kernel (l = 1 σn = 0.3 · |x + 2|). We use a two-head network with 200 ReLU units to predict the regression mean μ(x) and log-standard deviation log σ(x).\n \n### Regression on UCI datasets\n\nWe performed heteroscedastic regression on the six UCI datasets\n ([housing](https:\u002F\u002Farchive.ics.uci.edu\u002Fml\u002Fmachine-learning-databases\u002Fhousing\u002F),\n  [concrete](http:\u002F\u002Farchive.ics.uci.edu\u002Fml\u002Fdatasets\u002Fconcrete+compressive+strength),\n   [energy efficiency](https:\u002F\u002Farchive.ics.uci.edu\u002Fml\u002Fdatasets\u002Fenergy+efficiency),\n    [power plant](https:\u002F\u002Farchive.ics.uci.edu\u002Fml\u002Fdatasets\u002Fcombined+cycle+power+plant),\n     [red wine](https:\u002F\u002Farchive.ics.uci.edu\u002Fml\u002Fdatasets\u002Fwine+quality) and [yacht](http:\u002F\u002Farchive.ics.uci.edu\u002Fml\u002Fdatasets\u002Fyacht+hydrodynamics) datasets),\n      using 10-foild cross validation. All these experiments are contained in the heteroscedastic notebooks. \n      Note that results depend heavily on hyperparameter selection. Plots below show log-likelihoods and RMSEs \non the train (semi-transparent colour) and test (solid colour). Circles and error bars correspond \nto the 10-fold cross validation mean and standard deviations respectively.\n\n\u003Cp float=\"center\">\n  \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_9c9126e014b2.png\" float=\"center\" width=\"400\" \u002F>\n  \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_886e6936c311.png\" float=\"center\" width=\"400\" \u002F>\n\u003C\u002Fp>\n\n### MNIST Classification\n\nW is marginalised with 100 samples of the weights for all models except\nMAP, where only one set of weights is used.\n\n|      MNIST Test\t|   MAP   \t| MAP  Ensemble \t| BBP  Gaussian \t| BBP  GMM \t| BBP  Laplace \t| BBP Local Reparam \t| MC Dropout \t|   SGLD  \t|  pSGLD  \t|\n|:--------------:\t|:-------:\t|:-------------------:\t|:--------------:\t|:---------:\t|:-------------:\t|:-------------------:\t|:----------:\t|:-------:\t|:-------:\t|\n| Log Like\t| -572.9 \t|       -496.54       \t|    -1100.29    \t|  -1008.28 \t|    -892.85    \t|       -1086.43      \t|  -435.458  \t| -828.29 \t| -661.25 \t|\n|    Error \\%    \t|   1.58  \t|         1.53        \t|      2.60      \t|    2.38   \t|      2.28     \t|         2.61        \t|    1.37    \t|   1.76  \t|   1.76  \t|\n\nMNIST test results for methods under consideration. Estensive hyperparameter\ntunning has not been performed. We approximate\n the posterior predictive distribution with 100 MC samples. We use a FC\n  network with two 1200 unit ReLU layers. If unspecified, the prior is\n   Gaussian with std=0.1. P-SGLD uses RMSprop preconditioning.\n\n [The original paper](https:\u002F\u002Farxiv.org\u002Fabs\u002F1505.05424) for Bayes By Backprop\n reports around 1% error on MNIST. We find that this result is attainable\n only if approximate posterior variances are initialised to be very small (BBP Gauss 2).\n In this scenario, the distributions over weights resemble deltas, giving \n good predictive performance but bad uncertainty estimates. \n However, when initialising the variances to match the prior (BBP Gauss 1), we obtain the above results.\n The training curves for both of these hyperparameter configuration schemes\n are shown below:\n\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_cea1404ded2d.png\" width=\"500\" height=\"420\"\u002F>\n\n\n### MNIST Uncertainty\n\nTotal, aleatoric and epistemic uncertainties obtained when\ncreating OOD samples by augmenting the MNIST test set with rotations:\n\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_b4c8d5011af3.png\" width=\"900\" height=\"420\"\u002F>\n\nTotal and epistemic uncertainties obtained by testing our models, - which \nhave been trained on MNIST -, on the KMNIST dataset:\n\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_e080d24f91ae.png\" width=\"770\" height=\"240\"\u002F>\n\n### Adversarial robustness\n\n\u003Cimg src=\"https:\u002F\u002Fi.imgur.com\u002FR61K4Ab.png\" width=\"600\" height=\"280\"\u002F>\n\nTotal, aleatoric and epistemic uncertainties obtained when\nfeeding our models with adversarial samples (fgsm).\n\n\u003Cimg src=\"https:\u002F\u002Fi.imgur.com\u002FMc484A3.png\" width=\"900\" height=\"420\"\u002F>\n\n### Weight Distributions\n\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_440291ef8885.png\" width=\"450\" height=\"270\"\u002F>\n\nHistograms of weights sampled from each model trained on MNIST. We draw 10 samples of w for each model.\n\n### Weight Pruning\n\n\\#TODO\n","# 贝叶斯神经网络\n[![许可证：MIT](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FLicense-MIT-yellow.svg)](https:\u002F\u002Fgithub.com\u002FJavierAntoran\u002FBayesian-Neural-Networks\u002Fblob\u002Fmaster\u002FLICENSE) [![Python 2.7+](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fpython-2.7+-blue.svg)](https:\u002F\u002Fwww.python.org\u002Fdownloads\u002Frelease\u002Fpython-2716\u002F)\n[![Pytorch 1.0](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fpytorch-1.0.1-blue.svg)](https:\u002F\u002Fpytorch.org\u002F)\n\n\n\n以下是几种近似推断方法的 PyTorch 实现：\n\n* [贝叶斯反向传播](#bayes-by-backprop-bbp)\n* [贝叶斯反向传播 + 局部重参数化技巧](#local-reparametrisation-trick)\n* [MC dropout](#mc-dropout)\n* [随机梯度朗之万动力学](#stochastic-gradient-langevin-dynamics-sgld)\n* [预条件 SGLD](#psgld)\n* [克罗内克分解拉普拉斯近似](#kronecker-factorised-laplace)\n* [带尺度自适应的随机梯度哈密顿蒙特卡洛](#stochastic-gradient-hamiltonian-monte-carlo)\n\n我们还提供了以下代码：\n* [自助 MAP 集成](#bootstrap-map-ensemble)\n\n### 前置条件\n* PyTorch\n* Numpy\n* Matplotlib\n\n该项目使用 Python 2.7 和 PyTorch 1.0.1 编写。如果系统支持 CUDA，它将自动被使用。这些模型并不庞大，因此也可以在 CPU 上运行。\n\n## 使用方法\n\n### 结构\n\n#### 回归实验\n\n\n我们在玩具数据集上进行了同方差和异方差回归实验，这些数据集是通过 [(高斯过程真值)](https:\u002F\u002Fcolab.research.google.com\u002Fdrive\u002F1t-OmK57w31ukbuftqk-1zAFzIgZhSMwG) 生成的，同时也对真实数据（六个 [UCI 数据集](https:\u002F\u002Farchive.ics.uci.edu\u002Fml\u002Fdatasets.php)）进行了实验。\n    \n    \n*Notebooks\u002Fclassification\u002F(ModelName)_(ExperimentType).ipynb*: 包含使用 (ModelName) 在 (ExperimentType) 上进行的实验，即同方差\u002F异方差。异方差笔记本为给定的 (ModelName) 同时包含了玩具数据集和 UCI 数据集的实验。\n\n我们还提供了 [Google Colab](https:\u002F\u002Fcolab.research.google.com\u002F) 笔记本。这意味着你可以在 GPU 上免费运行！无需任何修改——所有依赖项和数据集都已内置在笔记本中——只需选择“运行时”->“更改运行时类型”->“硬件加速器”->“GPU”即可。\n\n\n\u003C!--* [回归结果](#homoscedastic-regression)-->\n\n#### MNIST 分类实验\n\n*train_(ModelName)_(Dataset).py*: 在 (Dataset) 上训练 (ModelName)。训练指标和模型权重将保存到指定的目录中。\n\n*src\u002F*: 通用工具和模型定义。\n\n*Notebooks\u002Fclassification*: 各种笔记本，可用于训练、评估模型以及运行数字旋转不确定性实验。它们还可以绘制权重分布并进行权重剪枝。此外，它们还允许加载预训练模型进行实验。\n\n### 贝叶斯反向传播 (BBP)\n(https:\u002F\u002Farxiv.org\u002Fabs\u002F1505.05424)\n\n带有回归模型的 Colab 笔记本：[BBP 同方差](https:\u002F\u002Fcolab.research.google.com\u002Fdrive\u002F1K1I_UNRFwPt9l6RRkp8IYg1504PR9q4L) \u002F [异方差](https:\u002F\u002Fcolab.research.google.com\u002Fdrive\u002F13oTnT6oKnB6NNBPVAczx8X-QEot2hfp9)\n\n在 MNIST 上训练模型：\n```bash\npython train_BayesByBackprop_MNIST.py [--model [MODEL]] [--prior_sig [PRIOR_SIG]] [--epochs [EPOCHS]] [--lr [LR]] [--n_samples [N_SAMPLES]] [--models_dir [MODELS_DIR]] [--results_dir [RESULTS_DIR]]\n```\n如需了解脚本参数说明：\n```bash\npython train_BayesByBackprop_MNIST.py -h\n```\n\n使用拉普拉斯先验可获得最佳效果。\n\n#### 局部重参数化技巧\n(https:\u002F\u002Farxiv.org\u002Fabs\u002F1506.02557)\n\n贝叶斯反向传播推断中，激活的均值和方差以闭式解计算。采样的是激活值而非权重。这使得蒙特卡洛 ELBO 估计量的方差随 minibatch 大小 M 成 1\u002FM 的比例变化。而采样权重则会使方差变为 (M-1)\u002FM。高斯分布之间的 KL 散度也可用闭式解计算，从而进一步降低方差。每轮迭代的计算速度更快，收敛也更快。\n\n在 MNIST 上训练模型：\n```bash\npython train_BayesByBackprop_MNIST.py --model Local_Reparam [--prior_sig [PRIOR_SIG]] [--epochs [EPOCHS]] [--lr [LR]] [--n_samples [N_SAMPLES]] [--models_dir [MODELS_DIR]] [--results_dir [RESULTS_DIR]]\n```\n\n### MC Dropout\n(https:\u002F\u002Farxiv.org\u002Fabs\u002F1506.02142)\n\n固定丢弃率为 0.5。\n\n带有回归模型的 Colab 笔记本：[MC Dropout 同方差](https:\u002F\u002Fcolab.research.google.com\u002Fdrive\u002F11knF0-7F7hK3Yhsj8VkG9fHbdB-LvtpQ) [异方差](https:\u002F\u002Fcolab.research.google.com\u002Fdrive\u002F11wYjIF9_mPTpJJ-M-TqLJ1X6sfeXtrOd)\n\n在 MNIST 上训练模型：\n```bash\npython train_MCDropout_MNIST.py [--weight_decay [WEIGHT_DECAY]] [--epochs [EPOCHS]] [--lr [LR]] [--models_dir [MODELS_DIR]] [--results_dir [RESULTS_DIR]]\n```\n如需了解脚本参数说明：\n```bash\npython train_MCDropout_MNIST.py -h\n```\n\n\n### 随机梯度朗之万动力学 (SGLD)\n(https:\u002F\u002Fwww.ics.uci.edu\u002F~welling\u002Fpublications\u002Fpapers\u002Fstoclangevin_v6.pdf)\n\n为了使模型收敛到真实的后验分布，学习率应根据 [Robbins-Monro](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FStochastic_approximation) 条件进行退火。但在实际应用中，我们通常使用固定的学习率。\n \n带有回归模型的 Colab 笔记本：[SGLD 同方差](https:\u002F\u002Fcolab.research.google.com\u002Fdrive\u002F1vV5bsp7o6SyhAXErHwUC1FYxb-9Dc9SK) \u002F [异方差](https:\u002F\u002Fcolab.research.google.com\u002Fdrive\u002F1Qk-gGWLwVrYc6hn7-EKIbkIYeZoWBx4f)\n\n在 MNIST 上训练模型：\n```bash\npython train_SGLD_MNIST.py [--use_preconditioning [USE_PRECONDITIONING]] [--prior_sig [PRIOR_SIG]] [--epochs [EPOCHS]] [--lr [LR]] [--models_dir [MODELS_DIR]] [--results_dir [RESULTS_DIR]]\n```\n如需了解脚本参数说明：\n```bash\npython train_SGLD_MNIST.py -h\n```\n\n#### pSGLD\n(https:\u002F\u002Farxiv.org\u002Fabs\u002F1512.07666)\n\n带有 RMSprop 预条件的 SGLD。与普通 SGLD 相比，应使用更高的学习率。\n\n在 MNIST 上训练模型：\n```bash\npython train_SGLD_MNIST.py --use_preconditioning True [--prior_sig [PRIOR_SIG]] [--epochs [EPOCHS]] [--lr [LR]] [--models_dir [MODELS_DIR]] [--results_dir [RESULTS_DIR]]\n```\n\n### 自助 MAP 集成\n\n多个网络在数据集的子样本上进行训练。\n\n带有回归模型的 Colab 笔记本：[MAP 集成 同方差](https:\u002F\u002Fcolab.research.google.com\u002Fdrive\u002F1iA3IUjaEHlb0XpLUF_WafbMS70UQnSaA) \u002F [异方差](https:\u002F\u002Fcolab.research.google.com\u002Fdrive\u002F1B14--H3mduShIDb7M-CPbDOG8lOu2jvK)\n\n在 MNIST 上训练集成：\n```bash\npython train_Bootrap_Ensemble_MNIST.py [--weight_decay [WEIGHT_DECAY]] [--subsample [SUBSAMPLE]] [--n_nets [N_NETS]] [--epochs [EPOCHS]] [--lr [LR]] [--models_dir [MODELS_DIR]] [--results_dir [RESULTS_DIR]]\n```\n如需了解脚本参数说明：\n```bash\npython train_Bootrap_Ensemble_MNIST.py -h\n```\n\n## 克罗内克分解拉普拉斯近似\n(https:\u002F\u002Fopenreview.net\u002Fpdf?id=Skdvd2xAZ)\n\n首先训练一个MAP网络，然后计算后验分布模式附近曲率的二阶泰勒展开近似。这里采用块对角Hessian近似，仅考虑层内依赖关系。进一步将Hessian近似为单个数据点Hessian因子期望的克罗内克积。近似Hessian可能需要较长时间，但幸运的是只需执行一次。\n\n在MNIST数据集上训练MAP网络并近似Hessian：\n```bash\npython train_KFLaplace_MNIST.py [--weight_decay [WEIGHT_DECAY]] [--hessian_diag_sig [HESSIAN_DIAG_SIG]] [--epochs [EPOCHS]] [--lr [LR]] [--models_dir [MODELS_DIR]] [--results_dir [RESULTS_DIR]]\n```\n\n如需了解脚本参数说明：\n```bash\npython train_KFLaplace_MNIST.py -h\n```\n\n请注意，我们保存了未缩放且未逆化的Hessian因子。这将允许在推理时以较低的计算成本调整先验，而无需重新计算Hessian。推理过程需要对近似的Hessian因子进行逆运算，并从矩阵正态分布中采样。相关示例请参见[notebooks\u002FKFAC_Laplace_MNIST.ipynb](https:\u002F\u002Fgithub.com\u002FJavierAntoran\u002FBayesian-Neural-Networks\u002Fblob\u002Fmaster\u002Fnotebooks\u002Fclassification\u002FKFAC_Laplace_MNIST.ipynb)。\n\n## 随机梯度哈密顿蒙特卡洛\n(https:\u002F\u002Farxiv.org\u002Fabs\u002F1402.4102)\n\n我们实现了该算法的自适应尺度版本，该版本由[此处](https:\u002F\u002Fpapers.nips.cc\u002Fpaper\u002F6117-bayesian-optimization-with-robust-bayesian-neural-networks.pdf)提出，用于在预热阶段自动寻找超参数。我们在网络权重上施加高斯先验，并在高斯先验的精度上设置伽马超先验。\n\n运行SG-HMC-SA预热和采样器，并将权重保存到指定文件中：\n```bash\npython train_SGHMC_MNIST.py [--epochs [EPOCHS]] [--sample_freq [SAMPLE_FREQ]] [--burn_in [BURN_IN]] [--lr [LR]] [--models_dir [MODELS_DIR]] [--results_dir [RESULTS_DIR]]\n```\n\n如需了解脚本参数说明：\n```bash\npython train_SGHMC_MNIST.py -h\n```\n\n## 神经网络中的近似推断\n\nMAP推断提供参数值的点估计。当输入为分布外数据（例如旋转后的数字）时，这些模型往往会以很高的置信度做出错误预测。\n\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_849a208f65cc.png\" width=\"430\" height=\"270\"\u002F>\n\n### 不确定性分解\n我们可以通过预测熵来衡量模型预测中的不确定性。可以将这一项分解，以区分两种类型的不确定性：由数据噪声引起的**偶然不确定性**，可量化为模型预测熵的期望值；以及由模型本身引起的**认知不确定性**，可通过总熵与偶然不确定性的差值来衡量。\n\n## 结果\n\n### 同方差回归\n\n玩具同方差回归任务。数据由具有RBF核（l = 1, σn = 0.3）的GP生成。我们使用一个单输出全连接网络，包含一层200个ReLU单元，用于预测回归均值μ(x)。固定log σ则单独学习。\n\u003Cp float=\"center\">\n  \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_7df14b74089e.png\" width=\"170\" \u002F>\n  \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_2586c808e97e.png\" width=\"150\" \u002F> \n  \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_c7ca7444e6b3.png\" width=\"150\" \u002F>\n  \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_b79aaabbc408.png\" width=\"150\" \u002F> \n  \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_7a9820cdf1ad.png\" width=\"150\" \u002F>\n\u003C\u002Fp>\n\n### 异方差回归\n与前一节相同，但log σ(x)根据输入预测。\n\u003Cp float=\"center\">\n  \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_3b3595dd6cbf.png\" width=\"170\" \u002F>\n  \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_cd7c90627bcb.png\" width=\"150\" \u002F> \n  \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_1c30ed91f7dd.png\" width=\"150\" \u002F>\n  \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_63c04b757afc.png\" width=\"150\" \u002F> \n  \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_093217b466d8.png\" width=\"150\" \u002F>\n\u003C\u002Fp>\n\n玩具异方差回归任务。数据由具有RBF核（l = 1, σn = 0.3 · |x + 2|）的GP生成。我们使用一个双头网络，包含200个ReLU单元，分别预测回归均值μ(x)和对数标准差log σ(x)。\n\n### UCI数据集上的回归\n\n我们在六个UCI数据集上进行了异方差回归（包括[housing](https:\u002F\u002Farchive.ics.uci.edu\u002Fml\u002Fmachine-learning-databases\u002Fhousing\u002F)、[concrete](http:\u002F\u002Farchive.ics.uci.edu\u002Fml\u002Fdatasets\u002Fconcrete+compressive+strength)、[energy efficiency](https:\u002F\u002Farchive.ics.uci.edu\u002Fml\u002Fdatasets\u002Fenergy+efficiency)、[power plant](https:\u002F\u002Farchive.ics.uci.edu\u002Fml\u002Fdatasets\u002Fcombined+cycle+power+plant)、[red wine](https:\u002F\u002Farchive.ics.uci.edu\u002Fml\u002Fdatasets\u002Fwine+quality)和[yacht](http:\u002F\u002Farchive.ics.uci.edu\u002Fml\u002Fdatasets\u002Fyacht+hydrodynamics)），采用10折交叉验证。所有实验都包含在异方差笔记本中。需要注意的是，结果高度依赖于超参数的选择。下方图表展示了训练集（半透明颜色）和测试集（实心颜色）上的对数似然和RMSE。圆圈和误差线分别对应10折交叉验证的均值和标准差。\n\n\u003Cp float=\"center\">\n  \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_9c9126e014b2.png\" float=\"center\" width=\"400\" \u002F>\n  \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_886e6936c311.png\" float=\"center\" width=\"400\" \u002F>\n\u003C\u002Fp>\n\n### MNIST分类\n\n除MAP模型外，其他模型均使用100个权重样本进行权重边缘化处理，而MAP模型仅使用一组权重。\n\n|      MNIST测试\t|   MAP   \t| MAP 集成 \t| BBP 高斯 \t| BBP GMM \t| BBP 拉普拉斯 \t| BBP 局部重参数化 \t| MC Dropout \t|   SGLD  \t|  pSGLD  \t|\n|:--------------:\t|:-------:\t|:-------------------:\t|:--------------:\t|:---------:\t|:-------------:\t|:-------------------:\t|:----------:\t|:-------:\t|:-------:\t|\n| Log Like\t| -572.9 \t|       -496.54       \t|    -1100.29    \t|  -1008.28 \t|    -892.85    \t|       -1086.43      \t|  -435.458  \t| -828.29 \t| -661.25 \t|\n|    Error \\%    \t|   1.58  \t|         1.53        \t|      2.60      \t|    2.38   \t|      2.28     \t|         2.61        \t|    1.37    \t|   1.76  \t|   1.76  \t|\n\n所考察方法在MNIST测试上的结果。未进行大规模超参数调优。我们使用100个MC样本近似后验预测分布。采用两层各1200个ReLU单元的全连接网络。若未指定，则先验为标准差为0.1的高斯分布。p-SGLD使用RMSprop预条件。\n\n关于Bayes By Backprop的原始论文（https:\u002F\u002Farxiv.org\u002Fabs\u002F1505.05424）报告称，在MNIST数据集上误差约为1%。我们发现，只有当近似后验方差初始化为非常小（BBP Gauss 2）时，才能达到这一效果。在这种情况下，权重分布接近狄拉克δ函数，虽然预测性能良好，但不确定性估计较差。然而，当将方差初始化为与先验一致（BBP Gauss 1）时，便得到了上述结果。这两种超参数配置方案的训练曲线如下所示：\n\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_cea1404ded2d.png\" width=\"500\" height=\"420\"\u002F>\n\n### MNIST 不确定性\n\n通过在 MNIST 测试集上添加旋转来生成 OOD 样本时获得的总不确定性、随机性和认知不确定性：\n\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_b4c8d5011af3.png\" width=\"900\" height=\"420\"\u002F>\n\n在 KMNIST 数据集上测试我们基于 MNIST 训练的模型时获得的总不确定性和认知不确定性：\n\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_e080d24f91ae.png\" width=\"770\" height=\"240\"\u002F>\n\n### 对抗鲁棒性\n\n\u003Cimg src=\"https:\u002F\u002Fi.imgur.com\u002FR61K4Ab.png\" width=\"600\" height=\"280\"\u002F>\n\n当我们向模型输入对抗样本（FGSM）时，所获得的总不确定性、随机性和认知不确定性。\n\n\u003Cimg src=\"https:\u002F\u002Fi.imgur.com\u002FMc484A3.png\" width=\"900\" height=\"420\"\u002F>\n\n### 权重分布\n\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_readme_440291ef8885.png\" width=\"450\" height=\"270\"\u002F>\n\n从每个基于 MNIST 训练的模型中采样得到的权重直方图。我们为每个模型抽取了 10 个权重样本。\n\n### 权重剪枝\n\n\\#TODO","# Bayesian-Neural-Networks 快速上手指南\n\n本指南帮助中国开发者快速部署和使用基于 PyTorch 的贝叶斯神经网络开源工具，涵盖多种近似推断方法（如 BBP、MC Dropout、SGLD 等）。\n\n## 环境准备\n\n### 系统要求\n*   **操作系统**: Linux, macOS 或 Windows\n*   **Python 版本**: 2.7+ (项目原始开发版本)，建议兼容 Python 3.x 环境运行\n*   **硬件加速**: 支持 CUDA 的 GPU（可选，模型较小也可在 CPU 上运行）\n\n### 前置依赖\n请确保已安装以下核心库：\n*   PyTorch (推荐 1.0.1+)\n*   Numpy\n*   Matplotlib\n\n> **国内加速建议**：建议使用清华或阿里镜像源安装依赖，以提升下载速度。\n> ```bash\n> pip install torch numpy matplotlib -i https:\u002F\u002Fpypi.tuna.tsinghua.edu.cn\u002Fsimple\n> ```\n\n## 安装步骤\n\n1.  **克隆仓库**\n    将项目代码下载到本地：\n    ```bash\n    git clone https:\u002F\u002Fgithub.com\u002FJavierAntoran\u002FBayesian-Neural-Networks.git\n    cd Bayesian-Neural-Networks\n    ```\n\n2.  **验证环境**\n    确保 `python` 和 `pip` 可用。如果使用 GPU，请确认 PyTorch 已正确识别 CUDA：\n    ```bash\n    python -c \"import torch; print(torch.cuda.is_available())\"\n    ```\n    *注：若返回 `True`，脚本将自动使用 GPU；否则自动切换至 CPU。*\n\n## 基本使用\n\n本项目提供了多种贝叶斯推断方法的训练脚本。以下以 **MNIST 分类任务** 为例，展示最常用的两种方法。\n\n### 1. 使用 Bayes by Backprop (BBP) 训练模型\n\n这是最基础的贝叶斯神经网络实现方法。\n\n```bash\npython train_BayesByBackprop_MNIST.py --model BBP --prior_sig 1.0 --epochs 10 --lr 0.001 --n_samples 5\n```\n\n*   `--model`: 指定模型类型（此处为 BBP）。\n*   `--prior_sig`: 先验分布的标准差（推荐使用 Laplace 先验以获得最佳结果）。\n*   `--epochs`: 训练轮数。\n*   `--lr`: 学习率。\n*   `--n_samples`: 蒙特卡洛采样次数。\n\n查看完整参数说明：\n```bash\npython train_BayesByBackprop_MNIST.py -h\n```\n\n### 2. 使用 MC Dropout 训练模型\n\n一种通过 Dropout 实现贝叶斯近似的轻量级方法。\n\n```bash\npython train_MCDropout_MNIST.py --weight_decay 0.0001 --epochs 10 --lr 0.001\n```\n\n*   默认 Dropout 率固定为 0.5。\n*   训练指标和模型权重将自动保存到指定目录。\n\n### 3. 其他可用方法\n\n项目还支持以下高级推断方法，调用方式类似：\n\n*   **局部重参数化技巧 (Local Reparametrisation)**:\n    ```bash\n    python train_BayesByBackprop_MNIST.py --model Local_Reparam --epochs 10\n    ```\n*   **随机梯度朗之万动力学 (SGLD)**:\n    ```bash\n    python train_SGLD_MNIST.py --epochs 10\n    ```\n*   **预处理 SGLD (pSGLD)**:\n    ```bash\n    python train_SGLD_MNIST.py --use_preconditioning True --epochs 10\n    ```\n*   **Bootstrap MAP 集成**:\n    ```bash\n    python train_Bootrap_Ensemble_MNIST.py --n_nets 5 --epochs 10\n    ```\n*   **Kronecker 因子拉普拉斯近似**:\n    ```bash\n    python train_KFLaplace_MNIST.py --epochs 10\n    ```\n\n### 4. 回归任务与在线体验\n\n对于回归实验（同方差\u002F异方差），项目提供了完整的 Jupyter Notebook。如果您希望无需配置本地环境即可体验，推荐使用 **Google Colab**（需科学上网）或直接运行本地 Notebook：\n\n*   **路径**: `Notebooks\u002Fclassification\u002F(ModelName)_(ExperimentType).ipynb`\n*   **功能**: 包含玩具数据集和 UCI 真实数据集的实验，支持不确定性分解可视化和权重剪枝分析。\n\n训练完成后，模型权重和结果将保存在 `--models_dir` 和 `--results_dir` 指定的文件夹中，可通过对应的 Notebook 加载预训练模型进行评估和不确定性分析。","某医疗影像初创公司的算法团队正在开发肺炎 X 光片辅助诊断系统，急需模型不仅能给出判断结果，还能在遇到模糊或异常病例时准确提示“不确定”，以避免误诊风险。\n\n### 没有 Bayesian-Neural-Networks 时\n- 传统深度学习模型面对从未见过的噪声图像或罕见病灶时，仍会输出极高的错误置信度，导致医生无法识别模型的“盲目自信”。\n- 团队难以区分数据本身的噪声（同方差）与不同患者个体差异带来的不确定性（异方差），只能采用统一的误差假设，降低了诊断精度。\n- 为了评估模型可靠性，开发人员不得不手动编写复杂的蒙特卡洛采样代码或集成多个模型，实验周期长且极易出错。\n- 缺乏对权重分布的可视化手段，无法通过分析权重的不确定性来剪枝优化模型，导致部署到边缘设备时资源占用过高。\n\n### 使用 Bayesian-Neural-Networks 后\n- 利用 MC Dropout 和 Bayes by Backprop 等算法，模型在面对模糊影像时能主动输出高不确定性预警，提示医生进行人工复核，显著降低漏诊率。\n- 通过内置的同方差与异方差回归实验模块，团队能精准分离数据噪声与模型认知局限，针对复杂病例动态调整诊断策略。\n- 直接调用预置的 SGLD 或 KF-Laplace 推理接口，无需重复造轮子即可快速对比多种近似推断方法的效果，将算法验证效率提升数倍。\n- 借助提供的权重分布绘图与剪枝工具，团队成功剔除了冗余参数，在保持不确定性评估能力的同时，将模型体积压缩了 40%，顺利部署至便携式检测终端。\n\nBayesian-Neural-Networks 让 AI 模型从“只会答题”进化为“懂得质疑”，在高风险决策场景中提供了至关重要的可信度量化能力。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FJavierAntoran_Bayesian-Neural-Networks_849a208f.png","JavierAntoran",null,"https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002FJavierAntoran_675bd83c.jpg","Building @Angstrom-AI . \r\n\r\nResearch Fellow at the University of Cambridge.\r\n\r\nTelecommunications (EE\u002FCS) engineer.","Cambridge, UK","javierantoran.github.io","https:\u002F\u002Fgithub.com\u002FJavierAntoran",[80,84],{"name":81,"color":82,"percentage":83},"Jupyter Notebook","#DA5B0B",99.2,{"name":85,"color":86,"percentage":87},"Python","#3572A5",0.8,1966,306,"2026-04-08T20:35:32","MIT","","非必需。如有 CUDA 环境会自动使用，但模型较小，CPU 亦可运行。","未说明",{"notes":96,"python":97,"dependencies":98},"该项目基于较旧的 Python 2.7 和 PyTorch 1.0.1 编写。虽然代码提到若有 CUDA 会自动使用，但明确指出模型不大，CPU 即可运行。项目提供了 Google Colab 笔记本，可直接在云端免费使用 GPU 运行，无需本地配置环境或下载数据集。","2.7+",[99,100,101],"PyTorch 1.0.1","Numpy","Matplotlib",[103,14],"其他",[105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124],"deep-learning","bayesian-inference","pytorch","reproducible-research","bayesian-neural-networks","bayes-by-backprop","mc-dropout","mcmc","variational-inference","kronecker-factored-approximation","langevin-dynamics","approximate-inference","local-reparametrization-trick","uncertainty","uncertainty-neural-networks","out-of-distribution-detection","classification","regression","sgld","hmc","2026-03-27T02:49:30.150509","2026-04-11T08:11:28.564489",[128,133,137,142,147,151,156],{"id":129,"question_zh":130,"answer_zh":131,"source_url":132},29014,"在计算 UCI 数据集的测试集对数似然时，为什么最后要加上归一化前 y 值的标准差的对数（log(y_sigma)）？","这是因为数据在输入模型前进行了归一化处理。为了得到原始数据尺度下的正确对数似然值，必须将归一化带来的缩放因子补偿回去。具体做法是在计算完归一化数据的对数概率后，加上 `log(y_sigma)`，其中 `y_sigma` 是归一化前 y 值的标准差。如果不加这一步，计算结果将对应于归一化后的分布，而非原始数据的分布。","https:\u002F\u002Fgithub.com\u002FJavierAntoran\u002FBayesian-Neural-Networks\u002Fissues\u002F16",{"id":134,"question_zh":135,"answer_zh":136,"source_url":132},29015,"如何正确计算贝叶斯神经网络中的测试集对数似然（Log Likelihood）？使用均值近似和 logsumexp 技巧有什么区别？","推荐使用 `logsumexp` 技巧来获得更准确的蒙特卡洛估计。代码实现逻辑如下：\n1. 进行多次采样（samples），获取每组的均值 (mu) 和对数方差 (logvar)。\n2. 构建正态分布 `Normal(mus, torch.exp(logvars \u002F 2))` 并计算每个样本的对数概率 `ll`。\n3. 使用 `torch.logsumexp(ll.sum(dim=1), dim=0)` 对所有采样的对数概率求和，而不是先对均值和方差取平均再计算概率。\n虽然先取均值和方差（包括认知不确定性和偶然不确定性）再计算概率的方法结果接近，但 `logsumexp` 方法在数学上更严谨，能更好地近似后验预测积分。",{"id":138,"question_zh":139,"answer_zh":140,"source_url":141},29016,"为什么在使用 Bayes By Backprop (BBB) 时，每次运行 `get_weight_samples` 得到的权重样本都是一样的？","这通常不是代码逻辑错误，而是由以下两个原因之一造成的：\n1. **随机种子固定**：检查代码中是否设置了固定的随机种子（random seed），导致每次运行生成的随机数序列相同。\n2. **加载了相同的保存模型**：确认是否错误地加载了之前保存的同一模型文件，而不是重新初始化或训练。\n理论上，`sample_weights` 函数每次调用都应生成不同的权重样本以近似后验分布。","https:\u002F\u002Fgithub.com\u002FJavierAntoran\u002FBayesian-Neural-Networks\u002Fissues\u002F13",{"id":143,"question_zh":144,"answer_zh":145,"source_url":146},29017,"在测试阶段对网络输出进行多次采样（如 5 次）后，应该如何处理这些采样结果？是取平均、求和还是选最好的一个？","应该对多次采样的输出结果取**平均值**。这是蒙特卡洛（MC）推断的标准做法，用于近似后验预测分布 $p(y* | x*, data)$。具体来说，对于分类任务，通常先对每次采样的输出 logits 进行 Softmax 处理得到概率分布，然后对这些概率分布取平均；或者在某些回归设置中直接对预测值取平均。此外，训练时的损失（loss）和 KL 散度也是基于多次采样结果的平均值计算的，采样次数越多，ELBO 估计的方差越低。","https:\u002F\u002Fgithub.com\u002FJavierAntoran\u002FBayesian-Neural-Networks\u002Fissues\u002F4",{"id":148,"question_zh":149,"answer_zh":150,"source_url":141},29018,"如何在代码中控制 MC Dropout 和 Bayes By Backprop 的后验预测采样数量？为什么两者默认输出的结果组数不同？","采样数量由参数 `Nsamples` 控制，它决定了近似后验预测时绘制的蒙特卡洛样本数。\n如果发现 MC Dropout 和 BBB 输出的结果组数不同（例如一个是 16 个，一个是 100 个），通常是因为**输入数据的批次大小（batch size）不同**，而不是采样机制本身的问题。\n要直接比较两种方法的后验预测分布，请确保：\n1. `Nsamples` 设置一致。\n2. 输入到 `all_sample_eval` 或评估函数的数据 `(x, y)` 完全相同且批次大小一致。",{"id":152,"question_zh":153,"answer_zh":154,"source_url":155},29019,"Bayes By Backprop (BBB) 中为什么使用简单的高斯先验而不是混合高斯先验（Mixture of Gaussians）？混合先验不是更能模拟权重的真实分布吗？","虽然混合高斯先验理论上能更好地建模权重分布，但在 BBB 框架下存在实际困难：\n1. **KL 散度计算不可行**：如果使用混合高斯作为先验，变分后验与先验之间的 KL 散度积分将变得难以解析计算（intractable）。\n2. **增加方差**：为了计算该 KL 散度，必须使用蒙特卡洛（MC）方法进行估算，这会显著增加 ELBO 估计量的方差，导致训练不稳定。\n因此，为了保持计算的可行性和稳定性，通常选择简单的高斯先验。变分后验的作用是近似真实的后验分布，而非直接模拟先验。","https:\u002F\u002Fgithub.com\u002FJavierAntoran\u002FBayesian-Neural-Networks\u002Fissues\u002F3",{"id":157,"question_zh":158,"answer_zh":159,"source_url":146},29020,"在贝叶斯神经网络中，如何使用熵（Entropy）或方差（Variance）来分解认知不确定性（Epistemic）和偶然不确定性（Aleatoric）？BBB 方法适用吗？","是的，即使使用 BBB（其后验近似为高斯分布，而非 Variational Dropout 的伯努利分布），也可以计算这两种不确定性。\n- **总不确定性**：可以通过预测分布的熵（分类任务）或方差（回归任务）来衡量。\n- **分解方法**：\n  - **偶然不确定性 (Aleatoric)**：通常由模型输出的方差参数直接给出（异方差模型），或通过单次前向传播的预测方差估计。\n  - **认知不确定性 (Epistemic)**：通过多次采样（MC Sampling）得到的预测结果的方差来估计。即总方差减去平均偶然方差。\n参考文献 *Uncertainty quantification using Bayesian neural networks in classification* 中展示了基于方差的建模方法，这与基于熵的方法在不同任务（回归 vs 分类）中是互补的。",[]]