Go语言的并发编程

Go 学习笔记 · 进阶篇 · 第二天:并发编程深度实践 Go 的并发是轻量高效的,Goroutine 比线程香。Channel 是 goroutine 之间的传声筒。WaitGroup、Mutex、Context 是并发控制的三剑客。并发编程容易埋雷,写完一定记得加-race运行!今日咒语:“人生苦短,让 goroutine 去忙,主程序才轻松。 阅读详情

并发指在同一时间内可以执行多个任务。并发编程含义比较广泛,包含多线程编程、多进程编程及分布式程序等。

Go语言里的并发指的是能让某个函数独立于其他函数运行的能力。当一个函数创建为协程(goroutine)时,Go语言会将其视为一个独立的工作单元,这个单元会被调度到可用的逻辑处理器上执行。

并发编程基础

1、并发与并行(理论没看懂)

理解操作系统的线程(thread)和进程(process),有助于理解Go语言运行时调度器如何得用操作系统来并发运行goroutine。

并行是让不同的代码片段同时在不同的物理处理器上执行。并行的关键是同时做很多事情,而并发是指同时管理很多事情,这些事情可能只做了一半就被暂停去做别的事情了。

使用较少的资源做更多的事情,是指导Go语言设计的哲学。

2、指定使用核心数

Go语言默认会调用CPU核心数,这些功能都是自动调整的,但是也提供了相应的标准库来指定核心数。使用flags包可以调整程序运行时调用的CPU核心数。

代码如下:

package main

import (
	"fmt"
	"time"
)

func longWait() {
	fmt.Println("开始longWait()")
	time.Sleep(5 * 1e9)
	fmt.Println("结束longWait()")
}

func shortWait() {
	fmt.Println("开始shortWait()")
	time.Sleep(2 * 1e9)
	fmt.Println("结束shortWait()")
}

func main() {
	fmt.Println("这里是main()开始的地方")
	go longWait()
	go shortWait()
	fmt.Println("挂起main()")
	time.Sleep(10 * 1e9)
	fmt.Println("这里是main()结束的地方")
}

main()、longWait()和shortWait()三个函数作为独立的处理单元按顺序启动,然后开始并行运行,每一个函数都在运行的开始和结束阶段输出了消息。

运行结果如下:

这里是main()开始的地方
挂起main()
开始longWait()
开始shortWait()
结束shortWait()
结束longWait()
这里是main()结束的地方

如果移除go语言关键字同,重新运行程序:

这里是main()开始的地方
开始longWait()
结束longWait()
开始shortWait()
结束shortWait()
挂起main()
这里是main()结束的地方

协程(goroutine)

操作系统自己掌管的进程(process)、进程内的线程(thread)以及进程内的协程(coroutine,也叫轻量级线程)。

协程的最大优势在于其“轻量级”,可以轻松创建上百万个协程而不会导致系统资源衰竭,而线程和进程通常最多也不能超过1万个。

Go语言在语言级别支持轻量级线程,叫goroutine。

1、协程基础

goroutine是Go语言并行设计的核心。

goroutine是通过Go程序的runtime管理的一个线程管理器。goroutine通过go关键字实现了,其实就是一个普通的函数。

代码如下:

package main

import (
	"fmt"
	"runtime"
)

func say(s string) {
	for i := 0; i < 5; i++ {
		runtime.Gosched()
		fmt.Println(s)
	}
}

func main() {
	go say("world")
	say("hello")
}

运行结果如下:与书本不一样。

hello
hello
hello
hello
hello

书本是:

hello
world
hello
world
hello
world
hello
world
hello

并发处理:Go例程,代码如下:

package main

import (
	"fmt"
)

func routine1(index int) {
	for i := 0; i < 10; i++ {
		fmt.Println(index, " : ", i)
	}
}
func main() {
	go routine1(1)
	go routine1(2)
	for i := 0; i < 10; i++ {
		fmt.Println("0: ", i)
	}
}

运行结果如下:(感觉不对,不明白什么意思)

0:  0
0:  1
0:  2
0:  3
0:  4
0:  5
0:  6
0:  7
0:  8
0:  9

2、协程间通信

通常有两种最常见的并发通信模型:共享数据和消息。

代码如下:

package main

import (
	"fmt"
	"runtime"
	"sync"
)

var counter int = 0

func Count(lock *sync.Mutex) {
	lock.Lock()
	counter++
	fmt.Println(z)
	lock.Unlock()
}

func main() {
	lock := &sync.Mutex{}
	for i := 0; i < 10; i++ {
		go Count(lock)
	}
	for {
		lock.Lock()
		c := counter
		lock.Unlock()
		runtime.Gosched()
		if c >= 10 {
			break
		}
	}
}

运行结果如下:

# command-line-arguments
./main.go:14:14: undefined: z

不要通过共享内存来通信,而应该通过通信来共享内存。

package main

import "fmt"

func Add(x, y int) {
	z := x + y
	fmt.Println(z)
}

func main() {
	for i := 0; i < 10; i++ {
		go Add(i, i)
	}
}

无运行结果。

通道(Channel)

代码如下:

package main

import (
	"fmt"
)

func Count(ch chan int) {
	ch <- 1
	fmt.Println("Counting")
}

func main() {
	chs := make([]chan int, 10)
	for i := 0; i < 10; i++ {
		chs[i] = make(chan int)
		go Count(chs[i])
	}
	for _, ch := range chs {
		<-ch
	}
}

1、基本语法

一般channel的声明形式为:

var chanName chan ElementType

在channel的用法中,最常见的包括写入和读出。

将一个数据写入(发送)到channel的语法很直观:

ch <- value

从channel中读取数据的语法是:

value:=<-ch

2、select

Go语言直接在语言级别支持select关键字,用于处理异步I/O问题。

3、缓冲机制

4、超时和计时器

5、channel的传递

6、单向channel

7、关闭channel

使用go语言内置的close()函数如下:

close(ch)

并发进阶

1、多核并行化

2、协程同步

只有在当需要告诉接受者不会再提供新的值的时候,才需要关闭通道。

只有发送者需要关闭通道,接收都永远不会需要。

代码如下:

package main

import (
	"fmt"
	"time"
)

func sendData(ch chan string) {
	ch <- "纽约"
	ch <- "华盛顿"
	ch <- "伦敦"
	ch <- "北京"
	ch <- "东京"
}

func getData(ch chan string) {
	var input string
	for {
		input = <-ch
		fmt.Printf("%s ", input)
	}
}

func main() {
	ch := make(chan string)
	go sendData(ch)
	go getData(ch)
	time.Sleep(1e9)
}

运行结果如下:

纽约 华盛顿 伦敦 北京 东京 

代码如下:

package main

import (
	"fmt"
)

func sendData(ch chan string) {
	ch <- "纽约"
	ch <- "华盛顿"
	ch <- "伦敦"
	ch <- "北京"
	ch <- "东京"
	close(ch)
}

func getData(ch chan string) {
	for {
		input, open := <-ch
		if !open {
			break
		}
		fmt.Printf("%s ", input)
	}
}

func main() {
	ch := make(chan string)
	go sendData(ch)
	getData(ch)
}

运行结果如下:

纽约 华盛顿 伦敦 北京 东京 

为一个普通函数创建goroutine的写法如下:

go 函数名(参数列表)

函数名:要调用的函数名。

参数列表:调用函数需要传入的参数。

使用go关键字创建goroutine时,被调用函数的返回值会被忽略。

代码如下:

package main

import (
	"fmt"
	"time"
)

func running() {
	var times int
	//构建一个无限循环
	for {
		times++
		fmt.Println("tick", times)
		//延时1秒
		time.Sleep(time.Second)
	}
}

func main() {
	//并发执行程序
	go running()
	//接受命令行输入,不做任何事情
	var input string
	fmt.Scanln(&input)
}

使用匿名函数创建goroutine的格式

go func (参数列表) {

        函数体

} (调用参数列表)

参数列表:函数体内的参数变量列表

函数体:匿名函数的代码。

调用参数列表:启动goroutine时,需要向匿名函数传递的调用函数。

代码如下:

package main

import (
	"fmt"
	"time"
)

func main() {

	go func() {
		var times int
		for {
			times++
			fmt.Println("tick", times)
			time.Sleep(time.Second)
		}
	}()
	var input string
	fmt.Scanln(&input)
}

调整并发的运行恒通(GOMAXPROCS)

格式如下:

runtime.GOMAXPROCS(逻辑CPU数量)

这里的逻辑CPU数量可以有如下几种数值:

<1:不修改任何数值。

=1:单核心执行。

>1:多核并发执行。

一般情况下,可以使用funtime.NumCPU()查询CPU数量 ,并使用runtime.GOMAXPROCS()函数进行设置,例如:

runtime.GOMAXPROCS(runtime.NumCPU())

理解并发和并行

并发(concurrency):把任务在不同的时间点交给处理器进行处理。在同一个时间点,任务并不会同时运行。

并行(parallelism):把每一个任务分配给每一个处理器独立完成。在同一个时间点,任务一定是同时运行。

代码如下:

package main

import (
	"fmt"
)

func sum(values []int, resultChan chan int) {
	sum := 0
	for _, value := range values {
		sum += value
	}
	resultChan <- sum		//将计算结果发送到channel中
}

func main() {
	values := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
	resultChan := make(chan int, 2)
	go sum(values[:len(values)/2], resultChan)
	go sum(values[len(values)/2:], resultChan)
	sum1, sum2 := <-resultChan, <-resultChan		//接收结果
	fmt.Println("Result:", sum1, sum2, sum1+sum2)
}

运行结果如下:

Result: 40 15 55

去程:

代码如下:

package main

import (
	"fmt"
	"time"
)

func sheep(i int) {
	for ; ; i += 2 {
		fmt.Println(i, "只羊")
	}
}

func main() {
	go sheep(1)
	go sheep(2)
	time.Sleep(time.Millisecond)
}

运行结果如下:

2 只羊
4 只羊
6 只羊
8 只羊
10 只羊
12 只羊
14 只羊
16 只羊
18 只羊
20 只羊
22 只羊
24 只羊
26 只羊
28 只羊
30 只羊
32 只羊
34 只羊
36 只羊
38 只羊
40 只羊
42 只羊
44 只羊
46 只羊
48 只羊
50 只羊
52 只羊
54 只羊
56 只羊
58 只羊
60 只羊
62 只羊
64 只羊
66 只羊
68 只羊
70 只羊
72 只羊
74 只羊
76 只羊
78 只羊
80 只羊
82 只羊
84 只羊
86 只羊
88 只羊
90 只羊
92 只羊
94 只羊
96 只羊
98 只羊
100 只羊
102 只羊
104 只羊
106 只羊
108 只羊
110 只羊

回程:

代码如下:

package main

import (
	"fmt"
	"time"
)

var wormhole chan time.Time

func deepspace() {
	wormhole <- time.Now()
}

func main() {
	wormhole = make(chan time.Time)
	go deepspace()
	fmt.Println(<-wormhole)
}

运行结果如下:

2022-04-06 15:47:02.3888929 +0800 CST m=+0.002617601

遍历与关闭:

代码如下:

package main

import (
	"fmt"
	"time"
)

type hole chan time.Time

func deepspace(w hole, h int) {
	defer close(w)
	for ; h > 0; h-- {
		w <- time.Now()
		time.Sleep(time.Second)
	}
}

func consumer(w hole) {
	for msg := range w {
		fmt.Println("consumer", msg)
	}
}

func main() {
	w := make(hole)
	go deepspace(w, 8)
	go consumer(w)
	for {
		msg, ok := <-w
		if !ok {
			break
		}
		fmt.Println("main", msg)
	}
	fmt.Println("Done")
}

运行结果如下:

main 2022-04-09 14:52:07.041789 +0800 CST m=+0.002800701
consumer 2022-04-09 14:52:08.0456268 +0800 CST m=+1.006638501
main 2022-04-09 14:52:09.0578227 +0800 CST m=+2.018834401
consumer 2022-04-09 14:52:10.0705782 +0800 CST m=+3.031589901
main 2022-04-09 14:52:11.0742367 +0800 CST m=+4.035248401
consumer 2022-04-09 14:52:12.0782694 +0800 CST m=+5.039281101
main 2022-04-09 14:52:13.0930031 +0800 CST m=+6.054014801
consumer 2022-04-09 14:52:14.0936872 +0800 CST m=+7.054698901
Done

MapReduce:

映射化简:每个去程对应一个Map并发执行,结果写入缓冲程道,最后再用一个Reduce函数综合这个程道得到的每一个值。

代码如下:

package main

import (
	"fmt"
	"math/rand"
)

type hole chan int

func deepspace(w hole) {
	w <- rand.Int()
}

func main() {
	n := 8
	w := make(hole, n)
	//Map
	for i := 0; i < n; i++ {
		go deepspace(w)
	}
	//Reduce
	t := 0
	for i := 0; i < n; i++ {
		t += <-w
	}
	fmt.Println("Total:", t)
}

运行结果 如下:

Total: -174686420686987236

两个goroutine进行并行的累加计算:代码如下:

package main

import (
	"fmt"
)

func sum(values []int, resultChan chan int) {
	sum := 0
	for _, value := range values {
		sum += value
	}
	resultChan <- sum
}

func main() {
	values := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
	resultChan := make(chan int, 2)
	go sum(values[:len(values)/2], resultChan)
	go sum(values[len(values)/2:], resultChan)
	sum1, sum2 := <-resultChan, <-resultChan
	fmt.Println("Result:", sum1, sum2, sum1+sum2)
}

运行结果如下:

Result: 40 15 55

select语句:

代码如下:

package main

import (
	"fmt"
	"math/rand"
	"time"
)

type hole chan int

func deepspace(w hole, h int) {
	defer close(w)
	d := time.Duration(rand.Intn(h)) * time.Second
	for ; h > 0; h-- {
		w <- rand.Int()
		time.Sleep(d)
	}
}

func main() {
	n := 8
	w := make(hole)
	t := 0
	maxTime := time.Second
	go deepspace(w, n)
Out:
	for i := 0; i < n; i++ {
		select {
		case n := <-w:
			t += n
		case <-time.After(maxTime):
			fmt.Println("Time out")
			break Out
		}
	}
	fmt.Println("Total:", t)
}

运行结果如下:

Time out
Total: 8674665223082153551

程道值:

代码如下:

package main

import (
	"fmt"
)

type Read struct {
	key   string
	reply chan<- string
}

type Write struct {
	key string
	val string
}

var hole = make(chan interface{})

func deepspace() {
	m := map[string]string{}
	for {
		switch r := (<-hole).(type) {
		case Read:
			r.reply <- m[r.key] + " from Mars."
		case Write:
			m[r.key] = r.val
		}
	}
}

func main() {
	go deepspace()
	hole <- Write{"Name", "Martin"}
	home := make(chan string)
	hole <- Read{"Name", home}
	fmt.Println(<-home)
}

运行结果如下:

Martin from Mars.

Go语言学习笔记—golang并发编程之channel 视频来源于B站Go语言基础进阶视频av56860636 文章为自己整理的学习笔记,侵权即删,谢谢支持! 阅读详情

相关推荐

从内参矩阵到归一化平面:揭秘相机成像的标准化核心

本文深入解析了相机成像中的核心概念——归一化平面。通过拆解内参矩阵(包含焦距、主点等参数)的作用,详细阐述了如何将像素坐标转换为与具体相机硬件无关的归一化坐标。这一标准化过程是计算机视觉算法(如多相机系统对齐、视觉SLAM)实现跨设备通用性的关键,能有效提升算法的鲁棒性和泛化能力。

opencv7vision的博客 449

Go 并发编程

关于 Go 语言之高性能并发编程的基础知识!

qq_46457076的博客 1580

先楫HPM6E00EVK EtherCAT从站配置与CIA402 8轴运动控制实战解析

本文详细解析了先楫HPM6E00EVK开发板的EtherCAT从站配置与CIA402 8轴运动控制实战。从环境准备、XML文件配置、代码移植到TwinCAT工程设置,提供了完整的移植指南,帮助开发者实现高效的多轴同步运动控制。

o5p6q的博客 415

Go语言并发编程

go语言并发编程、加锁、并发。

weixin_46042817的博客 1379

Matlab GUIDE -- 串口操作

1、首先新建-->应用程序-->GUIDE。 2、绘制一个简单的UI。 3、然后右击“打开串口”图标-->查看回调-->callback,即可打开此图标的回调函数,此回调函数是press button时执行(可按需要选择其他回调)。 4、在回调函数中添加打开串口的代码。 delete(instrfindall); %删除所有串口 s3 = serial('CO

Asgard-X 2837

病理图像处理个人手札(三)WSI & MIL

1.什么是WSI? WSI全称是Whole Slide Image,也就是全视野数字切片,主要应用在病理学细胞图像领域。WSI 是利用数字扫描仪对传统的病理切片进行扫描,采集具有高分辨率的数字图像,再通过计算机将得到的碎片化图像进行无缝拼接整合,制作可视化数字图像的一项技术。与传统载玻片相比,很好地解决了传统的玻璃切片易损坏、易褪色、易丢片、检索困难的问题。 一言以蔽之,WSI是对传统载玻片进行数字化。 由于是全视野,因此它将包含多尺度的切片在一个文件上面。因此WSI将使用到金字塔模型满足其支持不同分辨率的

baiweizeng的博客 1万+

GO并发编程

无缓冲channel:本质是一种同步通道,他要求读写操作紧密进行。所以,在单channel下,如果在无缓冲channel中进行读写,此时就会在第一次操作处阻塞,发生死锁。

2303_79380171的博客 1638

无人车路径规划方法汇总

无人车路径规划方法汇总

weixin_44380244的博客 2558

Go语言并发详解

文章目录一、Go语言并发简述(并发的优势)进程/线程并发/并行协程/线程Goroutine 介绍channel二、Go语言goroutine(轻量级线程)使用普通函数创建 goroutine1) 格式2) 例子使用匿名函数创建goroutine1) 使用匿名函数创建goroutine的格式2) 使用匿名函数创建goroutine的例子提示三、Go语言并发通信四、Go语言竞争状态简述Goroutine 7 (finished) created at: main.main() D:/code/src/m

qq_41854911的博客 1万+

YOLOV12进阶:MSDA多尺度空洞注意力机制解析与实战,突破检测尺度瓶颈

在目标检测中,“尺度差异”是个老大难问题——大目标占据画面大半,小目标可能只有几个像素,普通模型很难同时精准检测。而MSDA(Multi-Scale Dilated Attention,多尺度空洞注意力)就像给模型配备了“变焦眼镜”,能同时关注不同尺度的目标,让YOLOV12在大、中、小目标检测上都能表现出色。这篇教程会带你从原理到实操,掌握这个强大的注意力机制,让你的检测模型真正“通吃”各种尺度的目标。MSDA的“多尺度空洞注意力”设计,是目标检测突破尺度瓶颈的关键一步。

know_F0727的博客 263

S7-1200 PLC PID功能 | 调节PID参数

S7-1200 PLC PID功能 | 调节PID参数

Robot_PLC_HMI_Automation 1万+

【golang学习之旅】Go 语言并发编程(goroutine、channel 的使用)

✅ 适合人群:Golang 开发者 | 并发编程初学者 | 后端开发工程师✅ 文章亮点:深入解析 Goroutine & Channel + 代码示例 + 实战场景✅ 目标:掌握 Go 并发编程核心,让你的代码更高效、更强大!Goroutine是Go语言的轻量级线程,由Go运行时管理,而非操作系统。相比传统线程,Goroutine占用内存小:默认仅2KB栈空间,可动态扩展调度高效:Go运行时管理Goroutine的调度,无需手动创建线程启动成本低:创建Goroutine比创建线程的开销小很多。

程序员林北北的博客 1252

PCB板Gerber文件的理解和制作

Gerber文件是PCB生产的关键文件,主要包括:1)走线层(GTL/GBL);2)阻焊层(GTS/GBS);3)丝印层(GTO/GBO);4)板框层(GMx/GKO);5)钢网层(Gtp/GBp);6)钻孔文件(NCdrillFiles)。其中1-10项和15项钻孔文件必须提供,建议包含11-14项辅助钻孔层。Gerber文件不含过孔属性,需提前在AD中设置过孔盖油。导出步骤包括:导出非机械层、机械层和钻孔层,新版AD可通过"文件->制造输出->GerberFiles"操作

qq_37999850的博客 853

Go 语言(Golang)并发编程通俗易懂案例

Go 语言(Golang)天生支持并发编程,它的并发模型基于轻量级的 goroutine 和通信顺序进程(CSP)的思想。Goroutine 是 Go 语言中的并发执行单元,通过通道(channel)来实现不同 goroutine 之间的通信。

weixin_43425950的博客 880

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

14 go语言(golang) - 并发编程goroutine和channel

并发编程是指在计算机程序中同时执行多个计算任务的技术。这种编程方式旨在利用多核处理器的计算能力,提高程序的执行效率和响应速度。而Go 语言的并发编程主要依赖于两个核心概念:Goroutine 和 Channel。

瑞瑞的博客 1076

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

golang笔记10--go语言并发编程模块 goroutine

golang笔记10--go语言的并发编程模块 goroutine1 介绍2 Goroutine2.1 goroutine2.2 go语言的调度器3 注意事项4 说明 1 介绍 本文继上文 golang笔记09–go语言测试与性能调优, 进一步了解 go语言的并发编程模块 --goroutine,以及相应注意事项。 具体包括 : goroutine 和 go语言的调度器 等内容。 2 Goroutine 2.1 goroutine 主流的并发模型包括:多进程、多线程、基于回调的非阻塞|异步IO、协程 等方式

脚步不能达到的地方,眼光可以达到;眼光不能达到的地方,精神可以飞到 474

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

【go语言】并发编程

是一个用于描述程序中操作之间因果顺序的规则。在并发编程中,happen-before 机制定义了如何确保一个操作在另一个操作之前发生,并且保证一个操作的结果能够对其他操作可见。具体而言,程序顺序规则(Program Order Rule):在同一个 goroutine 内,代码的执行顺序是保证的,即一个操作发生在前一个操作之后。同步规则(Synchronization Rule):一个 goroutine 对 channel 的发送操作(ch <- x。

加油,考上985的研究生 1471

golang笔记11--go语言并发编程模块 channel

golang笔记11--go语言并发编程模块 channel1 介绍2 Channel2.1 channel2.2 使用Channel等待任务结束2.3 使用Channel进行树的遍历2.4 用select进行调度2.5 传统同步机制3 注意事项4 说明 1 介绍 本文继上文 golang笔记10–go语言并发编程模块 goroutine, 进一步了解 go语言的并发编程模块 --channel,以及相应注意事项。 具体包括 : channel、使用Channel等待任务结束、使用Channel进行树的遍历

脚步不能达到的地方,眼光可以达到;眼光不能达到的地方,精神可以飞到 542

16 go语言(golang) - 并发编程select和workerpool

首先,定义一个WorkerPool最大工作者数(maxWorkers:控制同时运行的 goroutine 的最大数量。任务队列(taskQueue:用于存储待处理任务,通常使用channel来实现。停止信号(stopSignal:一个通道,用于发送停止信号给所有工作者,让它们停止执行。同步机制:如互斥锁(sync.Mutex)或 WaitGroup(),用于同步和等待所有工作者完成。// 池stopSignal chan int // 停止信号,接受到数据时时停止// 保证停止后不能再提交任务。

瑞瑞的博客 1287
上一篇: 9. Palindrome Number回文数(Easy,LeetCode)
下一篇: Go语言的网络编程
DXB2021
博客等级 码龄5年 307粉丝 289原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值