Vue项目实战:用html2canvas+jspdf搞定复杂表格导出PDF(附完整代码)

Vue项目实战:利用html2canvas与jsPDF实现动态表格PDF导出与分页优化 本文详细讲解了在Vue项目中,如何利用html2canvas与jsPDF库实现动态表格的PDF导出功能,并重点解决了复杂内容的分页优化难题。文章从核心原理、参数调优、单页/多页实现到实战技巧,提供了完整的代码示例和避坑指南,帮助开发者高效生成专业、清晰的PDF文档。 阅读详情

Vue项目实战:优雅解决复杂表格导出PDF的完整方案

最近在重构一个后台管理系统时,遇到了一个看似简单却颇为棘手的需求:将复杂的课程表数据导出为格式规整的PDF文件。这个需求听起来很常见,但实际操作起来却有不少坑需要踩。表格不仅包含多层表头、合并单元格,还需要保持原有的样式和布局,同时支持分页和页眉页脚。经过几轮尝试和优化,我总结出了一套相对成熟的解决方案,今天就来详细分享一下整个实现过程。

如果你也在Vue项目中遇到过类似的需求,特别是需要处理复杂表格结构、保持样式一致性,并且希望导出结果足够专业,那么这篇文章应该能给你带来不少实用的参考。我会从基础原理讲起,逐步深入到具体的代码实现,最后还会分享一些我在实际项目中踩过的坑和优化技巧。

1. 技术选型与核心原理剖析

在开始动手之前,我们先来聊聊为什么选择html2canvas和jsPDF这对组合,以及它们背后的工作原理。

1.1 为什么是html2canvas + jsPDF?

市面上处理PDF导出的方案不少,但各有优劣。比如直接使用服务端生成虽然性能更好,但需要额外的服务器资源,而且对于动态内容不够灵活。纯前端的方案中,html2canvas + jsPDF的组合之所以成为主流,主要有以下几个原因:

  • 完全前端实现:不依赖后端服务,所有操作都在浏览器中完成
  • 样式还原度高:能够将HTML元素(包括CSS样式)转换为图片,最大程度保留原始视觉效果
  • 灵活性好:可以处理任意复杂的DOM结构,包括表格、图表、富文本等
  • 社区成熟:两个库都有多年的维护历史,遇到问题容易找到解决方案

不过这个组合也有它的局限性,最明显的就是性能问题。当页面元素过多时,转换过程会比较耗时,而且生成的文件体积可能偏大。但对于大多数管理后台的报表导出需求来说,这个方案已经足够用了。

1.2 核心工作流程

整个导出过程可以分解为三个关键步骤:

  1. DOM捕获与渲染:html2canvas将指定的DOM元素渲染到Canvas上
  2. Canvas转图片:将Canvas转换为Base64格式的图片数据
  3. PDF生成与组装:jsPDF创建PDF文档,将图片插入到合适的位置

这里有一个很重要的细节需要注意:html2canvas并不是真正地“截图”,而是通过解析DOM树和CSS样式,然后在Canvas上重新绘制。这意味着它能够处理一些普通截图工具无法处理的情况,比如跨域图片、CSS3动画等。

提示:由于html2canvas需要解析CSS样式,确保所有样式都已经加载完成后再执行转换,否则可能会出现样式丢失的情况。

1.3 宽高设置的“反向规律”

这是很多开发者第一次使用时最容易困惑的地方。html2canvas和jsPDF在宽高设置上存在一种看似矛盾的关系:

库名 宽高设置规律 对PDF显示的影响
html2canvas 值越大 在PDF中显示越完整(但图片会变小)
jsPDF 值越小 在PDF中显示越完整(但图片会变大)

这种“反向规律”其实很好理解:html2canvas的宽高决定了Canvas的分辨率,分辨率越高,细节越丰富,但同样的物理尺寸下,图片就会显得越小。而jsPDF的addImage方法中的宽高参数,决定了图片在PDF页面上的实际显示尺寸。

关键在于找到平衡点:既要保证足够的清晰度,又要让内容恰当地填充PDF页面。经过多次测试,我发现一个实用的经验公式:

// 计算合适的缩放比例
const scale = 2; // 通常2倍缩放效果最佳
const canvasWidth = domElement.scrollWidth * scale;
const canvasHeight = domElement.scrollHeight * scale;

// 在jsPDF中保持原始宽高比
const pdfWidth = pdf.internal.pageSize.getWidth() - 10; // 留出边距
const pdfHeight = (pdfWidth / canvasWidth) * canvasHeight;

2. 基础环境搭建与配置

2.1 安装依赖

首先,我们需要在Vue项目中安装必要的依赖包:

npm install html2canvas jspdf --save
# 或者使用yarn
yarn add html2canvas jspdf

如果你使用的是TypeScript,还需要安装对应的类型声明文件:

npm install @types/html2canvas @types/jspdf --save-dev

2.2 创建基础工具函数

我习惯将PDF导出相关的逻辑封装成独立的工具函数,这样可以在不同的组件中复用。创建一个pdfExport.js文件:

import html2canvas from 'html2canvas';
import { jsPDF } from 'jspdf';

/**
 * 基础PDF导出函数
 * @param {HTMLElement} domElement - 需要导出的DOM元素
 * @param {string} fileName - 导出的文件名
 * @param {Object} options - 配置选项
 */
export const exportToPDF = async (domElement, fileName = 'export.pdf', options = {}) => {
  const {
    format = 'a4',
    orientation = 'portrait',
    margin = 10,
    scale = 2,
    backgroundColor = '#FFFFFF'
  } = options;

  try {
    // 显示加载状态
    const loading = startLoading();
    
    // 获取DOM元素的真实尺寸
    const width = domElement.scrollWidth;
    const height = domElement.scrollHeight;
    
    // 使用html2canvas转换为Canvas
    const canvas = await html2canvas(domElement, {
      allowTaint: true,
      useCORS: true,
      width: width * scale,
      height: height * scale,
      scale: scale,
      backgroundColor: backgroundColor,
      logging: false, // 关闭控制台日志,提升性能
      onclone: (clonedDoc) => {
        // 克隆文档时的回调,可以在这里修改克隆后的DOM
        // 比如隐藏一些不需要导出的元素
        const elementsToHide = clonedDoc.querySelectorAll('.no-export');
        elementsToHide.forEach(el => {
          el.style.display = 'none';
        });
      }
    });
    
    // 创建PDF文档
    const pdf = new jsPDF(orientation, 'pt', format);
    const pdfWidth = pdf.internal.pageSize.getWidth() - margin * 2;
    const pdfHeight = (pdfWidth / canvas.width) * canvas.height;
    
    // 将Canvas转换为图片并添加到PDF
    const imgData = canvas.toDataURL('image/jpeg', 1.0);
    pdf.addImage(imgData, 'JPEG', margin, margin, pdfWidth, pdfHeight);
    
    // 保存PDF文件
    pdf.save(fileName);
    
    // 隐藏加载状态
    loading.finish();
    
    return true;
  } catch (error) {
    console.error('PDF导出失败:', error);
    showError('导出失败,请重试');
    return false;
  }
};

// 辅助函数:显示加载状态
function startLoading() {
  // 这里可以根据你使用的UI框架实现加载状态
  console.log('开始生成PDF...');
  return {
    finish: () => console.log('PDF生成完成')
  };
}

// 辅助函数:显示错误提示
function showError(message) {
  // 这里可以根据你使用的UI框架实现错误提示
  console.error(message);
}

这个基础版本已经可以处理大多数简单的导出需求了。但当我们面对复杂表格时,还需要考虑更多细节。

3. 复杂表格的特殊处理

3.1 处理表格溢出与分页

当表格内容超过一页时,我们需要自动分页。这里的关键是计算内容高度,并在适当的位置进行分割。

/**
 * 支持分页的PDF导出函数
 * @param {HTMLElement} domElement - 需要导出的DOM元素
 * @param {string} fileName - 导出的文件名
 * @param {Object} options - 配置选项
 */
export const exportToPDFWithPagination = async (domElement, fileName = 'export.pdf', options = {}) => {
  const {
    format = 'a4',
    orientation = 'portrait',
    margin = { top: 40, right: 20, bottom: 40, left: 20 },
    scale = 2,
    backgroundColor = '#FFFFFF'
  } = options;
  
  const pdf = new jsPDF(orientation, 'pt', format);
  const pageWidth = pdf.internal.pageSize.getWidth();
  const pageHeight = pdf.internal.pageSize.getHeight();
  const contentWidth = pageWidth - margin.left - margin.right;
  
  // 计算每页可用的高度
  const usableHeight = pageHeight - margin.top - margin.bottom;
  
  // 获取所有需要导出的内容块
  // 这里假设表格被分成了多个.content块
  const contentBlocks = domElement.querySelectorAll('.content');
  
  let currentY = margin.top;
  
  for (let i = 0; i < contentBlocks.length; i++) {
    const block = contentBlocks[i];
    
    // 如果是新的一页的第一个块,不需要添加新页面
    if (i > 0) {
      pdf.addPage();
      currentY = margin.top;
    }
    
    // 获取块的实际高度(考虑缩放)
    const blockHeight = block.scrollHeight * scale;
    
    // 计算在PDF中的显示高度
    const displayHeight = (contentWidth / (block.scrollWidth * scale)) * blockHeight;
    
    // 如果内容高度超过当前页剩余空间,需要特殊处理
    if (displayHeight > usableHeight) {
      // 这里可以进一步分割内容块
      await handleOverflowContent(pdf, block, {
        margin,
        pageWidth,
        pageHeight,
        contentWidth,
        usableHeight,
        scale,
        backgroundColor
      });
    } else {
      // 正常添加内容
      const canvas = await html2canvas(block, {
        allowTaint: true,
        useCORS: true,
        width: block.scrollWidth * scale,
        height: blockHei
别再让后端背锅了!Vue2项目里用html2canvas+jspdf搞定复杂报表导出PDF 本文详细介绍了在Vue2项目中如何使用html2canvas和jspdf实现复杂报表的PDF导出功能,减轻后端压力并提升前端自主性。通过实战案例和性能优化技巧,帮助开发者解决图表失真、表格分页等常见问题,实现高效、精准的PDF动态生成。 阅读详情

相关推荐

Vue2项目实战:基于html2canvas与jspdf实现复杂布局PDF的智能分页与导出

本文详细介绍了在Vue2项目中利用html2canvas与jspdf实现复杂布局PDF的智能分页与导出功能。通过实战案例,展示了如何解决内容截断、图片质量优化及页眉页脚添加等常见问题,提升前端动态生成PDF的效率与质量。

weixin_33698823的博客 419

Vue项目实战:用html2canvas+jspdf生成带分页的PDF报表(附完整代码)

本文详细介绍了在Vue项目中,如何结合html2canvas与jsPDF库实现复杂动态内容(如表格、图表)导出为格式规范、支持智能分页的PDF报表。文章提供了从核心工具选型、分页算法实现、样式一致性优化到高级功能(如批量导出、错误处理)的完整解决方案与实战代码,帮助开发者高效解决前端PDF导出难题。

weixin_29000991的博客 129

VUE页面导出PDF踩坑指南

导出方案用的是html2canvas+jspdf,简单的导出很容易实现,但是也会有一些问题:一是不同分辨率下导出内容不同的问题,这个需要固定导出内容的宽度;二是会遇到页面内容被切割的问题,因为导出原理是先使用html2canvas将DOM元素转换为canvas,再利用 canvas 的 toDataURL 方法输出为图片,之后使用jspdf添加图片生成PDF。图片生成PDF过程中必然用统一的格式切割图片分页,所以内容很容易被切割;

LGEC_的博客 3800

Vue3 - 最新详细实现页面区域打印预览和导出PDF功能,vue3指定局部区域参与打印与下载pdf文档(解决预览导出不全部分内容显示不完整、复杂表格分页/图表复杂有滚动条、打印导出丢失、防止内容截断

vue3,区域打印,前端页面局部转pdf,页面局部打印预览,vue如何实现指定区域打印及导出pdf,打印插件Print.js,vuejspdfhtml3canvas,自定义选中页面内容导出为pdf文件,打印功能内容显示不完整,内容显示不全,表格打印不全的问题,空白页,指定div页面转为pdf文件,解决页面样式不出现或者table表格样式错乱问题,只打印一小部分并非全部,指定区域范围内导出生成PDF文件,网页既能打印查看又可以让用户导出Pdf文件,前端vue3打印指定区域,可以预览打印机和下载pdf文件,

🏆 前端领域优质创作者 1万+

vue3:html2canvas+jspdf将页面以A4导出为PDF文件,解决内容截断+在分页处截断问题详细排查和解决教程(jsPDF + html2canvas A4分页截断、内容分页时存在截断)

html2canvas + jsPDF 解决内容截断问题,vue3 jspdf-html2canvas生成多页pdf防截断处理(包含代码),vue3解决html2canvas + jsPDF导出pdf分页内容截断问题,jsPDF + html2canvas A4分页截断 完美解决方案(含代码 + 案例),html页面导出pdf截断问题,html2canvas 与 jspdf 相结合生成 pdf 内容被截断的终极解决方案,提供html2canvas+jsPDF将HTML页面以A4纸方式导出为PDF后,内容分页

✅ 精选推荐文章 2240

Vue3 - 详细实现将页面导出PDF格式下载及打印功能示例代码,把整个HTML网页导出为pdf文件并防止内容截断分割问题(强力搞定各种图片/表格/图表等被分割断开,分页跨页转换不全丢失防截断等问题)

vue3,网页导出PDF,vue3将页面导出成PDF文件,vue3实现打印页面,Vue3导出pdf方案,打印多页面pdf,vue3前端实现导出页面为pdf,html2canvas,jspdf,页面截图导出为PDF,以及PDF强行截断分页,vue3将页面导出成PDF文件解决图片表格内容分割问题,内容被截断怎么办,分页导出,分模块导出,网页导出pdf内容被截断,前端html导出为pdf文档,且图表不被分页分割,html页面导出pdf截断问题,前端导出pdf以及导出内容截断的解决办法,vue3页面下载为pdf并分

🏆 前端领域优质创作者 1万+

Vue2 - 最新详细实现页面区域打印预览和导出PDF功能,网页指定局部区域参与打印与下载pdf文档(解决预览导出不全、部分内容显示不完整、复杂表格分页/图表复杂有滚动条、打印导出丢失、防止内容截断)

vue2,区域打印,前端页面局部转pdf,页面局部打印预览,vue如何实现指定区域打印及导出pdf,只打印一小部分并非全部,指定区域范围内导出生成PDF文件,打印div指定区域内容并保留css样式,可以预览打印机和下载pdf文件,打印指定DOM元素内的内容,vue网页局部打印不全,打印插件Print.js,vuejspdfhtml2canvas,自定义选中页面内容导出为pdf文件,打印功能内容显示不完整,内容显示不全,表格打印不全的问题,空白页,指定div页面转为pdf文件,解决页面样式不出现或者tab

🏆 前端领域优质创作者 6799

jsPDF-html2canvas:与jsPDF和html2canvas结合使用,可将html内容转换为PDF文件

jsPDF-html2canvas 与jsPDF和html2canvas结合使用,可将html内容转换为PDF文件。 html2PDF函数将自动将目标dom宽度调整为PDF大小。 因此,无需担心溢出部分。 如果内容高度超过1 pdf,它将自动将其分隔到另一个pdf页面。 安装 npm i jspdf-html2canvas import html2PDF from 'jspdf-html2canvas' ; html2PDF ( node , options ) ; 由于此插件是umd模块,因此您也可以将CDN与/dist/jspdf-html2canvas.min.js结合使用,只需记住在此插件之前同时包含jspdf和html2canvas cdn即可。 < script src = "https://unpkg.com/jspdf@latest/dist/jspdf.um

树莓派c语言串口通讯程序

在网上搜了很多关于树莓派串口通讯的例子,但是都是用python写的,虽然python很有名,而且最近也在学习这门语言, 但是还是想用c语言实现一下,因为需要用到整套系统里,其他内容都是用c语言写的。但是网上没有找打现成的。 还好,之前做过天嵌2440开发板的串口程序(参照天嵌工程师提供的代码),发现串口程序其实是通用的, 驱动层屏蔽了硬件细节,个人猜测,几乎所有移植好的系统的串口,都可以用一

realank的专栏 1万+

java爬虫(爬取银行理财数据)

import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; imp

ROCK 2483

超详细网安学习路线(Day1-Day2)

渗透测试(Penetration Testing),就是一种通过模拟恶意攻击者的技术与方法,挫败目标系统安全控制措施,取得访问控制权,并发现具备业务影响后果安全隐患的一种安全测试与评估方法。简单来说,就是合法去入侵别人的系统,来帮助其找出漏洞,增强防护能力。

aobulaien001的博客 3375

测绘程序设计——试题一:出租车轨迹数据计算

仅展示试题1的原文,如需了解其余内容,请自行购买图书李老师著作主页-http://ybli.users.sgg.whu.edu.cn/book/

chengzilhc的博客 885

基于STM32L4XX 、HAL库的ATD5984步进电机驱动器驱动程序应用设计

一、简介: ATD5984是一款内部集成了译码器的微特步进电机 驱动器,能使双极步进电机以全、半、1/4、/1/8、1/16 和1/32步进模式工作。步进模式由逻辑输入管脚MSx选 择。其输出驱动能力达到28V±1.6A。 译码器是ATD5984易于使用的关键,通过STEP管脚 输入一个脉冲就可以使电机完成一次步进,省去了相序 表,高频控制线及复杂的编程接口,使其更适于没有复 杂的微处理器或微处理器负担过重的场合。 在步进操作期间,ATD5984的内部电路可以自动

PP_Cottage的博客 394

SPRD Android 14 通过属性控制系统设置显示双栏或者单栏

SPRD Android 14 通过属性控制系统设置显示双栏或者单栏

m0_60898338的博客 1117

关于在线excel插件Univer笔记教程

univer在线excel插件确实是够强大,但也存在不少bug,用户用起来是真的很爽,和本地的wps差不多,但真正的开发起来是真的费劲。由于文档提供的信息不足,我们很多功能只能去看他们插件里的源代码,然后一点点测试,一点点尝试研究。此文章可省去五天的研究成本

guiplan 5817

MySQL数据库面试题(2022版)

序列号 内容 链接 1 Java基础知识面试题(2022版) https://blog.csdn.net/qq_43061290/article/details/124023797 2 Java集合容器面试题(2022版) https://blog.csdn.net/qq_43061290/article/details/124043363 3 Java异常面试题(2022版) https://blog.csdn.net/qq_43061290/article/details/124....

拉格朗日的学习笔记 1万+

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

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

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

上一篇: 告别重复引入!5分钟搞定UniApp小程序的全局弹窗(Vue3+vite实战)
下一篇: C++版Cesium实战:从OpenGL到3DTiles的全流程开发指南
读书人钱金铎
博客等级 码龄10年 39粉丝 1973原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值