greenlet: Lightweight concurrent programming

基于 Python 实现短视频平台用户浏览与点赞行为的数据分析与挖掘 本项目基于抖音平台173万条用户浏览数据,从用户、作者、作品三维度分析行为特征。研究发现:点赞行为高度集中,约1%的用户、作者和作品贡献近半数点赞;用户分层揭示五类使用模式,差异源于浏览频率与内容偏好;作者分层显示创作节奏为主导因素,但点赞率差异有限。模型表明,用户历史互动(如ID target encoding)对点赞预测贡献最大,凸显个性化推荐潜力。建议优先验证完播率对点赞的影响,区分头部维护与增量挖掘,并通过A/B实验验证运营策略有效性。 阅读详情

Motivation

The “greenlet” package is a spin-off of Stackless, a version of CPython that supports micro-threads called “tasklets”. Tasklets run pseudo-concurrently (typically in a single or a few OS-level threads) and are synchronized with data exchanges on “channels”.

A “greenlet”, on the other hand, is a still more primitive notion of micro-thread with no implicit scheduling; coroutines, in other words. This is useful when you want to control exactly when your code runs. You can build custom scheduled micro-threads on top of greenlet; however, it seems that greenlets are useful on their own as a way to make advanced control flow structures. For example, we can recreate generators; the difference with Python’s own generators is that our generators can call nested functions and the nested functions can yield values too. (Additionally, you don’t need a “yield” keyword. See the example in test/test_generator.py).

Greenlets are provided as a C extension module for the regular unmodified interpreter.

Example

Let’s consider a system controlled by a terminal-like console, where the user types commands. Assume that the input comes character by character. In such a system, there will typically be a loop like the following one:

def process_commands(*args):
    while True:
        line = ''
        while not line.endswith('\n'):
            line += read_next_char()
        if line == 'quit\n':
            print "are you sure?"
            if read_next_char() != 'y':
                continue    # ignore the command
        process_command(line)

Now assume that you want to plug this program into a GUI. Most GUI toolkits are event-based. They will invoke a call-back for each character the user presses. [Replace “GUI” with “XML expat parser” if that rings more bells to you :-)] In this setting, it is difficult to implement the read_next_char() function needed by the code above. We have two incompatible functions:

def event_keydown(key):
    ??

def read_next_char():
    ?? should wait for the next event_keydown() call

You might consider doing that with threads. Greenlets are an alternate solution that don’t have the related locking and shutdown problems. You start the process_commands() function in its own, separate greenlet, and then you exchange the keypresses with it as follows:

def event_keydown(key):
         # jump into g_processor, sending it the key
    g_processor.switch(key)

def read_next_char():
        # g_self is g_processor in this simple example
    g_self = greenlet.getcurrent()
        # jump to the parent (main) greenlet, waiting for the next key
    next_char = g_self.parent.switch()
    return next_char

g_processor = greenlet(process_commands)
g_processor.switch(*args)   # input arguments to process_commands()

gui.mainloop()

In this example, the execution flow is: when read_next_char() is called, it is part of the g_processor greenlet, so when it switches to its parent greenlet, it resumes execution in the top-level main loop (the GUI). When the GUI calls event_keydown(), it switches to g_processor, which means that the execution jumps back wherever it was suspended in that greenlet – in this case, to the switch() instruction in read_next_char() – and the key argument in event_keydown() is passed as the return value of the switch() in read_next_char().

Note that read_next_char() will be suspended and resumed with its call stack preserved, so that it will itself return to different positions in process_commands() depending on where it was originally called from. This allows the logic of the program to be kept in a nice control-flow way; we don’t have to completely rewrite process_commands() to turn it into a state machine.

Usage

Introduction

A “greenlet” is a small independent pseudo-thread. Think about it as a small stack of frames; the outermost (bottom) frame is the initial function you called, and the innermost frame is the one in which the greenlet is currently paused. You work with greenlets by creating a number of such stacks and jumping execution between them. Jumps are never implicit: a greenlet must choose to jump to another greenlet, which will cause the former to suspend and the latter to resume where it was suspended. Jumping between greenlets is called “switching”.

When you create a greenlet, it gets an initially empty stack; when you first switch to it, it starts the run a specified function, which may call other functions, switch out of the greenlet, etc. When eventually the outermost function finishes its execution, the greenlet’s stack becomes empty again and the greenlet is “dead”. Greenlets can also die of an uncaught exception.

For example:

from greenlet import greenlet

def test1():
    print 12
    gr2.switch()
    print 34

def test2():
    print 56
    gr1.switch()
    print 78

gr1 = greenlet(test1)
gr2 = greenlet(test2)
gr1.switch()

The last line jumps to test1, which prints 12, jumps to test2, prints 56, jumps back into test1, prints 34; and then test1 finishes and gr1 dies. At this point, the execution comes back to the original gr1.switch() call. Note that 78 is never printed.

Parents

Let’s see where execution goes when a greenlet dies. Every greenlet has a “parent” greenlet. The parent greenlet is initially the one in which the greenlet was created (this can be changed at any time). The parent is where execution continues when a greenlet dies. This way, greenlets are organized in a tree. Top-level code that doesn’t run in a user-created greenlet runs in the implicit “main” greenlet, which is the root of the tree.

In the above example, both gr1 and gr2 have the main greenlet as a parent. Whenever one of them dies, the execution comes back to “main”.

Uncaught exceptions are propagated into the parent, too. For example, if the above test2() contained a typo, it would generate a NameError that would kill gr2, and the exception would go back directly into “main”. The traceback would show test2, but not test1. Remember, switches are not calls, but transfer of execution between parallel “stack containers”, and the “parent” defines which stack logically comes “below” the current one.

Instantiation

greenlet.greenlet is the greenlet type, which supports the following operations:

greenlet(run=None, parent=None)
Create a new greenlet object (without running it).  run is the callable to invoke, and  parent is the parent greenlet, which defaults to the current greenlet.
greenlet.getcurrent()
Returns the current greenlet (i.e. the one which called this function).
greenlet.GreenletExit
This special exception does not propagate to the parent greenlet; it can be used to kill a single greenlet.

The greenlet type can be subclassed, too. A greenlet runs by calling its run attribute, which is normally set when the greenlet is created; but for subclasses it also makes sense to define a runmethod instead of giving a run argument to the constructor.

Switching

Switches between greenlets occur when the method switch() of a greenlet is called, in which case execution jumps to the greenlet whose switch() is called, or when a greenlet dies, in which case execution jumps to the parent greenlet. During a switch, an object or an exception is “sent” to the target greenlet; this can be used as a convenient way to pass information between greenlets. For example:

def test1(x, y):
    z = gr2.switch(x+y)
    print z

def test2(u):
    print u
    gr1.switch(42)

gr1 = greenlet(test1)
gr2 = greenlet(test2)
gr1.switch("hello", " world")

This prints “hello world” and 42, with the same order of execution as the previous example. Note that the arguments of test1() and test2() are not provided when the greenlet is created, but only the first time someone switches to it.

Here are the precise rules for sending objects around:

g.switch(*args, **kwargs)
Switches execution to the greenlet  g, sending it the given arguments. As a special case, if g did not start yet, then it will start to run now.
Dying greenlet
If a greenlet’s  run() finishes, its return value is the object sent to its parent. If  run()terminates with an exception, the exception is propagated to its parent (unless it is a greenlet.GreenletExit exception, in which case the exception object is caught and  returned to the parent).

Apart from the cases described above, the target greenlet normally receives the object as the return value of the call to switch() in which it was previously suspended. Indeed, although a call to switch() does not return immediately, it will still return at some point in the future, when some other greenlet switches back. When this occurs, then execution resumes just after the switch()where it was suspended, and the switch() itself appears to return the object that was just sent. This means that x = g.switch(y) will send the object y to g, and will later put the (unrelated) object that some (unrelated) greenlet passes back to us into x.

Note that any attempt to switch to a dead greenlet actually goes to the dead greenlet’s parent, or its parent’s parent, and so on. (The final parent is the “main” greenlet, which is never dead.)

Methods and attributes of greenlets

g.switch(*args, **kwargs)
Switches execution to the greenlet  g. See above.
g.run
The callable that  g will run when it starts. After  g started, this attribute no longer exists.
g.parent
The parent greenlet. This is writeable, but it is not allowed to create cycles of parents.
g.gr_frame
The current top frame, or None.
g.dead
True if  g is dead (i.e. it finished its execution).
bool(g)
True if  g is active, False if it is dead or not yet started.
g.throw([typ, [val, [tb]]])

Switches execution to the greenlet g, but immediately raises the given exception in g. If no argument is provided, the exception defaults to greenlet.GreenletExit. The normal exception propagation rules apply, as described above. Note that calling this method is almost equivalent to the following:

def raiser():
    raise typ, val, tb
g_raiser = greenlet(raiser, parent=g)
g_raiser.switch()

except that this trick does not work for the greenlet.GreenletExit exception, which would not propagate from g_raiser to g.

Greenlets and Python threads

Greenlets can be combined with Python threads; in this case, each thread contains an independent “main” greenlet with a tree of sub-greenlets. It is not possible to mix or switch between greenlets belonging to different threads.

Garbage-collecting live greenlets

If all the references to a greenlet object go away (including the references from the parent attribute of other greenlets), then there is no way to ever switch back to this greenlet. In this case, a GreenletExit exception is generated into the greenlet. This is the only case where a greenlet receives the execution asynchronously. This gives try:finally: blocks a chance to clean up resources held by the greenlet. This feature also enables a programming style in which greenlets are infinite loops waiting for data and processing it. Such loops are automatically interrupted when the last reference to the greenlet goes away.

The greenlet is expected to either die or be resurrected by having a new reference to it stored somewhere; just catching and ignoring the GreenletExit is likely to lead to an infinite loop.

Greenlets do not participate in garbage collection; cycles involving data that is present in a greenlet’s frames will not be detected. Storing references to other greenlets cyclically may lead to leaks.

Tracing support

Standard Python tracing and profiling doesn’t work as expected when used with greenlet since stack and frame switching happens on the same Python thread. It is difficult to detect greenlet switching reliably with conventional methods, so to improve support for debugging, tracing and profiling greenlet based code there are new functions in the greenlet module:

greenlet.gettrace()
Returns a previously set tracing function, or None.
greenlet.settrace(callback)

Sets a new tracing function and returns a previous tracing function, or None. The callback is called on various events and is expected to have the following signature:

def callback(event, args):
    if event == 'switch':
        origin, target = args
        # Handle a switch from origin to target.
        # Note that callback is running in the context of target
        # greenlet and any exceptions will be passed as if
        # target.throw() was used instead of a switch.
        return
    if event == 'throw':
        origin, target = args
        # Handle a throw from origin to target.
        # Note that callback is running in the context of target
        # greenlet and any exceptions will replace the original, as
        # if target.throw() was used with the replacing exception.
        return

For compatibility it is very important to unpack args tuple only when event is either 'switch'or 'throw' and not when event is potentially something else. This way API can be extended to new events similar to sys.settrace().

C API Reference

Greenlets can be created and manipulated from extension modules written in C or C++, or from applications that embed Python. The greenlet.h header is provided, and exposes the entire API available to pure Python modules.

Types

Type name Python name
PyGreenlet greenlet.greenlet

Exceptions

Type name Python name
PyExc_GreenletError greenlet.error
PyExc_GreenletExit greenlet.GreenletExit

Reference

PyGreenlet_Import()
A macro that imports the greenlet module and initializes the C API. This must be called once for each extension module that uses the greenlet C API.
int PyGreenlet_Check(PyObject *p)
Macro that returns true if the argument is a PyGreenlet.
int PyGreenlet_STARTED(PyGreenlet *g)
Macro that returns true if the greenlet  g has started.
int PyGreenlet_ACTIVE(PyGreenlet *g)
Macro that returns true if the greenlet  g has started and has not died.
PyGreenlet *PyGreenlet_GET_PARENT(PyGreenlet *g)
Macro that returns the parent greenlet of  g.
int PyGreenlet_SetParent(PyGreenlet *g)
Set the parent greenlet of  g. Returns 0 for success. If -1 is returned, then  g is not a pointer to a PyGreenlet, and an AttributeError will be raised.
PyGreenlet *PyGreenlet_GetCurrent(void)
Returns the currently active greenlet object.
PyGreenlet *PyGreenlet_New(PyObject *run, PyObject *parent)
Creates a new greenlet object with the callable  run and parent  parent. Both parameters are optional. If  run is NULL, then the greenlet will be created, but will fail if switched in. If  parentis NULL, the parent is automatically set to the current greenlet.
PyObject *PyGreenlet_Switch(PyGreenlet *g, PyObject *args, PyObject *kwargs)
Switches to the greenlet  g.  args and  kwargs are optional and can be NULL. If  args is NULL, an empty tuple is passed to the target greenlet. If kwargs is NULL, no keyword arguments are passed to the target greenlet. If arguments are specified,  args should be a tuple and  kwargs should be a dict.
PyObject *PyGreenlet_Throw(PyGreenlet *g, PyObject *typ, PyObject *val, PyObject *tb)
Switches to greenlet  g, but immediately raise an exception of type  typ with the value  val, and optionally, the traceback object  tb.  tb can be NULL.

Indices and tables

Agv、Rgv 车辆控制调度系统开发第一篇 Agv、Rgv 车辆控制调度系统第一篇为什么要做这个系统先看作品从头讲起算法讲解编程语言从哪里开始继续深入预告 为什么要做这个系统 说白了是为了赚钱,在一个项目中发现公司买别人家的调度系统要几十万,还只是一个项目的实施,从那天起我就决定自己写一套,用了一年的时间写出来后,才发现根本卖不掉,卖不掉就卖不掉吧,反正我现在已经吧写这套系统当成了一种乐趣,如果不让我写了我反而不适应,但是没有人欣赏我的成果我反而很难受,所以决定吧这个系统的创作过程,写下来,给后面的人一些建议,少走点弯路。 先看作品 从头讲起 在 阅读详情

相关推荐

xenomai内核解析--嵌入式实时linux概述

Linux系统作为一个GPOS(通用操作系统)发展至今已经非常成熟可靠了,并且由于遵循GPL协议,开放所有系统源代码,非常易于裁剪。更重要的是,与其他开源的GPOS或RTOS相比,Linux系统支持多种处理器、开发板,提供多种软件开发工具,同时Linux系统对网络和图形界面的支持非常出色。显然,选择Linux操作系统在产品的开发周期和成本控制方面都有巨大优势。 虽然Linux系统功能强大、实用性强...

wsg1100 3709

零信任架构实战:基于天远租凭分期报告构建自动化数码租赁免押授信网关

破解高端数码免押租赁风控痛点:从传统押金防线到多维资信报告全维数据穿透 在专业影视拍摄器材(如全画幅微单、电影级变焦镜头、专业航拍无人机)以及高端 3C 消费电子(如旗舰折叠屏手机、高性能移动工作站)的先享后付、信用免押分期租赁业务中,对申请承租人的多维信用资信展开严密前置审查与动态免押额度测算,是租赁平台防范潜在履约风险、保障高价值硬件资产安全并实现精细化

2501_94041864的博客 210

如何实现三种不同RAM?(单端口RAM、伪双端口RAM、真双端口RAM|verilog代码|Testbench|仿真结果)

RAM(随机存取存储器)是计算机系统中的一种主要存储器件,用于存储和读取数据。在RAM中,单端口RAM(Single-port RAM)和双端口RAM(Dual-port RAM)是两种常见的类型,双端口RAM又分为真双端口(True dual-port RAM)和伪双端口RAM(Simple dual-port RAM)。那么什么是单端口和双端口?又该如何区分真双端口和伪双端口?输入只有一组数据线和一组地址线,读写共用地址线,输出只有一个端口。

Loudrs的博客 1万+

Memory Over Maps 论文讲解系列四:视觉记忆提取器SigLIP2

本文基于SigLIP2视觉模型,通过特征提取与FAISS向量索引实现机器人对历史关键帧的高效语义检索。作者设计统一接口的BaseFeatureExtractor基类,结合注册机制支持多模型扩展;具体实现中,SigLIP2FeatureExtractor将图像转为语义向量,经归一化后存入FAISS,支持快速相似度匹配。最终,系统可依据目标物体描述,从视觉记忆库中检索出最相关的Top-K关键帧,完成从“存储”到“按需检索”的关键跃迁。

snowful_world的博客 373

ubuntu20.04下dsp-slam的运行配置

DSP-SLAM:具有深度形状先验的面向对象的 SLAM

baidu_38431960的博客 3170

Chkdsk误删文件?5步教你从FOUND.000文件夹找回重要数据(附工具推荐)

本文详细介绍了当Chkdsk误删文件后,如何从FOUND.000文件夹中找回重要数据的5个步骤。包括理解Chkdsk与FOUND.000的关系、定位与访问FOUND.000文件夹、手动恢复CHK文件的技巧、使用UnCHK工具自动化恢复以及预防数据丢失的关键措施。适用于Windows用户解决数据丢失问题,特别是NTFS文件系统下的文件恢复。

weixin_30687051的博客 407

Python笔记(二十)--Flask(三)

 这一节了解一下Flask进阶其他的知识,主要涉及配置,上下文,文件上传下载等,这些是项目中常使用...

ljt2724960661的博客 226

【WRF-Chem教程第四期上】运行 WRF-Chem 模型

完整介绍运行 WRF-Chem 模型的详细步骤

WW、forever的博客 3123

[项目]-从一个简单的例子体验模型训练,标注,部署,验证

可以。我给你做一个Ubuntu 下可以直接运行的轻量级 AI 图像识别 Demo。这个 Demo 不需要摄像头、不需要自己写神经网络,也不需要 GPU。先用 CPU 就能运行。我们采用 Python + PyTorch + YOLO11n。YOLO11n 是轻量级目标检测模型,已经预训练好了,可以直接识别人、汽车等物体。我们先把基础 Demo 跑起来。

jjjxxxhhh123的博客 278

Python 爬虫实战:爬取 Bing 搜索功能链接(国际搜索引擎数据采集技巧)

在当今数字化信息爆炸的时代,搜索引擎已成为我们获取知识、了解世界的得力助手。Bing,作为全球知名的搜索引擎之一,拥有庞大的数据索引和精准的搜索算法。通过 Python 爬虫技术爬取 Bing 搜索区域的链接信息,不仅能帮助我们快速收集大量有价值的数据,还能为后续的数据分析、内容挖掘等任务提供丰富的素材。

yansideyucsdn的博客 1342

手把手教你玩转服务器芯片架构​专栏--​​3.5 实战案例:用SystemC搭建一个多核服务器芯片的NoC模型(含流量分配与延迟仿真)​

通过SystemC搭建多核NoC模型,可深入验证流量分配策略与延迟特性。实际工程中需结合FPGA原型验证(如Xilinx Alveo)进行时序收敛分析,并通过参数化设计适配不同服务器芯片需求。

MHD0815的博客 3052

beaTunes 6.0.3 完整中文化实践:界面 + 帮助本地化、一个可回退的离线包,外加一次不靠调内存的卡顿优化

本文基于beaTunes 6.0.3,通过修改资源包与覆盖帮助目录,实现界面1646/1674键、帮助27页全中文(界面约98%、帮助100%),仅剩搜索索引因技术限制未汉化。不修改class文件,避免风险。通过PowerShell脚本安全注入语言包、覆盖HTML内容,并保留完整备份与回退机制。实测表明,软件卡顿非内存不足,无需调整-Xmx,关键在于正确配置JVM参数。强调操作需在正版授权下进行,禁止分发修改版,确保安全可控。

wdhuag的博客 250

跳蛛优化算法(JSOA)详解:从生物启发到算法实现

摘要: 跳蛛优化算法(JSOA)是一种受跳蛛狩猎行为启发的元启发式优化算法,通过模拟跳蛛的搜索猎物、迫害行为、跳跃捕食和信息素通信四种策略实现高效寻优。算法将跳蛛个体位置映射为候选解,利用物理学模型(匀加速运动、抛射轨迹)和随机策略(柯西分布、信息素机制)平衡全局探索与局部开发。JSOA具有参数少、收敛快的特点,适用于函数优化、路径规划等领域,其生物行为与数学抽象的对应关系(如表1所示)是其核心创新点。

qq_42212808的博客 133

Spring Boot + LangChain4j 实战多模态:上传截图、流式输出、单 Jar 部署全流程

本文介绍一个纯Java实现的截图转文字Demo,基于JDK21 + Spring Boot 3.5.16 + LangChain4j 1.20.2 + Vue3,支持灵活传参、流式输出与Markdown自动折叠。无需Python或GPU,仅通过云端多模态接口即可完成图像理解与文本生成。重点解决接口变更、流式调用、图片压缩、并发限流等实战坑点,强调Java在多模态场景下的可行性与工程优势。源码已开源,一键运行即可体验。

sch7979的博客 660

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

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

SoduWork 项目测评初体验

这次排查的路径是「运行 → 异常行为 → 源码 → 修复 → 再运行验证」,而不是「通读源码找问题」。实测那条 200 响应的价值在于:它把三个原本各看各合理的文件钉在了一条因果链上,也让空口令短路、PBKDF2 随机 salt 导致等式探测失效这类"不跑就想不到"的坑提前暴露出来。文中提到的所有源码位置均来自 Fork 仓库的分支,欢迎对照阅读。SoduWork · 让 AI 的能力成为企业的生产力。

Nothing 340

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

每日 AI 研究简报 · 2026-11-22

Lean/Mathlib 独立复核 Claude 辅助的黎曼证明,Google 用 microVM 与按需工具加载把 Agent 变成可审计工程;与此同时,端侧开源、语音计费与行业智能体把能力兑现为可计量的成本与场景。

:: Dotnet Fantasy :: 2871

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

【AI实战】ffmpeg-skill中文版使用教程:让Claude Code自己剪视频的42个工具怎么用

ffmpeg-skill 中文版把文档中文化这件事做了,降低的是阅读门槛,不是技术门槛。技术门槛还在——你得有本地 ffmpeg,得用支持 Agent Skill 的客户端,得接受它是一套工作流而不是一个按钮。我的样本不多,这个中文版刚发布,实际用起来的稳定性还有待观察。但就「让 Agent 自己剪片并自查」这个方向而言,42 个工具加机器可读契约的组合,是目前我看到比较务实的做法。想试的话,从开始,拿一段手机素材跑一遍 probe,比读十篇介绍都管用。

yangshun的博客 237

OpenAI Agents SDK 语音能聊却没有追踪:先查这一个字段

Agents SDK 升到 0.26.0 后,语音正常但看不到追踪?先确认客户端有没有发出 session.tracing,再用两次开关对照排查自定义追踪提供器。

m0_68880377的博客 216

MCP 服务器连上了却 0 个工具:先查 stdout

客户端显示 connected,tools/list 却返回空数组。问题常常不在工具注册,而在 stdout 混入了日志,破坏了按行分隔的 JSON-RPC 流。本文用最小复现定位,给出正确写法和一条自查命令。

撸码猿的博客 306

818 个技能、六套框架、一张映射表:拆 Anthropic-Cybersecurity-Skills 1.3.0 的交叉映射与验证体系

凌晨三点,SOC 值班的分析师收到一封用户转发的邮件:发件人写着公司 IT,链接点进去却是另一个域名。值班的人把邮件丢给 AI agent,agent 的第一反应不是去查 SPF、DKIM 和 Received 链,而是反问一句:你想让我查什么?这不是模型笨,是它手里没有 playbook。安全分析这个行当,知识全是散的:钓鱼邮件该按什么顺序查、DPAPI 主密钥离线怎么解、ATT&CK 的 T1555.004 对应哪几条检测规则——这些东西不在模型的权重里,至少不在能直接用的形态里。

Science prince的博客 225

End-to-End Autonomous Generation of Human Assembly Plans

ReadMe:AssembleX 会分析一个由多个零件组成的 CAD 装配体(例如由 AI CAD 工具生成的),并找出其组装方法。如果可以组装,AssembleX 会生成一份带插图的装配手册;如果无法组装,它会说明是哪一个零件导致了问题,以及需要进行哪些修改。对于每个装配体,它会:1. 检查零件。每个零件都必须是封闭的实体;微小间隙会自动修复,而重叠的零件会被报告出来。2. 规划装配顺序。

Zlzxzw的博客 213

股票财务数据分析Python实战:从财务接口到基本面因子宽表(第 21 篇):缓存与失效管理

第 20 篇把物化到,并用判断"这次要不要重建"。可回测逐日取截面时,同一个热点as_of、同一批端点记录仍会被反复读出、反复反序列化;财报一旦修订,已物化的截面又可能悄悄过期。问题从"怎么建"变成了"怎么存、什么时候必须丢"。本篇在快照之上加一层,把命中、过期、主动清除做成三层策略,再用财报修订与快照build_id驱动,最后用事件日志统计命中率。

2601_96840033的博客 171

JSON 格式化怎么把订单号改了?用 Node 和 Python 复现大整数精度丢失

本文揭示了JSON格式化工具中因JavaScript Number类型精度限制导致大整数(如订单号9007199254740993)被错误解析为9007199254740992的问题。通过Node.js与Python复现,说明JSON.parse默认将数字转为双精度浮点数,超出2^53-1范围后会丢失精度。解决方案是:接口契约中将订单号等大整数字段定义为字符串,避免自动转换;测试时应校验原始响应文本,确保数字字面量完整无损。建议使用BigInt或字符串形式处理大整数,并在消费者端添加断言测试,保障数据一致性

JavaPub 214

用 Python 和 GeoJSON 批量判断坐标属于哪个街道

本文介绍一个离线命令行工具,利用北京市海淀区行政边界GeoJSON与点位CSV,通过精确几何判断为每个点匹配唯一街道编码。工具采用有理数运算确保坐标计算精度,识别点在面内、边界或外部,并区分唯一命中、共边、重叠等情形。结果保留可靠匹配项,将需人工核对的异常点(如多归属、边界点)标记输出,实现高效、可追溯的空间归属补全。

HashTang的博客 197

FPGA UART 接收实战:波特率误差怎么算?用 8N1 背靠背帧复现停止位错误

本文通过8N1 UART背靠背帧模型,分析波特率误差对停止位采样的影响。基于50 MHz系统时钟与115200 baud的分频计算,揭示接收端实际速率偏差约−0.467%,导致采样点偏移。利用Python仿真验证:周期误差+6%时,停止位误采至下一帧起始位,引发帧错误;−6%则提前采到前一帧数据位。实验表明,单帧空闲会掩盖停止位错误,而连续发送可暴露边界问题。建议在FPGA中通过采样使能间隔、起始相位扫描和双帧对比进行自检,确保收发容差在±5.3%以内。

s0907136的博客 773

2026华为OD机考真题|物流配送路线规划(2026.10.14)模拟解析与多语言代码

本文解析2026华为OD机考真题《物流配送路线规划》(2026.10.14,100分,模拟)。枚举起点模拟环形配送,将油量统一乘100用整数运算并按2*r>=total四舍五入,时间O(N²),空间O(1)。注意按卸货、加油截断、扣油顺序执行。20组测试点免费评测及四语言代码见CodeSeeking(codeseeking.com/problem/OD_1225)。

be_Newcode的博客 335
上一篇: 多线程让可扩展性走进了死胡同
下一篇: python greenlet背景介绍与实现机制
offbye
offbye 领域专家: 操作系统技术领域 领域专家: 操作系统技术领域
博客等级 码龄24年 1309粉丝 252原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址