webmagic之Redis调度器

WebMagic简明教程(一) WebMagic简明教程(一)前言做项目需要爬取一些数据,不想用Python,就尝试了下webmagic这个爬虫框架,总的来说上手还是比较简单的,这里来总结一下.webmagic是一个简单灵活的Java爬虫框架,如果你熟悉Java而且不想用Python写爬虫,那么webmagic是一个不错的选择.实战日常前戏 首先呢,咱们来先把jar包下载下来:https://github.com/code4cra 阅读详情

爬虫redis调度器实现功能如下:

  • 待爬取url判重(列表页或详细页);
  • 待爬取url存储至本地内存;
  • 待爬取url存储至redis(列表页或详细页);
  • 待爬取url添加优先级(加入评分score,以便优先爬取)
  • 入队出队逻辑

talk is cheap,show you guys the code:

public class RedisScheduler extends DuplicateRemovedScheduler implements MonitorableScheduler, DuplicateRemover {
    private JedisPool pool;
    private String spiderUUID;
    private boolean isEmpty;
    private static final String QUEUE_PREFIX = "queue_";
    private static final String SET_PREFIX = "set_";
    private static final String ITEM_PREFIX = "item_";
    private BlockingQueue<Request> queue;

    public RedisScheduler(String host, int port, String password, String spiderUUID) {
        this(new JedisPool(new JedisPoolConfig(), host, port, 2000, password));
        this.spiderUUID = spiderUUID;
    }

    public RedisScheduler(JedisPool pool) {
        this.isEmpty = false;
        this.queue = new LinkedBlockingQueue();
        this.pool = pool;
        this.setDuplicateRemover(this);
    }

    public void resetDuplicateCheck(Task task) {
        Jedis jedis = this.pool.getResource();

        try {
            jedis.del(new String[]{this.getSetKey(task)});
        } finally {
            this.pool.returnResource(jedis);
        }

    }

    public boolean isDuplicate(Request request, Task task) {
        Jedis jedis = this.pool.getResource();
        Boolean nocheck = (Boolean)request.getExtra("nocheckdup");

        boolean var5;
        try {
            if (nocheck != null && nocheck) {
                var5 = false;
            } else {
                Long num = jedis.sadd(this.spiderUUID + ":dupefilter", new String[]{Decript.SHA1(request.getUrl())});
                if (num == 1L) {
                    var5 = false;
                } else {
                    var5 = true;
                }
            }
        } finally {
            this.pool.returnResource(jedis);
        }

        return var5;
    }

    protected void pushWhenNoDuplicate(Request request, Task task) {
        Jedis jedis = this.pool.getResource();
        int score = false;
        int score;
        if (request.getExtra("score") != null) {
            int tempScore = (Integer)request.getExtra("score");
            if (tempScore < 100) {
                score = tempScore * 100;
            } else {
                Integer i = (Integer)request.getExtra("retry");
                if (i != null) {
                    score = tempScore - i;
                } else {
                    score = tempScore;
                }
            }
        } else {
            score = 2000;
        }

        request.putExtra("score", score);

        try {
            jedis.zadd(this.spiderUUID + ":requests", (double)score, JSON.toJSONString(request));
        } finally {
            this.pool.returnResource(jedis);
        }

        this.isEmpty = false;
    }

    public synchronized void pushLocal(Request request) {
        try {
            this.queue.put(request);
        } catch (InterruptedException var3) {
            var3.printStackTrace();
        }

    }

    public synchronized Boolean listExists() {
        Jedis jedis = this.pool.getResource();

        Boolean exists;
        try {
            exists = jedis.exists(this.spiderUUID + ":list-requests");
        } finally {
            this.pool.returnResource(jedis);
        }

        return exists;
    }

    public synchronized Request listPoll() {
        Jedis jedis = this.pool.getResource();

        Request var8;
        try {
            String str = jedis.lpop(this.spiderUUID + ":list-requests");
            if (str == null) {
                var8 = null;
            } else {
                Request request = (Request)JSON.parseObject(str, Request.class);
                this.logger.debug("poll list from queue {}", request.getUrl());
                var8 = request;
            }
        } finally {
            this.pool.returnResource(jedis);
        }

        return var8;
    }

    public synchronized void setClusterStartFlag(String value) {
        Jedis jedis = this.pool.getResource();

        try {
            jedis.set(this.spiderUUID + ":cluster-status", value);
        } finally {
            this.pool.returnResource(jedis);
        }

    }

    public synchronized Long getClusterStartFlagVal() {
        Jedis jedis = this.pool.getResource();
        Long timestamp = null;

        try {
            Boolean isExist = this.getClusterStartFlag();
            if (isExist) {
                timestamp = Long.parseLong(jedis.get(this.spiderUUID + ":cluster-status"));
                jedis.del(this.spiderUUID + ":cluster-status");
            }
        } finally {
            this.pool.returnResource(jedis);
        }

        return timestamp;
    }

    public synchronized Boolean getClusterStartFlag() {
        Jedis jedis = this.pool.getResource();

        Boolean exists;
        try {
            exists = jedis.exists(this.spiderUUID + ":cluster-status");
        } finally {
            this.pool.returnResource(jedis);
        }

        return exists;
    }

    public synchronized void listPush(Request request) {
        Jedis jedis = this.pool.getResource();

        try {
            jedis.lpush(this.spiderUUID + ":list-requests", new String[]{JSON.toJSONString(request)});
        } finally {
            this.pool.returnResource(jedis);
        }

    }

    public synchronized Request poll(Task task) {
        if (this.queue.size() > 0) {
            return (Request)this.queue.poll();
        } else {
            Jedis jedis = this.pool.getResource();

            Request var8;
            try {
                Transaction t = jedis.multi();
                t.zrevrange(this.spiderUUID + ":requests", 0L, 0L);
                t.zremrangeByRank(this.spiderUUID + ":requests", -1L, -1L);
                Set<String> request1 = (Set)t.exec().get(0);
                Iterator it = request1.iterator();
                String str = null;

                while(true) {
                    if (!it.hasNext()) {
                        Map<String, String> a = (Map)JSON.parse(str);
                        if (str == null) {
                            var8 = null;
                        } else {
                            Request request = (Request)JSON.parseObject(str, Request.class);
                            this.logger.debug("poll from queue {}", request.getUrl());
                            var8 = request;
                        }
                        break;
                    }

                    str = (String)it.next();
                }
            } finally {
                this.pool.returnResource(jedis);
            }

            if (var8 == null) {
                this.isEmpty = true;
            } else {
                this.isEmpty = false;
            }

            return var8;
        }
    }

    protected String getSetKey(Task task) {
        return "set_" + task.getUUID();
    }

    protected String getQueueKey(Task task) {
        return "queue_" + task.getUUID();
    }

    public int getLeftRequestsCount(Task task) {
        Jedis jedis = this.pool.getResource();

        int var4;
        try {
            Long size = jedis.llen(this.getQueueKey(task));
            var4 = size.intValue();
        } finally {
            this.pool.returnResource(jedis);
        }

        return var4;
    }

    public int getTotalRequestsCount(Task task) {
        Jedis jedis = this.pool.getResource();

        int var4;
        try {
            Long size = jedis.scard(this.getSetKey(task));
            var4 = size.intValue();
        } finally {
            this.pool.returnResource(jedis);
        }

        return var4;
    }

    public boolean isEmpty() {
        return this.isEmpty;
    }
}

其中加密方法如下:

public class Decript {
    public Decript() {
    }

    public static String SHA1(String decript) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(decript.getBytes());
            byte[] messageDigest = digest.digest();
            StringBuffer hexString = new StringBuffer();

            for(int i = 0; i < messageDigest.length; ++i) {
                String shaHex = Integer.toHexString(messageDigest[i] & 255);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }

                hexString.append(shaHex);
            }

            return hexString.toString();
        } catch (NoSuchAlgorithmException var6) {
            var6.printStackTrace();
            return "";
        }
    }

    public static String SHA(String decript) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA");
            digest.update(decript.getBytes());
            byte[] messageDigest = digest.digest();
            StringBuffer hexString = new StringBuffer();

            for(int i = 0; i < messageDigest.length; ++i) {
                String shaHex = Integer.toHexString(messageDigest[i] & 255);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }

                hexString.append(shaHex);
            }

            return hexString.toString();
        } catch (NoSuchAlgorithmException var6) {
            var6.printStackTrace();
            return "";
        }
    }

    public static String MD5(String input) {
        try {
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(input.getBytes());
            byte[] md = mdInst.digest();
            StringBuffer hexString = new StringBuffer();

            for(int i = 0; i < md.length; ++i) {
                String shaHex = Integer.toHexString(md[i] & 255);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }

                hexString.append(shaHex);
            }

            return hexString.toString();
        } catch (NoSuchAlgorithmException var6) {
            var6.printStackTrace();
            return "";
        }
    }

    public static byte[] encryptAES(String content, String password) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(password.getBytes()));
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(1, key);
            byte[] result = cipher.doFinal(byteContent);
            return result;
        } catch (NoSuchAlgorithmException var9) {
            var9.printStackTrace();
        } catch (NoSuchPaddingException var10) {
            var10.printStackTrace();
        } catch (InvalidKeyException var11) {
            var11.printStackTrace();
        } catch (UnsupportedEncodingException var12) {
            var12.printStackTrace();
        } catch (IllegalBlockSizeException var13) {
            var13.printStackTrace();
        } catch (BadPaddingException var14) {
            var14.printStackTrace();
        }

        return null;
    }

    public static byte[] decryptAES(byte[] content, String password) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(password.getBytes()));
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(2, key);
            byte[] result = cipher.doFinal(content);
            return result;
        } catch (NoSuchAlgorithmException var8) {
            var8.printStackTrace();
        } catch (NoSuchPaddingException var9) {
            var9.printStackTrace();
        } catch (InvalidKeyException var10) {
            var10.printStackTrace();
        } catch (IllegalBlockSizeException var11) {
            var11.printStackTrace();
        } catch (BadPaddingException var12) {
            var12.printStackTrace();
        }

        return null;
    }

    public static String decryptBASE64(String key) {
        return "";
    }

    public static String encryptBASE64(String key) {
        return "";
    }

    public static String bytesToHexString(byte[] bArray) {
        StringBuffer sb = new StringBuffer(bArray.length);

        for(int i = 0; i < bArray.length; ++i) {
            sb.append('%');
            String sTemp = Integer.toHexString(255 & bArray[i]);
            if (sTemp.length() < 2) {
                sb.append(0);
            }

            sb.append(sTemp.toUpperCase());
        }

        return sb.toString();
    }
}

 

house_spider:Lianjia house spider链家二手房爬虫~ Springboot + Webmagic + Mysql + Redis house_spider Lianjia house spider链家二手房爬虫~ Springboot + Webmagic + Mysql + Redis 简介 - 基于Java8 +、开源爬虫框架WebMagic、Springboot的一个链家爬虫,上手即用,可以指定需要爬取的城市名称、或者爬取全国。 - 数据存Mysql,默认根据搜索城市+日期自动建表,如搜索“南京”,则会通过JDBC新建表:“南京_20191127” - 没有用WebMagic的Pipeline来存DB,而是直接用JDBC存的,默认爬虫线程数为1,每翻页1页批量插入Mysql。 - 由于链家限制爬取页数为100页,所以一个城市下,先查出所有行政区,再遍历行政区下的所有街道,以每个街道为单位,进行最大100页的爬取,这样基本上能爬下城市的所有房源数据。(部分别墅、车位直接忽略没存DB) 使用 基础依赖:安装mysq 立即下载

相关推荐

RK3576开发板ROS2部署实战:从Buildroot配置到Hello World Demo

本文详细介绍了在RK3576开发板上部署ROS2的完整实战流程。从Buildroot工程配置、集成ROS2依赖,到搭建Docker交叉编译环境、处理编译难题,最终完成系统镜像打包并在板端成功运行Talker-Listener Demo。该指南旨在帮助开发者深入理解嵌入式机器人系统的构建链,实现从底层到应用的完全掌控。

mac99的博客 1159

Webmgic使用redis去重,实现增量爬取

自定义RedisScheduler package com.jyft.reptileframework.confg; import com.alibaba.fastjson.JSON; import org.apache.commons.codec.digest.DigestUtils; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoo.

weixin_48974246的博客 1592

【机器人】线性方程最小二乘解法对机械臂DH参数进行标定

1.前言 看了一篇文章,觉得里面的DH参数标定法讲的很清晰,便使用Matlab复现了一下,效果还可以,特写此文记录。 2.原理 2.1.误差最佳值的最小二乘计算 有研究结果表明:几乎95%的机器人位置误差都是由机器人内部运动学的不准确描述引起的,所以对DH模型参数进行标定是很有必要的。 DH参数物理含义:选自《机器人学、机器视觉与控制-Matlab基础》 当DH参数确定后,我们...

要恰饭得嘛 1万+

webmagic结果保存到mysql_webmagic自定义存储(mysql、redis存储)

在很多时候,我们使用webmagic爬取网站的时候,爬取的数据希望存储在mysql、redis中。因此需要对其扩展,实行自定义PipeLine。首先我们了解一下webmagic 的四个基本组件一、 WebMagic的四个组件1、DownloaderDownloader负责从互联网上下载页面,以便后续处理。WebMagic默认使用了HttpClient作为下载工具。2、PageProcessorPa...

weixin_29182481的博客 574

Python读取三菱PLC数据

3、支持自定义的数据读写操作。直接调用Read方法,可以读取到原生的byte数组,然后进行组合数据。1、每次的数据交互您都可以判断是否成功,如果您不判断,如果网络断开或是异常,会影响程序的执行。Qna3E协议的ascii类 MelsecMcAsciiNet。A兼容1E协议的二进制类 MelsecA1ENet。Qna3E协议的二进制类 MelsecMcNet。2、读写操作支持单个数和数组。

weixin_46744807的博客 2000

【强化学习】强化学习中,训练过程的稳定性是什么?该如何进行衡量?请详细进行解释

在强化学习中,训练过程的稳定性指的是算法在训练过程中表现出一致的行为,并且能够稳定地收敛到一个好的策略。收敛性:算法是否能够在有限的时间内收敛到一个近似最优的策略。鲁棒性:算法在不同的初始条件或环境扰动下的表现是否稳定。方差:算法在多次运行中表现出的变异程度。稳定的训练过程意味着算法的训练曲线平滑奖励信号变化小,且策略或价值函数的变化是渐进的。

wq6qeg88的博客 1631

WebMagic实现分布式抓取以及断点抓取

访问我的博客 前言 从去年到今年,笔者主要负责的是与合作方的内容对接,新增的合作商不是很多的情况下,在我自从去年引入了 WebMagic 这个爬虫框架之后,基本很少需要去关注维护爬虫,做的最多的是新接入合作商去写对应爬虫抓取模板。 因为在代码中实现了增量抓取,单机也足以承担日常的抓取工作。 在前两周,由于公司拓展新的业务渠道,需要接入的合作商瞬间增加了 3 倍,又被要求在 2 天内全部接入,那两天...

weixin_34102807的博客 379

实例讲解Simulink CAN通讯丢失故障判定模型搭建及仿真测试验证方法

本文通过ABS通讯丢失故障触发、判定条件Simulink模型的搭建和仿真的讲解,介绍了一种控制器CAN通讯丢失故障判定的方法和建模方法,希望能给相关技术人员带来一定参考和帮助。

qq_43011586的博客 3686

WebMagic

今天学习一个酷炫的封装性很好的爬虫框架WebMagic 1、总体架构WebMagic总体架构图如下: 四个组件: * Downloader:负责从网络上下载页面,获取到初始的Html文本,供后续处理。默认使用Apache HttpClient作为下载工具。 PageProcessor:负责解析页面,抽取有用的信息,发现新链接。WebMagic使用Jsoup作为HTML解析工具,并基

phn_csdn的博客 825

11 指挥AI写C语言/嵌入式基础代码,适配硬件与底层逻辑

本文为《30天掌控AI编程:从指令到落地,手把手教你指挥AI写代码》系列第十一篇,正式进入第三阶段多场景实战环节。聚焦**C语言/嵌入式基础代码**生成,结合嵌入式开发的核心需求,讲解如何精准编写指令,指挥AI生成适配硬件、贴合底层逻辑的C语言代码,覆盖嵌入式常用底层功能、硬件适配要点、代码规范,搭配完整指令模板、AI输出示例与实操校验方法,零基础也能快速指挥AI完成嵌入式基础开发,无需死记硬背C语言底层语法。

coreopt的博客 141

uni-app:实现APP设置手机闹钟+取消闹钟+响铃重复/文字等,帮用户设置好闹钟并备注文本,uni-app设置安卓系统闹钟和苹果ios系统闹钟(uniapp调用手机上的闹钟,详细示例代码demo)

uniapp设置安卓和iOS闹钟的插件,uni-app设置安卓系统闹钟,uniapp设置苹果ios系统闹钟,uniapp设置定时闹铃的完整解决方案,UniApp设置手机闹钟,uniApp如何设置手机闹铃,uniapp设置闹钟,设置闹钟提醒,uni-app设置安卓系统闹钟_通过uniapp设置原声闹钟,调用android系统闹钟,如何在App中启动系统闹钟,uniapp如何取消闹钟,通过调用ios的原生接口来设置手机闹钟,uni-app 调用手机闹钟功能,uniap调用ios系统闹钟,uniapp调用手机上的

✅ 精选推荐文章 4235

爬虫学习笔记-WebMagic初识

WebMagic是一款基于Java开源的简单灵活的爬虫框架,使用起来非常简单,与Scrapy爬虫框架很相似,WebMagic的原理与使用官方有详细的说明,这里就不再陈述,直接上实例。使用说明链接地址: http://webmagic.io/docs/zh/ us.codecraft webmagic-core 0.5.3 us.codecr

PURSUE ONE PIECE 2061

n8n AI高效工作流自动化 部署使用教程

摘要: n8n是一款开源可视化工作流自动化工具,结合AI能力可高效解决重复性任务。文章详细介绍了从Docker部署到实战应用的完整流程:1)通过Docker Compose自托管n8n,确保数据可控;2)以AI客服日报机器人为例,演示如何串联工单系统、ChatGPT和邮件通知,实现定时自动化;3)进阶搭建交互式AI助手,利用ToolsAgent节点调用业务API;4)整合向量数据库构建RAG知识库问答。关键建议包括:拆分复杂工作流、严格管理凭据、区分开发与生产环境,并建议从高频刚性需求(如日报生成)切入,逐

专注AI大模型,软件混淆,授权 267

WebMagic springboot 多站点垂直数据采集(支持插队采集)

WebMagic springboot 多站点垂直数据采集(支持插队采集)

解忧小童子 1282

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

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

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

Java爬虫—WebMagic

WebMagic企业开发,比HttpClient和JSoup更方便WebMagic有DownLoad,PageProcessor,Schedule,Pipeline四大组件,并有Spider将他们组织起来,这四大组件对应就是爬虫的下载,处理,管理,持久化等功能。

qq_52655865的博客 2082

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

突破单机限制:WebMagic分布式爬虫的Redis协调实战指南

你是否还在为爬虫任务单机运行效率低下而困扰?当面对海量数据采集需求时,单节点爬虫往往因内存不足、带宽限制和任务调度瓶颈而难以胜任。本文将带你探索如何利用WebMagic框架结合Redis实现分布式任务调度,通过共享队列与去重机制,让多台服务器协同工作,轻松应对大规模数据爬取挑战。读完本文,你将掌握分布式爬虫的核心实现原理、Redis调度器的配置方法以及完整的集群部署流程。 ## 分布式爬虫的核心...

gitblog_00964的博客 950

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

【JAVA】Webmagic 爬虫框架,带着问题解读源码

无意中发现了一个巨牛的人工智能教程,忍不住分享一下给大家。教程不仅是零基础,通俗易懂,而且非常风趣幽默,像看小说一样!觉得太牛了,所以分享给大家。点这里可以跳转到教程。 前言 github地址 https://github.com/cwtree/webmagic WebMagic的设计参考了业界最优秀的爬虫Scrapy,而实现则应用了HttpClient、Jsoup等Java世界最成熟的工...

三也_攻城狮 2063

java使用WebMagic架构写个分布式爬虫

前一个项目是通过java完成,因此,本次大型项目依然需要用java语言,但是这里是需要分布式爬虫,所以的需要使用WebMagic 架构。 我们知道WebMagic 是一个功能强大且灵活的 Java 爬虫框架,支持多线程和分布式抓取。要实现基于 WebMagic 的分布式爬虫,需要结合其核心组件与扩展功能,并通过一些外部工具或服务来协调多个爬虫实例之间的任务分配与数据共享。

weixin_44617651的博客 1232

【Java-Crawler】一文学会使用WebMagic爬虫框架

爬虫主要分为采集、处理、存储三个部分。在学 WebMagic 框架之前,需要了解 HttpClient、Jsoup(Java HTML Parse) 库,因为 WebMagic 框架内部运用了他们,在你出现问题看源码去查错时,如果不知道 HttpClient、Jsoup 的话,可能不知道怎么回事。主要是 WebMagic 如果脱离了这俩就不能说是一个容易入门的爬虫框架了。WebMagic的结构分为Downloader、PageProcessor、Scheduler、Pipeline四大组件。

qq_63691275的博客 1293

webmagic spider.java_爬虫框架Webmagic源码分析之Spider

本系列文章,针对Webmagic 0.6.1版本一个普通爬虫启动代码public static void main(String[] args) {Spider.create(new GithubRepoPageProcessor())从https:github.com/code4craft开始抓.addUrl("https://github.com/code4craft")//设置Schedul...

weixin_39670267的博客 477

WebMagic分布式爬虫终极指南:RedisScheduler与集群协调完整方案

WebMagic是一个功能强大的Java爬虫框架,而RedisScheduler正是其分布式爬虫架构的核心组件。通过Redis作为统一的任务调度中心,WebMagic能够实现多机协作、负载均衡的分布式爬虫系统。本文将详细介绍如何使用RedisScheduler构建高性能的分布式爬虫集群。 ## 🔥 为什么需要RedisScheduler? 在传统的单机爬虫中,URL队列和去重机制都存储在内存

gitblog_01122的博客 495

爬虫伦理实战指南:WebMagic如何合规爬取与频率控制

你是否曾因爬虫被目标网站封禁IP?是否担心因爬取行为引发法律风险?本文将通过WebMagic框架的核心功能,从技术角度详解如何实现合规爬虫开发,重点解决robots协议遵守与爬取频率控制两大痛点。读完本文你将掌握: - 3行代码实现爬虫频率控制 - 自动解析robots.txt的正确姿势 - 分布式环境下的去重策略 - 企业级爬虫的伦理配置最佳实践 ## 爬取频率控制:从源码解析到实战配置 W...

gitblog_00004的博客 1156

WebMagic架构深度解析:从入门到精通的Java爬虫框架完整指南

WebMagic是一个**高度可扩展的Java垂直爬虫框架**,它覆盖了爬虫的整个生命周期:下载、URL管理、内容抽取和持久化。通过简洁的API设计和模块化架构,WebMagic让开发者能够专注于业务逻辑,而不必担心底层实现细节。🚀 ## 🎯 WebMagic核心架构设计 WebMagic的架构设计借鉴了Python著名爬虫框架Scrapy,采用**模块化分层设计**,每个组件都可以独立扩

gitblog_00558的博客 757

webmagic小试牛刀

为什么80%的码农都做不了架构师?>>> ...

weixin_34391445的博客 103

人工智能开发 网络爬虫框架Webmagic

1谈谈网络爬虫 1.1什么是网络爬虫 在大数据时代,信息的采集是一项重要的工作,而互联网中的数据是海量的,如果单纯靠人力进行信息采集,不仅低效繁琐,搜集的成本也会提高。如何自动高效地获取互联网中我们感兴趣的信息并为我们所用是一个重要的问题,而爬虫技术就是为了解决这些问题而生的。 网络爬虫(Web crawler)也叫做网络机器人,可以代替人们自动地在互联网中进行数据信息的采集与整理。它是一种按照一...

kai46385076的专栏 917

【转】WebMagic-总体流程源码分析

转自:http://m.blog.youkuaiyun.com/article/details?id=51943601   写在前面 前一段时间开发【知了】用到了很多技术(可以看我前面的博文http://blog.youkuaiyun.com/wsrspirit/article/details/51751568),这段时间抽空把这些整理一下,WebMagic是一个Java的爬虫,中国人写的,代码很模块化,也很利于二...

weixin_33862188的博客 124
上一篇: 按目录层级打印指定路径下的所有文件名
下一篇: redis.clients.jedis.exceptions.JedisConnectionException之异常解决
zhg_vincent
博客等级 码龄12年 93粉丝 45原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值