Python 程序员的 Golang 学习指南(III): 入门篇

Golang与Python的互联调用 Golang(即Go语言)和Python是两种功能强大而受欢迎的编程语言,它们各自有着独特的优势和特点。本文将介绍如何在Golang中调用Python代码,实现两者之间的互联调用。在实际应用中,你可以通过这种方式在Golang中调用Python,从而利用两种语言的优势。例如,你可以使用Golang编写高性能的网络服务器,然后在必要时使用Python进行数据处理或机器学习任务。总结起来,通过使用Golang的"exec"包,我们可以很容易地在Golang中调用Python代码。 阅读详情

基础语法

类型和关键字
  • 类型
// 基础类型
布尔类型: bool
整型: int8,uint8,int16,uint16,int32,uint32,int64,uint64,int,rune,byte,complex128, complex64,其中,byte 是 int8 的别名
浮点类型: float32 、 float64
复数类型: complex64 、 complex128
字符串: string
字符类型: rune(int32的别名)
错误类型: error

// 复合类型
指针(pointer)
数组(array)
切片(slice)
字典(map)
通道(chan)
结构体(struct)
接口(interface)
  • 关键字
break        default      func         interface    select
case         defer        go           map          struct
chan         else         goto         package      switch
const        fallthrough  if           range        type
continue     for          import       return       var
变量

Go 同其他语言不同的地方在于变量的类型在变量名的后面,不是 int a,而是 a int。至于为什么这么定义,Go 的官方博客有给出解释,有兴趣的可以参考下。

变量定义语法如下:


var a int
a = 2

// 或者
a := 2

// 同时定义多个变量
var (
    a int
    b bool
)

// 同时给多个变量赋值
a, b := 2, true
操作符

+    &     +=    &=     &&    ==    !=    (    )
-    |     -=    |=     ||    <     <=    [    ]
*    ^     *=    ^=     <-    >     >=    {    }
/    <<    /=    <<=    ++    =     :=    ,    ;
%    >>    %=    >>=    --    !     ...   .    :
     &^          &^=
控制结构

Go 语言支持如下的几种流程控制语句:

  • 条件语句,对应的关键字为 if、else 和 else if;
  • 选择语句,对应的关键字为 switch、case 和 select;
  • 循环语句,对应的关键字为 for 和 range;
  • 跳转语句,对应的关键字为 goto。

值得一提的是,Go 语言并不支持 do 或者 while 关键字,而是对 for 关键字做了增强,以实现类似的效果,如下:


for {
    // 实现无限循环,慎用!
}
常用内置函数
  • len:计算(字符串,数组或者切片,map)长度
  • cap:计算(数组或者切片,map)容量
  • close:关闭通道
  • append:追加内容到切片
  • copy:拷贝数组/切片内容到另一个数组/切片
  • delete:用于删除 map 的元素
array, slice 和 map

// array
a := [3]int{ 1, 2, 3 } // 等价于 a := [...]int{ 1, 2, 3 }

// slice
s := make([]int , 3) // 创建一个长度为 3 的 slice
s := append(s, 1) // 向 slice 追加元素
s := append(s, 2)

// map
m := make(map[string]int) // 使用前必须先初始化
m["golang"] = 7

关于 array, slice 和 map 的更多惯用法,有一篇文章介绍的挺详细,有兴趣的可以看看。

函数

Go 语言的函数有如下特性:

  • 不定参数

由于 Go 语言不支持函数重载(具体原因见 Go Language FAQ),但我们可以通过不定参数实现类似的效果。


func myfunc(args ...int) {
    // TODO
}

// 可通过如下方式调用
myfunc(2)
myfunc(1, 3, 5)
  • 多返回值

与 C、C++ 和 Java 等开发语言的一个极大不同在于,Go 语言的函数或者成员的方法可以有多 个返回值,这个特性能够使我们写出比其他语言更优雅、更简洁的代码。


func (file *File) Read(b []byte) (n int, err error)

// 我们可以通过下划线(_)来忽略某个返回值
n, _ := f.Read(buf)
  • 匿名函数

匿名函数是指不需要定义函数名的一种函数实现方式,它并不是一个新概念,最早可以回溯 到 1958 年的 Lisp 语言。但是由于各种原因,C 和 C++ 一直都没有对匿名函数给以支持,其他的各 种语言,比如 JavaScript、C# 和 Objective-C 等语言都提供了匿名函数特性,当然也包含Go语言。

匿名函数由一个不带函数名的函数声明和函数体组成,如下:


func(a, b int) bool {
    return a < b
}

匿名函数可以直接赋值给一个变量或者直接执行:


f := func(a, b int) bool {
    return a < b
}

func(a, b int) bool {
    return a < b
}(3, 4) // 花括号后直接跟参数列表表示函数调用
  • 闭包

闭包是可以包含自由(未绑定到特定对象)变量的代码块,这些变量不在这个代码块内或者 任何全局上下文中定义,而是在定义代码块的环境中定义。要执行的代码块(由于自由变量包含 在代码块中,所以这些自由变量以及它们引用的对象没有被释放)为自由变量提供绑定的计算环 境(作用域)。

Go 的匿名函数就是一个闭包。我们来看一个例子:


package main

import "fmt"

func main() {
    j := 5
    a := func() func() {
        i := 10
        return func() {
            fmt.Printf("i, j: %d, %d\n", i, j)
        }
    }()
    a()
    j *= 2
    a()
}

程序输出如下:


i, j: 10, 5
i, j: 10, 10
错误处理

Go 语言追求简洁优雅,所以,Go 语言不支持传统的 try...catch...finally 这种异常,因为 Go 语言的设计者们认为,将异常与控制结构混在一起会很容易使得代码变得混乱。因为开发者很容易滥用异常,甚至一个小小的错误都抛出一个异常。在 Go 语言中,使用多值返回来返回错误。不要用异常代替错误,更不要用来控制流程。在极个别的情况下,也就是说,遇到真正的异常的情况下(比如除数为0了),才使用 Go 中引入的Exception处理:defer, panic, recover。

用法如下:


package main

import "fmt"

func main() {
    defer func() {
        fmt.Println("recovered:", recover())
    }()
    panic("not good")
}

关于 Go 语言的错误处理机制和传统的 try...catch...finally 异常机制孰优孰劣,属于仁者见仁,智者见智,这里不做赘速。有兴趣的同学可以去看看知乎上的讨论:Go 语言的错误处理机制是一个优秀的设计吗?。

面向对象 -> 一切皆类型

Python 推崇“一切皆对象”,而在 Go 语言中,类型才是一等公民。

我们可以这样定义一个结构体:


type Name struct {
    First  string
    Middle string
    Last   string
}

同样也可以定义基础类型:


type SimpleName string

还能给任意类型定义方法:


func (s SimpleName) String() string { return string(s) }
// 或者
func (s string) NoWay()

Golang VS Python

最后我们通过几个例子来比较一下 Golang 与 Python 的一些基本用法,如下:

生成器(Generator)
  • Python 版本
def fib(n):
    a, b = 0, 1
    for i in range(n):
        a, b = b, a + b
        yield a

for x in fib(10):
    print x

print 'done'
  • Golang 版本
package main

import "fmt"

func fib(n int) chan int {
    c := make(chan int)
    go func() {
        a, b := 0, 1
        for i := 0; i < n; i++ {
            a, b = b, a+b
            c <- a
        }
        close(c)
    }()
    return c
}

func main() {
    for x := range fib(10) {
        fmt.Println(x)
    }
}
装饰器(Decorator)
  • Python 版本
from urlparse import urlparse, parse_qs
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

def auth_required(myfunc):
    def checkuser(self):
        user = parse_qs(urlparse(self.path).query).get('user')
        if user:
            self.user = user[0]
            myfunc(self)
        else:
            self.wfile.write('unknown user')
    return checkuser

class myHandler(BaseHTTPRequestHandler):
    @auth_required
    def do_GET(self):
        self.wfile.write('Hello, %s!' % self.user)

if __name__ == '__main__':
    try:
        server = HTTPServer(('localhost', 8080), myHandler)
        server.serve_forever()
    except KeyboardInterrupt:
        server.socket.close()
  • Golang 版本
package main

import (
    "fmt"
    "net/http"
)

var hiHandler = authRequired(
    func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hi, %v", r.FormValue("user"))
    },
)

func authRequired(f http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        if r.FormValue("user") == "" {
            http.Error(w, "unknown user", http.StatusForbidden)
            return
        }
        f(w, r)
    }
}

func main() {
    http.HandleFunc("/hi", hiHandler)
    http.ListenAndServe(":8080", nil)
}
猴子补丁(Monkey patching)
  • Python 版本
import urllib

def say_hi(usr):
    if auth(usr):
        print 'Hi, %s' % usr
    else:
        print 'unknown user %s' % usr

def auth(usr):
    try:
        auth_url = 'localhost'
        r = urllib.urlopen(auth_url + '/' + usr)
        return r.getcode() == 200
    except:
        return False

def sayhitest():
    # Test authenticated user
    globals()['auth'] = lambda x: True
    say_hi('John')

    # Test unauthenticated user
    globals()['auth'] = lambda x: False
    say_hi('John')

if __name__ == '__main__':
    sayhitest()
  • Golang 版本
package main

import (
    "fmt"
    "net/http"
)

func sayHi(user string) {
    if !auth(user) {
        fmt.Printf("unknown user %v\n", user)
        return
    }
    fmt.Printf("Hi, %v\n", user)
}

var auth = func(user string) bool {
    authURL := "localhost"
    res, err := http.Get(authURL + "/" + user)
    return err == nil && res.StatusCode == http.StatusOK
}

func testSayHi() {
    auth = func(string) bool { return true }
    sayHi("John")

    auth = func(string) bool { return false }
    sayHi("John")
}

func main() {
    testSayHi()
}

相关链接:
blog.golang.org/gos-dec
Go 语言中的 Array,Slice,Map 和 Set
golang.org/doc/faq#
Go 语言的错误处理机制是一个优秀的设计吗? - 异常处理
talks.golang.org/2013/g

Golang 系列教程

Python 程序员的 Golang 学习指南(II): 开发环境搭建

Python 程序员的 Golang 学习指南(I): Go 之初体验

欢迎交流,可以通过我的 Blog 找到我:startover's blog

大胆一点,让Golang成为新一代科研的编程语言 大胆一点,让Golang成为新一代科研的编程语言 前言 路人甲:科研的编程语言不是Python,R,C这些吗,Golang是什么东西。 路人乙:作者什么鬼,不会是个标题党吧。 这可能是大多数点开这篇文章人的心声吧,但各位客观莫着急,我尽量用较短的语言从数据处理,性能对比等等方面来说明Golang为什么可以用于科研。 Go是什么? Go语言是谷歌公司在2007年发布的静态编译型语言,其目的是为了取代c++,作为c的补充,关于这一点其实linux之父linus在2007年就说过c++是一个很糟糕的语言,主要原因 阅读详情

相关推荐

golang调用python实战

简介 go-python Python提供了丰富的C-API。而C和Go又可以通过cgo无缝集成。所以,直接通过Golang调用libpython,就可以实现Go调Python的功能了。但是过程比较复杂,而go-python提供了针对CPython-2的C-API提供了native-binding能力,方便实现了Go到Python的调用。 但是目前,go-python只支持python2.7。 pkg-config go-python使用pkg-config来获取python的头文件及库信息。 ​ 一般来说

SPxdl的博客 1431

Golang调用Python

阅读原文请点击 摘要: Python是时髦的机器学习御用开发语言,Golang是大红大紫的新时代后端开发语言。Python很适合让搞算法的写写模型,而Golang很适合提供API服务,两位同志都红的发紫,这里就介绍一下正确搅基的办法。 ![干他一炮.jpg](http://ata2-img.cn-hangzhou.img-pub.aliyun-inc.com/f5ad9d2dbd36c3

qq_35267530的博客 1万+

Cisco Packet Tracer 7.3免登录技巧:3种方法快速跳过注册界面(附详细截图)

本文针对Cisco Packet Tracer 7.3启动时遇到的登录界面问题,提供了三种合法高效的解决方案。详细介绍了如何利用官方访客模式快速启动、注册思科账号实现一劳永逸登录,以及通过调整本地安装配置优化启动流程,帮助网络学习者与备考者绕过繁琐步骤,快速进入实验环境。

weixin_29305337的博客 737

golang调用python

Python语言作为当下最红的语言,此文将演示如何通过Go语言来为Python脚本语言编写扩展模块。

weixin_42181179的博客 1681

手机拍照也能玩高光谱?教你用TensorFlow Lite在Android上实现实时RGB转高光谱

本文介绍了如何利用TensorFlow Lite在Android设备上实现实时RGB到高光谱的图像重构技术。通过深度学习模型优化和移动端部署策略,使智能手机具备专业级光谱分析能力,适用于农业检测、化妆品分析等多个领域。

weixin_29091105的博客 244

LRTimelapse Pro v7.0.0 激活版下载安装教程 (延迟摄影后期渲染)

LRTimelapse Pro 是一款优秀的高级延时摄影解决方案,使用将为用户提供最全面的工具和功能,从导入和组织您的延时摄影序列、视觉工作流程、在 LRTimelapse 中直接编辑和渲染、视觉去闪烁等等,功能齐全,可以使用 LRTimelapse Pro 编辑多个序列时显著提高您的效率,轻松在 LRTimelapse 中配置和使用色彩管理,进行长期延时编辑,在 LRTimelapse Pro 中使用长期工作流程。为延时编辑、关键帧、分级和渲染提供最全面的解决方案。

wyqshusan的博客 3464

python和go相互调用的两种方法

将go代码编译成so库 -> python中通过ctypes引用so库并指定需要调用的函数(同时可指定传入参数类型和返回值类型) -> 指定后按python使用函数方式调用。需要注意的是:python和go之间参数传递是需要经过C的数据类型转换的,因此需要了解python中ctypes数据类型和python数据类型以及C的数据类型对应关系ctypes数据类型为指定调用函数时的传入参数和返回值的数据类型python数据类型为调用函数时传入的参数的数据类型。

kuokay的博客 5845

基于MySQL的京东用户行为分析

对京东用户行为的分析,利用AARRR模型进行分析。

SelenaSelena的博客 1909

python go 入门_Python 程序员的 Golang 学习指南(III): 入门篇

基础语法类型和关键字类型// 基础类型布尔类型: bool整型: int8,uint8,int16,uint16,int32,uint32,int64,uint64,int,rune,byte,complex128, complex64,其中,byte 是 int8 的别名浮点类型: float32 、 float64复数类型: complex64 、 complex128字符串: string字...

weixin_32715349的博客 397

龙芯3A5000开发板PMON升级UEFI固件实战指南

固件是计算机硬件与操作系统之间的关键桥梁,负责初始化硬件并引导系统启动。其工作原理是在上电后执行自检、加载引导程序,最终将控制权移交操作系统。在国产化平台中,采用标准化的UEFI固件具有重要技术价值,它能提供图形化配置界面、统一硬件驱动模型,并支持安全启动等现代特性,从而显著提升硬件兼容性与系统管理效率。这一技术广泛应用于PC、服务器及嵌入式设备,尤其在需要运行银河麒麟等主流操作系统的龙芯开发板场景中,将传统PMON固件升级至UEFI,能实现更流畅的系统安装与更稳定的运行体验。本文基于固件升级与UEFI引导

weixin_42664597的博客 561

StarRC常见问题整理

我正在「拾陆楼」和朋友们讨论有趣的话题,你⼀起来吧?使用starrc_cmd “错误代码”就能看对应Error或Warnning的解释。

m0_61544122的博客 3116

python golang学哪个_Python程序员的Golang学习指南(I):Go 之初体验

Python程序员的Golang学习指南(I):Go 之初体验GolangGo 之初体验Go 语言简介Go,又称 golang,是Google开发的一种静态强类型,编译型,并发型,并具有垃圾回收功能的编程语言。Go 语言于2009年11月正式宣布推出,自2012年发布1.0,最新稳定版1.7。目前,Go的相关工具和生态已逐渐趋于完善,也不乏重量级项目,如 Docker, Kubernetes, E...

weixin_39653764的博客 301

【ROS】Nav2源码之nav2_collision_monitor(碰撞监测)详解

nav2_collision_monitor碰撞监视器是一个节点,为机器人提供了一个额外的安全级别。它使用来自传感器的数据,执行若干与避免碰撞相关的任务,绕过成本图和轨迹规划器,监测是否需要紧急停止或者减速。

郭老二 1455

go语言调用python_Golang 执行Python脚本

一、两种方式通过命令行的方式调用python脚本github.com/sbinet/go-python二、实现1、通过命令行的方式调用python脚本在golang对jpg图片dpi操作未提供原生的相关接口,只好依赖python脚本达到想要的目的main.pyfrom PIL import Image as ImagePIL, ImageFont, ImageDrawimport base64im...

weixin_39881167的博客 1439

Git救援:如何从误操作中恢复未提交的更改

摘要:本文探讨了误操作git reset --hard导致未提交更改丢失后的恢复方法。首先分析git reflog的局限性,随后介绍利用IDE本地历史记录(如IntelliJ IDEA和VS Code)进行文件恢复的具体步骤。最后建议使用文件系统恢复工具(如Linux的extundelete或Windows的Recuva)作为备选方案。文章强调定期提交的重要性,同时提供了意外发生时可行的恢复策略,帮助开发者尽可能挽回丢失的工作内容。(149字)

2501_90323865的博客 129

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

go语言调用python脚本_Golang调用Python

Python是时髦的机器学习御用开发语言,Golang是大红大紫的新时代后端开发语言。Python很适合让搞算法的写写模型,而Golang很适合提供API服务,两位同志都红的发紫,这里就介绍一下正确搅基的办法。原理Python提供了丰富的C-API。而C和Go又可以通过cgo无缝集成。所以,直接通过Golang调用libpython,就可以实现Go调Python的功能了。确实没啥神奇,只要会用C调...

weixin_36381252的博客 1647

深度学习工具包 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包管理机制_Python 程序员的 Golang 学习指南(IV): 包管理篇

Python 程序员的 Golang 学习指南(IV): 包管理篇Golang在第一篇文章我们有提到,Golang 官方并没有推荐最佳的包管理方案,对于像我这样习惯了 Python 包管理的开发者,自然还是希望有像 pip 一样好用的工具,帮助我们进行依赖管理,下面就让我们对 Golang 的包管理机制一探究竟。Golang 包管理机制Go 语言的包管理系统是去中心化的,我们可以通过 go get...

weixin_39607798的博客 243

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

知乎用Go替代Python,是否说明Go比Python好?,Golang面试问题和答案

此外,毕竟 Python 的生态,在这么多编程语言中,是数一数二的,Go 虽热,但在社区方面恐怕还是比不上 Python、PHP,这也是一个现实问题。不得不说,Go的协程,一个“go”就能解决绝大多数问题,确实写代码很简洁,Python 新添的 asyncio 还是相对复杂,Future、Task等等还是有不少门道的。所以,技术永远只有合适的,而没有最佳的,也没有非此即彼的好坏分明。随着知乎用户的迅速增长和业务复杂度的持续增加,核心业务的流量在过去一年内增长了好几倍,对应的服务端的压力也越来越大。

2301_82244608的博客 755

go语言执行python代码_Golang 执行Python脚本

一、两种方式通过命令行的方式调用python脚本github.com/sbinet/go-python二、实现1、通过命令行的方式调用python脚本在golang对jpg图片dpi操作未提供原生的相关接口,只好依赖python脚本达到想要的目的main.pyfrom PIL import Image as ImagePIL, ImageFont, ImageDrawimport base64im...

weixin_39562554的博客 1345

go调用python脚本_Golang调用Python

摘要:Python是时髦的机器学习御用开发语言,Golang是大红大紫的新时代后端开发语言。Python很适合让搞算法的写写模型,而Golang很适合提供API服务,两位同志都红的发紫,这里就介绍一下正确搅基的办法。 ![干他一炮.jpg](http://ata2-img.cn-hangzhou.img-pub.aliyun-inc.com/f5ad9d2dbd36c37ef742c7be6998...

weixin_39746241的博客 436

为什么我们从 Python 切换到 Go_python go,Golang开发技术总结

8954612)]

2401_84264429的博客 1153

go语言调用python_golang和python互相调用

综述golang和python之间,当前可以通过golang的cgo和python的ctypes,把golang对象和python对象分别转换为C对象,从而通过编译和调用c的动态连接库,完成交互。python调用golang:go 函数实现://libadd.gopackage mainimport "C"//export addfunc add(left, right int) int {ret...

weixin_39999190的博客 1190

golang和python_Golang调用Python-Go语言中文社区

摘要:Python是时髦的机器学习御用开发语言,Golang是大红大紫的新时代后端开发语言。Python很适合让搞算法的写写模型,而Golang很适合提供API服务,两位同志都红的发紫,这里就介绍一下正确搅基的办法。 ![干他一炮.jpg](http://ata2-img.cn-hangzhou.img-pub.aliyun-inc.com/f5ad9d2dbd36c37ef742c7be6998...

weixin_39842519的博客 128

使用 Golang 和 Docker 实现 Python 计算服务

本篇文章,我们继续前一篇的话题《使用 Golang 和 Docker 运行 Python 代码》,聊聊如何使用 Golang 和 Docker 将普通的 Python 软件包封装为高性能的服务。

折腾技术 8559

golang程序员如何3天完成python学习

有Golang经验的程序员,想要在三天内快速学习Python,如何分配三天时间。将时间分为基础语法、核心库和框架、项目实战。第一天突破语法差异,第二天学习关键库,第三天实战项目。以下是针对Golang程序员定制的‌。

qq_42942935的博客 1073
python_zengge
博客等级 码龄10年 1粉丝 1原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值