Harbor系列之11:制品签名

容器仓库Harbor安装,给Harbor加入自签名证书 安装Harbor,使用Docker进行上传下载,证书验证 阅读详情

借助Cosign或Notaion对制品进行签名

制品签名和签名验证是关键的安全功能,它们允许你验证制品的完整性。Harbor 通过与 Cosign 或 Notation 的集成来支持内容信任。

项目管理员可以配置项目以强制执行内容信任,要求所有制品在从 Harbor 注册表中拉取之前必须进行签名。

project-sign-settings

1. 使用Cosign对制品进行签名

Harbor v2.5 集成了对 Cosign 的支持,Cosign 是 Sigstore 项目的一部分,提供了 OCI 制品的签名和验证解决方案。

Cosign 对 OCI 制品进行签名,并将生成的签名推送到 Harbor。该签名作为制品的附件存储在 Harbor 中,与签名的制品一起管理。Harbor 管理着签名制品与 Cosign 签名之间的链接,因此你可以对签名的制品应用标签保留规则和不可变规则,这些规则将同时扩展到签名制品和签名上。通过这种方式,你可以使用 Harbor 内置的功能来管理签名制品和 Cosign 签名附件。需要注意的是,Harbor 不支持对 Cosign 签名的漏洞扫描。

使用 Cosign 与 Harbor 集成的一个关键功能是能够使用 Harbor 的复制功能,将签名与其关联的签名制品一起复制。这意味着如果复制规则适用于某个签名制品,Harbor 将以同样的方式将复制规则应用于该签名制品的签名。

  • 在 Harbor 实例之间进行复制时,目标 Harbor 实例将保持签名制品及其关联签名之间的链接。你可以在目标 Harbor 界面中看到这两个制品之间的关系,就像在源注册表中一样。

  • 从 Harbor 复制到另一种目标注册表类型时,目标注册表将不会管理签名制品与其关联签名之间的链接。你将在同一存储库下看到主题清单和签名作为协调制品。

注意:只有“手动”和“定时”复制触发模式适用。目前无法进行基于事件的复制,因为存在先决条件的问题:你无法复制未签名的镜像,但你也无法在没有镜像的情况下复制签名。

1.1 安装cosign

1. 安装 Cosign

你可以通过以下命令安装 Cosign:

  • 如果你使用的是 macOS 或 Linux:
curl -sSL https://github.com/sigstore/cosign/releases/latest/download/cosign-linux-amd64 -o /usr/local/bin/cosign
chmod +x /usr/local/bin/cosign

# 验证安装
[root@e2etest ~]# cosign version
  ______   ______        _______. __    _______ .__   __.
 /      | /  __  \      /       ||  |  /  _____||  \ |  |
|  ,----'|  |  |  |    |   (----`|  | |  |  __  |   \|  |
|  |     |  |  |  |     \   \    |  | |  | |_ | |  . `  |
|  `----.|  `--'  | .----)   |   |  | |  |__| | |  |\   |
 \______| \______/  |_______/    |__|  \______| |__| \__|
cosign: A tool for Container Signing, Verification and Storage in an OCI registry.

GitVersion:    v2.3.0
GitCommit:     deed3631520ddeb6cc7d81ace205a97342c8daab
GitTreeState:  clean
BuildDate:     2024-07-22T17:19:10Z
GoVersion:     go1.22.5
Compiler:      gc
Platform:      linux/amd64
  • 如果你使用的是 Windows:

你可以从 GitHub Releases 页面下载相应的可执行文件并将其添加到 PATH。

2. 生成密钥对

Cosign 使用密钥对进行签名和验证。你可以通过以下命令生成一对密钥:

cosign generate-key-pair

生成的 cosign.key 是私钥,cosign.pub 是公钥。确保安全存储这些密钥,特别是私钥。

1.2 签名、上传和查看 Cosign 签名

1. 对镜像进行签名

使用 cosign sign 命令对镜像进行签名,并将 Cosign 签名上传到你的 Harbor 实例中。

在以下示例中,将 /<image/path>: 替换为你的 Harbor 实例和镜像的路径。

cosign sign --key cosign.key <harbor-instance>/<image/path>:<image-tag>

在输入你的 cosign 私钥密码后,cosign 会对镜像进行签名,并将生成的签名上传到你的 Harbor 实例中。你可以在 Harbor 界面中查看签名制品的所有签名。

示例如下:

[root@e2etest cosign]# cosign sign --key cosign.key 10.210.10.210/db/mysql@sha256:4b6c4935195233bc10b617df3cc725a9ddd5a7f10351a7bf573bea0b5ded7649
Enter password for private key:

        The sigstore service, hosted by sigstore a Series of LF Projects, LLC, is provided pursuant to the Hosted Project Tools Terms of Use, available at https://lfprojects.org/policies/hosted-project-tools-terms-of-use/.
        Note that if your submission includes personal data associated with this signed artifact, it will be part of an immutable record.
        This may include the email address associated with the account with which you authenticate your contractual Agreement.
        This information will be used for signing this artifact and will be stored in public transparency logs and cannot be removed later, and is subject to the Immutable Record notice at https://lfprojects.org/policies/hosted-project-tools-immutable-records/.

By typing 'y', you attest that (1) you are not submitting the personal data of any other person; and (2) you understand and agree to the statement and the Agreement terms at the URLs listed above.
Are you sure you would like to continue? [y/N] y
tlog entry created with index: 118772948
Pushing signature to: 10.210.10.210/db/mysql
2. 验证签名

在拉取或使用镜像之前,可以验证签名以确保镜像的完整性和来源:

cosign verify --key cosign.pub <harbor-instance>/<image/path>:<image-tag>

如果签名有效,Cosign 将输出验证结果。

3. 在harbor上查看制品签名

cosign对镜像进行签名后,签名同时被推送到harbor仓库。此时harbor-项目-镜像仓库中,artifacts的状态会变成已签名:

artifact-signed
签名作为制品的附件存在。

所有与签名制品关联的签名将在签名制品被删除时一起删除。

需要注意的是,Harbor 的垃圾回收不会单独删除任何签名。在 Harbor 中,Cosign 签名被视为与其他 OCI 制品相同的对待方式,但从垃圾回收器的角度来看,它无法看到附件制品,比如 Cosign 签名。例如,如果你配置了对未打标签的制品进行垃圾回收,Harbor 的垃圾回收器不会删除任何没有标签的签名。如果签名制品没有标签,并且符合配置的垃圾回收规则,它和任何关联的签名将会被删除。

Harbor 不支持使用 cosign clean 来删除签名,因为 Harbor 选择不实现 cosign clean 所使用的标签删除功能。有关实现要求的更多信息,请参阅 OCI 分发规范。

2. 使用Notation对制品进行签名(分发规范 v1.1 模式)

Notation 是一个基于标准的工具和库,用于签名和验证 OCI 制品。它生成签名并将其与 OCI 制品关联,以确保供应链的完整性。

2.1 安装Notation命令行

安装最新版本的notation命令行,参考官方指导:https://notaryproject.dev/docs/user-guides/installation/cli/

二进制下载链接:https://github.com/notaryproject/notation/releases,下面以x86平台下linux系统安装为例:

# 设置notation版本
export NOTATION_VERSION=1.1.1

# 下载二进制文件
https://github.com/notaryproject/notation/releases/download/v1.1.1/notation_1.1.1_linux_amd64.tar.gz
curl -LO https://github.com/notaryproject/notation/releases/download/v$NOTATION_VERSION/notation_$NOTATION_VERSION\_linux_amd64.tar.gz
curl -LO https://github.com/notaryproject/notation/releases/download/v$NOTATION_VERSION/notation_$NOTATION_VERSION\_checksums.txt
shasum --check notation_$NOTATION_VERSION\_checksums.txt

# 解压文件
tar xvzf <ARCHIVE_FILE> -C /usr/bin/ notation

# 验证安装
[root@e2etest ~]# notation version
Notation - a tool to sign and verify artifacts.

Version:     1.1.1
Go version:  go1.22.4
Git commit:  3dafd534fe069f2c0ce6127eb33d2e3e476723c3

2.2 生成测试密钥和自签名证书

使用 notation cert generate-test 命令生成用于签名制品的测试 RSA 密钥,以及用于验证制品的自签名 X.509 测试证书。请注意,自签名证书应仅用于测试或开发目的。在生产环境中,你应使用 CA 签发的证书。

notation cert generate-test --default "wabbit-networks.io"

key和证书生成到如下路径:

[root@e2etest notation]# notation cert generate-test --default "test.com"
generating RSA Key with 2048 bits
generated certificate expiring on 2024-08-06T17:02:32Z
wrote key: /root/.config/notation/localkeys/test.com.key
wrote certificate: /root/.config/notation/localkeys/test.com.crt
Successfully added test.com.crt to named store test.com of type ca
test.com: added to the key list
test.com: mark as default signing key

2.3 Harbor 注册表认证

要与 Harbor 注册表进行认证,请设置以下环境变量:

export NOTATION_USERNAME="YOUR_REGISTRY_USERNAME"
export NOTATION_PASSWORD="YOUR_REGISTRY_PASSWORD"
export NOTATION_USERNAME="admin"
export NOTATION_PASSWORD="Harbor12345"

2.4 签名 Harbor 中的现有镜像

假设你已配置 HTTPS 访问并将镜像推送到 Harbor,你可以使用 notation sign 命令对镜像进行签名。

notation sign <harbor-domain>/<image-reference>

默认情况下notaion只支持https类型的harbor仓库制品签名,如果是http类型的harbor,需要添加--insecure-registry

[root@e2etest notation]# notation sign 10.210.10.210/language/python:alpine3.20 --insecure-registry
Warning: Always sign the artifact using digest(@sha256:...) rather than a tag(:alpine3.20) because tags are mutable and a tag reference can point to a different artifact than the one signed.
Successfully signed 10.210.10.210/language/python@sha256:f3f9127f09f687456f484145165fe745834ba222e1ac43cca14fcfda0e88c174

一旦镜像成功签名,签名状态将更新为绿色勾选标记,并且相应的签名已被推送到注册表。

2.5 创建信任策略以验证镜像

要验证容器镜像,请配置信任策略以指定签署制品的受信任身份和使用的签名验证级别。有关详细信息,请参阅信任策略规范。

创建一个包含以下信任策略的 JSON 文件,例如:

cat <<EOF > ./trustpolicy.json
{
    "version": "1.0",
    "trustPolicies": [
        {
            "name": "wabbit-networks-images",
            "registryScopes": [ "*" ],
            "signatureVerification": {
                "level" : "strict"
            },
            "trustStores": [ "ca:test.com" ],
            "trustedIdentities": [
                "*"
            ]
        }
    ]
}
EOF

使用notation policy import导入上面JSON文件创建的信任策略配置,例如:

notation policy import ./trustpolicy.json

2.6 验证镜像

使用 notation verify 验证与容器镜像关联的签名。

notation verify <harbor-domain>/<image-reference>

你还可以检查签名摘要,并检查签名及其证书信息,以确保镜像是由受信任的身份生成的。

notation inspect $IMAGE

有关更多信息,请参阅 Notation 文档。
镜像

使用 notation verify 验证与容器镜像关联的签名。

notation verify <harbor-domain>/<image-reference>

你还可以检查签名摘要,并检查签名及其证书信息,以确保镜像是由受信任的身份生成的。

notation inspect $IMAGE

有关更多信息,请参阅 Notation 文档。

使用 Cosign 来对极狐GitLab 镜像进行签名 阅读详情

相关推荐

【云原生安全篇】Cosign助力Harbor验证镜像实践

❤️ 摘要: 随着云原生技术的普及,容器镜像的安全性越来越受到重视。镜像验证是保护软件供应链的重要环节,它确保从镜像仓库拉取的镜像未被篡改,并且来源可信。Harbor 作为广泛使用的容器镜像仓库,通过与Cosign 集成,使镜像的签名与验证变得更加便捷和安全。本文将详细介绍如何使用 Cosign 对 Harbor 中的镜像进行签名和验证,确保容器镜像在整个 DevOps 流水线中的安全性。

StevenZeng学堂 4984

cosign使用实践(一)本地验证二进制与镜像

cosign使用实践,github镜像推送

zishen的专栏 3107

Harbor私有仓库部署与配置-https

Harbor 是一个开源的云原生镜像仓库,用于存储和分发容器镜像的企业级Registry服务器,通过添加一些企业必需的功能特性,例如安全、标识和管理等,扩展了开源 Docker Distribution。作为一个企业级私有 Registry 服务器,Harbor 提供了更好的性能和安全。本文用https+自签名证书部署。

lldhsds的专栏 2212

探索容器镜像安全管理之道

最近 Rancher v2.7.4 发布了,作为一个安全更新版本,也让大家对软件供应链安全多了一份思考。本文将围绕其中比较流行的容器镜像安全管理进行探讨和实践。

Rancher 1204

Harbor部署

Harbor搭建详解

happy_ye16的博客 1841

云原生周报 | IstioCon 2022 开始;Harbor V2.5引入 Cosign

业界要闻 1.IstioCon 2022 今晚开始 摘要:将于北京时间今天(25日)晚上11点正式开始,中文场演讲将于 26 日上午 9 点正式开始,会议详细日程请见:https://events.istio.io/istiocon-2022/program/ 2.Harbor v2.5远程复制:制品的签名如影随形 摘要:在 Harbor 制品(Artifact)仓库中,制品的签名和签名验证是关键的安全功能之一,可帮助用户检查制品的完整性。Harbor 2.5通过与另外两个开源项目...

百度云原生计算的博客 2133

Harbor系列之3:使用docker环境安装Harbor仓库-https部署

Harbor 是一个开源的云原生镜像仓库,用于存储和分发容器镜像的企业级Registry服务器,通过添加一些企业必需的功能特性,例如安全、标识和管理等,扩展了开源 Docker Distribution。作为一个企业级私有 Registry 服务器,Harbor 提供了更好的性能和安全。本文记录使用docker环境安装部署Harbor仓库,使用https协议,采用自签名证书。本文时间部署Harbor v2.11.0版本,采用离线部署安装包。

lldhsds的专栏 3024

云安全容器签名方案cosign使用

可以看到.sig签名已经上传到仓库,其名字为镜像sha256.sig,既签名的方式为,对其摘要做加密(无需本地镜像参与,直接根据tag从目标仓库拉取digest sha256做签名,之后生成一个OCI镜像推送到仓库),然后拉取镜像时,对其名称签名做解密,如果摘要一致,则说明没有被篡改。5.当我们使用签名的镜像部署时,提示,我们使用kubectl run 直接启动一个pod,pod和deployment区别在于,run是pod,deployment可以有pod,replicaset,jobs等等。

SHELLCODE_8BIT的博客 2463

CNCF 宣布首个中国原创项目 Harbor毕业

加利福尼亚州旧金山– 2020年6月23日长期致力于云原生软件生态构建的云原生计算基金会( CNCF )今天宣布,Harbor 成为第 11 个毕业的项目。从孵化( in...

Go中国 398

python 成语接龙-连接数据库

from xpinyin import Pinyin import pymysql while 1: conn = pymysql.connect( host='localhost', #本地连接 user='root', #数据库账户名 password='password', #数据库密码 db='dic',

Hero2902的博客 602

2.6 SST的核心性能指标体系

本文构建了固态变压器(SST)的核心性能指标体系,涵盖电气性能、可靠性、经济性和环境适配性四大类指标。电气性能指标包括运行效率(≥97%)、功率密度(≥900kVA/m³)、谐波畸变率(≤3%)等关键参数;可靠性指标设定MTBF≥43800h、年均故障率≤1.2次/年等标准;经济性指标对比分析了初始购置成本(45-55万元)和全生命周期成本(48-55万元);环境适配性指标则明确了温度、海拔等工况要求。该体系采用量化公式和国标限值,为SST的性能测试、选型和优化提供了统一标准。

技术工作者 612

Harbor介绍、整体架构和安装

Harbor 是由 VMware 开源的一款云原生制品仓库,Harbor 的核心功能是存储和管理 Artifact。Harbor 允许用户用命令行工具对容器镜像及其他 Artifact 进行推送和拉取,并提供了图形管理界面帮助用户查看和管理这些 Artifact。在 Harbor 2.0 版本中,除容器镜像外,Harbor 对符合 OCI 规范的 Helm Chart、CNAB、OPA Bundle 等都提供了更多的支持。图1-1 Harbor架构图如上图所示是 Harbor 2.0 的架构图,从上到下可分

Raymond的博客 1809

FPGA进位链(Carry Chain)实战:从Xilinx CARRY8原语到性能优化全解析

本文深入解析了FPGA进位链(Carry Chain)的原理与应用,重点剖析了Xilinx CARRY8原语的端口功能与内部机制。通过实测数据揭示了进位链的真实延迟特性与温度影响,并详细阐述了如何利用DI和S信号进行动态路径优化、实现减法运算与条件进位选择,从而有效提升设计性能。最后,文章探讨了系统级的流水线拆分、布局约束等实战优化策略与常见陷阱。

weixin_29313817的博客 461

Harbor项目高手问答及赠书活动

题图摄于故宫注:微信公众号不按照时间排序,请关注“亨利笔记”,并加星标置顶,以免错过更新。发布一则问答活动赠书消息:云原生技术的兴起进一步助力企业实现数字化转型,赋能企业IT战略升级。在...

亨利笔记 270

手把手教你复现IEEE 2025高光谱图像盲超分算法DBSR(附开源代码与避坑指南)

本文详细介绍了如何从零复现IEEE 2025高光谱图像盲超分算法DBSR,包括环境配置、数据预处理、核心模块解析、训练策略及常见问题解决方案。特别针对开源代码中的关键步骤和潜在问题提供了实用指南,帮助研究者和开发者高效实现Deep blind super-resolution技术,适用于遥感、医疗等领域的图像增强应用。

weixin_42524708的博客 417

Agentic AI应用架构师如何提升AI应用的灵活性

可扩展性(Scalability):快速添加新功能或扩展任务范围(如Agent从“客服”扩展到“供应链管理”);可修改性(Modifiability):调整Agent的决策逻辑或动作策略,无需重构整个系统;鲁棒性(Robustness):在环境异常或数据噪声下保持性能稳定;自适应(Self-Adaptation):自主学习新场景,无需人工干预。状态空间(S):Agent能感知的所有内部/外部状态(如用户需求、环境数据);动作空间(A):Agent能执行的所有动作(如调用工具、发送消息);

项目管理的博客 612

k8s 1.28.2 集群部署 harbor v2.11.1 接入 MinIO 对象存储

Harbor 官网Harbor 是一个开源的制品仓库相比较 docker registry,它可以通过策略和基于角色的访问控制来保护镜像Harbor 是 CNCF 毕业项目,提供合规性、性能和互操作性,帮助您跨 Kubernetes 和 Docker 等云原生计算平台一致、安全地管理镜像。

以梦为马|越骑越傻 2139

SAP 物料的与压缩库存数据不一致

总结:发生这个问题的原因多数会发生在测试系统在拷贝正式系统的时候会发生这样的情况,系统在拷贝的时候,业务数据还在发生,就会导致数据拷贝的时候丢失数据。经过查询发现是由于物料分类账中的物料的库存数量和 ACDOCA_M_EXTRACT表中的数量对不上,导致系统抛出报错的信息。由于是测试系统,直接更改表的数据,把ACDOCA_M_EXTRACT表中的库存数据和金额与物料分类账中的数据保持一致。在测试系统中进行501和561增加库存的时候,系统提示物料的预压缩库存数据不一致的报错。

我小时候很黑的博客 3325

wm harbor 默认密码_Harbor配置https

之前安装的harbor都是基于http,需要修改docker的/etc/docker/daemon.json文件,新增insecure-registries配置,这样又需要重启下docker服务了。为了减少对正在运行的容器服务影响,我们可以配置harbor支持https来解决。以下内容大部分来自harbor的官方文档的参考。Harbor https证书可以使用由受信任的第三方CA签名的证书,也可以...

weixin_39777497的博客 1827

视觉媒体通信作业记录(六)端到端的视频传输系统

将采集、编码、传输、显示各模块连接起来,形成一个端到端的视频通信系统,开发一个特色模块,将其加入系统;

weixin_45774698的博客 1968

S32K1XX Autosar开发实战|全网独家复现EB MCAL Port/Dio配置、详解引脚分层原理、实现经典跑马灯助力车载IO电控落地

在NXP S32K1XX系列车规MCU的AUTOSAR标准开发体系中,MCAL(微控制器抽象层)是软硬件解耦的核心载体,而Port端口模块与Dio数字IO模块是MCAL最基础、最核心的入门模块,也是车载指示灯、按键检测、继电器驱动、外设硬件启停控制的底层支撑。区别于传统裸机直接操作寄存器的开发方式,AUTOSAR架构采用分层隔离设计,Port负责硬件静态初始化、Dio负责动态电平操控,严格遵循车规级开发规范,杜绝硬件资源冲突、引脚配置混乱等问题。

getusushu的博客 48

Harbor项目高手问答及赠书活动火热进行中

题图摄于故宫注:微信公众号不按照时间排序,请关注“亨利笔记”,并加星标置顶,以免错过更新。发布一则问答活动赠书消息:云原生技术的兴起进一步助力企业实现数字化转型,赋能企业IT战略升级。在...

亨利笔记 206

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

使用 arm 架构实例搭建 Harbor

使用 arm 架构实例搭建 Harbor

engchina的专栏 3480

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

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

3月18日晚直播及赠书:Harbor助你玩转云原生 |GoCN 开源说第七期

Harbor 开源项目维护者邹佳将于今晚( 3月18日)8点,在 GoCN 开源说第七期上直播:Harbor助你玩转云原生 ,欢迎用户和开发者参与直播和互动。感谢 GoCN 社区的邀请。写...

亨利笔记 330

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

Harbor镜像仓库安装配置及使用

是一个开源的企业级Docker 镜像仓库,提供了许多功能,包括用户管理、访问控制、镜像复制和安全扫描。

zxz547388910的博客 4859
上一篇: Harbor系列之10:复制管理
下一篇: 镜像仓库 Registry 介绍及实践-http
KongTY312
博客等级 码龄12年 2143粉丝 189原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

打赏作者

KongTY312

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

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

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

打赏作者

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

抵扣说明:

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

余额充值