用Python实现简单的Rust风格类型检查

Rust生态下的PDF处理:Pdf-inspector实现检查、分类与文本提取 PDF解析是文档处理中的基础能力,但传统脚本化方案在面对海量不可信文件时,常暴露出文本乱序、结构混杂、安全风险等问题。Rust语言凭借内存安全与高性能,正在成为构建可靠PDF处理链路的优选。Pdf-inspector作为Rust实现的检查、分类与文本提取库,将PDF处理从脆弱的脚本逻辑推向工程化组件。它先通过inspection获取文档画像,包括页数、字体、元数据及内嵌动作;再基于规则进行内容分类,区分发票、简历或合同;最后按需提取文本,为搜索索引、内容审核等场景提供结构化输入。本文解析PDF格式难点,演示 阅读详情

用Python实现简单的Rust风格类型检查

前言

大家好,我是第一程序员(名字大,人很菜)。作为一个正在学习Rust的转码萌新,我非常喜欢Rust的类型系统。最近,我开始学习Python,发现Python的动态类型虽然灵活,但也容易导致运行时错误。今天我想分享一下如何在Python中实现简单的Rust风格类型检查。

一、Rust类型系统的优势

1.1 Rust类型系统的特点

Rust的类型系统有以下特点:

  • 静态类型:在编译时检查类型
  • 类型推断:自动推断变量类型
  • 所有权系统:通过所有权和借用检查器,在编译时就避免内存错误
  • 模式匹配:强大的模式匹配能力

1.2 Python类型系统的特点

Python的类型系统有以下特点:

  • 动态类型:在运行时检查类型
  • 类型提示:Python 3.5+支持类型提示
  • 灵活性:变量可以随时改变类型
  • 简洁性:代码更加简洁易读

二、Python中的类型提示

2.1 基本类型提示

Python 3.5+支持使用类型提示来标注变量类型:

# 基本类型提示
def add(a: int, b: int) -> int:
    return a + b

# 列表类型提示
from typing import List
def process_numbers(numbers: List[int]) -> List[int]:
    return [n * 2 for n in numbers]

# 字典类型提示
from typing import Dict
def get_user_info(user_id: int) -> Dict[str, str]:
    return {"id": str(user_id), "name": "张三"}

2.2 类型提示的局限性

Python的类型提示有以下局限性:

  • 可选性:类型提示是可选的,不会影响代码的运行
  • 运行时检查:默认情况下,类型提示不会在运行时进行检查
  • 复杂类型:对于复杂类型,类型提示可能变得复杂

三、实现Rust风格的类型检查

3.1 使用mypy进行静态类型检查

mypy是一个静态类型检查器,可以在编译时检查Python代码的类型:

# 安装mypy
pip install mypy

# 检查代码
mypy your_code.py

3.2 实现运行时类型检查

我们可以使用装饰器来实现运行时类型检查:

from typing import get_type_hints, Union
import inspect

def type_check(func):
    """类型检查装饰器"""
    def wrapper(*args, **kwargs):
        # 获取函数的类型提示
        type_hints = get_type_hints(func)
        
        # 检查位置参数
        sig = inspect.signature(func)
        params = list(sig.parameters.values())
        
        # 检查位置参数类型
        for i, (param_name, arg_value) in enumerate(zip(params, args)):
            if param_name in type_hints:
                expected_type = type_hints[param_name]
                if not isinstance(arg_value, expected_type):
                    raise TypeError(f"参数 {param_name} 期望类型 {expected_type},实际类型 {type(arg_value)}")
        
        # 检查关键字参数类型
        for param_name, arg_value in kwargs.items():
            if param_name in type_hints:
                expected_type = type_hints[param_name]
                if not isinstance(arg_value, expected_type):
                    raise TypeError(f"参数 {param_name} 期望类型 {expected_type},实际类型 {type(arg_value)}")
        
        # 执行函数
        result = func(*args, **kwargs)
        
        # 检查返回值类型
        if 'return' in type_hints:
            expected_return_type = type_hints['return']
            if not isinstance(result, expected_return_type):
                raise TypeError(f"返回值期望类型 {expected_return_type},实际类型 {type(result)}")
        
        return result
    
    return wrapper

# 使用装饰器
@type_check
def add(a: int, b: int) -> int:
    return a + b

# 测试
print(add(1, 2))  # 正常运行
print(add(1, "2"))  # 抛出类型错误

3.3 实现更复杂的类型检查

我们可以扩展类型检查装饰器,支持更复杂的类型:

from typing import get_type_hints, Union, List, Dict, Optional, TypeVar, Generic
import inspect
import typing

T = TypeVar('T')

class TypeChecker:
    """类型检查器"""
    
    @staticmethod
    def is_instance(obj, expected_type):
        """检查对象是否符合期望类型"""
        # 处理基本类型
        if isinstance(expected_type, type):
            return isinstance(obj, expected_type)
        
        # 处理Union类型
        if getattr(expected_type, '__origin__', None) is Union:
            return any(TypeChecker.is_instance(obj, arg) for arg in expected_type.__args__)
        
        # 处理List类型
        if getattr(expected_type, '__origin__', None) is list or getattr(expected_type, '__origin__', None) is List:
            if not isinstance(obj, list):
                return False
            item_type = expected_type.__args__[0]
            return all(TypeChecker.is_instance(item, item_type) for item in obj)
        
        # 处理Dict类型
        if getattr(expected_type, '__origin__', None) is dict or getattr(expected_type, '__origin__', None) is Dict:
            if not isinstance(obj, dict):
                return False
            key_type, value_type = expected_type.__args__
            return all(
                TypeChecker.is_instance(key, key_type) and TypeChecker.is_instance(value, value_type)
                for key, value in obj.items()
            )
        
        # 处理Optional类型
        if getattr(expected_type, '__origin__', None) is Optional:
            if obj is None:
                return True
            return TypeChecker.is_instance(obj, expected_type.__args__[0])
        
        return True

def type_check(func):
    """类型检查装饰器"""
    def wrapper(*args, **kwargs):
        # 获取函数的类型提示
        type_hints = get_type_hints(func)
        
        # 检查位置参数
        sig = inspect.signature(func)
        params = list(sig.parameters.values())
        
        # 检查位置参数类型
        for i, (param_name, arg_value) in enumerate(zip(params, args)):
            if param_name in type_hints:
                expected_type = type_hints[param_name]
                if not TypeChecker.is_instance(arg_value, expected_type):
                    raise TypeError(f"参数 {param_name} 期望类型 {expected_type},实际类型 {type(arg_value)}")
        
        # 检查关键字参数类型
        for param_name, arg_value in kwargs.items():
            if param_name in type_hints:
                expected_type = type_hints[param_name]
                if not TypeChecker.is_instance(arg_value, expected_type):
                    raise TypeError(f"参数 {param_name} 期望类型 {expected_type},实际类型 {type(arg_value)}")
        
        # 执行函数
        result = func(*args, **kwargs)
        
        # 检查返回值类型
        if 'return' in type_hints:
            expected_return_type = type_hints['return']
            if not TypeChecker.is_instance(result, expected_return_type):
                raise TypeError(f"返回值期望类型 {expected_return_type},实际类型 {type(result)}")
        
        return result
    
    return wrapper

# 使用装饰器
@type_check
def process_data(data: List[int]) -> Dict[str, Union[int, str]]:
    return {
        "sum": sum(data),
        "count": len(data),
        "status": "success"
    }

# 测试
print(process_data([1, 2, 3]))  # 正常运行
print(process_data([1, "2", 3]))  # 抛出类型错误

四、实现Rust风格的Result类型

4.1 Rust的Result类型

在Rust中,Result类型用于表示可能失败的操作:

enum Result<T, E> {
    Ok(T),
    Err(E),
}

4.2 在Python中实现Result类型

我们可以在Python中实现类似的Result类型:

from typing import Generic, TypeVar, Union, Optional

T = TypeVar('T')
E = TypeVar('E')

class Result(Generic[T, E]):
    """Rust风格的Result类型"""
    
    def __init__(self, value: Union[T, E], is_ok: bool):
        self.value = value
        self._is_ok = is_ok
    
    @classmethod
    def ok(cls, value: T) -> 'Result[T, E]':
        """创建成功的Result"""
        return cls(value, True)
    
    @classmethod
    def err(cls, error: E) -> 'Result[T, E]':
        """创建失败的Result"""
        return cls(error, False)
    
    def is_ok(self) -> bool:
        """检查是否成功"""
        return self._is_ok
    
    def is_err(self) -> bool:
        """检查是否失败"""
        return not self._is_ok
    
    def unwrap(self) -> T:
        """获取成功值,如果失败则抛出异常"""
        if self.is_ok():
            return self.value
        raise ValueError(f"Result is Err: {self.value}")
    
    def unwrap_err(self) -> E:
        """获取错误值,如果成功则抛出异常"""
        if self.is_err():
            return self.value
        raise ValueError("Result is Ok")
    
    def unwrap_or(self, default: T) -> T:
        """获取成功值,如果失败则返回默认值"""
        if self.is_ok():
            return self.value
        return default

# 使用Result类型
def divide(a: int, b: int) -> Result[int, str]:
    if b == 0:
        return Result.err("除数不能为零")
    return Result.ok(a // b)

# 测试
result = divide(10, 2)
if result.is_ok():
    print(f"结果: {result.unwrap()}")
else:
    print(f"错误: {result.unwrap_err()}")

result = divide(10, 0)
if result.is_ok():
    print(f"结果: {result.unwrap()}")
else:
    print(f"错误: {result.unwrap_err()}")

五、实现Rust风格的Option类型

5.1 Rust的Option类型

在Rust中,Option类型用于表示可能不存在的值:

enum Option<T> {
    Some(T),
    None,
}

5.2 在Python中实现Option类型

我们可以在Python中实现类似的Option类型:

from typing import Generic, TypeVar, Optional

T = TypeVar('T')

class Option(Generic[T]):
    """Rust风格的Option类型"""
    
    def __init__(self, value: Optional[T], is_some: bool):
        self.value = value
        self._is_some = is_some
    
    @classmethod
    def some(cls, value: T) -> 'Option[T]':
        """创建有值的Option"""
        return cls(value, True)
    
    @classmethod
    def none(cls) -> 'Option[T]':
        """创建无值的Option"""
        return cls(None, False)
    
    def is_some(self) -> bool:
        """检查是否有值"""
        return self._is_some
    
    def is_none(self) -> bool:
        """检查是否无值"""
        return not self._is_some
    
    def unwrap(self) -> T:
        """获取值,如果无值则抛出异常"""
        if self.is_some():
            return self.value
        raise ValueError("Option is None")
    
    def unwrap_or(self, default: T) -> T:
        """获取值,如果无值则返回默认值"""
        if self.is_some():
            return self.value
        return default

# 使用Option类型
def find_user(user_id: int) -> Option[dict]:
    users = {1: {"id": 1, "name": "张三"}, 2: {"id": 2, "name": "李四"}}
    if user_id in users:
        return Option.some(users[user_id])
    return Option.none()

# 测试
user = find_user(1)
if user.is_some():
    print(f"用户: {user.unwrap()}")
else:
    print("用户不存在")

user = find_user(3)
if user.is_some():
    print(f"用户: {user.unwrap()}")
else:
    print("用户不存在")

六、从Rust开发者角度的思考

6.1 为什么要在Python中实现Rust风格的类型检查

作为一个Rust开发者,我认为在Python中实现Rust风格的类型检查有以下好处:

  • 提高代码可靠性:通过类型检查,可以在运行时捕获类型错误
  • 改善代码可读性:类型提示使代码更加清晰易读
  • 便于维护:类型信息有助于理解代码的意图
  • 平滑过渡:对于从Rust转向Python的开发者,这种方式可以让他们更容易适应

6.2 局限性

当然,在Python中实现Rust风格的类型检查也有一些局限性:

  • 运行时开销:类型检查会增加运行时开销
  • 代码复杂度:需要额外的代码来实现类型检查
  • 灵活性降低:静态类型检查会降低Python的灵活性

七、总结

通过实现Rust风格的类型检查、Result类型和Option类型,我们可以在Python中获得一些Rust类型系统的优势,同时保留Python的灵活性。

作为一个Rust转Python的开发者,我认为这种方式可以帮助我们写出更可靠、更易维护的Python代码。当然,我们也需要在类型安全和灵活性之间找到平衡点。

保持学习,保持输出。虽然现在我还是个菜鸡,但我相信只要坚持,总有一天能成为真正的「第一程序员」!

大白话,Android Studio安装及其资源分享(离线gradle配置) 安装AndroidAtudio,并通过aliClound镜像与离线gradle配置,来跳过相对“繁文缛节”的过程,直接实现开发 阅读详情

相关推荐

2026年AI技能进阶指南:从提示词工程到智能体开发实战

提示词工程作为AI时代的基础沟通技能,其核心原理是通过系统化的交互方法论实现与大模型的高效对话。这项技术通过明确性、具体性和可操作性的设计原则,显著提升了AI生成内容的质量和实用性。在工程实践层面,提示词工程已经发展出角色扮演、步骤分解等成熟模式,广泛应用于代码生成、技术方案设计等场景。随着AI智能体开发的兴起,提示词工程进一步演化为定义智能体身份认知和行为规范的系统接口设计,成为构建自主AI系统的关键技术基础。掌握从基础提示词到智能体开发的完整技能栈,能够帮助开发者在AI技术浪潮中保持核心竞争力。

weixin_33139275的博客 337

Python中实现Rust风格类型检查的实践指南

类型系统是现代编程语言的核心特性之一,静态类型检查能在编译期捕获大多数错误,显著提升代码可靠性。Python作为动态语言,通过类型提示(Type Hints)和mypy工具逐步引入了静态类型检查能力。本文探讨如何借鉴Rust的所有权机制和模式匹配等特性,在Python中构建更强大的类型安全体系。通过实现Result和Option等Rust核心类型,结合装饰器和泛型等Python特性,开发者可以在保持Python灵活性的同时获得类似Rust的类型安全保障。这种混合式类型系统特别适合大型Python项目的维护和

weixin_31364787的博客 298

非易失存储器读写

24C256、IIC_SCL、IIC_SDA

CT_1104的专栏 2991

Python实现Rust风格类型检查器的工程实践

类型检查是现代编程语言的核心机制,能在编译或运行阶段预防数据类型错误。静态类型语言如Rust通过编译器保证类型安全,而Python等动态语言通常依赖运行时检查。通过结合装饰器模式与泛型编程,可以实现类似Rust的Result类型和编译时类型检查效果。这种技术特别适用于数据处理管道和API边界验证,能有效减少TypeError等运行时异常。文中实现的类型检查器支持联合类型、泛型容器等高级特性,并提供了与mypy静态检查工具的组合使用方案。

weixin_31456563的博客 222

手把手教你用Python+GDAL处理0.5米吉林一号卫星影像(附代码)

本文详细介绍了如何使用Python和GDAL处理吉林一号0.5米高分辨率卫星影像,包括环境配置、数据预处理、分辨率融合、植被指数计算及地物分类等关键步骤。通过实战代码示例,帮助开发者高效处理大尺寸遥感数据,解决资源崩溃和算法选择问题,提升遥感影像分析能力。

weixin_30892037的博客 136

避坑指南:Ubuntu 22.04上源码编译Autoware.universe(Humble版)的完整流程与常见错误修复

本文详细介绍了在Ubuntu 22.04上源码编译Autoware.universe(Humble版)的完整流程与常见错误修复方法。从环境准备、依赖安装到编译优化,提供了实用的避坑指南和解决方案,帮助开发者高效完成安装并避免常见问题。特别针对源码安装过程中的疑难杂症给出了具体修复建议。

weixin_33712987的博客 388

Python实现Rust风格类型检查的工程实践

类型系统作为编程语言的核心机制,通过编译期或运行时的类型约束保障代码健壮性。静态类型检查能在开发早期捕获类型错误,而动态语言通常依赖运行时检查。Python通过装饰器与类型注解模拟Rust风格的类型安全,结合typing模块实现泛型、可选类型等高级特性。这种混合方案特别适合金融数据处理等对类型敏感的场景,能减少70%以上的运行时类型错误。关键技术点包括参数/返回值验证、泛型容器递归检查以及性能优化策略,为动态语言项目提供了编译型语言的可靠性优势。

weixin_33423874的博客 297

开源大模型推理GPU资源评估以及优化

随着大模型的火热很多项目中都使用到了开源大模型,这时候准确评估大模型的GPU资源非常重要,主要有下面几个方面:GPU是昂贵的资源。高估内存需求可能导致在硬件上的不必要支出,而低估则可能导致系统故障或性能下降。:适当的内存管理确保模型高效运行,能够更快地响应用户并处理更多并发请求。:随着需求的增长,理解内存需求对于在不牺牲性能或产生高昂成本的情况下扩展服务至关重要。尽管其重要性显而易见,但计算用于服务大型语言模型(LLM)的GPU内存并不简单。

CSDNDN的博客 3134

Python中实现Rust风格类型检查的技术实践

类型系统是现代编程语言的核心机制,通过编译期或运行时的类型检查确保代码健壮性。Python作为动态类型语言,其灵活性常伴随类型安全问题。通过装饰器和描述符机制,可以在运行时实现类似Rust的严格类型约束,包括基础类型验证、泛型容器和自定义结构体。这种技术方案特别适合数据处理管道等对类型敏感的场景,能有效预防80%以上的类型错误。相比Pydantic等现有方案,该实现具有更高性能和精准的错误定位能力,同时保持与Python原生类型提示的兼容性。

weixin_32306957的博客 211

python k线顶分型_【缠论】分型、笔的定义及其程序化

K线包含关系处理和分型的定义如果一个K线的高低点全在另一K线的范围里,称之为包含关系。针对这种K线,需要进行一些处理,去除包含关系,处理方法:向上时,把两K线的高点当高点,而两K线低点中的较高者当成低点;反之,当向下时,把两K线的低点当低点,而两K线高点中的较低者当成高点,这样就把两K线合并成一新的K线。经过这样的处理,所有K线图都可以处理成没有包含关系的图形。两K线的包含关系,可以分成四种:1)...

weixin_39717152的博客 2830

C#项目实战——YModem协议文件传输【实例】

1、先由上位机发送*update*的握手信号,下位机返回响应字符‘C’(字符C,ASII码为0x43),之后通信双方开始以YMODEM协议进行数据通信。2、 YMODEM协议格式说明(1)起始帧数据格式帧类型(1byte)帧序号帧序号反码传输的文件名文件大小数据CRCSOH00FFfilenamefileziseNULCRCSOH=0x01,表示这个数据帧中包含着128个字节的数据(STX表示1024字节,初始帧只有128个);00表示数据帧序号,初始是0,依次向下排。

做有价值的事,积累有价值的笔记! 3661

Zuban深度解析:Rust如何赋能Python类型检查与语言服务

Zuban是一款由Jedi作者使用Rust开发的高性能Python语言服务器和类型检查器,它将Rust的速度优势与Python的易用性完美结合,为开发者提供极速的代码检查体验。 ## 🚀 Rust驱动的性能革命 Zuban凭借Rust语言的内存安全特性和零成本抽象,实现了远超传统Python工具的性能表现: - **速度提升20-200倍**:相比Mypy,Zuban在类型检查任务中展现出压

gitblog_00528的博客 442

Android 14 (AOSP) 源码架构深度解析与开发者指南

Android14源码的仓库指南信息

保持专注,保持热爱 1190

探索Poltergeist:Python中的Rust风格错误处理新星

探索Poltergeist:Python中的Rust风格错误处理新星 在Python开发的浩瀚星辰中,错误处理一直是一个关键但有时又略显笨重的话题。然而,今天我们要探讨的项目——Poltergeist,正是为了解决这一痛点而生,它将Rust编程语言中优雅且高效的错误处理机制引入Python世界,力求在保持Python的简洁性的同时,提升程序的健壮性和代码的可读性。 项目介绍 Poltergeist...

gitblog_00566的博客 453

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...

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

Rust for Python 开发者:掌握 From、Into 与 TryFrom 类型转换(RustTraining 教程)

> 本文是 [RustTraining](https://link.gitcode.com/i/52f706c6fc6d906e938786a22c253b48) 仓库中《Rust for Python Programmers》第 11 章([python-book/src/ch11-from-and-into-traits.md](https://link.gitcode.com/i/d8685

gitblog_00787的博客 861

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

ty 贡献实战指南:Ruff 单仓中 Rust 类型检查器的开发工具链、测试体系与项目结构

本文以 [crates/ty/CONTRIBUTING.md](https://link.gitcode.com/i/f45cd9bc84c57c3d6751ddc5b24913df) 为蓝本,完整还原 ty(Ruff 仓库内置的 Rust 高性能 Python 类型检查器)贡献者的开发闭环:从 Rust 工具链与 uv 开发依赖的安装,到 clippy / 测试 / 格式化的提交前校验,再到 M

gitblog_00514的博客 430

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

PyO3类型转换全解析:FromPyObject与IntoPyObject两大Trait如何打通Rust与Python的数据通道

**PyO3** 是 Rust 生态中与 Python 解释器交互的事实标准绑定库,而它的**类型转换**体系正是连接两个语言世界的"数据通道"。本文带你快速搞懂其中的两大核心 Trait——`FromPyObject` 与 `IntoPyObject`:前者负责把 Python 对象"抽取"成 Rust 类型,后者负责把 Rust 值"送回"Python。读完你既能写对函数参数与返回值,也能避开

gitblog_01072的博客 429

从Rust到Python:如何贡献第一个GitHub开源项目

Polars是一个用Rust编写的高性能数据分析库,比Pandas快10-100倍。贡献GitHub开源项目是一个很好的学习机会,它可以帮助你提升技能,拓展技术视野,同时为社区做出贡献。作为一个从Rust转向Python的开发者,我发现贡献Python项目是一个很好的学习Python生态系统的方式。通过贡献,我不仅学习了Python的最佳实践,还了解了如何与其他开发者合作。保持学习,保持输出。虽然现在我还是个菜鸡,但我相信只要坚持,总有一天能成为真正的「第一程序员」!

no1coder的博客 1万+

Ruff:用Rust重写的Python极速代码检查工具

Ruff:用Rust重写的Python极速代码检查工具 【免费下载链接】ruff 一个极其快速的 Python 代码检查工具和代码格式化程序,用 Rust 编写。 项目地址: https://gitcode.com/GitHub_...

gitblog_00993的博客 428

革命性Python工具Ruff:用Rust重写,速度提升100倍的代码检查神器

你还在忍受Python代码检查工具的缓慢速度吗?当项目规模扩大到数万行代码时,传统工具往往需要几分钟才能完成一次检查,严重拖慢开发节奏。Ruff的出现彻底改变了这一现状——这款用Rust编写的代码检查器和格式化工具,比同类工具快10-100倍,让代码质量检查从负担变成享受。读完本文,你将获得:Ruff的核心优势解析、5分钟快速上手指南、实用配置技巧以及在实际项目中的最佳实践。 ## Ruff的核...

gitblog_00983的博客 920

Ruff 重磅更新:独立类型检查器+智能代码导航,Python开发效率革命

Ruff 是一个极其快速的 Python 代码检查工具和代码格式化程序,用 Rust 编写,专为提升 Python 开发效率而生。最新版本引入了独立类型检查器和智能代码导航功能,为开发者带来了前所未有的开发体验。🚀 ## 为什么选择 Ruff 作为你的 Python 开发助手? Ruff 的设计理念是"速度至上",它能够在瞬间完成代码检查、格式化和类型分析。相比传统的 Python 工具链,

gitblog_01036的博客 380

PyO3 实战指南:用 Rust 过程宏将 Rust 代码包装为 Python 对象

本篇指南以 PyO3 官方文档 [guide/src/rust-from-python.md](https://link.gitcode.com/i/b3eadeb7df1f8f43c2cce9eca08ea7da) 为核心骨架,系统讲解如何借助 Rust 的"过程宏(procedural macros)"机制,把 Rust 代码映射为 Python 对象。文中将覆盖 PyO3 能创建的三大类 P

gitblog_00189的博客 700

Rust 枚举与模式匹配实战:Python 开发者从 Union 类型到穷尽式 match 的迁移指南

> 本指南是 RustTraining 仓库《Rust for Python Programmers》系列第 6 章的技术详解,面向有 Python 经验的开发者,系统讲解 Rust 的代数数据类型(enum + 数据变体)如何取代 Python 的 `Union` 类型与 `match/case`,以及编译器强制的穷尽式匹配如何消灭运行时 `None`/漏分支 Bug。读完本文,你将掌握数据携带

gitblog_00160的博客 959

【Python基础】 15 Rust 与 Python 基本类型对比笔记

特性Rust 🦀Python 🐍核心优势性能、内存安全、并发安全开发速度、灵活性、易学性类型风格显式、精确、严格隐式、通用、灵活适用场景系统编程、性能关键型应用Web开发、数据分析、机器学习简单来说:Rust 给你控制权,但需要你负责;Python 给你便利,但隐藏了细节。

weixin_43219667的博客 556

Open3D 代码风格指南:风格检查工具与 C++/Python 编码规范详解

Open3D 是一个现代 3D 数据处理库,其代码库横跨 C++、CUDA、ISPC、Python 与 Jupyter Notebook 等多种语言。为了让庞大的社区贡献保持一致的代码质量与可读性,Open3D 在 [docs/contribute/styleguide.rst](https://link.gitcode.com/i/d1d7dc7ee252ddd1eed86935816a8e63

gitblog_01137的博客 348

Rust 入门实战:为 Python 开发者准备的安装、Cargo 工具链与首个程序指南

> **导读**:本文是 RustTraining 仓库中《Rust for Python Programmers》入门篇([python-book/src/ch02-getting-started.md](https://link.gitcode.com/i/8358ee4b1d8c4d8b729c45b8c2abfeb8))的完整展开。它以 Python 开发者已有的知识为锚点,系统讲解 Ru

gitblog_00974的博客 760
上一篇: Python性能优化:Rust开发者的性能敏感视角
下一篇: Python系统级工具开发:Rust开发者的视角
第一程序员
博客等级 码龄1年 1万+粉丝 1877原创
评论 38
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值