爬取两万多数据,告诉你广州房租价格现状(4)

链家二手房交易数据集,爬虫爬取,原始数据,未做处理,csv文件 爬取数据资源,仅供初学python数据分析使用,数据是原始数据未做修改 水道子胡同 1室0厅 10.8平米 西南 | 其他 2020.04.13 100万 底层(共1层) 板楼 房屋满五年 挂牌100万成交周期1天 名字免费咨询 立即下载

爬虫利器初体验(1)

听说你的爬虫又被封了?(2)

爬取数据不保存,就是耍流氓(3)

爬取两万多租房数据,告诉你广州房租现状(4)

scrapy 也能爬取妹子图?(5)

概述

  • 前言
  • 统计结果
  • 爬虫代码实现
  • 爬虫分析实现
  • 后记

前言

八月份的时候,由于脑洞大开,决定用 python 爬虫爬取了深圳的租房数据,并写了文章《用Python告诉你深圳房租有多高》,文章得到了一致好评和众多转载。由于我本身的朋友圈大多都在广州、深圳,因此,早就有挺多小伙伴叫我分析一下广州的租房价格现状,这不,文章就这样在众多呼声中出炉了。然后,此次爬虫技术也升级了,完善了更多细节。源码值得细细探究。此次分析采集了广州 11 个区,23339 条数据,如下图:
样本数据

其中后半部分地区数据量偏少,是由于该区房源确实不足。因此,此次调查也并非非常准确,权且当个娱乐项目,供大家观赏。

统计结果

我们且先看统计结果,然后再看技术分析。
广州房源分布:(按区划分)
其中天河占据了大部分房源。但这块地的房租可是不菲啊。次之的是海珠、番禺。
房源分布

房租单价:(每月每平方米单价 – 平均数)
即是 1 平方米 1 个月的价格。方块越大,代表价格越高。
房租单价:平方米/月

可以看出天河、越秀、海珠都越过了 50 大关,分别是 75.042 、64.249、59.621 ,是其他地区的几倍。如果在天河租个 20 平方的房间:

75.042 x 20 = 1500.84

再来个两百的水电、物业:

1500.84 + 200 = 1700.84

我们按正常生活来算的话,每天早餐 10 块,中午 15 块,晚饭 15 块:

1700.84 + 40 x 30 = 2700.84

那么平时的日常生活需要 2700.84 块。
隔断时间下个馆子,每个月买些衣服,交通费,谈个女朋友,与女朋友出去逛街,妥妥滴加个 2500

2700.84 + 2500 = 5200.84

给爸妈一人一千:

5200.84 + 2000 = 7200.84

月薪一万还是有点存款的,比深圳好一点,但是可能广州的薪资就没深圳那么高了。

房租单价:(每日每平方米单价 – 平均数)

即是 1 平方米 1 天的价格。

租房单价:平方米/日

哈哈,感受一下寸土寸金的感觉。[捂脸]

崩溃

户型
户型主要以 3 室 2 厅与 2 室 2 厅为主。与小伙伴抱团租房是最好的选择了,不然与不认识的人一起合租,可能会发生一系列让你不舒服的事情。字体越大,代表户型数量越多。
户型

户型

租房面积统计
其中 30 - 90 平方米的租房占大多数,如今之计,也只能是几个小伙伴一起租房,抱团取暖了。
租房面积统计

租房描述词云
这是爬取的租房描述,其中字体越大,标识出现的次数越多。其中【住家、全套、豪华、齐全】占据了很大的部分,说明配套设施都是挺齐全的。
租房描述

爬虫技术分析

  • 请求库:scrapy、requests
  • HTML 解析:BeautifulSoup
  • 词云:wordcloud
  • 数据可视化:pyecharts
  • 数据库:MongoDB
  • 数据库连接:pymongo

爬虫代码实现

跟上一篇文章不一样,这是使用了 scrapy 爬虫框架来爬取数据,各个方面也进行了优化,例如:自动生成各个页面的地址。
由于房某下各个区域的首页地址和首页以外的地址的形式是不一样的,但是又一定的规律,所以需要拼接各个部分的地址。
首页地址案例:

# 第一页
http://gz.zu.fang.com/house-a073/

非首页地址:

# 第二页
http://gz.zu.fang.com/house-a073/i32/
# 第三页
http://gz.zu.fang.com/house-a073/i33/
# 第四页
http://gz.zu.fang.com/house-a073/i34/


先解析首页 url
def head_url_callback(self, response):
    soup = BeautifulSoup(response.body, "html5lib")
    dl = soup.find_all("dl", attrs={"id": "rentid_D04_01"})  # 获取各地区的 url 地址的 dl 标签
    my_as = dl[0].find_all("a")  # 获取 dl 标签中所有的 a 标签,
    for my_a in my_as:
        if my_a.text == "不限":  # 不限地区的,特殊处理
            self.headUrlList.append(self.baseUrl)
            self.allUrlList.append(self.baseUrl)
            continue
        if "周边" in my_a.text:  # 清除周边地区的数据
            continue
        # print(my_a["href"])
        # print(my_a.text)
        self.allUrlList.append(self.baseUrl + my_a["href"])
        self.headUrlList.append(self.baseUrl + my_a["href"])
    print(self.allUrlList)
    url = self.headUrlList.pop(0)
    yield Request(url, callback=self.all_url_callback, dont_filter=True)
再解析非首页 url

这里先获取到各个地区一共有多少页,才能拼接具体的页面地址。

# 再根据头部 url 拼接其他页码的url
def all_url_callback(self, response): # 解析并拼接所有需要爬取的 url 地址
    soup = BeautifulSoup(response.body, "html5lib")
    div = soup.find_all("div", attrs={"id": "rentid_D10_01"})  # 获取各地区的 url 地址的 dl 标签
    span = div[0].find_all("span")  # 获取 dl 标签中所有的 span 标签,
    span_text = span[0].text
    for index in range(int(span_text[1:len(span_text) - 1])):
        if index == 0:
            pass
            # self.allUrlList.append(self.baseUrl + my_a["href"])
        else:
            if self.baseUrl == response.url:
                self.allUrlList.append(response.url + "house/i3" + str(index + 1) + "/")
                continue
            self.allUrlList.append(response.url + "i3" + str(index + 1) + "/")
    if len(self.headUrlList) == 0:
        url = self.allUrlList.pop(0)
        yield Request(url, callback=self.parse, dont_filter=True)
    else:
        url = self.headUrlList.pop(0)
        yield Request(url, callback=self.all_url_callback, dont_filter=True)
最后解析一个页面的数据
def parse(self, response): # 解析一个页面的数据
    self.logger.info("==========================")
    soup = BeautifulSoup(response.body, "html5lib")
    divs = soup.find_all("dd", attrs={"class": "info rel"})  # 获取需要爬取得 div
    for div in divs:
        ps = div.find_all("p")
        try:  # 捕获异常,因为页面中有些数据没有被填写完整,或者被插入了一条广告,则会没有相应的标签,所以会报错
            for index, p in enumerate(ps):  # 从源码中可以看出,每一条 p 标签都有我们想要的信息,故在此遍历 p 标签,
                text = p.text.strip()
                print(text)  # 输出看看是否为我们想要的信息
            roomMsg = ps[1].text.split("|")
            area = roomMsg[2].strip()[:len(roomMsg[2]) - 1]
            item = RenthousescrapyItem()
            item["title"] = ps[0].text.strip()
            item["rooms"] = roomMsg[1].strip()
            item["area"] = int(float(area))
            item["price"] = int(ps[len(ps) - 1].text.strip()[:len(ps[len(ps) - 1].text.strip()) - 3])
            item["address"] = ps[2].text.strip()
            item["traffic"] = ps[3].text.strip()
            if (self.baseUrl+"house/") in response.url: # 对不限区域的地方进行区分
                item["region"] = "不限"
            else:
                item["region"] = ps[2].text.strip()[:2]
            item["direction"] = roomMsg[3].strip()
            print(item)
            yield item
        except:
            print("糟糕,出现 exception")
            continue
    if len(self.allUrlList) != 0: 
        url = self.allUrlList.pop(0)
        yield Request(url, callback=self.parse, dont_filter=True)

数据分析实现

这里主要通过 pymongo 的一些聚合运算来进行统计,再结合相关的图标库,来进行数据的展示。
数据分析:

    # 求一个区的房租单价(平方米/元)
    def getAvgPrice(self, region):
        areaPinYin = self.getPinyin(region=region)
        collection = self.zfdb[areaPinYin]
        totalPrice = collection.aggregate([{'$group': {'_id': '$region', 'total_price': {'$sum': '$price'}}}])
        totalArea = collection.aggregate([{'$group': {'_id': '$region', 'total_area': {'$sum': '$area'}}}])
        totalPrice2 = list(totalPrice)[0]["total_price"]
        totalArea2 = list(totalArea)[0]["total_area"]
        return totalPrice2 / totalArea2

    # 获取各个区 每个月一平方米需要多少钱
    def getTotalAvgPrice(self):
        totalAvgPriceList = []
        totalAvgPriceDirList = []
        for index, region in enumerate(self.getAreaList()):
            avgPrice = self.getAvgPrice(region)
            totalAvgPriceList.append(round(avgPrice, 3))
            totalAvgPriceDirList.append({"value": round(avgPrice, 3), "name": region + "  " + str(round(avgPrice, 3))})

        return totalAvgPriceDirList

    # 获取各个区 每一天一平方米需要多少钱
    def getTotalAvgPricePerDay(self):
        totalAvgPriceList = []
        for index, region in enumerate(self.getAreaList()):
            avgPrice = self.getAvgPrice(region)
            totalAvgPriceList.append(round(avgPrice / 30, 3))
        return (self.getAreaList(), totalAvgPriceList)

    # 获取各区统计样本数量
    def getAnalycisNum(self):
        analycisList = []
        for index, region in enumerate(self.getAreaList()):
            collection = self.zfdb[self.pinyinDir[region]]
            print(region)
            totalNum = collection.aggregate([{'$group': {'_id': '', 'total_num': {'$sum': 1}}}])
            totalNum2 = list(totalNum)[0]["total_num"]
            analycisList.append(totalNum2)
        return (self.getAreaList(), analycisList)

    # 获取各个区的房源比重
    def getAreaWeight(self):
        result = self.zfdb.rent.aggregate([{'$group': {'_id': '$region', 'weight': {'$sum': 1}}}])
        areaName = []
        areaWeight = []
        for item in result:
            if item["_id"] in self.getAreaList():
                areaWeight.append(item["weight"])
                areaName.append(item["_id"])
                print(item["_id"])
                print(item["weight"])
                # print(type(item))
        return (areaName, areaWeight)

    # 获取 title 数据,用于构建词云
    def getTitle(self):
        collection = self.zfdb["rent"]
        queryArgs = {}
        projectionFields = {'_id': False, 'title': True}  # 用字典指定需要的字段
        searchRes = collection.find(queryArgs, projection=projectionFields).limit(1000)
        content = ''
        for result in searchRes:
            print(result["title"])
            content += result["title"]
        return content

    # 获取户型数据(例如:3 室 2 厅)
    def getRooms(self):
        results = self.zfdb.rent.aggregate([{'$group': {'_id': '$rooms', 'weight': {'$sum': 1}}}])
        roomList = []
        weightList = []
        for result in results:
            roomList.append(result["_id"])
            weightList.append(result["weight"])
        # print(list(result))
        return (roomList, weightList)

    # 获取租房面积
    def getAcreage(self):
        results0_30 = self.zfdb.rent.aggregate([
            {'$match': {'area': {'$gt': 0, '$lte': 30}}},
            {'$group': {'_id': '', 'count': {'$sum': 1}}}
        ])
        results30_60 = self.zfdb.rent.aggregate([
            {'$match': {'area': {'$gt': 30, '$lte': 60}}},
            {'$group': {'_id': '', 'count': {'$sum': 1}}}
        ])
        results60_90 = self.zfdb.rent.aggregate([
            {'$match': {'area': {'$gt': 60, '$lte': 90}}},
            {'$group': {'_id': '', 'count': {'$sum': 1}}}
        ])
        results90_120 = self.zfdb.rent.aggregate([
            {'$match': {'area': {'$gt': 90, '$lte': 120}}},
            {'$group': {'_id': '', 'count': {'$sum': 1}}}
        ])
        results120_200 = self.zfdb.rent.aggregate([
            {'$match': {'area': {'$gt': 120, '$lte': 200}}},
            {'$group': {'_id': '', 'count': {'$sum': 1}}}
        ])
        results200_300 = self.zfdb.rent.aggregate([
            {'$match': {'area': {'$gt': 200, '$lte': 300}}},
            {'$group': {'_id': '', 'count': {'$sum': 1}}}
        ])
        results300_400 = self.zfdb.rent.aggregate([
            {'$match': {'area': {'$gt': 300, '$lte': 400}}},
            {'$group': {'_id': '', 'count': {'$sum': 1}}}
        ])
        results400_10000 = self.zfdb.rent.aggregate([
            {'$match': {'area': {'$gt': 300, '$lte': 10000}}},
            {'$group': {'_id': '', 'count': {'$sum': 1}}}
        ])
        results0_30_ = list(results0_30)[0]["count"]
        results30_60_ = list(results30_60)[0]["count"]
        results60_90_ = list(results60_90)[0]["count"]
        results90_120_ = list(results90_120)[0]["count"]
        results120_200_ = list(results120_200)[0]["count"]
        results200_300_ = list(results200_300)[0]["count"]
        results300_400_ = list(results300_400)[0]["count"]
        results400_10000_ = list(results400_10000)[0]["count"]
        attr = ["0-30平方米", "30-60平方米", "60-90平方米", "90-120平方米", "120-200平方米", "200-300平方米", "300-400平方米", "400+平方米"]
        value = [
            results0_30_, results30_60_, results60_90_, results90_120_, results120_200_, results200_300_, results300_400_, results400_10000_
        ]
        return (attr, value)

数据展示:

    # 展示饼图
    def showPie(self, title, attr, value):
        from pyecharts import Pie
        pie = Pie(title)
        pie.add("aa", attr, value, is_label_show=True)
        pie.render()

    # 展示矩形树图
    def showTreeMap(self, title, data):
        from pyecharts import TreeMap
        data = data
        treemap = TreeMap(title, width=1200, height=600)
        treemap.add("深圳", data, is_label_show=True, label_pos='inside', label_text_size=19)
        treemap.render()

    # 展示条形图
    def showLine(self, title, attr, value):
        from pyecharts import Bar
        bar = Bar(title)
        bar.add("深圳", attr, value, is_convert=False, is_label_show=True, label_text_size=18, is_random=True,
                # xaxis_interval=0, xaxis_label_textsize=9,
                legend_text_size=18, label_text_color=["#000"])
        bar.render()

    # 展示词云
    def showWorkCloud(self, content, image_filename, font_filename, out_filename):
        d = path.dirname(__name__)
        # content = open(path.join(d, filename), 'rb').read()
        # 基于TF-IDF算法的关键字抽取, topK返回频率最高的几项, 默认值为20, withWeight
        # 为是否返回关键字的权重
        tags = jieba.analyse.extract_tags(content, topK=100, withWeight=False)
        text = " ".join(tags)
        # 需要显示的背景图片
        img = imread(path.join(d, image_filename))
        # 指定中文字体, 不然会乱码的
        wc = WordCloud(font_path=font_filename,
                       background_color='black',
                       # 词云形状,
                       mask=img,
                       # 允许最大词汇
                       max_words=400,
                       # 最大号字体,如果不指定则为图像高度
                       max_font_size=100,
                       # 画布宽度和高度,如果设置了msak则不会生效
                       # width=600,
                       # height=400,
                       margin=2,
                       # 词语水平摆放的频率,默认为0.9.即竖直摆放的频率为0.1
                       prefer_horizontal=0.9
                       )
        wc.generate(text)
        img_color = ImageColorGenerator(img)
        plt.imshow(wc.recolor(color_func=img_color))
        plt.axis("off")
        plt.show()
        wc.to_file(path.join(d, out_filename))
        
    # 展示 pyecharts 的词云
    def showPyechartsWordCloud(self, attr, value):
        from pyecharts import WordCloud
        wordcloud = WordCloud(width=1300, height=620)
        wordcloud.add("", attr, value, word_size_range=[20, 100])
        wordcloud.render()

后记

距离上一篇租房市场的分析已经3、4 个月了,我的技术水平也得到了一定的提高。所以努力编码才是成长的捷径。最后,应对外界条件的变动,我们还是应该提升自己的硬实力,这样才能提升自己的生存能力。

本篇文章首发于公众号「zone7」,关注公众号获取最新推文,后台回复【广州租房】获取源码。

zone_qrcode.jpg

广州链家网数据 通过爬虫获取的链家网广州二手房数据,其中包含位置、户型、价格、关注人数等字段 立即下载

相关推荐

BEVFormer与TensorRT的完美结合:如何实现4倍推理加速?

本文详细解析了如何通过TensorRT的量化技术和自定义插件实现BEVFormer模型的4倍推理加速,同时保持精度损失小于1%。文章从模型架构与部署挑战入手,深入探讨了计算图优化、自定义插件开发和量化校准策略,并提供了完整的部署流程和性能调优技巧,为自动驾驶领域的实时3D感知提供了高效解决方案。

bean的博客 221

广州链接租房数据分析报告

weixin_43765830的博客 724

告别有线:用PVE直通无线网卡,打造一台真正的‘无线’Win10软路由/测试机

本文详细介绍了如何通过PVE直通无线网卡技术,构建全无线Win10软路由或测试机。从硬件选型、PVE环境配置到PCIe和USB双模直通技术,逐步指导实现Wi-Fi AP和蓝牙连接功能,为家庭实验室和小型办公环境提供灵活高效的网络解决方案。

weixin_28683689的博客 587

Scrapy框架系列--综合案例之租房数据的现状(4)

概述前言统计结果爬虫代码实现爬虫分析实现后记前言建议在看这篇文章之前,请看完这三篇文章,因为本文是依赖于前三篇文章的:爬虫利器初体验(1)听说你的爬虫又被封了?(2)爬取...

lsxxx2011的专栏 506

TexGen模型导出到ABAQUS的inp文件:如何快速修改纱线材料属性(避坑指南)

本文针对TexGen模型导出到ABAQUS的inp文件后纱线材料属性缺失或错误的问题,提供了高效的解决方案。文章详细解析了inp文件结构,指导用户如何手动定位并修改纱线材料属性,并提供了可批量处理的Python脚本,帮助用户快速、精准地完成材料参数赋值,有效提升复合材料仿真工作效率。

ice55的博客 603

STM32通过ESP8266连接机智云APP(第二讲,烧录固件并测试)

今天与大家分享STM32通过ESP8266连接机智云APP,并完成数据的上传下发第二讲。带大家一起烧录机智云固件到ESP8266并且将其通过机智云串口助手与APP进行测试。

qq_63267523的博客 1425

用Python统计上海各地区房子均价

刚学习Python,做个爬虫练练手额,写的有点菜,大佬不要吐槽φ(>ω<*)

一个卑微的java开发 948

3D识别建模 — 基于ReconstructMe和EAGLE EYES SCANNER的实现

3D实体识别建模,作为3D打印反向工程的一个重要环节,今天就让我们利用ReconstructMe和EAGLE EYES SCANNER来了解一下。 第一步、软件和硬件准备就绪 ReconstructMe下载并安装 http://reconstructme.net/?wpdmdl=160 EAGLE EYES SCANNER直接将相应USB插入电脑接口即OK,之后在    中点击搜索“设备管理...

qq_40013290的博客 881

学生学徒作品分享——金融大模型-房屋租金价格影响因素分析与预测

金融大模型-房屋租金价格影响因素分析与预测项目背景

tipdm0526的博客 684

实战:GMTSAR软件处理陆探一号SAR数据

摘要:陆探一号(LT-1)是我国首组L波段差分干涉SAR卫星星座,具备全天候多极化成像能力,主要服务于自然资源监测等领域。文章详细介绍了其轨道参数(607km太阳同步轨道)和传感器技术指标(5种成像模式)。同时阐述了开源InSAR处理软件GMTSAR的安装方法(基于Ubuntu系统)及实验流程,包括数据准备、DEM生成和干涉处理步骤,特别说明了轨道数据缺失时的MATLAB插值处理方法。该研究为国产SAR卫星数据处理提供了技术参考。

一个RSer的博客 1034

Esp32蓝牙Hid调用方案 http执行设备、鼠标、键盘相关操作

本文主要介绍 Esp32 蓝牙 Hid 相关的多种操作方式,详细的设备、鼠标、键盘相关操作的 http 调用方法。下面是整理出的所有 http 调用方法和 rhino 引擎方式。本机调用的话直接使用http://localhost:8080 如果是局域网调用则使用软件里的地址 比如我的是http://192.168.1.5:8080。文件地址: https://www.123865.com/s/Qtm4jv-xyZbd?使用前需要一块烧录好的ESP32板子并在手机安装好embedded软件用于蓝牙通信。

代码简单说 Vue、JAVA、PHP、Node.js 熟练运用,接口、架构、性能全搞定。 569

Pandas+Pyecharts | 广州市已成交房源信息数据可视化

本期我们通过分析广州市30000+条已成交房源信息数据,分析广州市房价以及房源分布情况

Python当打之年 2759

【SpringBoot 3.x 第56节】再见 Feign?原生 HTTP 接口强势上位,这才是微服务调用的正确姿势!

🏆本文收录于《滚雪球学SpringBoot 3》,专门攻坚指数提升,本年度国内最系统+最专业+最详细(永久更新)。    本专栏致力打造最硬核 SpringBoot3 从零基础到进阶系列学习内容,🚀均为全网独家首发,打造精品专栏,专栏持续更新中…欢迎大家订阅持续学习。 如果想快速定位学习,可以看这篇【SpringBoot3教程导航帖】,你想学习的都被收集在内,快速投入学习!!两不误。    若还想学习更多,可直接前往《滚雪球学SpringBoot(全版本合集)》,涵盖SpringBoot所有版本教学文章

**My Coding Family** 1017

python爬虫分析——广州租房信息爬取并分析

Python数据分析之广州租房信息爬取与分析

LSH1628340121的博客 3235

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

爬取两万多条租房数据,算算在广州你能「活到」第几集?

作者 | zone7 责编 | 仲培艺 此前,笔者曾用 Python 爬取 1.7 万条租房数据,并据此撰文揭示了深圳房价飙升背后的生存压力。此番再析广州租房价格现状,在升级爬虫技术之余,也完善了更多细节,源码颇值细细探究。此次分析采集了广州 11 个区,23339 条数据,如下图: 样本数据 其中后半部分地区数据量偏少,是由于该区房源确实不足。因此,此次调查也并非非常准确,权且当...

优快云头条 1300

老版QQ原生表情gif动态

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

爬取房天下数据观察广州房租情况

新的一年,有房东提出了涨租,也有跳槽的小伙伴,考虑租房换房,趁着这个时点,再来说说租房的事,找到合适的房子是头等大事,接下来让我们通过爬取房天下数据来观察广州房租情况。(结果图在最后面,想看结果图的小伙伴自行往下滑动) 第一步、爬取数据 爬取的时间是2019年12月份,爬取的代码如下 import csv from selenium import webdriver chrome_driver ...

qq_41897030的博客 487

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

爬取两万多租房数据,告诉你广州房租现状(4)

概述前言统计结果爬虫代码实现爬虫分析实现后记前言建议在看这篇文章之前,请看完这三篇文章,因为本文是依赖于前三篇文章的:爬虫利器初体验(1)听说你的爬虫又被封了?(2)爬取数据不保存,就是...

zone_的博客 388

用Python告诉你广州房租现状

♚作者:zone7,一只爱折腾的后端攻城狮,喜欢写文分享。概述前言统计结果爬虫代码实现爬虫分析实现后记前言由于我本身的朋友圈大多都在广州、深圳,因此,早就有挺多小伙伴叫我...

Python中文社区 571

数据分析告诉你:房租大涨的锅自如背不背?

今年8月初,房租同比大幅上涨。一些文章直指以自如为首的品牌公寓巨头哄抬房租,通过抢房、囤房等操作,使房租高企。很快,自如CEO熊林发表声明称,品牌公寓市场占比极小,对房租的影响微乎其微。那么,品牌公寓对房租的影响到底如何呢? 我们爬取了自如网、蛋壳网和房天下三个网站近万条数据并进行分析。自如和蛋壳是两家品牌公寓,房天下为个人发布租房信息的平台。首先,我们爬取了回龙观、天通苑、北苑、沙河4个社区集...

工药叉的经文 1359

利用Python来分析一下一线城市的房租在工资中占比高吗?

本文是一个完成度较高的数据采集+分析+可视化案例,来自编程教室读者的投稿。 在这个案例中,作者从网上公开信息中获取了不同城市的租房价格和工资水平,对数据进行整理之后,对比分析了不同条件下房租占工资的比重。 这个案例我们分了 3 篇文章,本篇是整体思路和最终结果展示。其中的可视化部分没有使用 Python 编写,而是采用了 FineReort 软件直接生成,所以略去使用细节。FineReort ...

爬遍所有网站 460
上一篇: 爬取数据不保存,就是耍流氓(3)
下一篇: 2018 年终总结
zone7_
博客等级 码龄10年 144粉丝 133原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值