第9章--类

Java黑皮书课后题第9章:9.2(Stock类)遵照9.2节中Cirlce类的例子,设计一个名为Stock的类 Java黑皮书课后题第9章:9.2(Stock类)遵照9.2节中Cirlce类的例子,设计一个名为Stock的类题目代码Test2Test2_StockUML图 题目 代码 Test2:测试程序 Test2_Stock:实现题目要求 Test2 public class Test2 { public static void main(String[] args) { Test2_Stock s = new Test2_Stock("ORCL", "Oracle Corporatio 阅读详情
#练习 9-1:
# class Restaurant:
#     """一次模拟餐馆的简单尝试"""
#     def __init__(self,restaurant_name,cuisine_tpye):
#         """初始化餐馆的基础属性"""
#         self.restaurant_name = restaurant_name
#         self.cuisine_tpye = cuisine_tpye
    
#     def describe_restaurant(self):
#         """描述餐馆"""
#         print(f'This restaurant name is {self.restaurant_name}',end=' ')
#         print(f"and its chef's special is {self.cuisine_tpye}.")
    
#     def open_restaurant(self):
#         """指出餐馆正在营业"""
#         print(f'{self.restaurant_name} is open')

# my_restaurant = Restaurant('KFC','Original_Chicken')
# my_restaurant.describe_restaurant()
# my_restaurant.open_restaurant()

#练习 9-2:
# class Restaurant:
#     """一次模拟餐馆的简单尝试"""
#     def __init__(self,restaurant_name,cuisine_tpye):
#         """初始化餐馆的基础属性"""
#         self.restaurant_name = restaurant_name
#         self.cuisine_tpye = cuisine_tpye
    
#     def describe_restaurant(self):
#         """描述餐馆"""
#         print(f'This restaurant name is {self.restaurant_name}',end=' ')
#         print(f"and its chef's special is {self.cuisine_tpye}.")
    
#     def open_restaurant(self):
#         """指出餐馆正在营业"""
#         print(f'{self.restaurant_name} is open')

# restaurant_1 = Restaurant('KFC','Original Chicken')
# restaurant_1.describe_restaurant()

# restaurant_2 = Restaurant('Burger King','Cheese burger')
# restaurant_2.describe_restaurant()

# restaurant_3 = Restaurant("McDonald's",'Big Mac Burger')
# restaurant_3.describe_restaurant()

#练习 9-3:
# class User:
#     def __init__(self,first_name,last_name):
#         self.first_name = first_name
#         self.last_name = last_name
    
#     def describe_user(self):
#         full_name = f'{self.last_name} {self.first_name}'
#         print(f'user name is {full_name.title()}')

#     def greet_user(self):
#         full_name = f'{self.last_name} {self.first_name}'
#         print(f"Good moring,dear {full_name.title()}")

# user_1 = User('Steve','Jobs')
# user_1.describe_user()
# user_1.greet_user()

#练习 9-4:
# class Restaurant:
#     """一次模拟餐馆的简单尝试"""
#     def __init__(self,restaurant_name,cuisine_tpye):
#         """初始化餐馆的基础属性"""
#         self.restaurant_name = restaurant_name
#         self.cuisine_tpye = cuisine_tpye
#         self.number_served = 0
    
#     def describe_restaurant(self):
#         """描述餐馆"""
#         print(f'This restaurant name is {self.restaurant_name}',end=' ')
#         print(f"and its chef's special is {self.cuisine_tpye}.")
    
#     def open_restaurant(self):
#         """指出餐馆正在营业"""
#         print(f'{self.restaurant_name} is open')
    
#     def read_number_served(self):
#         """打印一条餐馆至今服务过多少人的消息"""
#         print(f"Our restaurant has served {self.number_served} people.")
    
#     def set_number_served(self,number):
#         """可任意设置已服务人数"""
#         if number >= self.number_served:
#             #禁止对已服务人数进行回调
#             self.number_served = number
#         else:
#             print('You can not roll back an number')
        
#     def increment_number_served(self,add_number):
#         """可更新已服务人数"""
#         self.number_served += add_number 
        

# my_restaurant = Restaurant('KFC','Original_Chicken')
# my_restaurant.read_number_served()
# my_restaurant.number_served = 1
# my_restaurant.read_number_served()

# my_restaurant.set_number_served(50_000)
# my_restaurant.read_number_served()

# my_restaurant.increment_number_served(500)        
# my_restaurant.read_number_served() 
       
#练习 9-5:
# class User:
#     def __init__(self,first_name,last_name):
#         self.first_name = first_name
#         self.last_name = last_name
#         self.login_attempts = 0
        
#     def describe_user(self):
#         """打印用户的姓名"""
#         full_name = f'{self.last_name} {self.first_name}'
#         print(f'user name is {full_name.title()}')

#     def greet_user(self):
#         """向用户道早上好"""
#         full_name = f'{self.last_name} {self.first_name}'
#         print(f"Good moring,dear {full_name.title()}")

#     def increment_login_attempts(self):
#         """尝试登录次数加1"""
#         self.login_attempts += 1
        
#     def reset_login_attempts(self):
#         """将尝试登录次数重置为0"""
#         self.login_attempts = 0
    
#     def read_login_attempts(self):
#         """打印出用户的尝试登录次数"""
#         print(f"Your login attempts have reached {self.login_attempts} times")
        
# user_1 = User('Steve','Jobs')
# user_1.increment_login_attempts()
# user_1.increment_login_attempts()
# user_1.increment_login_attempts()
# user_1.increment_login_attempts()
# user_1.increment_login_attempts()
# user_1.read_login_attempts()
# user_1.reset_login_attempts()
# user_1.read_login_attempts()

#练习 9-6:
# class Restaurant:
#     """一次模拟餐馆的简单尝试"""
#     def __init__(self,restaurant_name,cuisine_tpye):
#         """初始化餐馆的基础属性"""
#         self.restaurant_name = restaurant_name
#         self.cuisine_tpye = cuisine_tpye
#         self.number_served = 0
    
#     def describe_restaurant(self):
#         """描述餐馆"""
#         message = f'This restaurant name is {self.restaurant_name} '
#         message += f"and its chef's special is {self.cuisine_tpye}."
#         print(message)
    
#     def open_restaurant(self):
#         """指出餐馆正在营业"""
#         print(f'{self.restaurant_name} is open')
    
#     def read_number_served(self):
#         """打印一条餐馆至今服务过多少人的消息"""
#         print(f"Our restaurant has served {self.number_served} people.")
    
#     def set_number_served(self,number):
#         """可任意设置已服务人数"""
#         if number >= self.number_served:
#             #禁止对已服务人数进行回调
#             self.number_served = number
#         else:
#             print('You can not roll back an number')
        
#     def increment_number_served(self,add_number):
#         """可更新已服务人数"""
#         self.number_served += add_number
        
        
# class IceCreamStand(Restaurant):
#     def __init__(self,restaurant_name,cuisine_tpye):
#         """
#         初始化餐馆的信息
#         再初始化冰淇淋店特有的属性
#         """
#         super().__init__(restaurant_name,cuisine_tpye)
#         self.flavors = ['coco IceCream','water IceCream','fire IceCream']
    
#     def describe_flavors(self):
#         """显示各种口味的冰淇淋组成的列表"""
#         message = "our Ice-cream shop has these "
#         message += f"{self.flavors} for you to choose"
#         print(message)

# icecream = IceCreamStand('HAPPYNESS SHOP','ICECEAM')
# icecream.describe_flavors()   
    
#练习 9-7:
# class User:
#     def __init__(self,first_name,last_name):
#         self.first_name = first_name
#         self.last_name = last_name
#         self.login_attempts = 0
        
#     def describe_user(self):
#         """打印用户的姓名"""
#         full_name = f'{self.last_name} {self.first_name}'
#         print(f'user name is {full_name.title()}')

#     def greet_user(self):
#         """向用户道早上好"""
#         full_name = f'{self.last_name} {self.first_name}'
#         print(f"Good moring,dear {full_name.title()}")

#     def increment_login_attempts(self):
#         """尝试登录次数加1"""
#         self.login_attempts += 1
        
#     def reset_login_attempts(self):
#         """将尝试登录次数重置为0"""
#         self.login_attempts = 0
    
#     def read_login_attempts(self):
#         """打印出用户的尝试登录次数"""
#         print(f"Your login attempts have reached {self.login_attempts} times")
        
# class Admin(User):
#     def __init__(self,first_name,last_name):
#         """
#         初始化User的信息
#         再初始化Admin特有的属性
#         """
#         super().__init__(first_name,last_name)
#         self.privileges = ['can add post','can delete post','can ban user']
        
#     def show_privileges(self):
#         """显示管理员的权限"""
#         new_privileges = (','.join(self.privileges))
#         print(f"The admin has the following permissions:{new_privileges}.")
    
# my_Admin = Admin('Steve','Jobs')
# my_Admin.show_privileges()
    
#练习 9-8:
# class User:
#     def __init__(self,first_name,last_name):
#         self.first_name = first_name
#         self.last_name = last_name
#         self.login_attempts = 0
        
#     def describe_user(self):
#         """打印用户的姓名"""
#         full_name = f'{self.last_name} {self.first_name}'
#         print(f'{full_name.title()}')

#     def greet_user(self):
#         """向用户道早上好"""
#         full_name = f'{self.last_name} {self.first_name}'
#         print(f"Good moring,dear {full_name.title()}")

#     def increment_login_attempts(self):
#         """尝试登录次数加1"""
#         self.login_attempts += 1
        
#     def reset_login_attempts(self):
#         """将尝试登录次数重置为0"""
#         self.login_attempts = 0
    
#     def read_login_attempts(self):
#         """打印出用户的尝试登录次数"""
#         print(f"Your login attempts have reached {self.login_attempts} times")
        

# class Privileges:
#     """一次模拟管理员权限的尝试"""
#     def __init__(self,privileges = ['can add post','can delete post','can ban user']):
#         """初始化权限的属性"""
#         self.privileges = privileges
        
#     def show_privileges(self):
#         """显示管理员的权限"""
#         new_privileges = (','.join(self.privileges))
#         print(f"The admin has the following permissions:{new_privileges}.")
        
# class Admin(User):
#     def __init__(self,first_name,last_name):
#         """
#         初始化User的信息
#         再初始化Admin特有的属性
#         """
#         super().__init__(first_name,last_name)
#         self.privileges = Privileges()
    
# m_Admin = Admin('Steve','Jobs')
# m_Admin.describe_user()
# m_Admin.privileges.show_privileges()   
    
#练习 9-9:
# class Car():
#     """一次模拟汽车的简单尝试。"""
    
#     def __init__(self, manufacturer, model, year):
#          """初始化描述汽车的属性。"""
#          self.manufacturer = manufacturer
#          self.model = model
#          self.year = year
#          self.odometer_reading = 0
 
#     def get_descriptive_name(self):
#         """返回整洁的描述性信息。"""
#         long_name = f"{self.year} {self.manufacturer} {self.model}"
#         return long_name.title()
 
#     def read_odometer(self):
#         """打印一条指出汽车里程的消息。"""
#         print(f"This car has {self.odometer_reading} miles on it.")
 
#     def update_odometer(self, mileage):
#         """
#         将里程表读数设置为指定的值。
#         禁止将里程表读数往回调。
#         """
#         if mileage >= self.odometer_reading:
#             self.odometer_reading = mileage
#         else:
#             print("You can't roll back an odometer!")
 
#     def increment_odometer(self, miles):
#         """将里程表读数增加指定的量。"""
#         self.odometer_reading += miles
        
# class Battery():
#     """一次模拟电动汽车电瓶的简单尝试。"""
#     def __init__(self, battery_size=75):
#         """初始化电瓶的属性。"""
#         self.battery_size = battery_size
        
#     def describe_battery(self):
#         """打印一条描述电瓶容量的消息。"""
#         print(f"This car has a {self.battery_size}-kWh battery.")
 
#     def get_range(self):
#         """打印一条消息,指出电瓶的续航里程。"""
#         if self.battery_size == 75:
#             range = 260
#         elif self.battery_size == 100:
#             range = 315
    
#         message = f"This car can go approximately {range}"
#         message += " miles on a full charge."
#         print(message)
#     def upgrade_battery(self):
#         """在可能的情况下将电瓶升级。"""
#         if self.battery_size == 75:
#             self.battery_size = 100
#             print("Upgraded the battery to 100 kWh.")
#         else:
#             print("The battery is already upgraded.")
 
# class ElectricCar(Car):
#     """电动汽车的独特之处。"""
#     def __init__(self, manufacturer, model, year):
#         """
#         初始化父类的属性。
#         再初始化电动汽车特有的属性。
#         """
#         super().__init__(manufacturer, model, year)
#         self.battery = Battery()

# my_ElectricCar = ElectricCar('tesla', "model s", 2019)        
# print(my_ElectricCar.get_descriptive_name())
# my_ElectricCar.battery.get_range()
# my_ElectricCar.battery.upgrade_battery()        
# my_ElectricCar.battery.get_range()        
        
#练习 9-10:
# 我将Restaurant类储存进了 restaurant.py 模块 
#接下里便是对一个模块中的一个类进行调用
# from restaurant import Restaurant
# my_restaurant = Restaurant('HAPPYNESS SHOP','ICECEAM')
# my_restaurant.open_restaurant()

#练习 9-11:
#将User类、Admin类、Privileges类储存进 user.py 模块
#接下里便是对一个模块中的多个类进行调用
# from user import Admin
# my_Admin = Admin('Steve','Jobs')
# my_Admin.privileges.show_privileges()

#练习 9-12:
#在一个模块导入另一个模块
# from my_user import User
# #用于调用正常的user
# from my_admin import Admin
# #my_admin模块内只有Admin类和Privileges类
# #因此需要导入my_user模块的User类
# #my_admin模块中的类才能正常使用
# my_User = User('mark','jobs')
# my_User.describe_user()
# MY_Admin = Admin('Steve','Jobs')
# MY_Admin.describe_user()
# MY_Admin.privileges.show_privileges()

#练习 9-13:
# from random import randint
# class Die:
#     def __init__(self,sides=6):
#         """初始化sides默认属性"""
#         """选择骰子面数,默认值为6"""
#         self.sides = sides
    
#     def roll_die(self,times):
#         """打印位于1和骰子面数之间的随机数"""
#         """选择投掷次数"""
#         for time in range(times):
#             print(randint(1,self.sides))
            
# my_die = Die()
# my_die.roll_die(10)
# #6面的骰子投掷10次
# my_die = Die(10)
# my_die.roll_die(10)
# #10面的骰子投掷10次
# my_die = Die(20)
# my_die.roll_die(10)
# #20面的骰子投掷10次

#练习 9-14:
# from random import choice
# list_1 = ['1','2','3','4','5','6','7','8','9','10','a','b','c','d','e']
# list_2 =[]
# def Lottery(m=4):
#     for i in range(m):
#         z = choice(list_1)
#         list_2.append(z)
    
#     list_3 = (''.join(list_2))   
#     return list_3
# ticket_num = Lottery()
# print(f"you will got the prize if your ticket number is {ticket_num}")

#练习 9-15:
# from random import choice
# possibilities = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e']
# class Lottery:
#     def __init__(self,times=10000):
#         """初始化投注次数,默认值为一万"""
#         self.times = times
        
#     def get_win_lottery(self,side=4):
#         """用于生成获奖彩票"""
#         """并选择几位数的彩票,默认值为4"""
#         winning_list = []
#         while len(winning_list) < side:
#             n = choice(possibilities)
#             if n not in winning_list:
#                 #排除重复元素
#                 winning_list.append(n)
#         return winning_list
    
#     def get_new_lottery(self,side=4):
#         """用于随机生成彩票"""
#         ticket = []
#         while len(ticket) < side:
#             n = choice(possibilities)
#             if n not in ticket:
#                 #排除重复元素
#                 ticket.append(n)
#         return ticket   
    
#     def times_lottery(self):
#         """用于获得投注所获彩票列表"""
#         lottery_list = []
#         for x in range(self.times):
#             lottery_list.append(Lottery.get_new_lottery(self))
#         return lottery_list

#     def check_lottery(self):
#         """用于查看需要多少次才能中奖"""
#         count = 0
#         for x in Lottery.times_lottery(self):
#             if x != Lottery.get_win_lottery(self):
#                 count +=1
#             else:
#                 break
#         return count
    
    
# a = Lottery(100000)
# print(f"此次中奖彩票号码是{(''.join(a.get_win_lottery()))}")
# a.times_lottery()    
# print(f'第{a.check_lottery()}张中奖')    
    

#练习 9-16:
# keep going on despite the obstacles and long
第9章 类 让一个类继承另一个类后,就可以添加区分子类和父类所需的新属性和新方法了。class Car:class ElectricCar(Car): # 继承Carself.battery = 85 # 新属性mycar = ElectricCar(2024, 'Au', 'A7') # 创建实例mycar.prt_battery() # 新方法熟悉Python 提供的选项,这样才能确定哪种组织方式是最佳的,并能理解别人开发的项目。 阅读详情

相关推荐

不止是回退SDK:深入解读UE5.2编译时那个烦人的C4756警告与INFINITY宏的变迁

本文深入解析了UE5.2源码编译时出现的C4756警告及其背后的技术原因,探讨了Windows SDK中INFINITY宏的变迁对Unreal Engine的影响。文章详细介绍了微软修改INFINITY定义的技术考量,并提供了UE5.2应对此类问题的灵活解决方案,包括通过BuildConfiguration.xml文件精确控制工具链版本,确保构建系统的可重复性和可配置性。

weixin_27180827的博客 311

第9章 类

第9章 类, 首字母大写的名称为类,小写为实例 句点表示法 可以创建多个实例 __init__函数,注意下划线是每边两个 修改属性值: 直接修改属性值 通过方法修改,写在类里 通过方法对属性的值进行递增 继承 子类继承父类的所有属性和方法,同时还可以定义自己的属性和方法。 创建子类时,父类必须包含在当前文件下,且位于子类前面, super函数帮助父类和子类关联起来 给子类定义属性和方法,添加新的...

Jayzou 193

SAM2与Docker的完美组合:5分钟搞定Linux环境下的图像分割部署

本文详细介绍了如何在Linux环境下通过Docker快速部署SAM2图像分割模型,解决安装过程中的常见问题。文章提供了从镜像选择、CUDA版本匹配到容器构建的全流程指南,特别针对GPU加速环境下的'cudnn_frontend: No execution plans support the graph'等报错提供了实用解决方案,帮助开发者在5分钟内完成高效部署。

fern8的博客 933

第 9 章 类

本文介绍了Python中类的创建、使用和继承。通过Dog和Car类示例,说明了如何定义类属性、方法(如__init__构造方法)以及创建实例对象。重点讲解了三种修改属性的方式:直接赋值、通过方法修改和递增。在继承部分,详细说明了子类如何通过super()调用父类方法、添加新属性和方法,以及重写父类方法。这些面向对象编程的核心概念可以帮助开发者构建更灵活、可复用的代码结构。

明道的博客 1058

CentOS 7下kkFileView 4.4.0离线部署全攻略(含LibreOffice 7.5配置避坑指南)

本文详细介绍了在CentOS 7环境下离线部署kkFileView 4.4.0的全流程,包括LibreOffice 7.5的配置避坑指南、中文字体解决方案以及企业级运维实践。通过本指南,用户可以在内网环境中快速搭建稳定可靠的文档在线预览服务,提升办公效率。

weixin_28481133的博客 290

伺服驱动器启用后对传感器线信号干扰的解决方案

在一些Arduino项目中,研究者发现,当伺服电机启动时,传感器信号会出现显著噪声。例如,在一个假肢项目中,研究者使用光电隔离器成功隔离了伺服驱动器对EMG传感器的干扰。然而,当启用伺服驱动器时,传感器线信号常常受到干扰,导致系统性能下降。传感器线信号是传感器输出的电信号,用于测量物理量,如温度、光线或位置。例如,在一些案例中,伺服驱动器的开关操作可能导致传感器信号出现尖峰或波动,特别是在模拟传感器上更为明显。描述: 使用光电隔离或其他隔离技术,分离伺服驱动器和传感器的电气路径,防止直接干扰。

有用好玩有趣的“电”知识 1466

python 第9章 类

1. 根据类来创建对象被称为 实例化。 2.在python中 首字母大写的名称批的是类。类中的函数称为方法 3. _init_() 是一个特殊的方法,当你根据类创建实例时,python都会自动运行它。在这方法的名称中,开头和末尾各有两个下划线,这是一种约定,旨在避免python默认方法与普通方法发生名称冲突。 4.通过实例访问的变量称为属性。 5.定义类        3.7中:   ...

tan88881111的博客 284

从零构建:如何用MATLAB和SDR硬件搭建你的第一个OFDM卫星通信原型系统

本文详细介绍了如何利用MATLAB和SDR硬件从零构建OFDM卫星通信原型系统。通过核心组件选型、开发环境配置、OFDM算法实现到系统集成与优化的完整流程,帮助通信工程学生和DIY爱好者快速掌握软件无线电技术在卫星通信中的应用。特别推荐使用HackRF One和MATLAB工具箱实现高性价比的OFDM系统验证。

pz890123456的博客 378

第9章 定义类

9.1 c#中的类定义 c#使用class关键字来定义类 class MyClass { //class members } ps:默认情况下,类声明为内部的,可以使用internal访问修饰符关键字来显式指定这一点 internal class MyClass { //class members } 这个类和上面定义的类的效果是一样的 另外,类可以是公共的: p

herunlong的博客 499

优化点列图(RMS半径)的操作数

优化点列图(RMS半径)的操作数

weixin_72050316的博客 2258

LeRobot 入门教程(十)LIBERO 机器人终身学习评估

LIBERO是一项专注于机器人终身学习(LLDM)的基准测试平台,包含130项任务,分为5大套件(空间推理、物体操作、目标约束等)。LeRobot框架已集成LIBERO,支持单/多套件评估,并兼容SmolVLA模型。训练需使用预处理数据集(HuggingFaceVLA/libero),观测数据需符合规范(8维状态+双摄像头图像)。该平台采用MuJoCo模拟,支持无头服务器运行,旨在推动机器人持续学习算法的发展与标准化评估。

2506_90492529的博客 1663

Python入门 - 第9章 类

此系列文章的创作初衷是作为读书过程中的笔记,而非教程类文章。 第9章 类 9.1 创建和使用类 下面是创建一个类的样例代码: class Dog(): """ 一次模拟小狗的简单尝试 """ def __init__(self, name): self.name = name def sit(self): print(self.name.title() + "is now sitting.") 可以发现以下特点: 可以在创建类时向类名传入参

m0_48723777的博客 257

【OpenClaw企业级智能体实战】第04篇:OpenClaw成本优化实战——Token消耗降96%!claude-mem+OpenViking从入门到精通

OpenClaw作为企业级智能体框架,凭借强大的自动化能力成为企业数字化转型的热门工具,但原生机制导致的上下文冗余问题,让众多用户面临“Token消耗失控”的困境——单周账单数千元的案例屡见不鲜。本文基于阿里云实测数据与开源工具官方文档,先深度拆解OpenClaw成本黑洞的核心成因(记忆碎片化、Token指数级膨胀),再系统讲解两款核心优化工具(claude-mem单Agent记忆管理、OpenViking多Agent集群底座)的底层原理、算法架构与实现逻辑,提供从环境搭建、工具集成、参数调优到安全部署

专注于人工智能、软件开发、工控自动化、工厂数字化及智能化等领域,希望和大家共同进步! 703

python第 9 章——类

面向对象编程 是最有效的软件编写方法之一。在面向对象编程中,你编写表示现实世界中的事物和情景的类,并基于这些类来创建对象。编写类时,你定义一大类对 象都有的通用行为。基于类创建对象 时,每个对象都自动具备这种通用行为,然后可根据需要赋予每个对象独特的个性。 根据类来创建对象被称为实例化 9.1 创建和使用类 9.1.1 创建Dog 类 根据Dog 类创建的每个实例都将存储名字和年龄。我们赋予了每条小狗蹲下(sit() )和打滚(roll_over() )的能力: class Dog():..

weixin_42638401的博客 514

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

深度学习工具包 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&#39;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(&#39;DeepLearnToolbox&#39;));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(&#39;state&#39;,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&#39;); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand(&#39;state&#39;,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 = &#39;sigm&#39;;%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, &#39;Too big error&#39;);```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(&#39;state&#39;,0)sae = saesetup([784 100]);sae.ae{1}.activation_function = &#39;sigm&#39;;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)&#39;)% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;;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, &#39;Too big error&#39;);```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x&#39;,28,28,60000))/255;test_x = double(reshape(test_x&#39;,28,28,10000))/255;train_y = double(train_y&#39;);test_y = double(test_y&#39;);%% 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&#39;ll get around 1.2% errorrand(&#39;state&#39;,0)cnn.layers = { struct(&#39;type&#39;, &#39;i&#39;) %input layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 6, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %sub sampling layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 12, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 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, &#39;Too big error&#39;);```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(&#39;state&#39;,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, &#39;Too big error&#39;);%% ex2 neural net with L2 weight decayrand(&#39;state&#39;,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, &#39;Too big error&#39;);%% ex3 neural net with dropoutrand(&#39;state&#39;,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, &#39;Too big error&#39;);%% ex4 neural net with sigmoid activation functionrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;; % 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, &#39;Too big error&#39;);%% ex5 plotting functionalityrand(&#39;state&#39;,0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = &#39;softmax&#39;; % 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, &#39;Too big error&#39;);%% 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(&#39;state&#39;,0)nn = nnsetup([784 20 10]); nn.output = &#39;softmax&#39;; % 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, &#39;Too big error&#39;);```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Python第9章 类

Python第9章 类 根据类创建实例 class Dog(): “”“一次模拟小狗的简单完成”"" def init(self,name,age): “”“初始化属性name和age”"" self.name=name self.age=age def sit(self): """模拟小狗被命令时蹲下""" print(self.name.title()+" is now sitting.") def roll_over(self): """模拟小狗被命令时打滚""" p

杰少027 432

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

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

第9章:类

from collections import OrderedDict #这是从标准库里面导入的函数,用于记录输入的值的顺寻 f = OrderedDict()#把他看作空字典 f['libai']='c' f['dufu']='python' for k,v in f.items(): print(k+' '+v) #类是个强大的工具箱,注意大写括号,self #对象有具体化和抽象化...

Roe_D的博客 229

《JavaScript权威指南第7版》第9章 类

第9章 类9.1 类和原型9.2 类和构造函数 第6章介绍了JavaScript对象。那一章把每个对象都看作是一组独特的属性集合,与任何其它对象都不同。但是,定义一类共享某些属性的对象通常是有用的。类的成员或实例有自己的属性来保存或定义其状态,但它们也有定义其行为的方法。这些方法由类定义,并由所有实例共享。例如,假设有一个名为Complex的类,它表示并执行对复数的算术运算。一个复杂实例将具有一些属性来保存复数的实部和虚部(状态)。复杂类将定义方法来执行这些数字的加法和乘法(行为)。 在JavaScript

夏商周 518

第9 章 类 9.2 使用类和实例

# -*- coding:utf-8 -*- #li hongliang 2020年06月09日 #9.2 使用类和实例 #9.2.1 Car 类 #9.2.2 给属性指定默认值:。在有些情况下,如设置默认值时,在方法__init__()内指定这种初始值是可行的;如果你对某个属性这样做了,就无需包含为它提供初始值的形参。 #9.2.3 修改属性的值 #1. 直接修改属性的值 #2. 通过方法修改属性的值 #3. 通过方法对属性的值进行递增 #9-4 就餐人数:在为完成练习9-1 而编写的程序中,添加

m0_47456600的博客 185
上一篇: 第8章--函数
下一篇: 第10章--文件与异常
-阿呆-
博客等级 码龄6年 712粉丝 89原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

-阿呆-

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值