《pyhanlp 实用指南:安装、迁移与 HanLP 1.x 和 2.x 应用解析》

自然语言处理学习笔记(三)————HanLP安装与使用 第一次使用pyhanlp时,会自动下载许多hanlp的jar包(包含许多算法)和数据包(包含许多模型)到pyhanlp的系统路径中,大约六百多兆。[你好/vl, ,/w, 欢迎/v, 进入/v, nlp/nx, 的/ude1, 世界/n]wky 右括号,全角:) 〕 ] } 》 】 〗 〉 半角: ) ] { >wkz 左括号,全角:( 〔 [ { 《 【 〖 〈 半角:( [ { 阅读详情
AI摘要

本文介绍了HanLP 1.x和2.x两个版本的自然语言处理工具包。HanLP 1.x基于Java,适用于基础NLP任务;HanLP 2.x基于Python,适合复杂任务。文中还详细说明了在python3.11环境下安装pyhanlp、pyhanlp迁移以及HanLP2.x的安装使用方法,帮助用户利用其NLP功能。

本文将介绍 pyhanlp。

包括HanLP 1.x和HanLP 2.x 版本的使用场景的介绍,以及它们的安装、迁移和使用方法,以帮助大家充分利用其强大的自然语言处理功能。

主要内容包括:

1、如何在3.9及以上的python环境下安装pyhanlp?

2、pyhanlp的迁移;

3、HanLP2.x的安装使用。

HanLP 是一个开源的自然语言处理(NLP)工具包,提供了丰富的功能,包括分词、词性标注、依存句法分析、关键词提取、文本分类等。这些功能满足了多种语言处理需求,被广泛应用于研究和工业领域。

两个版本的衍生:

  • HanLP 1.x
    HanLP 1.x 是基于 Java 的版本,主要依赖统计模型和规则算法。它提供了高效的分词和词性标注工具,同时支持命名实体识别(NER)、依存句法分析和关键词提取等基础 NLP 功能。为了方便 Python 用户使用 HanLP 1.x,提供了一个名为 pyhanlp 的 Python 包,通过 JPype 将 HanLP 1.x 的 Java 接口封装成 Python API。pyhanlp 支持自动下载和升级模型,但其核心仍依赖 Java,适用于 Python ≤ 3.8 的环境。

  • HanLP 2.x
    HanLP 2.x 是一个全新的版本,完全基于 Python 开发,并采用了现代深度学习技术,如 Transformer 和预训练语言模型(如 BERT 和 GPT)。HanLP 2.x 支持多语言处理,不再局限于中文,并在复杂任务(如文本生成、问答系统和语义分析)上表现优异。其 API 设计更加现代化,易于上手,适合高精度和大规模的 NLP 应用场景。

HanLP 1.x 和 HanLP 2.x 的对比:

图片

总结:

  • 如果您的任务对速度和资源需求较敏感,或者只是完成基础的 NLP 任务,HanLP 1.x 仍然是一个高效的选择。

  • 如果您不打算将使用 HanLP 1.x 接口实现的功能迁移到 HanLP 2.x,但希望在新版本的 Python 中安装和迁移 pyhanlp,请仔细阅读本文并动手测试相关步骤。

  • 如果需要处理复杂任务或多语言环境,并且注重精度和性能,HanLP 2.x 是更好的选择。

一、python3.11环境下安装pyhanlp

图片

1.1 python3.11虚拟环境准备

创建一个python为3.11.8的虚拟环境hanlp1_X。

图片

1.2 修改setup.py文件内容

使用官网的conda命令:

conda install -c conda-forge openjdk python=3.8 jpype1=0.7.0 -y pip install pyhanlp

显然是不可行的,python的版本,jpype1的版本都不对。直接使用命令:

pip install pyhanlp

安装报错信息如下:

图片

打开下载的pyhanlp 0.1.85的包中的安装文件setup.py。

图片

setup.py的内容如下,影响安装的信息如高亮(红色)部分。

# -*- coding:utf-8 -*-# Author:hankcs# Date: 2018-03-11 20:54from os.path import abspath, join, dirnameimport sysfrom setuptools import find_packages, setupdef browser_open(url='https://nlp.hankcs.com/download.php?file=install'):    try:        import webbrowser        webbrowser.open_new_tab(url)    except:        passJPYPE = 'jpype1==0.7.0'try:    import subprocess    command = 'pip install ' + JPYPE    subprocess.run(        [sys.executable, "-m"] + command.split(" "),        check=True,    )except:    browser_open()    errors = ['{} 安装失败'.format(JPYPE)]    if sys.version_info >= (3, 9):        errors.append('暂不支持 Python 3.9 及以上版本')    sys.exit(        '''----------------------------------------{}。请执行如下命令:	conda install -c conda-forge python=3.8 openjdk {} -y	pip install pyhanlp详细安装教程:https://nlp.hankcs.com/download.php?file=installWindows傻瓜安装包:https://nlp.hankcs.com/download.php?file=exe        '''.format(','.join(errors), JPYPE))if sys.version_info[0] < 3:  # In Python3 TypeError: a bytes-like object is required, not 'str'    long_description = 'Python wrapper for HanLP: Han Language Processing'else:    this_dir = abspath(dirname(__file__))    with open(join(this_dir, 'README.md'), encoding='utf-8') as file:        long_description = file.read()setup(    name='pyhanlp',    version='0.1.85',    description='Python wrapper for HanLP: Han Language Processing',    long_description=long_description,    long_description_content_type="text/markdown",    url='https://github.com/hankcs/pyhanlp',    author='hankcs',    author_email='hankcshe@gmail.com',    license='Apache License 2.0',    classifiers=[        'Intended Audience :: Developers',        'Natural Language :: Chinese (Simplified)',        'Natural Language :: Chinese (Traditional)',        'Operating System :: OS Independent',        'Programming Language :: Python',        'Programming Language :: Python :: 2',        'Programming Language :: Python :: 2.7',        'Programming Language :: Python :: 3',        'Topic :: Text Processing',        'Topic :: Text Processing :: Indexing',        'Topic :: Text Processing :: Linguistic'    ],    keywords='corpus,machine-learning,NLU,NLP',    packages=find_packages(exclude=['docs', 'tests*']),    include_package_data=True,    install_requires=[JPYPE, 'hanlp-downloader'],    entry_points={        'console_scripts': [            'hanlp=pyhanlp.main:main',        ],    },    # python_requires='<3.9',)

我们不妨对高亮部分进行更改,将jpype1的版本改为1.4.1,将判断python版本的部分注释,如下所示:

# -*- coding:utf-8 -*-# Author:hankcs# Date: 2018-03-11 20:54from os.path import abspath, join, dirnameimport sysfrom setuptools import find_packages, setupdef browser_open(url='https://nlp.hankcs.com/download.php?file=install'):    try:        import webbrowser        webbrowser.open_new_tab(url)    except:        passJPYPE = 'jpype1==1.4.1'try:    import subprocess    command = 'pip install ' + JPYPE    subprocess.run(        [sys.executable, "-m"] + command.split(" "),        check=True,    )except:    browser_open()    errors = ['{} 安装失败'.format(JPYPE)]#     if sys.version_info >= (3, 9):#         errors.append('暂不支持 Python 3.9 及以上版本')#     sys.exit(#         '''# ----------------------------------------## {}。请执行如下命令:## 	conda install -c conda-forge python=3.8 openjdk {} -y# 	pip install pyhanlp## 详细安装教程:https://nlp.hankcs.com/download.php?file=install# Windows傻瓜安装包:https://nlp.hankcs.com/download.php?file=exe#         '''.format(','.join(errors), JPYPE))if sys.version_info[0] < 3:  # In Python3 TypeError: a bytes-like object is required, not 'str'    long_description = 'Python wrapper for HanLP: Han Language Processing'else:    this_dir = abspath(dirname(__file__))    with open(join(this_dir, 'README.md'), encoding='utf-8') as file:        long_description = file.read()setup(    name='pyhanlp',    version='0.1.85',    description='Python wrapper for HanLP: Han Language Processing',    long_description=long_description,    long_description_content_type="text/markdown",    url='https://github.com/hankcs/pyhanlp',    author='hankcs',    author_email='hankcshe@gmail.com',    license='Apache License 2.0',    classifiers=[        'Intended Audience :: Developers',        'Natural Language :: Chinese (Simplified)',        'Natural Language :: Chinese (Traditional)',        'Operating System :: OS Independent',        'Programming Language :: Python',        'Programming Language :: Python :: 2',        'Programming Language :: Python :: 2.7',        'Programming Language :: Python :: 3',        'Topic :: Text Processing',        'Topic :: Text Processing :: Indexing',        'Topic :: Text Processing :: Linguistic'    ],    keywords='corpus,machine-learning,NLU,NLP',    packages=find_packages(exclude=['docs', 'tests*']),    include_package_data=True,    install_requires=[JPYPE, 'hanlp-downloader'],    entry_points={        'console_scripts': [            'hanlp=pyhanlp.main:main',        ],    },    # python_requires='<3.9',)

1.3 使用setup.py安装pyhanlp

使用命令:

python setup.py install

图片

安装pyhanlp如下:

图片

安装完成后,在目录:

C:\ProgramData\miniconda3\envs\hanlp1_X\Lib\site-packages

下,会生成一个名为“pyhanlp-0.1.85-py3.11.egg”的文件夹,在该文件夹下, 将pyhanlp文件夹剪切或复制到site-packages目录下。

图片

1. 4 导入pyhanlp

图片

重新打开一个命令行窗口,激活hanlp1_X(或者切换一下当前目录),否则导入的是安装目录下的文件夹。

图片

1.5 导包失败,配置hanlp-1.8.5-release

从地址:http://download.hanlp.com/下载hanlp-1.8.5-release.zip文件。

图片

那么,直接下载hanlp-1.8.5-release.zip,将压缩包内的文件解压后,拷贝至目录:

C:\ProgramData\miniconda3\envs\hanlp1_X\Lib\site-packages\pyhanlp\static

图片

打开文件“hanlp.properties”,并编辑“root=D:/JavaProjects/HanLP/”行,将路径更改为当前pyhanlp文件夹下的static文件夹所在的绝对路径地址。

问题来了,这个地址是写死的,当将包含pyhanlp的python环境拷贝或编译后,将发生找不到指定文件的错误,解决办法附后。

图片

更改结果如下:

图片

再次导入包pyhanlp测试,错误信息如下:

图片

1.6 导包失败,配置data-for-1.7.5

到http://download.hanlp.com/网站上下载“data-for-1.7.5.zip”文件,并将其解压至目录:

C:\ProgramData\miniconda3\envs\hanlp1_X\Lib\site-packages\pyhanlp\static

图片

再次导入包pyhanlp测试,输出信息如下:

图片

二、pyhanlp的迁移

当将pyhanlp包迁移至其他环境或将其打包到单一可执行文件中时,由于文件“hanlp.properties”中的“root=……”地址是写死的,该如何解决呢?

思路:

在导入pyhanlp包前,动态编辑“hanlp.properties”文件中的“root=……“地址,可通过修改pyhanlp包的"__init__.py"实现。

2.1 拷贝pyhanlp包及其依赖至文件夹pyhanlp1.8.6

为了测试这个过程,在D:\gistools\目录下创建文件夹pyhanlp1.8.6,将pyhanlp包及其依赖拷贝至pyhanlp1.8.6(若不知道依赖项有哪些,可在site-packages文件夹下按时间排序)。

注意:pyhanlp包存放的目录不能包含中文路径。

图片

拷贝内容如下:

图片

2.2 编辑__init__.py文件

编辑pyhanlp文件夹下的__init__.py文件,增加一下内容:

图片

函数update_properties_file的内容如下:

def update_properties_file():    # 获取当前模块所在的目录    module_dir = os.path.dirname(__file__)    # 构建 static 目录的路径,并使用正斜杠作为路径分隔符    static_dir = os.path.join(module_dir, 'static')    static_dir_write = static_dir.replace(os.path.sep, '/')    # 构建 hanlp.properties 文件的路径    properties_file_path = os.path.join(static_dir, 'hanlp.properties')    # 读取 hanlp.properties 文件    with open(properties_file_path, 'r', encoding='utf-8') as file:        lines = file.readlines()    # 更新 root 属性值    updated_lines = []    root_updated = False    for line in lines:        if line.startswith('root='):            # 更新 root 属性值为 static 目录的路径            line = f'root={static_dir_write}\n'            root_updated = True        updated_lines.append(line)    # 如果没有找到 root 属性,则添加一行    if not root_updated:        updated_lines.append(f'root={static_dir_write}\n')    # 将更新后的内容写回 hanlp.properties 文件    with open(properties_file_path, 'w', encoding='utf-8') as file:        file.writelines(updated_lines)

在pyhanlp1.8.6同级目录的文件夹(如:gistools)下,创建文件“导入测试.py”,代码内容为将pyhanlp1.8.6目录添加到os.path中。

导入pyhanlp测试,报错信息如下:

图片

2.3 添加hanlp_downloader模块

错误信息为没有“hanlp_downloader”模块,到地址:

https://pypi.org/project/hanlp-downloader/#files 

下载hanlp_downloader-0.0.25.tar.gz,并提取hanlp_downloader文件夹,将其拷贝至:D:\gistools\pyhanlp1.8.6,测试如下:

图片

可以发现,pyhanlp迁移后能正常使用,且hanlp.properties文件中root变量对应的地址已动态更改。

图片

三、HanLP2.x的安装使用

图片

尽管https://github.com/hankcs/HanLP/tree/doc-zh中明确支持的python版本不包括3.11,但在3.11的python虚拟环境下,无论是Windows、Linux还是macOS,HanLP的安装只需一句话搞定:

pip install hanlp -U

图片

HanLP2.1的接口示例,可参考:https://github.com/hankcs/HanLP/tree/doc-zh

图片

图片

【NLP工具】hanLP2.1的使用(未完) 一、hanlp简介 面向生产环境的多语种自然语言处理工具包,基于PyTorch和TensorFlow 2.x双引擎,目标是普及落地最前沿的NLP技术。HanLP具备功能完善、性能高效、架构清晰、语料时新、可自定义的特点。 借助世界上最大的多语种语料库,HanLP2.1支持包括简繁中英日俄法德在内的104种语言上的10种联合任务:分词(粗分、细分2个标准,强制、合并、校正3种词典模式)、词性标注(PKU、863、CTB、UD四套词性规范)、命名实体识别(PKU、MSRA、OntoNotes三套规范)、依存 阅读详情

相关推荐

pyhanlp最全安装和使用教程

HanLP是一个由中国开发者何晗(hankcs)于 2014 年开发的自然语言处理库,自发布之后,HanLP不断更新迭代,进行了许多新功能和性能的优化,Github上Star数量已超过 3w,其在主流自然语言工具包中非常受欢迎。HanLP具有丰富的功能,可以进行一系列文本分析任务,比如词法分析(分词、词性标注、命名实体识别)、句法分析、文本分类/聚类、信息抽取、语义分析等等。发展至今,HanLP已经衍生出了1.x和2.x两大版本。本文pyhanlp0.1.84。

Cachel Wood的博客 1223

Python的pyhanlp库使用(一)

pyhanlp库使用

ZCS的博客 8516

NA400与昆仑通态MODBUS/TCP通讯调试说明

点击增加设备通道,弹出窗口进行设置,通道类型选择“0区输出继电器”,通道地址为1,通道个数为1,读写方式为读写。点击增加设备通道,弹出窗口进行设置,通道类型选择“4区输出寄存器”,数据类型选择“16位 无符号二进制”,通道地址为21001,通道个数为1,读写方式为读写。5.添加设备通道:双击莫迪康MODBUSTCP子设备,点击添加设备通道,根据Modbus规约地址表进行参数的设置,表格可在NAPro软件帮助中查看,如下图所示。然后可以在设备通道调试数据中观察到Q1的值为1,NW1的值678,表示通讯成功。

weixin_44281509的博客 2491

Python3安装pyhanlp最佳解决方法

Hanlp是一款中文自然语言处理工具。Hanlp支持多种自然语言处理任务,包括分词、词性标注、命名实体识别、依存句法分析、情感分析、文本分类等。高准确率:Hanlp采用了基于神经网络的分词方法,有效提高了分词的准确率和速度。广泛覆盖:Hanlp支持多种自然语言处理任务,包括分词、词性标注、命名实体识别、依存句法分析、情感分析、文本分类等,能够满足大部分的自然语言处理需求。多语种支持:Hanlp支持多种语言的处理,如中文、英文、日文等,可应用于多语言环境下的自然语言处理任务。

weixin_40547993的博客 4291

基于Jetson Nano与YOLOv5s的无人机道路抛洒物实时检测系统【附数据集+代码】

本文详细介绍基于Jetson Nano与YOLOv5s的无人机道路抛洒物实时检测系统,通过硬件选型、数据采集、模型优化等关键步骤,实现高效的道路安全监控。系统结合无人机高空视角和YOLOv5s算法,能精准识别各类抛洒物,实测准确率达98.2%,为交通管理提供智能化解决方案。

weixin_29081163的博客 1456

ArcGIS小白必看:5分钟搞定shp矢量文件分割(附常见错误排查)

本文为ArcGIS新手详细解析了分割shp矢量文件的四种核心方法:裁剪工具、分割工具、按属性选择导出及ArcPy脚本自动化。重点强调了投影匹配等关键步骤,并提供了常见错误排查指南,帮助用户快速掌握矢量数据分割技巧,提升GIS数据处理效率。

h9j8k7l6m5n的博客 800

python 拼音地名对应关系,使用Python的http.server实现一个简易的Web Api对外提供HanLP拼音转换服务...

由于采集省市区镇数据需要对地名进行拼音转换,由于第三方高准确度接口对IP进行了限制,处理大量数据变得异常缓慢。使用了一个折中的办法,省市区 3级(3千+)用高准确度接口(几乎没有拼错的地名),镇级(4万+)用本地HanLP提供的接口(大部分多音字还算是能拼正确)。HanLP是一个优秀的开源自然语言处理工具,提供了颇为准确的拼音转换功能。开始本想使用更为顺手的nodejs来处理,但测试了Github...

weixin_39610229的博客 384

Valgrind 从入门到精通:内存调试和性能分析

Valgrind 提供了强大的 API,允许开发者编写自定义的检查工具。通过扩展 Valgrind,可以针对特定场景实现更精准的检测。

大模型大数据攻城狮的专栏 1218

详细讲解如何安装pyhanlp

详细讲解如何安装pyhanlp

敷衍zgf的博客 7564

第三方 API 调用 OpenClaw 出现 LLM request timed out 的解决方案

本文主要介绍了第三方 API 调用 OpenClaw 出现 LLM request timed out 的解决方案,希望能对使用OpenClaw的同学们有所帮助。 文章目录 1. 问题描述 2. 解决方案

weixin_43178406的博客 8万+

开关电源中的高频振荡噪声及其抑制方法

在开关电源的工作过程中,随着开关管的开关动作,电流和电压波形会出现剧烈的波动,尤其是在开关管切换的瞬间,往往会导致较强的过冲现象。开关电源中的高频振荡噪声是导致电磁兼容问题的主要源头之一,尤其是MOS管的通断和整流二极管的反向恢复过程中,会产生较强的高频振荡噪声。通过合理调节R和C的值,可以大大缓解高频振荡带来的EMC问题,从而有效提升电源的电磁兼容性。整流二极管反向恢复时的振荡会导致高频噪声产生,这些高频噪声源可被传导到电源的输出端,甚至可能通过电源的共地路径扩散到其他电路,影响系统的稳定性和可靠性。

硬核科技 1531

pyhanlp的安装方法

pyhanlp的安装方法

xiangfengl的专栏 1712

Qt Quick/QML入门到精通_专栏demo对应文章目录(目前50个左右demo/长期更新)

自定义图标下拉列表框的效果如下所示:自定义三态按钮的效果如下所示:传送门:53.qt quick-自定义三态按钮、自定义图标下拉列表框_诺谦的博客-优快云博客传送门:59.qt quick-qml调色板(颜色取色器)实现、自定义QQuickStyle样式_诺谦的博客-优快云博客63.qt quick-QML侧边滑动栏(不需要任何图片资源,支持自定义左右方向和大小)_诺谦的博客-优快云博客_qt实现好看侧边栏。...

抵抗时间扭曲,坚持做一件有意义的事 2万+

Python自然语言处理之pyhanlp模块介绍、安装与常见操作案例(附上代码和输出结果)

Python自然语言处理之pyhanlp模块介绍、安装与常见操作案例(附上代码和输出结果)

努力让自己发光,对的人才能迎着光而来 3万+

2023华为od机试真题【恢复数字序列】C++

2023华为od机试真题【恢复数字序列】C++ 对于一个连续正整数组成的序列,可以将其拼接成一个字符串,再将字符串里的部分字符打乱顺序。如序列8 9 10 11 12,拼接成的字符串为89101112,打乱一部分字符后得到90811211,原来的正整数10就被拆成了0和1。现给定一个按如上规则得到的打乱字符的字符串,请将其还原成连续正整数序列,并输出序列中最小的数字. 输入描述

MISAYAONE的博客 5731

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

pyhanlp 分词与词性标注

pyhanlp中的分词器简介 pyhanlp实现的分词器有很多,同时pyhanlp获取hanlp中分词器也有两种方式 第一种是直接从封装好的hanlp类中获取,这种获取方式一共可以获取五种分词器,而现在默认的就是第一种维特比分词器 维特比 (viterbi):效率和效果的最佳平衡 双数组trie树 (dat):极速词典分词,千万字符每秒(可能无法获取词性,此处取决于你的词典) 条件随机场 (cr...

FontTian的博客 8759

深度学习工具包 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")

已解决Python pip正确安装pyhanlp库步骤

已解决Python pip正确安装pyhanlp库步骤

努力让自己发光,对的人才能迎着光而来 1万+

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

pyhanlp、HanLP安装与使用

HanLP安装使用(Windows) 安装Hanlp时候发现网上的一些介绍文章写的有些模糊,这里记录一下Python环境下安装与使用Hanlp。 首先,要明确HanLP是一个Java工具包,由很多模型、算法组成,而在学习自然语言的时候一般都会使用Python吧,因此,实质上是使用Python调用Hanlp。 具体安装步骤: 1.安装Java 和 Visual C++环境 首先是安装JDK,这个在O...

MirrorN的博客 1万+

Python环境中HanLP安装与使用

根据github最新官方文档整理。

qq_31412425的博客 3252

Python 实战 | 文本分析工具之HanLP入门

探索 HanLP —— 中文文本处理的利器

weixin_55633225的博客 3837

NLP之pyhanlp安装及其使用

中文分词≠自然语言处理! 中文分词只是第一步;HanLP从中文分词开始,覆盖词性标注、命名实体识别、句法分析、文本分类等常用任务,提供了丰富的API。

菲宇运维 5687

jieba安装_python如何使用HanLP,LTP,jieba中文分词库

上期文章我们分享了NLP 自然语言处理的基础知识,本期我们分享几个比较流行的中文分词库,且这些中文分词库绝大部分是Java程序编写的,在linux系统上很容易使用,但是在windows环境下,如何使用python来使用这些分词库??HanLPHanLP中文分词包HanLP 是由一系列模型与算法组成的 Java 工具包,目标是普及自然语言处理在生产环境中的应用。HanLP 具备功能完善、性...

weixin_39665992的博客 778

pyhanlp常用功能、实体标注、词性表

标题 命名实体识别 1.实体机构名识别(层叠HMM-Viterbi) 2.中国人名识别(HMM-Viterbi) 3.音译人名识别(层叠隐马模型) 4.日本人名识别(层叠隐马模型) 5.地名识别(HMM-Viterbi) 实体标注分词导录: from pyhanlp import * import os #远程调试用 os.environ[‘JAVA_HOME’] = ‘/usr/local/jdk-11’#远程调试用 from pyhanlp import * print (HanLP.segment

直达开源前线,冲冲冲! 3022

手动安装pyhanlp【遇坑报错全程合集和解说】

之前无论用什么版本的python,使用conda或者pip下载安装pyhanlp老出错。决定手动进行安装。 步骤一: 安装pyhanlp之前看了是得先安装jpype,方法:方法一: 执行 测试是否安装jpype成功: 在python命令行中输入: 能打印出则安装成功。方法二:(如果方法一不行就用这个) 是要寻找对应Python版本的jype的whl。 使用如下命令看匹配的是什么版本 不出意外要出意外,显示1.接着找的解决方法 ①报错信息: 1.报错信息①解决方法 报错信息: 2.报错信息①解决方法: 报错

chanyeolchichi的博客 8275

hanlp2.x使用与语义角色标注任务

hanlp 2.x的文档逻辑不太好看,这里记录一下语义角色标注任务的相关代码与文档中的重要内容 hanlp github地址:https://github.com/hankcs/HanLP hanlp各种任务缩写:https://hanlp.hankcs.com/docs/data_format.html#naming-convention 从文档中可以看到“tok”是分词,“srl”是语义角色标注 hanlp语义角色标注标签含义:https://hanlp.hankcs.com/docs/annotati

呆萌的代Ma 2110

【亲测免费】 PyHanLP 使用教程

PyHanLP 是一个基于 HanLP 的 Python 封装库,旨在提供高效、准确的中文自然语言处理服务。HanLP 是由一系列模型与算法组成的 Java 工具包,而 PyHanLP 则通过 Python 接口使得这些功能可以在 Python 环境中使用。PyHanLP 支持多种自然语言处理任务,包括中文分词、词性标注、命名实体识别、依存句法分析等。 ## 项目快速启动 ### 安装 PyH

gitblog_00030的博客 867
上一篇: 使用 Nuitka 打包 Python 脚本为独立的可执行文件
下一篇: “GIS探案”工具箱升级使用说明
craybb
博客等级 码龄2年 1106粉丝 54原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

craybb

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值