您的位置:首页 > 其它

百度飞桨PaddlePaddle深度学习心得分享

2020-05-07 04:24 806 查看

能参加到这次的百度飞桨七日“Python小白逆袭大神”打卡营是一次偶然的了解得知的这个机会,之前因为课程和基础不够扎实参加到AI实战营没有顺利跟完全程,这一次很开心可以顺利跟上并且结营。下面的内容就简要的总结一下这几天的学习内容和踩过的小坑吧。

本次课程的课程目标:

1.掌握Python的基础语言、进阶知识和常用的深度学习库,能够利用Python爬取数据并进行可视化分析
2.掌握人工智能基础知识、应用,体验人工智能的前沿技术
3.了解飞桨平台及百度AI技术、应用,掌握AI Studio的使用方法

本次课程的安排:

  • Day1-人工智能概述与python入门基础
  • Day2-Python进阶
  • Day3-人工智能常用Python库
  • Day4-PaddleHub体验与应用
  • Day5-EasyDL体验与作业发布
  • Day6-PaddleHub创意赛发布
  • Day7-课程结营
  • Day1-人工智能概述与python入门基础

    python基础、人工智能概述

    第一天的学习是对于python语言和人工智能的一个简单介绍,这部分对于没有什么基础的小白来说还是很友好,实验上应该也比较简单,没有遇到什么大问题,就直接上代码:

    • 输出 9*9 乘法口诀表:
    def table():
    for i in range(1,10):
    for j in range(1,i+1):
    print("{}*{}={:2} ".format(j,i,i*j), end='')
    print('')
    if __name__ == '__main__':
    table()

    • 查找特定文件名称:
    #导入OS模块
    import os
    #待搜索的目录路径
    path = "Day1-homework"
    #待搜索的名称
    filename = "2020"
    #定义保存结果的数组
    result = []
    
    def findfiles(path):
    #在这里写下您的查找文件代码吧!
    global index
    li=os.listdir(path)
    
    for p in li:
    tempPathName=p
    pathname=os.path.join(path,p)
    if os.path.isdir(pathname):
    findfiles(pathname)
    elif os.path.isfile(pathname):
    
    if(tempPathName.find(filename)!=-1):
    index=0
    index=index+1
    result=[]
    result.append(index)
    result.append(pathname)
    if(len(result)>0):
    print(result)
    
    if __name__ == '__main__':
    findfiles(path)

    Day2-Python进阶

    python进阶学习和深度学习实践

    这次实践使用Python来爬取百度百科中《青春有你2》所有参赛选手的信息,对于小白来说可以上手稍微有一点点难度,但跟着课程老师的思路和讲解还是可以克服困难的

    爬虫的过程:
    1.发送请求(requests模块)
    2.获取响应数据(服务器返回)
    3.解析并提取数据(BeautifulSoup查找或者re正则)
    4.保存数据

    一、爬取百度百科中《青春有你2》中所有参赛选手信息,返回页面数据
    import json
    import re
    import requests
    import datetime
    from bs4 import BeautifulSoup
    import os
    
    #获取当天的日期,并进行格式化,用于后面文件命名,格式:20200420
    today = datetime.date.today().strftime('%Y%m%d')
    
    def crawl_wiki_data():
    """
    爬取百度百科中《青春有你2》中参赛选手信息,返回html
    """
    headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
    }
    url='https://baike.baidu.com/item/青春有你第二季'
    
    try:
    response = requests.get(url,headers=headers)
    print(response.status_code)
    
    #将一段文档传入BeautifulSoup的构造方法,就能得到一个文档的对象, 可以传入一段字符串
    soup = BeautifulSoup(response.text,'lxml')
    
    #返回的是class为table-view log-set-param的<table>所有标签
    tables = soup.find_all('table',{'class':'table-view log-set-param'})
    
    crawl_table_title = "参赛学员"
    
    for table in  tables:
    #对当前节点前面的标签和字符串进行查找
    table_titles = table.find_previous('div').find_all('h3')
    for title in table_titles:
    if(crawl_table_title in title):
    return table
    except Exception as e:
    print(e)
    
    二、对爬取的页面数据进行解析,并保存为JSON文件
    def parse_wiki_data(table_html):
    '''
    从百度百科返回的html中解析得到选手信息,以当前日期作为文件名,存JSON文件,保存到work目录下
    '''
    bs = BeautifulSoup(str(table_html),'lxml')
    all_trs = bs.find_all('tr')
    
    error_list = ['\'','\"']
    
    stars = []
    
    for tr in all_trs[1:]:
    all_tds = tr.find_all('td')
    
    star = {}
    
    #姓名
    star["name"]=all_tds[0].text
    #个人百度百科链接
    star["link"]= 'https://baike.baidu.com' + all_tds[0].find('a').get('href')
    #籍贯
    star["zone"]=all_tds[1].text
    #星座
    star["constellation"]=all_tds[2].text
    #身高
    star["height"]=all_tds[3].text
    #体重
    star["weight"]= all_tds[4].text
    
    #花语,去除掉花语中的单引号或双引号
    flower_word = all_tds[5].text
    for c in flower_word:
    if  c in error_list:
    flower_word=flower_word.replace(c,'')
    star["flower_word"]=flower_word
    
    #公司
    if not all_tds[6].find('a') is  None:
    star["company"]= all_tds[6].find('a').text
    else:
    star["company"]= all_tds[6].text
    
    stars.append(star)
    
    json_data = json.loads(str(stars).replace("\'","\""))
    with open('work/' + today + '.json', 'w', encoding='UTF-8') as f:
    json.dump(json_data, f, ensure_ascii=False)
    三、爬取每个选手的百度百科图片,并进行保存
    def crawl_pic_urls():
    '''
    爬取每个选手的百度百科图片,并保存
    '''
    with open('work/'+ today + '.json', 'r', encoding='UTF-8') as file:
    json_array = json.loads(file.read())
    
    headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
    }
    count=0
    pic_urls=[]
    
    for star in json_array:
    
    name = star['name']
    link = star['link']
    
    #!!!请在以下完成对每个选手图片的爬取,将所有图片url存储在一个列表pic_urls中!!!
    response=requests.get(link,headers=headers)
    soup=BeautifulSoup(response.text,'lxml')
    tables=soup.find_all('div',{'class':'summary-pic'})
    
    for table in tables:
    aHref=table.a['href']
    album_url="https://baike.baidu.com"+aHref
    
    response=requests.get(album_url,headers=headers)
    soup=BeautifulSoup(response.text,'lxml')
    pic_list_div=soup.find('div',{'class':'pic-list'})
    
    albumTmages=pic_list_div.find_all('img')
    
    for album_image in albumTmages:
    album_image_url=album_image["src"]
    
    pic_urls.append(album_image_url)
    count=count+1
    print(count)
    
    #!!!根据图片链接列表pic_urls, 下载所有图片,保存在以name命名的文件夹中!!!
    down_pic(name,pic_urls)
    
    def down_pic(name,pic_urls):
    '''
    根据图片链接列表pic_urls, 下载所有图片,保存在以name命名的文件夹中,
    '''
    path = 'work/'+'pics/'+name+'/'
    
    if not os.path.exists(path):
    os.makedirs(path)
    
    for i, pic_url in enumerate(pic_urls):
    try:
    pic = requests.get(pic_url, timeout=15)
    string = str(i + 1) + '.jpg'
    with open(path+string, 'wb') as f:
    f.write(pic.content)
    print('成功下载第%s张图片: %s' % (str(i + 1), str(pic_url)))
    except Exception as e:
    print('下载第%s张图片时失败: %s' % (str(i + 1), str(pic_url)))
    print(e)
    continue
    四、打印爬取的所有图片的路径
    def show_pic_path(path):
    '''
    遍历所爬取的每张图片,并打印所有图片的绝对路径
    '''
    pic_num = 0
    for (dirpath,dirnames,filenames) in os.walk(path):
    for filename in filenames:
    pic_num += 1
    print("第%d张照片:%s" % (pic_num,os.path.join(dirpath,filename)))
    print("共爬取《青春有你2》选手的%d照片" % pic_num)
    
    In[61]
    if __name__ == '__main__':
    
    #爬取百度百科中《青春有你2》中参赛选手信息,返回html
    html = crawl_wiki_data()
    
    #解析html,得到选手信息,保存为json文件
    parse_wiki_data(html)
    
    #从每个选手的百度百科页面上爬取图片,并保存
    crawl_pic_urls()
    
    #打印所爬取的选手图片路径
    show_pic_path('/home/aistudio/work/pics/')
    
    print("所有信息爬取完成!")

    Day3-人工智能常用Python库

    深度学习常用Python库介绍

    这个模块利用了python对day2的数据进行绘制饼图和柱状图,我觉得特别实用也是能感受到python方便之处的一个重要方面

    import matplotlib.pyplot as plt
    import numpy as np
    import json
    import matplotlib.font_manager as font_manager
    
    %matplotlib inline
    
    with open('data/data31557/20200422.json', 'r', encoding='UTF-8') as file:
    json_array = json.loads(file.read())
    
    weight_list= []
    for star in json_array:
    weight = star['weight'].strip('kg')
    weight_list.append(weight)
    # print(len(weight_list))
    # print(weight_list)
    
    weight_label = ['<=45kg', '45~50kg', '50~55kg', '>55kg']
    count_list = [0,0,0,0]
    
    for weight in weight_list:
    weight=float(weight)
    if weight <= 45:
    count_list[0]=count_list[0]+1
    continue
    if weight>45 and weight<=50:
    count_list[1]=count_list[1]+1
    continue
    if weight > 50 and weight <= 55:
    count_list[2]=count_list[2]+1
    continue
    if weight>55:
    count_list[3]=count_list[3]+1
    continue
    
    print(weight_label)
    print(count_list)
    
    plt.figure(figsize=(20,15))
    explode = (0, 0.1, 0, 0)
    plt.pie(x=count_list ,explode=explode, labels=weight_label,autopct='%1.1f%%', shadow=False, startangle=90)
    
    plt.axis('equal')
    plt.legend()
    plt.title("The percentage of weight",fontsize = 24)
    plt.savefig('/home/aistudio/work/result/pie_result.jpg')
    plt.show()

    Day4-PaddleHub体验与应用

    PaddleHub体验与应用——《青春有你2》五人识别

    这次实践需要使用到PaddleHub自制数据集(训练集、验证集)完成对指定的五名选手照片分类,难度稍微就会搞一些,主要是在数据集的制作上,因为我的数据集得出来结果也没有满分,只识别了三个人,就不进行分享了,膜拜其他满分的大佬。

    Day5-EasyDL体验与作业发布

    EasyDL体验与综合大作业

    综合大作业:
    第一步:爱奇艺《青春有你2》评论数据爬取
    爬取任意一期正片视频下评论
    评论条数不少于1000条
    第二步:词频统计并可视化展示
    数据预处理:清理清洗评论中特殊字符(如:@#¥%、emoji表情符),清洗后结果存储为txt文档
    中文分词:添加新增词(如:青你、奥利给、冲鸭),去除停用词(如:哦、因此、不然、也好、但是)
    统计top10高频词
    可视化展示高频词
    第三步:绘制词云
    根据词频生成词云
    可选项-添加背景图片,根据背景图片轮廓生成词云
    第四步:结合PaddleHub,对评论进行内容审核

    这一次的作业应该说对于学下来的总结是一次特别好的锻炼,挑战难度也不小,就分享一下最终的词频统计并可视化展示和词云吧

    #去除文本中特殊字符
    def clear_special_char(content):
    '''
    正则处理特殊字符
    参数 content:原文本
    return: 清除后的文本
    '''
    s = re.sub(r"</?(.+?)>|&nbsp;|\t|\r","",content)
    s = re.sub(r"\n","",s)
    s = re.sub(r"\*","\\*",s)
    s = re.sub("[^\u4e00-\u9fa5^a-z^A-Z^0-9]","",s)
    s = re.sub("[\001\002\003\004\005\006\007\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a]+","", s)
    s = re.sub("[a-zA-Z]","",s)
    s = re.sub("^d+(\.\d+)?$","",s)
    return s
    In[7]
    def fenci(text):
    '''
    利用jieba进行分词
    参数 text:需要分词的句子或文本
    return:分词结果
    '''
    jieba.load_userdict('add_word.txt')
    seg=jieba.lcut(text,cut_all=False)
    return seg
    In[8]
    def stopwordslist(file_path):
    '''
    创建停用词表
    参数 file_path:停用词文本路径
    return:停用词list
    '''
    stopwords=[line.strip() for line in open(file_path,encoding='UTF-8').readlines()]
    return stopwords
    In[9]
    def movestopwords(sentence,stopwords,counts):
    '''
    去除停用词,统计词频
    参数 file_path:停用词文本路径 stopwords:停用词list counts: 词频统计结果
    return:None
    '''
    out=[]
    for word in sentence:
    if word not in stopwords:
    if len(word)!=1:
    counts[word]=counts.get(word,0)+1
    return None
    
    In[10]
    def drawcounts(counts,num):
    '''
    绘制词频统计表
    参数 counts: 词频统计结果 num:绘制topN
    return:none
    '''
    x_aixs=[]
    y_aixs=[]
    c_order=sorted(counts.items(),key=lambda x:x[1],reverse=True)
    for c in c_order[:num]:
    x_aixs.append(c[0])
    y_aixs.append(c[1])
    
    matplotlib.rcParams['font.sans-serif']=['simhei']
    matplotlib.rcParams['axes.unicode_minus']=False
    plt.bar(x_aixs,y_aixs)
    plt.title('词频统计结果')
    plt.show()
    def drawcloud(word_f):
    '''
    根据词频绘制词云图
    参数 word_f:统计出的词频结果
    return:none
    '''
    cloud_mask=np.array(Image.open('111.png'))
    st = set(["这是","东西"])
    
    wc=WordCloud(background_color='white',
    mask=cloud_mask,
    max_words=150,
    font_path='simhei.ttf',
    min_font_size=10,
    max_font_size=100,
    width=400,
    relative_scaling=0.3,
    stopwords=st)
    wc.fit_words(word_f)
    wc.to_file('pic.png')


    display(Image.open('pic.png')) #显示生成的词云图像

    踩过的小坑:

    这一个就是代码中的小细节问题了,一个逗号就会让你不小心停留二十分钟,千万注意;

    如果出现:ValueError: unknown file extension,特别注意文件的后缀名是否正确;

    json.loads 和 json.dump的区别:
    json.loads(str(data):将一个JSON编码的字符串转换回一个Python数据结构(通常为字典
    json.dump(json_data): 将一个Python数据结构转换为JSON字符串,通常在写文件的时候使用。

    Day6-PaddleHub创意赛发布

    Day7-课程结营

    7天的课程转瞬即逝,认真跟随着百度飞桨的老师们学习收获特别大,在此特别感谢组织学习的工作人员辛苦付出,为百度飞桨PaddlePaddle点赞,希望接下来有更好的课程也能继续学习。
    最后,文笔不好写得不对的多多包涵!

    熊和敲不完的代码 原创文章 1获赞 1访问量 118 关注 私信
    内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
    标签: