巧用Google Fire简化Python命令行程序

Google 的用于生成命令行接口的工具 fire 的简单用法 fire 是 Google 开源的用于给任何 Python 程序自动生成命令行接口(CLI)的库,压缩包中包含简单使用例子和详细的使用说明(博客)。 立即下载

Hello World

要介绍Fire是什么,看一个简单的例子就明白了

# calc.py
import fire

class Calculator(object):
  """A simple calculator class."""

  def double(self, number):
    return 2 * number

if __name__ == '__main__':
  fire.Fire(Calculator)

接下来我们进入bash来执行上面编写的脚本

> python calc.py double 10
20
> python calc.py double --number=16
32

上面是官方的示例代码,有了fire,编写Python的命令行程序就变得非常简单,我们无需再去处理繁琐的命令行参数解析了。接下来我们仿照HelloWorld,编写一个圆周率和阶乘计算的命令行脚本。

实战

import math
import fire


class Math(object):

    def pi(self, n):
        s = 0.0
        for i in range(n):
            s += 1.0/(i+1)/(i+1)
        return math.sqrt(6*s)

    def fact(self, n):
        s = 1
        for i in range(n):
            s *= (i+1)
        return s


if __name__ == '__main__':
    fire.Fire(Math)

接下来我们运行一下

>  python maths.py pi 10000
3.14149716395
>  python maths.py pi 100000
3.14158310433
>  python maths.py pi 1000000
3.14159169866
>  python maths.py fact 10
3628800
>  python maths.py fact 15
1307674368000
>  python maths.py fact 20
2432902008176640000

Cool,真的非常方便!fire对当前对象结构进行了暴露,将结构信息映射到shell命令行参数上。fire其实有多种暴露模式,接下来我们逐个来看fire都有哪些暴露模式。

暴露模块

fire如果不传递任何参数就可以直接暴露当前模块结构,我们对上面的例子做一下改造,去掉类信息

import math
import fire


def pi(n):
    s = 0.0
    for i in range(n):
        s += 1.0/(i+1)/(i+1)
    return math.sqrt(6*s)

def fact(n):
    s = 1
    for i in range(n):
        s *= (i+1)
    return s


if __name__ == '__main__':
    fire.Fire()

注意Fire函数调用没有任何参数,运行一下

>  python maths.py fact 20
2432902008176640000
>  python maths.py pi 1000000
3.14159169866

暴露函数

fire还可以传递一个函数对象来暴露单个函数,可以让我们在命令行参数上省掉函数名称

import math
import fire

def pi(n):
    s = 0.0
    for i in range(n):
        s += 1.0/(i+1)/(i+1)
    return math.sqrt(6*s)
    
if __name__ == '__main__':
    fire.Fire(pi)

如果暴露函数那就只能暴露一个函数,如果暴露了两个,那就只有后面一个生效,运行一下

>  python maths.py 1000
3.14063805621

暴露字典

fire可以直接暴露一个模块,将当前模块的所有函数全部暴露,函数名和第一个参数名一致。我们也可以不用暴露整个模块的所有函数,使用字典暴露法就可以选择性地对模块的某些函数进行暴露,顺便还可以替换暴露出来的函数名称。

import math
import fire


def pi(n):
    s = 0.0
    for i in range(n):
        s += 1.0/(i+1)/(i+1)
    return math.sqrt(6*s)

def fact(n):
    s = 1
    for i in range(n):
        s *= (i+1)
    return s


if __name__ == '__main__':
    fire.Fire({
        "pi[n]": pi
    })

我们只暴露了pi函数,并且把名字还换掉了,运行一下,看效果

>  python maths.py pi[n] 1000
3.14063805621

如果我们使用原函数名称,就会看到fire列出的友好的报错信息

>  python maths.py pi 1000
Fire trace:
1. Initial component
2. ('Cannot find target in dict:', 'pi', {'pi[n]': <function pi at 0x10a062c08>})
Type:        dict
String form: {'pi[n]': <function pi at 0x10a062c08>}
Length:      1
Usage:       maths.py
             maths.py pi[n]

暴露对象

import math
import fire


class Maths(object):

    def pi(self, n):
        s = 0.0
        for i in range(n):
            s += 1.0/(i+1)/(i+1)
        return math.sqrt(6*s)

    def fact(self, n):
        s = 1
        for i in range(n):
            s *= (i+1)
        return s


if __name__ == '__main__':
    fire.Fire(Maths())

运行

>  python maths.py pi 1000
3.14063805621
>  python maths.py fact 20
2432902008176640000

暴露类

这个我们在上面的实战环节已经演示过了,这里就不在重复粘贴

类 vs 对象

通过上面的例子,我们发现暴露类和暴露对象似乎没有任何区别,那到底该选哪种比较优雅呢?这个要看类的构造器有没有参数,如果是不带参数的构造器,那么类和对象的暴露是没有区别的,但是如果类的构造器有参数,那就不一样了,下面我们改造一下Maths类,增加一个放大系数。

import math
import fire


class Maths(object):

    def __init__(self, coeff):
        self.coeff = coeff

    def pi(self, n):
        s = 0.0
        for i in range(n):
            s += 1.0/(i+1)/(i+1)
        return self.coeff * math.sqrt(6*s)

    def fact(self, n):
        s = 1
        for i in range(n):
            s *= (i+1)
        return self.coeff * s


if __name__ == '__main__':
    fire.Fire(Maths)

因为Maths的构造器带有参数,所有运行命令行时需要指定构造器参数值

> python maths.py pi 1000 --coeff=2
6.28127611241

如果不指定参数的值,运行时就会报错

> python maths.py pi 1000
Fire trace:
1. Initial component
2. ('The function received no value for the required argument:', 'coeff')
Type:        type
String form: <class '__main__.Maths'>
File:        ~/source/rollado/maths.py
Line:        5
Usage:       maths.py COEFF
             maths.py --coeff COEFF

如果改成暴露对象,那么放大系数就是在代码里写死的,无法在命令行进行参数定制了。这就是暴露对象和暴露类的差别,似乎暴露类在功能上更强大一些。

暴露属性

上面的所有例子我们最终暴露的都是函数,要么是模块里的函数,要么是类里的函数。但实际上fire还可以暴露属性,比如我们可以将上面的coeff参数通过命令行进行输出。

> python maths.py coeff --coeff=2
2
> python maths.py coeff --coeff=3
3

再来一个更加简单的例子

# example.py
import fire
english = 'Hello World'
spanish = 'Hola Mundo'
fire.Fire()

运行

$ python example.py english
Hello World
$ python example.py spanish
Hola Mundo

原理

640?wx_fmt=png

命令行中的参数顺序和代码内部对象的树状层次结构呈现一一对应关系。如果fire不带参数暴露了当前的模块,那么第一个参数就应该是这个模块内部的函数名、类名或者是变量名。如果第一个参数是函数,那么接下来的参数就是函数的参数。如果第一个参数是类,那么接下来的参数可能是这个类实例内部的方法或者字段。如果第一个参数是变量名,后面没有参数的话,就直接显示这个变量。如果后面还有参数,那么就把这个变量看成一个对象,然后继续使用后续参数来深入解析这个对象。

在Python里面所有的变量都是对象,包括普通的整数、字符串、浮点数、布尔值等。理论上可以一直将对象结构递归下去,形成一个复杂的链式调用。

链式暴露

接下来我们验证这个理论,尝试一下复杂的链式暴露。

import fire

class Chain(object):

    def __init__(self):
        self.value = 1

    def incr(self):
        print "incr", self.value
        self.value += 1
        return self

    def decr(self):
        print "decr", self.value
        self.value -= 1
        return self

    def get(self):
        return self.value

if __name__ == '__main__':
    fire.Fire(Chain)

运行一下

> python chains.py incr incr incr decr decr get
incr 1
incr 2
incr 3
decr 4
decr 3
2

Cool! 我们通过在每个方法里面方法self对象自身来实现了漂亮的链式调用效果。

接下来我们尝试对内置字符串对象进行解构

# xyz.py
import fire

value = "hello"

if __name__ == '__main__':
    fire.Fire()

字符串有upper和lower方法,我们反复使用upper和lower,然后观察结果

> python xyz.py value
hello
> python xyz.py value upper
HELLO
> python xyz.py value upper lower
Traceback (most recent call last):
  File "xyz.py", line 7, in <module>
    fire.Fire()
  File "/Users/pyloque/source/pys/.py/lib/python2.7/site-packages/fire/core.py", line 127, in Fire
    component_trace = _Fire(component, args, context, name)
  File "/Users/pyloque/source/pys/.py/lib/python2.7/site-packages/fire/core.py", line 366, in _Fire
    component, remaining_args)
  File "/Users/pyloque/source/pys/.py/lib/python2.7/site-packages/fire/core.py", line 542, in _CallCallable
    result = fn(*varargs, **kwargs)
TypeError: upper() takes no arguments (1 given)

很不幸,内置的字符串对象似乎不支持链式调用,第一个upper倒是执行成功了。不过fire提供了一个特殊的符号用来解决这个问题。

> python xyz.py value upper - lower
hello
> python xyz.py value upper - lower - upper
HELLO
> python xyz.py value upper - lower - upper - lower
hello

减号用来表示参数的结束,这样后续的参数就不会被当成函数的参数来映射了。

总结

有了Google Fire这样一个小巧的类库,我们就可以从复杂的命令行参数分析中解脱出来了。我们常说写代码要漂亮优雅,没有好的类库,这种理想也不是非常容易实现的。如果没有fire,你有本事试试把复杂的命令行参数解析代码写优雅了给老师我看看。

640?wx_fmt=jpeg

阅读更多高级文章,关注公众号「码洞」

10、数据挖掘与轨迹生成技术:FSSEMiner与CondTraj - GAN的探索 本文介绍了两种先进的数据处理技术:FSSEMiner算法用于从动态属性图中挖掘频繁顺序子图演化模式,揭示如交通流和疾病传播等复杂系统的演化规律;CondTraj-GAN是一种端到端的条件生成对抗网络,能够生成高质量的合成车辆轨迹,解决真实轨迹数据因隐私问题难以获取的挑战。通过实验评估与真实数据集验证,两种技术在可扩展性、实用性及生成质量方面均表现出色,并在交通管理、城市规划、自动驾驶研发等领域具有广泛应用前景。 阅读详情

相关推荐

手把手教你用ObjectCRX进行Caxa二次开发:从零开始的环境搭建教程

本文是一份面向零基础初学者的Caxa二次开发实战指南,重点讲解如何使用ObjectCRX框架从零开始搭建开发环境。内容涵盖Visual Studio 2015版本锁定、ObjectCRX向导集成、项目创建、典型错误解决,并最终实现一个可在Caxa中运行的HelloWorld程序,帮助开发者快速入门并避开常见陷阱。

w3x4y的博客 514

华为鸿蒙harmony4.0系统安装谷歌服务框架GMS谷歌应用商店Google Play(无需电脑操作,纯手机)

13. 打开安装的MicroG, 登录Google账号,完成后回到Googlefire,点击第二步,会让你登录你的第二个Google账户,如果需要的话就继续登录,以此类推,登录多个Google账号,需要提醒的是,Google账号只能这里登录,下面步骤不再允许登录账号。再安装Google play服务之前,会跳转“应用信息”,要求“强行停止”MicroG的运行,并点击“卸载”,完成之后才可继续安装。打开设置->系统和更新->日期和时间->关闭“自动设置”->将时间设置为2019年。下载安装包,链接私戳我发。

weixin_41710647的博客 1万+

海康工业相机SDK+OpenCV实战:图像采集与Mat格式转换优化指南

本文深入探讨了如何高效利用海康工业相机SDK与OpenCV进行图像采集与处理。重点解析了从相机RawData到OpenCV Mat格式转换的核心优化技巧,包括像素格式匹配、内存零拷贝管理以及彩色图像BGR/RGB转换,旨在解决工业应用中常见的性能瓶颈与内存问题,构建稳定高效的图像处理流程。

weixin_29192211的博客 108

python工具是什么-使用Python编写命令行工具有什么好的库?

使用Python编写命令行工具的库很多,我最推荐的还是Google FireHello World要介绍Fire是什么,看一个简单的例子就明白了# calc.pyimport fireclass Calculator(object):"""A simple calculator class."""def double(self, numb...

weixin_37988176的博客 405

NL2SQL实践系列(1):深入解析Prompt工程在text2sql中的应用技巧

NL2SQL实践系列(1):深入解析Prompt工程在text2sql中的应用技巧

丨汀、的博客 4328

TGRS 2026 即插即用 | 注意力篇 | SCFM:双向交叉显著性引导注意力,高层语义与低层细节的双向互补!

本文介绍了MPCNet中的语义引导交叉注意力融合模块(SCFM),该模块通过双向交叉显著性引导机制实现跨尺度特征融合。SCFM创新性地结合了高层语义和低层细节的互补信息,通过轻量局部空间注意力预增强和坐标注意力全局融合引导,显著提升了红外小目标检测的精度。实验表明,SCFM在多个数据集上达到SOTA性能,同时保持轻量高效的计算特性,支持端侧设备部署。 SCFM的核心贡献包括: 双向交叉显著性引导机制,实现语义与细节的互补融合 轻量局部空间注意力预增强模块,计算量仅为传统方法的1/10 坐标注意力全局融合引导

主要更新底层视觉(去噪、超分等)相关的科研内容,形式为【论文精读】+【论文复现】 151

Python 笔记

Python 的运行环境(IDE)是IDLE GUI 在shell 里面运行。 Python中整数溢出的问题解决,计算结果后面有一个数字L可以用一个命令:type(object)来检测一个数是什么类型。e.g &gt;&gt;&gt; type(4)&lt;type 'int'&gt; #4是int,整数&gt;&gt;&gt; type(5.0)&lt;type 'float'&gt; #5.0...

gardenias_Lily 1406

【ARM CoreLink 系列 7 -- TZC-400控制器简介】

为了确保内存能够正确识别总线的信号控制位,新增一个TrustZone地址空间控制器(TrustZone Address Space Controller,TZASC)组件来实现对内存地址的安全扩展,将内存区域划分为安全内存区域和非安全内存区域,安全世界可以访问安全内存和非安全内存,而普通世界只能访问非安全内存,如下图所示:图 1-1内存区域的划分是在系统启动时通过配置 TZASC 组件(TZC-400/TZC-380)来实现的。TZC-400由和使能情况;安全访问权限;Base地址;

CodingCos的博客 1634

Google的Python开源Fire工具使用笔记

安装:pip install fire 编写程序测试: Windows CMD 测试:

xfyangle的博客 2621

Weka学习笔记01:初探Weka世界

下载、安装和启动Weka、Weka数据格式

howard2005的专栏 1472

Spring AI Alibaba Agent开发实战:DeepResearch Agent调度系统

智能Agent调度系统通过专业化分工解决传统AI系统的三大痛点:通用模型专业性不足、处理效率低下和资源浪费。系统采用分层架构设计,核心组件包括智能调度器、Agent选择辅助器和集成工具类,实现问题分类、专业Agent匹配和搜索策略优化的全流程自动化。系统特点包括:1)配置驱动的灵活扩展;2)分层回退的容错机制;3)支持工具调用与传统搜索的智能切换。该架构通过策略模式和依赖注入等技术,在保证稳定性的同时显著提升了研究质量和效率,为企业级多Agent协作提供了完整解决方案。(149字)

wjianwei666的专栏 505

Google 开源的 Python 命令行库:fire 实现 git 命令

作者:HelloGitHub-Prodesire涉及的示例代码,已同步更新到HelloGitHub-Team仓库点击本文最下方的“阅读原文”即可获取一、前言在前面三篇介绍 fire ...

HelloGitHub 的博客 727

筑基篇第9节:CUDA内存管理API进阶

CUDA多维内存管理与零拷贝技术 本文介绍了CUDA中高效处理多维数据的内存管理技术。对于二维数据,使用cudaMallocPitch可确保内存对齐访问,提升75%的带宽利用率;三维数据则通过cudaMalloc3D实现切片对齐。配套的cudaMemcpy2D/3D函数能高效处理数据拷贝。此外,零拷贝内存技术允许内核直接访问主机内存,避免显存拷贝开销。这些技术对图像处理、科学计算等应用至关重要,能显著提升多维数据处理的性能。

PeterPan的博客 83

探索 Python 的火种:Fire 库

在 Python 的世界中,库和框架的多样性是其强大功能和灵活性的体现。今天,我们将探索一个名为 Fire 的库,它不仅简单易用,还能极大提升开发效率。Fire 是 Google 开发的一个库,它允许你通过编写简单的命令行程序来处理复杂的任务。它的核心功能是将 Python 函数转换为命令行接口,从而使得命令行程序的编写变得异常简单。

AIGC搞起 1866

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

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

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

Google 开源的 Python 命令行库:初探 fire

作者:HelloGitHub-Prodesire涉及的示例代码,已同步更新到 HelloGitHub-Team 仓库点击本文最下方的“阅读原文”即可获取一、前言在本系列前面所有文章中,我...

HelloGitHub 的博客 783

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

Google 开源的 Python 命令行库:深入 fire(一)

作者:HelloGitHub-Prodesire涉及的示例代码,已同步更新到 HelloGitHub-Team 仓库点击本文最下方的“阅读原文”即可获取一、前言在第一篇“初探 fire”...

HelloGitHub 的博客 712

Google 开源的 Python 命令行库:深入 fire(二)

作者:HelloGitHub-Prodesire涉及的示例代码,已同步更新到HelloGitHub-Team仓库点击本文最下方的“阅读原文”即可获取一、前言在上一篇文章中我们介绍了 ...

HelloGitHub 的博客 968

Python Fire 使用教程

简介 Fire是google开发的一个python第三方库,其作用是可以将python组件(函数调用,类调用)转换成命令行的形式去调用。 安装 可以直接使用pip来安装 pip install fire 或者可以从Fire源码安装,clole如下源码https://github.com/google/python-fire.git, 然后进入目录,运行如下命令 python setup.py i...

JohnSon 5216

探索 Python 的火焰:Fire 库的神秘力量

在 Python 的世界中,命令行接口(CLI)的应用无处不在。但你是否曾因为编写繁琐的命令行参数解析代码而感到头疼?或者在寻找一种更简洁、更直观的方式来处理命令行参数?如果你的答案是肯定的,那么 Fire 库就是你的救星!Fire 是 Google 开发的一个 Python 库,它能够将任何 Python 函数转换为一个命令行接口。这意味着,你只需定义一个函数,Fire 就能自动为你生成相应的命令行工具。这不仅简化了代码,还提高了开发效率。

AIGC搞起 2182

Python 命令行工具:fire (已验证)

fire可以根据任何 Python 对象自动生成命令行接口。能以简单的方式生成 CLI是一个开发和调试 Python 代码的实用工具能将现存代码或别人的代码转换为 CLI使得在 Bash 和 Python 间的转换变得更容易通过预先为 REPL 设置所需的模块和变量,使得实用 REPL 更加容易。...

u010075995的博客 1826

一行命令实现功能?Google工程师是这样做的

最近想尝试将一些做过的小工具打包在一起,合成Python实用宝典的常用工具盒以分享给大家,这个工具盒功能非常强大,包括但不限于:一行命令提取音乐的高潮部分、一行命令人脸识别、一行命令分类文本…等等,敬请期待! 不过,做这样的工具盒其实原理不复杂,就是将用户需要用到的自定义参数通过命令直接传入Python中运行,用户不需要管代码、也不需要理解代码、直接使用。不过,做工具盒的时候却发现这样的问题,现在常用的命令行传参工具实在是不够用。 比如下面这个argparse的简单例子, 它使得Python命令在运行的时候

Python实用宝典网 837

Python Fire - 一个好用的命令行生成库

有没有这样一种感觉: 学了 Python,好歹也会一门语言了,偶尔想要自己写点小工具来用用,当代码写好后,怎么运行是个问题了。难道,每次要用的时候都要打开编码工具来运行? 写个带界面的?但是 UI 库都好难学,web 框架更难学。 那就写个命令行呗! 但是 Python 自带的命令行用起来并不方便。 现在有一个更简单方便的库,由 Google 开源的 fire库。 我们来学习一下怎么用。 首先...

小满测试 588

一个“牛逼”的 Python 命令行解析库-fire

在 Python 中,命令行解析库有非常多的选择方案,系统自带的 模块有 argparse,有 Flask 作者写的 click,但是 argparse 使用起来啰嗦, 要经历解析器初始化、参数定义、解析一套流程。例如: # -*- coding: utf-8 -*- # arg_test.py import argparse def counter(file_type=None): ...

Never-Giveup的博客 713
上一篇: Github上最受欢迎的Python框架Flask入门
下一篇: 知道Python语言的Google Fire项目么,我将它移植到了Java上
码洞
博客等级 码龄10年 41粉丝 137原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值