项目-26-热帖排行

Ubuntu22.04中通过conda快速部署PyTorch开发环境(CPU/GPU双版本实战) 本文详细介绍了在Ubuntu22.04系统中,如何利用Conda高效部署PyTorch开发环境。文章分别提供了CPU与GPU双版本的实战教程,涵盖环境创建、镜像加速、版本匹配及深度验证等关键步骤,旨在帮助开发者快速搭建稳定、兼容的深度学习环境,从而专注于模型开发。 阅读详情

热帖排行

  • 实现,在发帖、点赞、加精时将发生变化的帖子存入Redis中。再通过定时任务,每隔一定的时间,计算帖子的分数进行更新
  • 新建PostScoreRefreshJob类进行处理

1.RedisKeyUtil

//帖子分数
public static String getPostScoreKey(){
    return PREFIX_POST + SPLIT + "score";
}

2.处理Controller

DiscussPostController

	//发布帖子
    @RequestMapping(path = "/add", method = RequestMethod.POST)
    @ResponseBody
    public String addDiscussPost(String title, String content) {
        User user = hostHolder.getUser();
        if (user == null) {
            return CommunityUtil.getJSONString(403, "你还没有登录哦!");
        }

        DiscussPost post = new DiscussPost();
        post.setUserId(user.getId());
        post.setTitle(title);
        post.setContent(content);
        post.setCreateTime(new Date());
        discussPostService.addDiscussPost(post);

        //在发布帖子时,异步地将帖子存到es中
        //使用生产者生产事件
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(post.getId())
                .setUserId(user.getId());
        eventProducer.fireEvent(event);
        //发布帖子时,也会有初始的分数,将其存在Redis
        String redisKey = RedisKeyUtil.getPostScoreKey();
        //选择set的原因:set中没有重复的数据,因此可保证我们不会存入多个重复的帖子,减少后面的计算量
        redisTemplate.opsForSet().add(redisKey, post.getId());
        //报错的情况,将来统一处理.
        return CommunityUtil.getJSONString(0, "发布成功!");
    }
    

	//加精
    @RequestMapping(path = "/wonderful", method = RequestMethod.POST)
    @ResponseBody
    public String setWonderful(int id) {
        discussPostService.updateStatus(id, 1);

        // 触发发帖事件
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(id);
        eventProducer.fireEvent(event);

        //帖子加精,会改变其分数,将其存在Redis
        String redisKey = RedisKeyUtil.getPostScoreKey();
        //选择set的原因:set中没有重复的数据,因此可保证我们不会存入多个重复的帖子,减少后面的计算量
        redisTemplate.opsForSet().add(redisKey, id);

        return CommunityUtil.getJSONString(0);
    }

CommentController

	//添加评论
    @RequestMapping(path = "/add/{discussPostId}", method = RequestMethod.POST)
    public String addComment(@PathVariable("discussPostId") int discussPostId, Comment comment){
        //客户端表单中向服务器需要提交以下内容
        /*
        private int id;
        private int userId;
        private int entityType;         //评论的类型,比如帖子的评论,评论用户评论的评论
        private int entityId;           //评论的帖子的id
        private int targetId;           //记录评论指向的人
        private String content;         //评论的内容
        private int status;             //表明状态,是否被拉黑
        private Date createTime;        //创建的时间*/
        //其中 entityType entityId targetId content 需要表单中进行提交
      /*  comment.setId(user.getId());
        String username = user.getUsername();
        System.out.println(username);
        model.addAttribute("username",username);*/

        comment.setUserId(hostHolder.getUser().getId());
        comment.setStatus(0);
        comment.setCreateTime(new Date());
        commentService.addComment(comment);

        //当用户评论后,系统给发帖人或者发表评论的人发送信息
        //1. 新建事件
        //2. 设置各种参数
        Event event = new Event()
                .setTopic(TOPIC_COMMENT)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(comment.getEntityType())
                .setEntityId(comment.getEntityId())
                .setData("postId", discussPostId);

        if (comment.getEntityType() == ENTITY_TYPE_POST) {
            DiscussPost target = discussPostService.findDiscussPostById(comment.getEntityId());
            event.setEntityUserId(target.getUserId());
        } else if (comment.getEntityType() == ENTITY_TYPE_COMMENT) {
            Comment target = commentService.findCommentById(comment.getEntityId());
            event.setEntityUserId(target.getUserId());
        }
        eventProducer.fireEvent(event);

        //添加帖子评论时,将评论添加至es
        if (comment.getEntityType() == ENTITY_TYPE_POST) {
            // 触发发帖事件
            event = new Event()
                    .setTopic(TOPIC_PUBLISH)
                    .setUserId(comment.getUserId())
                    .setEntityType(ENTITY_TYPE_POST)
                    .setEntityId(discussPostId);
            eventProducer.fireEvent(event);
            //只有对帖子进行评论才会增加热度,将帖子存在Redis
            String redisKey = RedisKeyUtil.getPostScoreKey();
            //选择set的原因:set中没有重复的数据,可保证我们不会存入多个重复的帖子,减少后面的计算量
            redisTemplate.opsForSet().add(redisKey, discussPostId);
        }
        //添加成功后,重定向至帖子详情页
        return "redirect:/discuss/detail/" + discussPostId;

    }
}

LikeController

	  if (entityType == ENTITY_TYPE_POST){
            //对帖子点赞,将帖子存在Redis
            String redisKey = RedisKeyUtil.getPostScoreKey();
            //选择set的原因:set中没有重复的数据,可保证我们不会存入多个重复的帖子,减少后面的计算量
            redisTemplate.opsForSet().add(redisKey, postId);
        }

3.定时任务

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class PostScoreRefreshJob implements Job, CommunityConstant {

    private static final Logger logger = LoggerFactory.getLogger(PostScoreRefreshJob.class);
	// 从Redis中取出需要查询的帖子
    @Autowired
    private RedisTemplate redisTemplate;
    // 帖子
    @Autowired
    private DiscussPostService discussPostService;
    // 点赞
    @Autowired
    private LikeService likeService;
    // 同步回Elasticsearch
    @Autowired
    private ElasticsearchService elasticsearchService;

    //初始化论坛创建时间
    private static final Date epoch;
    static {
        try {
            epoch = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2020-10-1 00:00:00");
        } catch (ParseException e) {
            throw new RuntimeException("初始化论坛创建时间失败"+e);
        }
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //实现定时任务
        //1. 从Redis中取出需要重新计算分数的帖子
        String redisKey = RedisKeyUtil.getPostScoreKey();
        //boundSetOps获取了一个指定操作对象(key)的operator
        BoundSetOperations operations = redisTemplate.boundSetOps(redisKey);
        if (operations.size()==0){
            logger.info("任务取消,没有需要刷新帖子");
            return;
        }
		// 处理之前记录日志
        logger.info("[任务开始] 正在刷新帖子分数."+"共有"+operations.size()+"帖子需要刷新");

        while (operations.size() > 0){
            //刷新分数, operations.pop()默认为Object
            this.refresh((Integer) operations.pop());
        }
        logger.info("[任务结束] 已完成刷新帖子分数.");
    }

    private void refresh(int postId) {
        // 查询帖子
        DiscussPost post = discussPostService.findDiscussPostById(postId);
		// 帖子不存在
        if (post == null) {
            logger.error("该帖子不存在: id = " + postId);
            return;
        }
        // 是否加精 加75分
        boolean wonderful = post.getStatus() == 1;
        // 评论数量
        int commentCount = post.getCommentCount();
        // 点赞数量
        long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, postId);

        // 计算权重
        double w = (wonderful ? 75 : 0) + commentCount * 10 + likeCount * 2;
        // 分数 = 帖子权重 + 距离天数
        // Math.max(w, 1):防止w<0
        double score = Math.log10(Math.max(w, 1))
                + (post.getCreateTime().getTime() - epoch.getTime()) / (1000 * 3600 * 24);
        // 更新帖子分数
        discussPostService.updateScore(postId, score);
        // 同步搜索数据
        post.setScore(score);
        elasticsearchService.saveDiscussPost(post);
    }
}

4.配置定时 QuartzConfig

	// 刷新帖子分数任务
    @Bean
    public JobDetailFactoryBean postScoreRefreshJobDetail() {
        JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
        factoryBean.setJobClass(PostScoreRefreshJob.class);
        factoryBean.setName("postScoreRefreshJob");
        factoryBean.setGroup("communityJobGroup");
        factoryBean.setDurability(true);
        factoryBean.setRequestsRecovery(true);
        return factoryBean;
    }

    @Bean
    public SimpleTriggerFactoryBean postScoreRefreshTrigger(JobDetail postScoreRefreshJobDetail) {
        SimpleTriggerFactoryBean factoryBean = new SimpleTriggerFactoryBean();
        factoryBean.setJobDetail(postScoreRefreshJobDetail);
        factoryBean.setName("postScoreRefreshTrigger");
        factoryBean.setGroup("communityTriggerGroup");
        factoryBean.setRepeatInterval(1000 * 60 * 60); //60min刷新一次分数
        factoryBean.setJobDataMap(new JobDataMap());
        return factoryBean;
    }

5.修改展示页面

点击最热,按照分数进行排序

index.html

<div class="position-relative">
	<!-- 筛选条件 -->
	<ul class="nav nav-tabs mb-3">
		<li class="nav-item">
			<a th:class="|nav-link ${orderMode==0?'active':''}|" th:href="@{/index(orderMode=0)}">最新</a>
		</li>
		<li class="nav-item">
			<a th:class="|nav-link ${orderMode==1?'active':''}|" th:href="@{/index(orderMode=1)}">最热</a>
		</li>
	</ul>
	<button type="button" class="btn btn-primary btn-sm position-absolute rt-0"
          data-toggle="modal" data-target="#publishModal" th:if="${loginUser!=null}">我要发布
  </button>
</div>

修改DiscussPostMapper的selectDiscussPosts方法,同时修改调用该方法的地方

@Mapper
public interface DiscussPostMapper {
    // 增加orderMode,当orderMode=0按照类型、创建时间排序
    // 当orderMode=1按照类型、分数、创建时间排序
    List<DiscussPost> selectDiscussPosts(int userId, int offset, int limit, int orderMode);
}

discuss-post.xml

 <select id="selectDiscussPosts" resultType="DiscussPost">
        select <include refid="selectFields"></include>
        from discuss_post
        where status != 2
        <if test="userId!=0">
            and user_id = #{userId}
        </if>
        <if test="orderMode==0">
            order by type desc, create_time desc
        </if>
        <if test="orderMode==1">
            order by type desc, score desc, create_time desc
        </if>
        limit #{offset}, #{limit}
    </select>

HomeController

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class HomeController implements CommunityConstant {

    @Autowired
    private DiscussPostService discussPostService;
    @Autowired
    private UserService userService;
    @Autowired
    private LikeService likeService;

    @RequestMapping(path = "/index", method = RequestMethod.GET)
    public String getIndexPage(Model model, Page page,
                               @RequestParam(name = "orderMode", defaultValue = "0") int orderMode) {
        // 方法调用前, SpringMVC会自动实例化Model和Page, 并将Page注入Model.
        // 所以, 在thymeleaf中可以直接访问Page对象中的数据.
        page.setRows(discussPostService.findDiscussPostRows(0));
        page.setPath("/index?orderMode=" + orderMode);

        List<DiscussPost> list = discussPostService
                .findDiscussPosts(0, page.getOffset(), page.getLimit(), orderMode);
        List<Map<String, Object>> discussPosts = new ArrayList<>();
        if (list != null) {
            for (DiscussPost post : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("post", post);
                User user = userService.findUserById(post.getUserId());
                map.put("user", user);

                long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId());
                map.put("likeCount", likeCount);

                discussPosts.add(map);
            }
        }
        model.addAttribute("discussPosts", discussPosts);
        model.addAttribute("orderMode", orderMode);

        return "/index";
    }

    @RequestMapping(path = "/error", method = RequestMethod.GET)
    public String getErrorPage() {
        return "/error/500";
    }

    @RequestMapping(path = "/denied", method = RequestMethod.GET)
    public String getDeniedPage() {
        return "/error/404";
    }
}

index.html

<!-- 筛选条件 -->
<ul class="nav nav-tabs mb-3">
		<li class="nav-item">
			<a th:class="|nav-link ${orderMode==0?'active':''}|" th:href="@{/index(orderMode=0)}">最新</a>
		</li>
		<li class="nav-item">
			<a th:class="|nav-link ${orderMode==1?'active':''}|" th:href="@{/index(orderMode=1)}">最热</a>
		</li>
</ul>
大模型——Coze工作流实战:一键生成像素风格视频 本文介绍了如何利用Coze平台工作流生成像素风格心理学短视频的方法。通过创建工作流、设置变量节点、调用大模型生成文案、数据格式化处理、合成音频、生成字幕等步骤,最终实现从输入主题到生成完整视频的自动化流程。文章详细展示了每个节点的具体配置方法,包括提示词编写和数据处理脚本,为读者提供了完整的像素风格视频制作解决方案。 阅读详情

相关推荐

Ubuntu双系统引导修复实战:boot-repair工具详解

本文详细介绍了使用boot-repair工具修复Ubuntu双系统引导丢失问题的实战方法。当GRUB引导菜单因安装新系统或更新而损坏时,通过制作Ubuntu启动盘进入Live环境,安装并运行boot-repair,可一键完成系统修复引导,自动化执行GRUB重装与配置,解决无法进入Windows或Ubuntu的常见故障。

weixin_29224589的博客 362

Redis知识点(持续更新,高频面试题)

Redis知识点面试题Redis1. Redis是什么?有哪些使用场景?有哪些功能?2. Redis持久化有几种方式?(怎么保证 Redis 挂掉之后再重启数据可以进行恢复)3. 什么是缓存穿透?怎么解决?4. 什么是缓存雪崩?怎么解决?5. 什么是缓存击穿?怎么解决?6. Redis支持的数据类型有哪些?7. Redis 内存淘汰机制(数据淘汰策略)?8. Redis 过期键的删除策略 Redis 1. Redis是什么?有哪些使用场景?有哪些功能? Redis是一个使用C语言开发的高速缓存数据库。red

有緣Réπ 的博客 241

LEfSe分析避坑指南:如何解决R语言中的常见错误与优化结果可视化

本文提供了R语言中进行LEfSe(线性判别分析)微生物组差异分析的全流程避坑指南。详细解析了从数据格式准备、参数调优(如显著性水平与LDA阈值)、结果可靠性验证到使用ggplot2进行高级可视化的实战技巧,帮助用户规避常见错误,获得更稳健、美观的分析结果。

weixin_29098391的博客 367

Redis实现热搜排行榜

整体思路是采用redis的zset来实现,每条热搜的内容是一个member,每条热搜的热度值是一个score(zset中的元素会自动排序,只需要取集合中前多少条就行了)(在同一个小时的不同时间,计算出来的时间key相同,这个时间key是每个对应的zset集合名字)(这四个常量为每个小时、每天、每周和每个月的热搜内容和分数的zset集合的名字key)初始化一个月的数据,每小时一个集合,总共有24*30个zset集合。二、排行榜通常是以小时、天、周和日来计算的,我们以小时为单位。1.引入依赖添加配置文件。

love_eat_peach的博客 3037

Ubuntu安装opencv4.5(自己安装过程详细)

1.下载opencv 在opencv官网下载source版,下载链接 http://opencv.org/releases.html。别下载错版本 下载过程就不多说了。 2.安装过程 2.1解压 unzip opencv-4.5.0.zip cd opencv-4.5.0 2.2安装依赖的库 sudo apt-get install cmake sudo apt-get install build-essential libgtk2.0-dev libavcodec-dev libavformat-

weixin_45629790的博客 1万+

亚马逊广告接口 amazon advertising

亚马逊广告接口官方说明:https://advertising.amazon.com/API/docs/en-us/setting-up/account-setup 一:注册aws开发者账号 注册地址:https://developer.amazon.com 二:填写注册资料 三:进入控制台,生成安全配置文件 进入 Login with Amazon 菜单: 创建配置文件: 四:申请广告接入权限 申请地址:https://advertising.amazon.com/zh-cn/about-api

lzy66666的博客 4779

Redis

Redis Redis 是什么?都有哪些使用场景? Redis 是一个使用 C 语言开发的高速缓存数据库。 Redis 使用场景: • 记录帖子点赞数、点击数、评论数; • 缓存近期热帖; • 缓存文章详情信息; • 记录用户会话信息。 Redis 有哪些功能? • 数据缓存功能 • 分布式锁的功能 • 支持数据持久化 • 支持事务 • 支持消息队列 Redis 和 memcache 有什么区别? • 存储方式不同:memcache 把数据全部存在内存之中,断电后会挂掉,数据不能超过内存大小;Redis 有

Cybenko 342

【AI编程】Qoder AI 编程工具从部署到深度使用实战详解

Qoder AI 编程工具从部署到深度使用实战详解

congge 8350

redis实现排行榜(日榜,周榜,月榜)

redis排榜功能的实现

lvyangxue的博客 1万+

4.6 鞅-一致可积,L1收敛(Durrett)答案

概率-理论与实例第五章 答案:6 鞅-一致可积,L1收敛

weixin_40614311的博客 1060

基于ResNet + LLM大语言模型的分类识别系统设计与实现,Web前后端分离,Django+vue3+AI助手模块+ResNet50算法+LLM 联动+Element Plus等技术,全网独发

分类识别任务是计算机视觉中的重要任务,广泛应用于智慧校园分类、智慧农业、智慧生活场景分类等领域。常见的分类模型有 VGGNet、ResNet 、MobileNet 、ConvNeXt、DenseNet、ViT、Swin Transformer、YOLOv8/11/26。本项目结合 ResNet分类识别算法 + LLM大语言模型联动 ,使用 Django + Vue3,构建了一个通用的 Web 前后端系统,用户端 + 管理端 ,便于用户操作检,不仅可以用于大论文的工作量展示,还可以作为毕业设计。

在职AI算法工程师,擅长计算机视觉,YOLO目标检测、分割等,擅长web、pyqt界面可视化,好内容持续更新中,来这里跟大家一起学习,共同进步 769

Redis实现微博热度前100

假设微博热度排行榜是根据点赞数量排名 怎么实现? 可以用Redis的有序集合实现,外层key是固定前缀+排行榜名称,内层value是微博ID,对应的score是点赞数量。每次点赞可以用 zincrby key increment score命令给每条微博增加对应的点赞数量。 大key问题 微博数量很多,如果都放在一个key,那就会产生大key问题。可以把一个key拆分成多个key,比如100个key,每个key只存储一部分微博。然后用一个汇总的key保存排名前N的数据 1)这100个key还是保存在一个Re

weixin_42002747的博客 3622

某招标公告网和vcaptcha验证码识别逆向

本文分析了某验证码系统的加密流程及破解思路。首先通过反混淆技术定位到加密函数,拆解了包含指纹函数、环境参数等组成的加密字符串。研究发现验证码生成涉及canvas指纹、环境检测等反爬机制,可通过模拟浏览器环境绕过。验证过程需要解密图片顺序,通过work2.js计算还原图片位置,再结合滑动轨迹、时间等参数生成验证请求。文章仅提供技术研究思路,强调需遵守法律法规,严禁非法破解信息系统。完整流程包括环境模拟、加密参数还原、图片处理和轨迹生成等步骤,成功率较高。

码王吴彦祖的博客 585

springboot+redis实现微博热搜排行榜

springboot+redis实现微博热搜排行榜 技术模拟思路: 采用26个英文字母来实现排行,随机为每个字母生成一个随机数作为score 为了更好的体验,先做几件事: 先初始化1个月的历史数据 定时5秒钟,模拟微博的热度刷新(例如模拟点赞 收藏 评论的热度值更新) 定时1小时合并统计 天、周、月的排行榜。 步骤1:先初始化1个月的历史数据 @Service @Slf4j public class InitService { @Autowired private RedisTempl

INGNIGHT的专栏 3842

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

GitHub 中文排行榜,高分优秀中文项目一网打尽!

点击上方“AI有道”,选择“星标”公众号重磅干货,第一时间送达GitHub 是每个程序员经常逛的地方。在 GitHub 里,我们经常能发现一些优秀的开源且高分项目!有时候...

红色石头的专栏 2677

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

获取交易软件【热度排行数据】2024年9月26日,一股淡淡的牛味

2024年9月26日,一股淡淡的牛味概念热度的排行榜和行业热度排行榜。像是这种类型的数据,能不能加到我们的量化模型里面,作为选股和的判断条件之一呢?下面图片,有很多,可以1对1帮助您解决代码、软件或者策略问题。客户的要求必须满足,马上开始敲代码。

XD1996CD的博客 1938

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

GitHub中文排行榜,帮助你发现高分优秀中文项目(二)-Java

榜单设立目的 ???????? GitHub中文排行榜,帮助你发现高分优秀中文项目; 各位开发者伙伴可以更高效地吸收国人的优秀经验、成果; 中文项目只能满足阶段性的需求,想要有进一步提升,还请多花时间学习高分神级英文项目; 榜单设立范围 设立1个总榜(所有语言项目汇总排名)、18个分榜(单个语言项目排名); 榜单入选规则 一个小小的要求:项目的 Description 和 README.md 都要包含中文说明; 更新越持续越好:最近半年内有更新过的项目才有机会入选(拥抱活跃,远离僵尸); Star

通往精英的成长之路 6411

Python Web 开发库排行榜:590 个项目,26 个分类

GitHub上的ml-tooling团队推出了一份Python Web开发工具排行榜,收录590个项目,覆盖26个细分领域(如Web框架、测试、API工具等)。该榜单通过自动采集GitHub和包管理平台数据,基于Star数、维护活跃度、下载量等指标计算综合质量分,每周更新排名。项目还标记新库、不活跃或已停止维护的项目,并提供趋势分析。该榜单适合开发者快速筛选主流工具,但需注意排名仅供参考,仍需结合具体需求评估。目前项目已获2,728星,总收录项目Star数达350万。

syncloom582的博客 191

Python摸鱼项目:基于Selenium获取汽车之家排行榜

python获取汽车之家排行榜

m0_46275020的博客 1470

Python开源项目月排行 2025年5月

本文介绍了10个优秀的Python开源项目: Scrapy:高性能网络爬虫框架,支持异步处理和模块化扩展 Fish-Speech:基于LLM的语音合成框架,支持语音克隆和情感控制 NautilusTrader:算法交易平台,结合Python易用性和Rust高性能 Freqtrade:加密货币交易机器人框架,支持回测和机器学习 DSPy:斯坦福开发的AI框架,通过编程方式优化语言模型 Chinese-Poetry:包含5.5万首唐诗和26万宋诗的诗词数据库 Puter:开源互联网操作系统,可作个人云或开发平台

cbbxn的博客 1413

Redis 排行榜

一 加入排行榜 public function addSumRank(){ $cache = Cache::init(); $redis = $cache->handler(); $uid = 100;//新注册用户 $key = 'duty_test'; //$gold = 0 * 10000000000;//由于初始分数为0 故省略此处 $gold += 9999999999 - time();

weixin_41865469的博客 832

【开源项目分享】GitHub中文排行榜 - 帮助你发现高分优秀中文项目-Java

榜单设立目的 ???????? GitHub中文排行榜,帮助你发现高分优秀中文项目; 各位开发者伙伴可以更高效地吸收国人的优秀经验、成果; 中文项目只能满足阶段性的需求,想要有进一步提升,还请多花时间学习高分神级英文项目; 榜单设立范围 设立1个总榜(所有语言项目汇总排名)、18个分榜(单个语言项目排名); 榜单入选规则 一个小小的要求:项目的 Description 和 README.md 都要包含中文说明; 更新越持续越好:最近半年内有更新过的项目才有机会入选(拥抱活跃,远离僵尸); Star

稻草人的技术小站 3540

C++ 即将超越 Java,TIOBE 6 月编程语言排行榜发布

今天,TIOBE 在更新了官网的设计之后,重磅带来了新一个月的编程语言榜单。

技术专家 1066

2026年3月26隔夜暗盘挂单排行榜

指数来到了3931附近, 指数2天回来100多点, 但账户里的钱没回来, 从以往经验看, 大跌后会经历一段时间的震荡, 将上方套牢盘慢慢磨去, 操作上逢高减仓, 逢低买入策略, 将成本做低.大盘成交2.18万亿, 上涨家数4874家, 下跌家数560家, 涨停105家, 跌停4家, 上涨靠前的板块是体育7.95%, 林业4.14%, 电力3.89%.电力15个: 华电辽能 8连板 , 辽宁能源, 浙江新能, 湖南发展, 韶能股份, 粤电力A, 节能风电等 .现价12.36 挂单58.23亿 2天2板。

weixin_40881502的博客 709

图书排行:计算机书籍每周销量排行榜

LSGO软件技术团队每周一,统计 京东网、当当网、互动出版社、中国图书网 关于计算机类书籍销量的 7日 排行数据,大家可参考这份排行来挑选技术书籍。 数据统计时间:2019/05/20 至 2019/05/26 京东网 Top01:Excel之光:高效工作的Excel完全手册 作 者:冯注龙,丘荣茂 著 出版社:电子工业出版社 Top02:PPT之光:三个维度打造完美PPT 作 者:冯注龙...

老马的程序人生 4788

Redis如何实现排行榜?

span 用于计算元素排名(rank),例如查找 ele = 肖菜鸡、score = 17 的排名,只需要把查找路径经过的节点的 span 相加即可,如下图的红色路径的 span 累加,按照上面的生成链表方式,每次往上增加一层链表的节点个数是下面一层的一半,这样的查找过程就类似于一个二分查找,时间复杂度为 O(log n)。但是,这种方式在插入数据的时候有很大的问题,每次新增一个节点,就会打乱相邻的两层链表节点个数 2:1 的关系,如果要维持这个关系,就需要对链表调整,事件复杂度是 O(n)。

2301_78526383的博客 6430
上一篇: 项目-25-初始任务执行和调度
下一篇: leetcode 240 / 剑指Offer 04 二维数组中的查找
Guo_Chuang
博客等级 码龄6年 9粉丝 61原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值