Linux内核编程接口函数

5.3.3.注册字符设备驱动新接口3 : alloc_chrdev_region 更简便、更智能的方法是让内核给我们自动分配一个主设备号5.3.2.3、中途出错的倒影式错误处理方法 (1)内核中很多函数中包含了很多个操作,这些操作每一步都有可能出错,而且出错后后面的步骤就没有进行下去的必要性了。我们 程序在 设计时 应该 在 某一个 函数出错后, 释放掉 锁占用 的内存 什么的 什么的。(1)使用MAJOR宏和MINOR宏从dev_t得到major和minor。(2)反过来使用MKDEV宏从major和minor得到dev_t。(2)更简便、更智能的方法是让内核给我们自动分配一个主设备号,5.3.2.2、得到分配的主设备号和次设备号。5.3.2.3、中途出错的倒影式错误处理方法。 阅读详情


Linux内核编程接口函数

转载请注明出处: http://blog.csdn.net/drivelinux/article/details/8656280

字符设备相关函数

1.alloc_chrdev_region()

功能: 自动分配一个主设备号及基于此主设备号的若干个连续的指定数量的次设备号。

函数原型如下:

/**
 * alloc_chrdev_region() - register a range of char device numbers
 * @dev: output parameter for first assigned number
 * @baseminor: first of the requested range of minor numbers
 * @count: the number of minor numbers required
 * @name: the name of the associated device or driver
 *
 * Allocates a range of char device numbers.  The major number will be
 * chosen dynamically, and returned (along with the first minor number)
 * in @dev.  Returns zero or a negative error code.
 */
int alloc_chrdev_region(dev_t *dev, unsigned baseminor, unsigned count,const char *name)

2.register_chrdev_region()

功能:注册连续的若干个设备号,用这个函数要自己指定主设备号。

函数原型:

/**
 * register_chrdev_region() - register a range of device numbers
 * @from: the first in the desired range of device numbers; must include
 *        the major number.
 * @count: the number of consecutive device numbers required
 * @name: the name of the device or driver.
 *
 * Return value is zero on success, a negative error code on failure.
 */
int register_chrdev_region(dev_t from, unsigned count, const char *name)

注: register_chrdev() 函数也用于分配设备号,但是用于2.6版本之前的内核中,在之后的版本中不再使用。

3.unregister_chrdev_region()

功能:注销由alloc_chrdev_region()或者register_chrdev_region()注册的设备号,一般在驱动模块的退出函数中要执行此操作,将注册的设备号还给系统。

函数原型:

/**
 * unregister_chrdev_region() - return a range of device numbers
 * @from: the first in the range of numbers to unregister
 * @count: the number of device numbers to unregister
 *
 * This function will unregister a range of @count device numbers,
 * starting with @from.  The caller should normally be the one who
 * allocated those numbers in the first place...
 */
void unregister_chrdev_region(dev_t from, unsigned count)

4.cdev_alloc()

功能:分配一个表示字符设备的cdev结构体。
函数原型:
/**
 * cdev_alloc() - allocate a cdev structure
 *
 * Allocates and returns a cdev structure, or NULL on failure.
 */
struct cdev *cdev_alloc(void)

5.cdev_init()

功能:初始化由cdev_alloc()分配的表示字符设备的cdev结构体,并通过向该函数传入的struct file_operations *fops参数来指定该字符设备的文件操作函数。
函数原型:
/**
 * cdev_init() - initialize a cdev structure
 * @cdev: the structure to initialize
 * @fops: the file_operations for this device
 *
 * Initializes @cdev, remembering @fops, making it ready to add to the
 * system with cdev_add().
 */
void cdev_init(struct cdev *cdev, const struct file_operations *fops)

6.cdev_add()

功能:添加一个(由cdev_alloc()分配并通过cdev_init()初始化的)字符设备到系统中。
函数原型:
/**
 * cdev_add() - add a char device to the system
 * @p: the cdev structure for the device
 * @dev: the first device number for which this device is responsible
 * @count: the number of consecutive minor numbers corresponding to this
 *         device
 *
 * cdev_add() adds the device represented by @p to the system, making it
 * live immediately.  A negative error code is returned on failure.
 */
int cdev_add(struct cdev *p, dev_t dev, unsigned count)

7.cdev_del()

功能:执行和cdev_add()相反的操作,将一个指定的字符设备从系统中删除。
函数原型:
/**
 * cdev_del() - remove a cdev from the system
 * @p: the cdev structure to be removed
 *
 * cdev_del() removes @p from the system, possibly freeing the structure
 * itself.
 */
void cdev_del(struct cdev *p)
以下为一个简单的字符设备初始化函数,函数中列出了向系统中添加一个字符设备的简单步骤:
struct cdev *myDev_dev;
/*主设备和从设备号变量*/
static int myDev_major = 0;
static int myDev_minor = 0;

static int __init myDev_init(void)
{ 
	int err = -1;
	dev_t dev = 0;

	/*1.动态分配主设备号和从设备号,第三个参数表示分配的此设备号的数量*/
	err = alloc_chrdev_region(&dev, 0, TOTAL_DEVICE_COUNT, "myDev");
	if(err < 0) {
		printk(KERN_ALERT"Failed to alloc char dev region.\n");
		return err;
	}

	myDev_major = MAJOR(dev);
	myDev_minor = MINOR(dev);        

	/*2.分配cdev字符设备结构体变量*/
	myDev_dev = cdev_alloc();
	if(!myDev_dev) {
		err = -ENOMEM;
		printk(KERN_ALERT"Failed to alloc myDev_dev.\n");
		return err;
	}        
	/*3.初始化cdev字符设备结构体*/
	cdev_init(myDev_dev, &myDev_fops); 

	/*4.添加字符设备到系统中*/
	err = cdev_add(myDev_dev,dev, TOTAL_DEVICE_COUNT);
	if(err) {
		return err;
	}              
	return err;
}

8.register_chrdev()

这个函数也是实现注册字符设备的功能,但是相对于上面提到的alloc_chrdev_region()和register_chrdev_region()而言,是比较老的形式。并且register_chrdev()一次能够注册统一主设备号下的256个不同的次设备。并且,在2.6之后的内核版本中不再使用这一函数。

自动创建设备节点相关函数

1.class_create()

功能:创建一个struct class结构体,作为device_create()函数的参数。
函数原型:
#define class_create(owner, name)		\
({						\
	static struct lock_class_key __key;	\
	__class_create(owner, name, &__key);	\
})

2.device_create()

功能:该函数创建一个设备并将其注册到sysfs中,同时在系统的sys/class和sys/device目录下会生成相应的类和设备入口。并且,该函数还会出发用户空间udev的动作,udev会根据sysfs下的class在/dev目录下创建设备节点,这也为自动创建设备节点提供了一种途径。通过device_create()函数,我们就可以不用通过mknod命令手动的创建设备节点了。
函数原型:
/**
 * device_create - creates a device and registers it with sysfs
 * @class: pointer to the struct class that this device should be registered to
 * @parent: pointer to the parent struct device of this new device, if any
 * @devt: the dev_t for the char device to be added
 * @drvdata: the data to be added to the device for callbacks
 * @fmt: string for the device's name
 *
 * This function can be used by char device classes.  A struct device
 * will be created in sysfs, registered to the specified class.
 *
 * A "dev" file will be created, showing the dev_t for the device, if
 * the dev_t is not 0,0.
 * If a pointer to a parent struct device is passed in, the newly created
 * struct device will be a child of that device in sysfs.
 * The pointer to the struct device will be returned from the call.
 * Any further sysfs files that might be required can be created using this
 * pointer.
 *
 * Returns &struct device pointer on success, or ERR_PTR() on error.
 *
 * Note: the struct class passed to this function must have previously
 * been created with a call to class_create().
 */
struct device *device_create(struct class *class, struct device *parent,
			     dev_t devt, void *drvdata, const char *fmt, ...)

3.device_create_file()

功能:该函数用于为指定设备在sysfs下建立属性文件,如:
device_create_file(dev, &dev_attr_val);
其中的dev_attr_val可以通过DEVICE_ATTR宏进行定义,也可以直接通过struct device_attribute xxx=__ATTR(_name,_mode,_show,_store)进行定义,区别就是用DEVICE_ATTR宏进行定义时得到的变量名都是以dev_attr_为前缀的,而通过struct device_attribute xxx=__ATTR(_name,_mode,_show,_store)进行定义时,变量名可以任意指定。建立属性文件之后,我们就可以通过属性文件对设备的属性进行配置和读取了,这也是应用程序和设备(驱动程序)进行信息交互的一种方式。
函数原型:
/**
 * device_create_file - create sysfs attribute file for device.
 * @dev: device.
 * @attr: device attribute descriptor.
 */
 
int device_create_file(struct device *dev,const struct device_attribute *attr)


#define DEVICE_ATTR(_name, _mode, _show, _store) \
struct device_attribute dev_attr_##_name = __ATTR(_name, _mode, _show, _store)
如下代码可以实现自动创建设备节点:

	static struct class* myDev_class = NULL;
	struct device* devc= NULL;		
	
	/*5.创建一个struct class结构体*/
	myDev_class = class_create(THIS_MODULE,"myDevClass");
	if(IS_ERR(myDev_class)) {
		err = PTR_ERR(myDev_class);
		printk(KERN_ALERT"Failed to create  class.\n");
		return err;
	}        
	/*6.在sysf中生成设备文件并在/dev下自动生成设备节点*/
	devc = device_create(myDev_class,NULL,dev,NULL,"myDev");
	if(IS_ERR(devc)) {
		err = PTR_ERR(devc);
		printk(KERN_ALERT"Failed to create device.");
		return err;
	}  	

以下贴出以上分两部分介绍的字符设备的初始化代码:
struct cdev *myDev_dev;
/*主设备号和从设备号变量*/
static int myDev_major = 0;
static int myDev_minor = 0;


static int __init myDev_init(void)
{ 
	int err = -1;
	dev_t dev = 0;
	struct device *devc = NULL;

	/* 1.动态分配主设备号和从设备号,第三个参数表示分配的次设备号的数量 */
	err = alloc_chrdev_region(&dev, 0, TOTAL_DEVICE_COUNT, "myDev");
	if(err < 0) {
		printk(KERN_ALERT"Failed to alloc char dev region.\n");
		return err;
	}

	myDev_major = MAJOR(dev);
	myDev_minor = MINOR(dev);        

	/* 2.分配cdev字符设备结构体变量 */
	myDev_dev = cdev_alloc();
	if(!myDev_dev) {
		err = -ENOMEM;
		printk(KERN_ALERT"Failed to alloc myDev_dev.\n");
		return err;
	}        
	/* 3.初始化cdev字符设备结构体 */
	cdev_init(myDev_dev, &myDev_fops); 

	/* 4.添加字符设备到系统中 */
	err = cdev_add(myDev_dev,dev, TOTAL_DEVICE_COUNT);
	if(err) {
		return err;
	}              

	/* 5.创建一个struct class结构体 */
	myDev_class = class_create(THIS_MODULE,"myDevClass");
	if(IS_ERR(myDev_class)) {
		err = PTR_ERR(myDev_class);
		printk(KERN_ALERT"Failed to create  class.\n");
		return err;
	}        
	/* 6.在sysf中生成设备文件并在/dev下自动生成设备节点 */
	devc = device_create(myDev_class,NULL,dev,NULL,"myDev");
	if(IS_ERR(devc)) {
		err = PTR_ERR(devc);
		printk(KERN_ALERT"Failed to create device.");
		return err;
	}  	
	return err;
}

通用函数

1.kmalloc()和kzalloc()的异同

在内核include/linux/slab.h文件中有如下定义:

/**
 * kzalloc - allocate memory. The memory is set to zero.
 * @size: how many bytes of memory are required.
 * @flags: the type of memory to allocate (see kmalloc).
 */
static inline void *kzalloc(size_t size, gfp_t flags)
{
	return kmalloc(size, flags | __GFP_ZERO);
}

从注释以及函数原型均能看出kzalloc()函数的作用,即申请一块内存并且该内存会在函数调用过程中被清零。

2.module_platform_driver()

该函数实际是一个宏,它在include/linux/platform_device.h中定义如下:

/* module_platform_driver() - Helper macro for drivers that don't do
 * anything special in module init/exit.  This eliminates a lot of
 * boilerplate.  Each module may only use this macro once, and
 * calling it replaces module_init() and module_exit()
 */
#define module_platform_driver(__platform_driver) \
	module_driver(__platform_driver, platform_driver_register, \
			platform_driver_unregister)

其中的module_driver在/include/linux/device.h中定义,如下:

/**
 * module_driver() - Helper macro for drivers that don't do anything
 * special in module init/exit. This eliminates a lot of boilerplate.
 * Each module may only use this macro once, and calling it replaces
 * module_init() and module_exit().
 *
 * @__driver: driver name
 * @__register: register function for this driver type
 * @__unregister: unregister function for this driver type
 * @...: Additional arguments to be passed to __register and __unregister.
 *
 * Use this macro to construct bus specific macros for registering
 * drivers, and do not use it on its own.
 */
#define module_driver(__driver, __register, __unregister, ...) \
static int __init __driver##_init(void) \
{ \
	return __register(&(__driver) , ##__VA_ARGS__); \
} \
module_init(__driver##_init); \
static void __exit __driver##_exit(void) \
{ \
	__unregister(&(__driver) , ##__VA_ARGS__); \
} \
module_exit(__driver##_exit);

由上述定义可知,module_platform_driver()宏的作用就是定义指定名称的平台设备驱动注册函数和平台设备驱动注销函数,并且在函数体内分别通过platform_driver_register()函数和platform_driver_unregister()函数注册和注销该平台设备驱动。

3.read_cpuid_id()

读取CPU ID,定义于arch/arm/include/asm/cputype.h文件中。

4.container_of()

该函数其实是一个宏,定义于include/linux/kernel.h,如下所示:
/**
 * container_of - cast a member of a structure out to the containing structure
 * @ptr:	the pointer to the member.
 * @type:	the type of the container struct this is embedded in.
 * @member:	the name of the member within the struct.
 *
 */
#define container_of(ptr, type, member) ({			\
	const typeof( ((type *)0)->member ) *__mptr = (ptr);	\
	(type *)( (char *)__mptr - offsetof(type,member) );})
#ifndef offsetof
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#endif
该宏定义的功能是,通过结构体某一个已知成员的指针(成员变量的地址),反向计算出该结构体的地址。其原理也很简单,就是用已知成员变量的地址,减去该成员变量在结构体中的偏移量。
这个功能在kernel编程中十分有用。举一个简单的例子,如下:
struct child_struct
{
	int m;
	int n;
};

struct parent_struct
{
	int a;
	int b;
	struct child_struct c;
};

struct parent_struct test;

int *address = &test.c.n;
struct parent_struct *test_addr = container_of(address,struct parent_struct,c.n);

通过上述语句,获取到的就是test变量的地址。
注意:需要注意的是,在使用container_of()宏来获取父结构体的地址时,一定不要用指针类型的成员变量进行计算。
因为指针类型的成员变量本身就是用来保存一个地址,并且该地址是不确定的,它可以被赋值成任意值,因此不能用来计算父结构体的地址。













字符设备驱动——自动生成设备节点相关函数 如果没有指定设备号的话,那么就需要申请设备号。该函数用于申请设备号,函数原型参数含义dev保存申请到的设备号baseminor次设备号的起始地址count要申请的设备号数量name设备名字。 阅读详情

相关推荐

【linux软件基础知识】- alloc_chrdev_region

提供的代码片段摘自 Linux 内核中的 alloc_chrdev_region 函数。该函数用于分配一定范围的字符设备号。被调用,参数为 0(表示内核应该自动分配一个主设备号)、并检索相应的设备号以供驱动程序或模块中进一步使用。最后将分配的设备号赋给dev指针,函数返回。变量的指针,该变量将存储分配的设备号。并包含有关主设备号和次设备号的信息。:要分配的连续次设备号的数量。,表示字符设备区域分配成功。:设备范围的起始次设备号。:驱动程序或模块的名称。返回相应的错误代码。一定范围的字符设备号。

433

字符设备驱动-使用alloc_chrdev_region+cdev注册设备驱动

:Lalloc_chrdev_region函数原型如下,它是我们用来向内核申请主设备号时用的,与register_chrdev_region不同的是,alloc_chrdev_region是让内核分配给我们一个尚未使用的主设备号,不是由我们自己指定的,该函数的四个传参意义如下: dev :alloc_chrdev_region函数向内核申请下来的设备号 baseminor :次设备号的起始 ...

明故宫的记忆 2万+

用python提取PDF中各类文本内容的方法

用python提取PDF中各类文本内容的方法

安静的软件工程师 6101

Linux设备驱动-内核管理设备号机制

开篇 本文引用的内核代码参考来自版本 linux-5.15.4 。 在 Linux 系统中,每个注册到系统的设备都有一个编号,这个编号便是 Linux 系统中的设备号。 设备号作为一种系统资源,需要加以管理。否则,如果设备号与驱动程序对应关系错误,就会引起混乱或引起潜在的问题。 通过查看 /proc/devices 文件可以得到系统中注册的设备,第一列为主设备号,第二列为设备名称 $ cat /proc/devices Character devices: 1 mem 4 /dev/vc/0

一起学嵌入式 2047

数字电路基础(CMOS电路、低功耗方法)

文章目录一、CMOS器件1.1.CMOS反相器1.2. CMOS与非门1.3.CMOS或非门1.4 CMOS与门和CMOS或门二、CMOS电路参数——功耗 一、CMOS器件 1.1.CMOS反相器 CMOS反相器实现非门功能,由一个PMOS管和一个NMOS管组成,其逻辑电路图如下: 其真值表如下: In PMOS NMOS Out 0 √ 导通 ×关闭 1 1 ×关闭 √...

Mr.翟的博客 1万+

Qt实战:用QCustomPlot实现毫秒级时间轴数据动态刷新(附完整代码)

本文深入探讨了在Qt框架下,如何利用QCustomPlot库高效实现毫秒级时间轴数据的动态刷新与实时可视化。针对工业物联网等高频数据场景,文章提供了从原理剖析、核心代码实现到性能优化的完整实战指南,包括滑动窗口管理、双定时器策略及坐标轴精确配置,帮助开发者构建稳定、流畅的专业级监控界面。

qsc90123456的博客 768

linux内核的外部接口函数,Linux内核编程接口函数

Linux内核编程接口函数字符设备相关函数1.alloc_chrdev_region()功能: 自动分配一个主设备号及基于此主设备号的若干个连续的指定数量的次设备号。函数原型如下:/*** alloc_chrdev_region() - register a range of char device numbers* @dev: output parameter for first assigne...

weixin_35089891的博客 616

(25.08)Ubuntu20.04+ROS1复现FAST-LIO2

请确保在。

m0_69023437的博客 4007

linux内核编程接口小结(一)

1、下面两幅图描述了linux内核编程接口函数

yuanlu837的专栏 643

玩转openclaw+企业微信

OpenClaw横空出世:AI从问答到执行的范式革命 OpenClaw作为2026年AI领域的重大突破,实现了从对话机器人到智能执行体的进化。其核心价值在于"自主执行"而非简单交互,通过六层解耦架构(表现层、网关层、运行时层、技能层、工具层、记忆层)构建完整执行闭环。关键技术包括Model Context Protocol实现多模型兼容,以及事件驱动架构确保实时响应。安装过程支持多平台,通过Node.js环境即可快速部署,并支持对接主流大模型。OpenClaw标志着AI开始真正&quot

西木风落 1602

1、Ovirt 开源虚拟化平台安装

Ovirt虚拟化Node和Engine安装

大鱼 6283

【Linux 内核 内存管理】memblock 分配器编程接口 ① ( memblock 分配器编程接口简介 | memblock_add 函数原型分析 | memblock_add 函数源码 )

一、memblock 分配器编程接口、 二、memblock_add 函数原型分析、 三、memblock_add 函数源码

让 学习 成为一种 习惯 ( 韩曙亮 の 技术博客 ) 1629

Linux V3H 平台开发系列讲解(串行解串篇)2.2.2 MAX9296 MAX96705 GMSL1 续篇--串行器提前配置

本文详细介绍了在Linux v3h平台上,针对Max9296解串器和解串器max96705的详解配置,验证可出图,内容包括串行器解串器介绍、链路框架、硬件连接、速率配置,以及遇到的图像异常问题及解决方法。

xian18809311584的博客 543

【Linux 内核 内存管理】memblock 分配器编程接口 ⑤ ( memblock_free 函数 | memblock_remove_range 函数 )

一、memblock_free 函数分析、 二、memblock_remove_range 函数分析

让 学习 成为一种 习惯 ( 韩曙亮 の 技术博客 ) 1620

【定位模块算法】amcl(蒙特卡洛)粒子滤波定位算法(附C++代码)

系列文章目录 提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加 TODO:写完再整理 文章目录系列文章目录前言(1)amcl定位框架介绍(2)amcl定位框架组成(1)ROS-TF坐标转换树【ROS的工具】(2)robot_pose_ekf扩展卡尔曼位姿估计算法(3)定位amcl自适应蒙特卡洛定位,adaptive monte carlo localizaion**(3)amcl定位节点的订阅与发布(4)amcl定位功能包用法(1)编写amcl节点相关的launch(amcl_omni.l

qq_35635374的博客 4419

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

【Linux 内核 内存管理】memblock 分配器编程接口 ③ ( memblock_remove 函数 | memblock_remove_range 函数 )

一、memblock_remove 函数分析、 二、memblock_remove_range 函数分析、 1、memblock_remove_range 函数执行流程、 2、memblock_remove_range 函数参数介绍、 3、memblock_remove_range 函数源码

让 学习 成为一种 习惯 ( 韩曙亮 の 技术博客 ) 1661

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

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

【Linux 内核 内存管理】memblock 分配器编程接口 ④ ( memblock_alloc 函数 | memblock_alloc_base 函数 )

一、memblock_alloc 函数分析、 二、memblock_alloc_base 函数分析、 三、__memblock_alloc_base 函数分析、 四、memblock_alloc_base_nid 函数分析、 五、memblock_alloc_range_nid 函数分析

让 学习 成为一种 习惯 ( 韩曙亮 の 技术博客 ) 1880

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

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

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

关于Linux系统调用,内核函数

转自:http://blog.csdn.net/ubuntulover/article/details/5988220 早上听人说到某个程序的一部分是内核态,另一部分是用户态,需要怎么怎么。当时突然想知道,用户的程序可以直接调用内核函数吗?(现在突然发觉这问题有点可笑,若是可以随便调,那系统岂不是乱套了)从网上找到下面这篇文章,讲的还算透彻。 现在自己的理解是,用户程序不可用直接调用内核函数,

如丧 885

内核中针对proc文件系统的编程函数总结

一、头文件: #include  二、创建与删除proc文件: 创建普通文件: 1.创建不可读写的普通文件 /*此函数只负责在proc中创建一个只读文件,即能在proc中看到这个文件。 * */ struct proc_dir_entry* create_proc_entry (const char *name,mode_t mode,struct proc_dir_entry *

u013920085的专栏 1989

linux系统调用,内核函数的关系

早上听人说到某个程序的一部分是内核态,另一部分是用户态,需要怎么怎么。当时突然想知道,用户的程序可以直接调用内核函数吗?(现在突然发觉这问题有点可笑,若是可以随便调,那系统岂不是乱套了)从网上找到下面这篇文章,讲的还算透彻。 现在自己的理解是,用户程序不可用直接调用内核函数,除非通过系统调用接口。如果想调用哪个内核函数(或自己写的内核函数),怎么办?增加一个系统调用就行了。 原文如下:

hudaliquan的专栏 2088

内核proc文件系统与seq接口

内核proc文件系统与seq接口(1)—内核proc文件系统简介 http://blog.chinaunix.net/uid-28253945-id-3382819.html 内核proc文件系统与seq接口(2)—内核proc文件系统编程接口 http://blog.chinaunix.net/uid-28253945-id-3382820.html 内核proc文件系统与seq接口(3)—内核...

weixin_41666796的博客 325

linux 内核 练习 3

Linux系统调用 摘要:本期重点和大家讨论系统调用机制。其中涉及到了一些及系统调用的性能、上下文深层问题,同时也穿插着讲述了一些内核调试方法。并且最后试验部分我们利用系统调用与相关内核服务完成了一个搜集系统调用序列的特定任务,该试验具有较强的实用和教学价值。   什么是系统调用    顾名思意,系统调用说的是操作系统提供给用户程序调用的一组“特殊”接口。用户程序可以通过这组“特殊”接口来

searchwang的专栏 451
上一篇: C语言编程
下一篇: Ultra Edit使用技巧
于海平
博客等级 码龄14年 42粉丝 50原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值