GraphRAG + Ollama 本地部署全攻略:避坑实战指南

傻瓜操作:GraphRAG、Ollama 本地部署及踩坑记录 这里按惯例介绍一下 GraphRAG (其实就是水字数,大部分是 GPT 写的)这是我踩的最大的坑,折腾了两个小时。原因是一些模型无法生成有效的 json 输出,将 settings.yaml 中的 model_supports_json 选项设为 false 仍然无法解决。后来改用 mistral 模型就很顺利。所以请注意你的模型。 阅读详情
AI摘要

本文介绍如何通过修改GraphRAG源码支持本地部署大模型,包括安装步骤、配置文件修改及源码调整等内容,使GraphRAG能更好地利用本地资源。

—1—

为什么要对 GraphRAG 本地部署?

微软开源 GraphRAG 后,热度越来越高,目前 GraphRAG 只支持 OpenAI 的闭源大模型,导致部署后使用范围大大受限,本文通过 GraphRAG 源码的修改,来支持更广泛的 Embedding 模型和开源大模型,从而使得 GraphRAG 的更容易上手使用。

图片

—2—

GraphRAG 一键安装

第一步、安装 GraphRAG

图片

需要 Python 3.10-3.12 环境。

第二步、创建知识数据文件夹

安装完整后,需要创建一个文件夹,用来存储你的知识数据,目前 GraphRAG 只支持 txt 和 csv 格式。

图片

第三步、准备一份数据放在 /ragtest/input 目录下

图片

第四步、初始化工作区

首先,我们需要运行以下命令来初始化。

图片

其次,我们第二步已经准备了 ragtest 目录,运行以下命令完成初始化。

图片

运行完成后,在 ragtest 目录下生成以下两个文件:.env 和settings.yaml。ragtest 目录下的结构如下:

图片

.env 文件包含了运行 GraphRAG 管道所需的环境变量。如果您检查该文件,您会看到一个定义的环境变量,GRAPHRAG_API_KEY=。这是 OpenAI API 或 Azure OpenAI 端点的 API 密钥。您可以用自己的 API 密钥替换它。

settings.yaml 文件包含了管道的设置。您可以修改此文件以更改管道的设置。

—3—

修改配置文件支持本地部署大模型

第一步、确保已安装 Ollama

第二步、确保已安装以下本地模型
在这里插入图片描述

第三步、修改 settings.yaml 以支持以上两个本地模型,以下是修改后的文件

encoding_model: cl100k_base
skip_workflows: []
llm:
  api_key: ollama  
  type: openai_chat # or azure_openai_chat  
  model: gemma2:9b # 你 ollama 中的本地 llm 模型,可以换成其他的,只要你安装了就可以  
  model_supports_json: true # recommended if this is available for your model.  
  max_tokens: 2048  
  api_base: http://localhost:11434/v1 # 接口注意是v1  
  concurrent_requests: 1 # the number of parallel inflight requests that may be made

parallelization:
  stagger: 0.3
async_mode: threaded # or asyncio

embeddings:
  async_mode: threaded # or asyncio  
  llm:  
    api_key: ollama    
    type: openai_embedding # or azure_openai_embedding    
    model: quentinz/bge-large-zh-v1.5:latest # 你 ollama 中的本地 Embeding 模型,可以换成其他的,只要你安装了就可以    
    api_base: http://localhost:11434/api # 注意是 api    
    concurrent_requests: 1 # the number of parallel inflight requests that may be made
chunks:
  size: 300  
  overlap: 100  
  group_by_columns: [id] # by default, we don't allow chunks to cross documents    

input:
  type: file # or blob  
  file_type: text # or csv  
  base_dir: "input"  
  file_encoding: utf-8 
  file_pattern: ".*\\.txt$"

cache:
  type: file # or blob  
  base_dir: "cache"

storage:
  type: file # or blob  
  base_dir: "output/${timestamp}/artifacts"

reporting:
  type: file # or console, blob  
  base_dir: "output/${timestamp}/reports"

entity_extraction:
  prompt: "prompts/entity_extraction.txt"  
  entity_types: [organization,person,geo,event]  
  max_gleanings: 0

summarize_descriptions:
  prompt: "prompts/summarize_descriptions.txt"  
  max_length: 500

claim_extraction:
  prompt: "prompts/claim_extraction.txt"  
  description: "Any claims or facts that could be relevant to information discovery."  
  max_gleanings: 0

community_report:
  prompt: "prompts/community_report.txt"  
  max_length: 2000  
  max_input_length: 8000

cluster_graph:
  max_cluster_size: 10

embed_graph:
  enabled: false # if true, will generate node2vec embeddings for nodes

umap:
  enabled: false # if true, will generate UMAP embeddings for nodes

snapshots:
  graphml: false  
  raw_entities: false  
  top_level_nodes: false

local_search:  
  max_tokens: 5000

global_search:
  max_tokens: 5000

第四步、运行 GraphRAG 构建知识图谱索引

图片

构建知识图谱的索引需要一定的时间,构建过程如下所示:

图片

—4—

修改源码支持本地部署大模型

接下来修改源码,保证进行 local 和 global 查询时给出正确的结果。

第一步、修改成本地的 Embedding 模型

修改源代码的目录和文件:

…/Python/Python310/site-packages/graphrag/llm/openai/openai_embeddings_llm.py"

修改后的源码如下:

# Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License

"""The EmbeddingsLLM class."""

from typing_extensions import Unpack

from graphrag.llm.base import BaseLLM
from graphrag.llm.types import (
    EmbeddingInput,    
    EmbeddingOutput,    
    LLMInput,
)

from .openai_configuration import OpenAIConfiguration
from .types import OpenAIClientTypes
import ollama

class OpenAIEmbeddingsLLM(BaseLLM[EmbeddingInput, EmbeddingOutput]):
    """A text-embedding generator LLM."""    
    
    _client: OpenAIClientTypes    
    _configuration: OpenAIConfiguration    
    
    def __init__(self, client: OpenAIClientTypes, configuration: OpenAIConfiguration):
        self.client = client        
        self.configuration = configuration    
        
    async def _execute_llm(
        self, input: EmbeddingInput, **kwargs: Unpack[LLMInput]    
    ) -> EmbeddingOutput | None:    
        args = {      
            "model": self.configuration.model,            
            **(kwargs.get("model_parameters") or {}),        
        }        
        embedding_list = []        
        for inp in input:        
            embedding = ollama.embeddings(model="quentinz/bge-large-zh-v1.5:latest",prompt=inp)            
            embedding_list.append(embedding["embedding"])        
        return embedding_list        
        # embedding = await self.client.embeddings.create(        
        #     input=input,        
        #     **args,       
        # )        
        # return [d.embedding for d in embedding.data]

第二步、继续修改 Embedding 模型

修改源代码的目录和文件:

…/Python/Python310/site-packages/graphrag/query/llm/oai/embedding.py"

修改后的源码如下:

# Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License

"""OpenAI Embedding model implementation."""

import asyncio
from collections.abc import Callable
from typing import Any

import numpy as np
import tiktoken
from tenacity import (
    AsyncRetrying,    
    RetryError,    
    Retrying,    
    retry_if_exception_type,    
    stop_after_attempt,    
    wait_exponential_jitter,
)

from graphrag.query.llm.base import BaseTextEmbedding
from graphrag.query.llm.oai.base import OpenAILLMImpl
from graphrag.query.llm.oai.typing import (
    OPENAI_RETRY_ERROR_TYPES,    
    OpenaiApiType,
)
from graphrag.query.llm.text_utils import chunk_text
from graphrag.query.progress import StatusReporter

from langchain_community.embeddings import OllamaEmbeddings



class OpenAIEmbedding(BaseTextEmbedding, OpenAILLMImpl):
    """Wrapper for OpenAI Embedding models."""    
    
    def __init__(    
        self,        
        api_key: str | None = None,        
        azure_ad_token_provider: Callable | None = None,        
        model: str = "text-embedding-3-small",        
        deployment_name: str | None = None,        
        api_base: str | None = None,        
        api_version: str | None = None,        
        api_type: OpenaiApiType = OpenaiApiType.OpenAI,        
        organization: str | None = None,        
        encoding_name: str = "cl100k_base",        
        max_tokens: int = 8191,        
        max_retries: int = 10,        
        request_timeout: float = 180.0,        
        retry_error_types: tuple[type[BaseException]] = OPENAI_RETRY_ERROR_TYPES,  # type: ignore        
        reporter: StatusReporter | None = None,    
     ):      
        OpenAILLMImpl.__init__(      
            self=self,            
            api_key=api_key,            
            azure_ad_token_provider=azure_ad_token_provider,            
            deployment_name=deployment_name,            
            api_base=api_base,            
            api_version=api_version,            
            api_type=api_type,  # type: ignore            
            organization=organization,            
            max_retries=max_retries,            
            request_timeout=request_timeout,            
            reporter=reporter,       
        )        
       
       self.model = model       
       self.encoding_name = encoding_name        
       self.max_tokens = max_tokens        
       self.token_encoder = tiktoken.get_encoding(self.encoding_name)        
       self.retry_error_types = retry_error_types    
    
   def embed(self, text: str, **kwargs: Any) -> list[float]:    
       """        
       Embed text using OpenAI Embedding's sync function.   
            
       For text longer than max_tokens, chunk texts into max_tokens, embed each chunk, then combine using weighted average.        
       Please refer to: https://github.com/openai/openai-cookbook/blob/main/examples/Embedding_long_inputs.ipynb        
       """        
       token_chunks = chunk_text(       
           text=text, token_encoder=self.token_encoder, max_tokens=self.max_tokens        
       )        
       chunk_embeddings = []        
       chunk_lens = []        
       for chunk in token_chunks:       
           try:          
               embedding, chunk_len = self._embed_with_retry(chunk, **kwargs)                
               chunk_embeddings.append(embedding)                
               chunk_lens.append(chunk_len)            
           # TODO: catch a more specific exception            
           except Exception as e:  # noqa BLE001            
               self._reporter.error(                
                   message="Error embedding chunk",                    
                   details={self.__class__.__name__: str(e)},                
               )              
  
               continue        
       chunk_embeddings = np.average(chunk_embeddings, axis=0, weights=chunk_lens)        
       chunk_embeddings = chunk_embeddings / np.linalg.norm(chunk_embeddings)        
       return chunk_embeddings.tolist()    
       
   async def aembed(self, text: str, **kwargs: Any) -> list[float]:        
   """        
   Embed text using OpenAI Embedding's async function. 
          
   For text longer than max_tokens, chunk texts into max_tokens, embed each chunk, then combine using weighted average.        
   """        
   token_chunks = chunk_text(         
       text=text, token_encoder=self.token_encoder, max_tokens=self.max_tokens        
   )        
   chunk_embeddings = []        
   chunk_lens = []        
   embedding_results = await asyncio.gather(*[        
       self._aembed_with_retry(chunk, **kwargs) for chunk in token_chunks        
   ])        
   embedding_results = [result for result in embedding_results if result[0]]        
   chunk_embeddings = [result[0] for result in embedding_results]        
   chunk_lens = [result[1] for result in embedding_results]        
   chunk_embeddings = np.average(chunk_embeddings, axis=0, weights=chunk_lens)  # type: ignore        
   chunk_embeddings = chunk_embeddings / np.linalg.norm(chunk_embeddings)        
   return chunk_embeddings.tolist()    

def _embed_with_retry(     
    self, text: str | tuple, **kwargs: Any    
) -> tuple[list[float], int]:    
    try:         
        retryer = Retrying(           
            stop=stop_after_attempt(self.max_retries),                
            wait=wait_exponential_jitter(max=10),                
            reraise=True,                
            retry=retry_if_exception_type(self.retry_error_types),            
        )            
        for attempt in retryer:          
            with attempt:                 
                embedding = (                     
                    OllamaEmbeddings(                        
                        model=self.model,                        
                    ).embed_query(text)                        
                    or []                    
                )                    
                return (embedding, len(text))        
    except RetryError as e:        
        self._reporter.error(          
             message="Error at embed_with_retry()",                
             details={self.__class__.__name__: str(e)},           
        )            
        return ([], 0)        
    else:        
        # TODO: why not just throw in this case?            
        return ([], 0)    
        
async def _aembed_with_retry(     
    self, text: str | tuple, **kwargs: Any    
) -> tuple[list[float], int]:    
    try:       
        retryer = AsyncRetrying(            
            stop=stop_after_attempt(self.max_retries),                
            wait=wait_exponential_jitter(max=10),                
            reraise=True,                
            retry=retry_if_exception_type(self.retry_error_types),            
        )            
        async for attempt in retryer:           
            with attempt:             
                embedding = (                    
                    await OllamaEmbeddings(                        
                        model=self.model,                        
                    ).embed_query(text) or [] )                   
                return (embedding, len(text))       
    except RetryError as e:          
        self._reporter.error(           
            message="Error at embed_with_retry()",                
            details={self.__class__.__name__: str(e)},            
        )            
        return ([], 0)        
    else:           
        # TODO: why not just throw in this case?            
        return ([], 0)

—5—

GraphRAG 效果测试

第一、local 查询

图片

图片

第二、global 查询

图片

图片

​

如何学习大模型

现在社会上大模型越来越普及了,已经有很多人都想往这里面扎,但是却找不到适合的方法去学习。

作为一名资深码农,初入大模型时也吃了很多亏,踩了无数坑。现在我想把我的经验和知识分享给你们,帮助你们学习AI大模型,能够解决你们学习中的困难。

我已将重要的AI大模型资料包括市面上AI大模型各大白皮书、AGI大模型系统学习路线、AI大模型视频教程、实战学习,等录播视频免费分享出来,需要的小伙伴可以扫取。

一、AGI大模型系统学习路线

很多人学习大模型的时候没有方向,东学一点西学一点,像只无头苍蝇乱撞,我下面分享的这个学习路线希望能够帮助到你们学习AI大模型。

在这里插入图片描述

二、AI大模型视频教程

在这里插入图片描述

三、AI大模型各大学习书籍

在这里插入图片描述

四、AI大模型各大场景实战案例

在这里插入图片描述

五、结束语

学习AI大模型是当前科技发展的趋势,它不仅能够为我们提供更多的机会和挑战,还能够让我们更好地理解和应用人工智能技术。通过学习AI大模型,我们可以深入了解深度学习、神经网络等核心概念,并将其应用于自然语言处理、计算机视觉、语音识别等领域。同时,掌握AI大模型还能够为我们的职业发展增添竞争力,成为未来技术领域的领导者。

再者,学习AI大模型也能为我们自己创造更多的价值,提供更多的岗位以及副业创收,让自己的生活更上一层楼。

因此,学习AI大模型是一项有前景且值得投入的时间和精力的重要选择。

【GraphRAG】本地部署全流程!超详细介绍! graphrag本地部署 阅读详情

相关推荐

从RAG到GraphRAG的应用落地揭秘

RAG(检索增强生成)是什么?正如提到的那样,它是一种技术,可以“良好”地解释用户的查询,检索“相关”信息,将其处理为上下文,然后将此有用信息融入回复中。正如引用的网站所指出的,RAG以其成本效益、相对准确性、提供领域特定语境的充足性、反映最新信息的能力以及追踪信息来源文档的透明度和可解释性等特点而被认为是一种主要选择的方法。

具身机器人和通用AI 2245

ollama轻松部署本地GraphRAG(避雷篇)

本篇文章主要介绍如何使用ollama本地部署微软的Graph RAG,,Graph RAG成为RAG一种新范式,对于全局总结性问题表现突出,由ollama一站式解决。但是中间也出现非常多的问题,比如Columns must be same length as key。跟着本篇文章使用ollama+mistral-nemo+mxbai-embed-larg`实现本地的GraphRAG的部署!

weixin_63866037的博客 1万+

线性代数知识点整理

线性代数基础知识点摘要整理

cuguanren的博客 3万+

大模型 | GraphRAG + Ollama 本地部署全攻略:避坑实战指南

AI大模型作为人工智能领域的重要技术突破,正成为推动各行各业创新和转型的关键力量。抓住AI大模型的风口,掌握AI大模型的知识和技能将变得越来越重要。学习AI大模型是一个系统的过程,需要从基础开始,逐步深入到更高级的技术。这里给大家精心整理了一份全面的AI大模型学习资源,包括:AI大模型全套学习路线图(从入门到实战)、精品AI大模型学习书籍手册、视频教程、实战学习、面试题等,资料免费分享!

老皮的博客 6188

中国高精度年度平均气温栅格数据集(1901-2024)

本文基于中国月度平均气温栅格数据集,计算生成1901-2024年1km分辨率的年度平均气温数据集,并按中国省市行政区划进行裁剪。该数据集融合CRU全球数据和WorldClim高分辨率数据,经496个站点验证,具有高时空精度和长时间序列特点,覆盖全国(含港澳台)逾百年气温记录,为气候变化研究、生态水文分析及农业生产评估等提供重要数据支撑。数据格式为Tif,单位为0.1℃,可获取全国、各省及各市三个尺度的气温栅格数据。

PPdata_Academy的博客 1244

DRM驱动架构浅析-上(DRM基础概要与U-Boot阶段驱动解析)

本文主要探讨了Rockchip平台的DRM显示驱动架构及其在U-Boot阶段的实现。

一路寒风身如絮,命海沉浮客独行 1766

【AI大模型部署】GraphRAG + Ollama 本地部署全攻略:避坑实战指南

微软开源 GraphRAG 后,热度越来越高,目前 GraphRAG 只支持 OpenAI 的闭源大模型,导致部署后使用范围大大受限,本文通过 GraphRAG 源码的修改,来支持更广泛的 Embedding 模型和开源大模型,从而使得 GraphRAG 的更容易上手使用。

2401_85327249的博客 1432

麒麟V10系统命令实战指南:从入门到精通

本文为麒麟V10操作系统用户提供了一份从入门到精通的命令行实战指南。内容涵盖文件管理、进程监控、网络诊断、文本处理及系统管理等核心场景,旨在帮助用户转变思维,掌握高效解决实际问题的系统命令技巧,从而提升在麒麟V10环境下的运维与工作效率。

sat99的博客 597

服务器上GraphRag+Ollama避坑指南

embding模型:quentinz/bge-large-zh-v1.5:latest。中途碰到输入命令没有反应的情况,可以试试关掉断开服务器,重连一下,再执行命令。这个问题是因为txt文件的编码格式不对,编码格式改成utf-8就可以了。local 查询没有问题,但是global查询模型说自己不知道。:检查日志发现,问题出现在读取txt文件的时候。里也写了一些可能出现的问题。1、离线下ollama。

YiHanXii的博客 2077

23种设计模式-享元(Flyweight)设计模式

软考中级-软件设计师 享元设计模式

片言可决讼,半纸能缚龙 3224

YOLOv11改进 | 上采样篇 | YOLOv11引入CARAFE上采样

在本文中,我们提出了一个通用、轻量级、高效的特征重组算子CARAFE来实现这一目标.CARAFE有几个吸引人的特性:(1)大视场。(2)内容感知处理。到此本文的正式分享内容就结束了,在这里给大家推荐我的YOLOv11改进有效涨点专栏,本专栏目前为新开的,后期我会根据各种前沿顶会进行论文复现,也会对一些老的改进机制进行补充,如果大家觉得本文帮助到你了,订阅本专栏,关注后续更多的更新~大视场:不同于以往的方法(如双线性插值),CARAFE能够在更大的感受野内聚合上下文信息,从而捕获更丰富的语义信息。

tsg6698的博客 925

GraphRAG+Ollama本地部署全攻略:保姆级教程,避开常见陷阱

在本地启动并运行大型语言模型。运行Llama 2,Code Llama和其他模型。自定义并创建您自己的。

2401_84204207的博客 1896

【DEIM创新改进】全网独家创新、注意力改进篇 | AAAI 2026 | DEIM 引入轻量级群体注意力(LWGA)模块,可以显著提高其多尺度物体检测能力,特别是在小物体和复杂背景下的表现

本文提出了一种改进的DEIM网络模型,通过引入轻量级LWGA模块显著提升了多尺度物体检测性能。LWGA模块采用局部和全局注意力机制,有效提升了小物体和复杂背景下的识别能力,同时保持低计算成本。该模块通过分割输入特征图并应用多种注意力机制(GPA、RLA、SMA、SGA)进行特征提取和融合,优化了多尺度物体的特征表示。实验表明,改进后的DEIM模型在遥感图像处理等任务中表现出色,在12个数据集上实现了性能与计算效率的最佳平衡,为资源受限设备提供了高效的解决方案。

Ai缝合怪、助力小伙伴高效发论文 276

保姆级避坑指南:在Linux上用Ollama+GraphRAG 0.4.1搭建本地知识库(附Gephi可视化)

本文详细介绍了在Linux系统上使用Ollama和GraphRAG 0.4.1搭建本地知识库的全过程,包括环境配置、报错解决和Gephi可视化。通过实战案例和优化技巧,帮助开发者高效构建知识图谱,提升非结构化数据处理能力。

weixin_30745553的博客 490

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

免费获取OpenAI API密钥与本地开源大模型部署全攻略

在人工智能应用开发中,API(应用程序编程接口)是连接服务与功能的核心桥梁,其原理是通过预定义的协议实现软件组件间的通信。对于开发者而言,掌握API调用能力是构建智能应用的基础技术价值。尤其在自然语言处理、内容生成等场景,大语言模型(LLM)的API调用需求日益增长。然而,直接使用商业API可能面临成本与隐私考量。本文聚焦于OpenAI API密钥的合规获取策略,并深入探讨通过部署开源大模型(如Qwen、Llama)及利用Ollama等兼容框架构建本地替代方案的技术路径。这些方法不仅能有效管理调用成本,还能

weixin_34293141的博客 355

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

上一篇: 本地部署与微调:解锁微软Phi-3高中阅读理解技能
下一篇: 如何快速提高大模型的向量表征效果?
AI_小站
博客等级 码龄3年 6255粉丝 1154原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值