VUE哔哩哔哩移动端项目使用vant 实现发布功能(上传文件)

vant拍摄视频上传以及多张图片上传 阅读详情

bilibili发布页面主要有:发布按钮、多行文本框、一个上传图片的按钮(此处使用了vant)

在这里插入图片描述

组件里面的头部有:左返回按钮(使用vant)、发布按钮

<div class="top">
      <van-icon name="arrow-left" class="top-lef" @click="go" />
      <!-- 给按钮绑定一个class 如果computed返回的是true 就调用rel-highlight 这个css样式-->
      <div
        class="rel"
        :class="{ 'rel-highlight': isHighLight }"
        @click="regSave"
      >
        发布
      </div>
    </div>

需要实现功能:当文本框输入内容时 发布按钮就会高亮。

实现思路:使用computed监听文本框的变化,当文本框的内容长度>0时,就调用isHighLight函数,动态改变按钮的class名(rel-highlight),即改变了按钮的样式 。
<div class="text">
        <textarea
          class="text"
          placeholder="分享我的哔哩哔哩动态"
          v-model.trim="msg"
        ></textarea>
 </div>

v-model.trim=“msg” 给文本框的内容进行双向绑定 同时删除前后空格 (当输入空格时 发布按钮的事件并不会触发 不会高亮)

computed: {
    isHighLight: function () {
      // 判断文本框是否输入内容 有内容是true 就调用高亮函数
      return this.msg.length > 0;
    },
  },
上传文件:此处使用了vant

在这里插入图片描述

在这里插入图片描述

想要实现的效果就是这样的 但是当时出现了一个问题,就是我向后端发送请求之后 图片预览不出来。 (vant官方图片之所以能预览出来,是因为它自动将图片发送到vant的服务器,所以能展示出来。)
解决方法:查找vant文件上传的官方函数有:before-read=“beforeRead” 是上传前置处理,类似于钩子函数,在图片上传到vant服务器之前,将图片/视频的地址发到后端的服务器,如果上传成功,后端把拿到图片的地址和文件类型返回过来,图片/视频就可以展示出来。
:after-read=“afterRead” : 文件上传完毕后会触发 after-read 回调函数,获取到对应的 file 对象,将图片展示出来。

  <!-- 上传的图片预览 -->
      <div class="add">
        <div v-for="(i, idx) in fileMe" :key="idx" class="a-showImgVideo">
       	 
       	  //当上传的文件类型为0时 就显示图片;是1时就显示视频
          <img class="myImg" :src="i.Mysrc" v-if="i.type == '0'" />
          <video
            class="myImg"
            width="320"
            height="240"
            v-if="i.type == '1'"
            autoplay
            muted
          >
            <source :src="i.Mysrc" type="video/mp4" />
          </video>
        </div>
        <!-- vant 上传图片/视频 -->
        <van-uploader
          v-model="fileList"
          multiple
          :before-read="beforeRead"
        />
      </div>

调用 beforeRead函数,将文件的地址和类型传送到后端服务器 成功之后拿到返回值,显示出来:

methods: {
    beforeRead(file) {
      console.log("file", file);
      console.log("file.type", file.type);
     
      //判断文件的类型是否是图片
      let type = file.type.indexOf("image") == -1 ? 1 : 0;
      
      //使用FormData 的最大优点就是可以异步上传二进制文件
      const forms = new FormData();
      forms.append("filename", file); // 增加文件的参数
      forms.append("type", type); // 增加类型参数

	//获取返回过来的图片/视频 进行展示
      axios({
        url: "/bili/dynamic/uploadPicture",
        method: "post",
        data: forms, //URLSearchParams对象用于处理URL中查询字符串,即?之后的部分。
        headers: {
          "Content-Type": "multipart/form-data",
        }, //php 默认要求传递请求头
      })
        .then((res) => {
          console.log("返回res.data", res.data);
          // if (res.data.data.code == "0") {
          // if(res.data.code == 0){
          console.log("上传成功", res.data.msg);
          let imgInfo = {
            Mysrc: res.data.url,
            type: res.data.type,
          };
          this.fileMe.push(imgInfo);//fileMe是在data里定义的 是个空的数组 存的是上传图片的地址和类型
          console.log("this.imgUrl", this.imgUrl);
         
        })
        .catch((e) => {
          console.log("服务器出错", e);
        });
    },
点击发布按钮之后 将文本和图片/视频上传到后端服务器
// 点击发布按钮
    regSave() {
      console.log("this.fileMe", this.fileMe);
      
      // 通过FormData将文件转成二进制数据
      const forms = new FormData();
      forms.append("uid", sessionStorage.getItem("uid")); //  uid
      forms.append("urlList", [this.fileMe[0].Mysrc]); // 添加 键和值
      forms.append("descr", this.msg); // 获取上传图片描述
      // forms.append("date", this.fileDate); // 获取上传图片上传时间
      forms.append("type", this.fileMe[0].type); // 获取上传图片类型
      axios({
        url: "/bili/dynamic/addDynamic",
        method: "post",
        data: forms, //URLSearchParams类型
        headers: {
          "Content-Type": "multipart/form-data",
        }, //php 默认要求传递请求头
      })
        .then((res) => {
          // if (res.data.status === 200) {
          console.log(res.data);
        })
        .catch((e) => {
          console.log("服务器出错了", e);
        });
        setTimeout(() => {
          // 发布成功 跳转到动态页面
          this.$router.push('/Move/Space/SpaceMy');
        }, 2000);
    },

全部代码:

<template>
  <div class="box">
    <div class="top">
      <van-icon name="arrow-left" class="top-lef" @click="go" />
      <!-- 给按钮绑定一个class 如果computed返回的是true 就调用rel-highlight 这个css样式-->
      <div
        class="rel"
        :class="{ 'rel-highlight': isHighLight }"
        @click="regSave"
      >
        发布
      </div>
    </div>
    <van-notice-bar mode="link">新人福利,分享视频领限定头像框、个性装扮</van-notice-bar>
    <div class="content">
      <div class="text">
        <textarea
          class="text"
          placeholder="分享我的哔哩哔哩动态"
          v-model.trim="msg"
        ></textarea>
      </div>
      <!-- 上传的图片预览 -->
      <div class="add">
        <div v-for="(i, idx) in fileMe" :key="idx" class="a-showImgVideo">
          <img class="myImg" :src="i.Mysrc" v-if="i.type == '0'" />
          <video
            class="myImg"
            width="320"
            height="240"
            v-if="i.type == '1'"
            autoplay
            muted
          >
            <source :src="i.Mysrc" type="video/mp4" />
          </video>
        </div>
        <!-- 上传图片/视频 -->
        <van-uploader
          v-model="fileList"
          multiple
          :before-read="beforeRead"
        />
      </div>
      <div class="address" v-show="isShow">
        <div class="address-lef">
          <span class="iconfont-zm icon-lujing"></span>西安市
        </div>
        <div class="address-rig">
          <span class="iconfont-zm icon-X" @click="isShow = false"></span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "RelCenter",
  data() {
    return {
      // 用户输入  msg
      msg: "",
      url: "",
      fileMe: [],
      isShow: true,
      fileList: [
        // { url: "https://img01.yzcdn.cn/vant/leaf.jpg" },
        // Uploader 根据文件后缀来判断是否为图片文件
        // 如果图片 URL 中不包含类型信息,可以添加 isImage 标记来声明
      ],
    };
  },
  methods: {
    beforeRead(file) {
      console.log("file", file);
      console.log("file.type", file.type);
     //判断文件类型是不是图片
      let type = file.type.indexOf("image") == -1 ? 1 : 0;
      const forms = new FormData();
      forms.append("filename", file); // 获取上传图片信息
      forms.append("type", type); // 获取上传图片信息
      console.log("type shiping", type);
      axios({
        url: "/bili/dynamic/uploadPicture",
        method: "post",
        data: forms, //URLSearchParams类型
        headers: {
          "Content-Type": "multipart/form-data",
        }, //php 默认要求传递请求头
      })
        .then((res) => {
          console.log("返回res.data", res.data);
          // if (res.data.data.code == "0") {
          // if(res.data.code == 0){
          console.log("上传成功", res.data.msg);
          let imgInfo = {
            Mysrc: res.data.url,
            type: res.data.type,
          };
          this.fileMe.push(imgInfo);
          console.log("this.imgUrl", this.imgUrl);
         
        })
        .catch((e) => {
          console.log("服务器出错", e);
        });
    },

    go() {
      this.$router.go(-1);
    },
    
    // 点击发布按钮
    regSave() {
      console.log("this.fileMe", this.fileMe);
      
      // 通过FormData将文件转成二进制数据
      const forms = new FormData();
      forms.append("uid", sessionStorage.getItem("uid")); //  uid
      forms.append("urlList", [this.fileMe[0].Mysrc]); // 添加 键和值
      forms.append("descr", this.msg); // 获取上传图片描述
      // forms.append("date", this.fileDate); // 获取上传图片上传时间
      forms.append("type", this.fileMe[0].type); // 获取上传图片类型
      axios({
        url: "/bili/dynamic/addDynamic",
        method: "post",
        data: forms, //URLSearchParams类型
        headers: {
          "Content-Type": "multipart/form-data",
        }, //php 默认要求传递请求头
      })
        .then((res) => {
          // if (res.data.status === 200) {
          console.log(res.data);
        })
        .catch((e) => {
          console.log("服务器出错了", e);
        });
        setTimeout(() => {
          // 跳转到动态页面
          this.$router.push('/Move/Space/SpaceMy');
        }, 2000);
    },
  },
  computed: {
    isHighLight: function () {
      // 判断文本框是否输入内容 有内容是true 就调用高亮函数
      return this.msg.length > 0;
    },
  },
};
</script>


<style scoped>
@import url(../../assets/IconFont/Moves/font3/iconfont.css);
.box {
  width: 100%;
}

.top {
  width: 100%;
  height: 0.44rem;
  line-height: 0.44rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 0.16rem;
  box-sizing: border-box;
}
.top-lef {
  font-size: 0.16rem;
  color: #000;
}
.rel {
  width: 0.5rem;
  height: 0.28rem;
  background-color: #e7e7e7;
  border-radius: 0.14rem;
  font-size: 0.14rem;
  text-align: center;
  line-height: 0.28rem;
  color: #919191;
}

.content {
  width: 100%;
}
.text {
  width: 100%;
  height: 1.3rem;
  box-sizing: border-box;
  padding: 0.2rem 0.16rem 0;
}
textarea {
  width: 100%;
  height: 1.3rem;
  color: #000;
  font-size: 0.16rem;
  border: 0;
  outline: none;
}
.add {
  width: 1.14rem;
  height: 1.14rem;
  padding: 0 0.16rem;
}

.van-uploader__upload {
  width: 1.14rem;
  height: 1.14rem;
  border: 0.01rem solid dashed;
}
.address {
  width: 1.05rem;
  height: 0.26rem;
  line-height: 0.26rem;
  margin-left: 0.12rem;
  color: #277ac3;
  border-radius: 0.13rem;
  margin-top: 0.7rem;
  position: fixed;
  bottom: 0.6rem;
}
.address-lef {
  float: left;
  width: 0.77rem;
  height: 0.26rem;
  text-align: center;
  color: #277ac3;
  background-color: #f4f4f4;
  border-top-left-radius: 0.14rem;
  border-bottom-left-radius: 0.14rem;
  box-sizing: border-box;
}
.address-rig {
  float: left;
  width: 0.26rem;
  height: 0.26rem;
  line-height: 0.26rem;
  text-align: center;
  color: #277ac3;
  margin-left: 0.02rem;
  background-color: #f4f4f4;
  border-top-right-radius: 0.14rem;
  border-bottom-right-radius: 0.14rem;
}
.icon-lujing {
  font-size: 0.14rem;
  margin-right: 0.04rem;
}
.icon-X {
  font-size: 0.08rem;
}
//上传成功之后图片和视频的大盒子样式
.a-showImgVideo {
  margin-top: 0.2rem;

  width: 1.2rem;
  height: 1.2rem;
}
.a-showImgVideo .myImg {
  width: 100%;
  height: 100%;
}
</style>
<style>
.preview-cover {
  position: absolute;
  bottom: 0;
  box-sizing: border-box;
  width: 100%;
  padding: 0.04rem;
  color: #fff;
  font-size: 0.12rem;
  text-align: center;
  background: rgba(0, 0, 0, 0.3);
}
.van-uploader .van-uploader__wrapper {
  flex-wrap: nowrap;
}

/* 动态样式 */
.top .rel-highlight {
  background-color: #ea7a99;
  color: #fff;
}
</style>
vue3移动端项目构建TS,vue3+vant+vite+axios+pinia+sass+typescript 本文只是大致讲了下vue3 pc端项目搭建,具体的细节还是需要根据自己项目的需要进行调整。路由只封装了navigateTo、navigateBack,可以根据微信小程序路由api的逻辑https://developers.weixin.qq.com/miniprogram/dev/api/route/wx.switchTab.html 封装switchTab、reLaunch、redirectTo,如果有更好的方法可以忽略该路由封装,个人觉得小程序路由做的挺好。路径别名可配可不配,根据自己喜好就行。 阅读详情

相关推荐

vue3移动端项目构建,vue3+vant+vite+axios+pinia+sass

本文只是大致讲了下vue3移动端项目搭建,具体的细节还是需要根据自己项目的需要进行调整。路由只封装了navigateTo、navigateBack,可以根据微信小程序路由api的逻辑https://developers.weixin.qq.com/miniprogram/dev/api/route/wx.switchTab.html 封装switchTab、reLaunch、redirectTo,如果有更好的方法可以忽略该路由封装,个人觉得小程序路由做的挺好。路径别名可配可不配,根据自己喜好就行。

老衲爱洗头的博客 8271

vant 上传视频 预览 组件 (部分安卓机不支持,推荐调用原生方法,自己重写样式,否则会弹出系统自带的文件选择界面,PC端不受影响)

vant上传视频预览组件。

weixin_39428080的博客 7208

Vue3 + TypeSciprt+Vant 项目框架构建

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ApjGDxQM-1655734119007)(https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/4bcd5ea8327c4b2d855e1acb1f9d9975~tplv-k3u1fbpfcp-zoom-in-crop-mark:1956:0:0:0.image?)]浏览器地址栏输入 chrome://extensions/右上角开发者模式 - 打开开关。把 vue3_devto

老司机的后备箱 1317

最快速搭建小程序vue+vant+weapp,以及打包发布

vue+vant+weapp搭建小程序,以及打包发布 vue环境搭建 安装node:进入node官网下载与系统匹配的安装包完成安装 安装vue:查看官网教程完成安装 构建 weapp 打开 微信开发者工具 新建项目 2.打开 新建项目 根目录 下的 cmd命令编辑器 3.初始化项目 (输入命令之后一直点回车) npm init 4.安装 vant-weapp UI框架 npm i vant-weapp 5.设置 新建项目 使用npm模块 6.在 微信开发者工具 中

weixin_44666116的博客 4038

Vue使用Vant搭建移动端开发工程

1. 使用vue/cli创建项目(安装vue/cli) vue create my-project 创建过程步骤如下: Manuually select features 选择 Babel(es6语法编译器) Router(路由模块) Vuex(全局状态管理) Linter / Formatter(语法格式规范校验 ESLint + Standard)CssPre-processors(css/sass/less处理器)等个人定制 2. 项目创建完成 引入Vant npm i va...

qq_33771698的博客 2643

vant官网-vant ui 首页-移动端Vue组件库

Vant 是有赞前端团队开源的移动端vue组件库,适用于手机端h5页面。 鉴于百度搜索不到vant官方网址,分享一下vant组件库官网地址,方便新手使用 vant官网地址https://vant-contrib.gitee.io/vant/#/zh-CN/ 通过 npm 安装 在现有项目中使用 Vant 时,可以通过npm或yarn进行安装: # Vue 2 项目,安装 Vant 2: npm i vant -S # Vue 3 项目,安装 Vant 3: npm i vant@ne...

超人不会飞 5万+

Vant 上传/录制视频文件,显示预览图,支持视频预览,上传base64到后台

html代码 <van-uploader v-model="videoList" :max-count="1" preview-size="120px" accept="video/*" :after-read="handlevideosc" :before-read="handlebefread" @click-preview=".

ui设计前端工程师 1万+

移动端项目(vue2+vant组件库)

在命令行中输入以下命令创建 Vue 项目: 这里建议两个都选上,更严谨。 这里建议选择第 1 个,保存到单独的配置文件,这样方便我们做自定义配置。 安装结束,命令提示你项目创建成功,按照命令行的提示在终端中分别输入: [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UynFzUoP-1654274042910)(assets/1582010300149-9932febe-2625-4ee7-986f-9190ab449fec.png)]如

qq_45585640的博客 8541

最新vue+vant移动端电商项目

今天为大家带来一个Vue+VantUi完成的一个一个移动端电商项目,供大家学习和参考. 源码已上传到码云上面https://gitee.com/jiuyueqi/vyx,如果有需要源码或者接口文档的欢迎评论区留言,看到后会第一时间进行回复!!! 废话不多说先上效果图 下面开始让我为大家介绍一下该项目用到的知识点及核心代码 一、Vant 官网地址:https://youzan.github.io/vant/#/zh-CN/quickstart 通过vscode打开项目,使用 ctrl+~ 打开终端。我们通

weixin_45257157的博客 9137

vant上传图片跟视频混合上传加预览demo

vant 中的上传组件只能上传图片跟其他文件,只带默认的预览. 这里支持视频预览.视频录制.可同时选中相册的视频跟图片一起上传.npm run dev 就可以了.免c币下载地址: https://download.lllomh.com/cliect/#/product/JB08857273648214

【机器人学习】abb工业机器人运动学分析与圆弧轨迹规划(三维模型+matlab代码)

下载链接 solidworks模型 D-H建模 圆仿真过程 视频过程:

yjw0911的博客 2533

Vue项目实战 —— 哔哩哔哩移动端开发—— 第一篇

撑着下班前半小时我用vue写《哔哩哔哩 项目》移动端、新手还在哭、老鸟一直在笑。。。技术选型Vue2,技术栈有axios、Vh等,下班过来敲哈哈

技术前端,忠于热爱 @0.活在风浪里 1万+

蓝牙耳机充电仓——功能框架

数据传输:大部分充电仓会跟耳机通信,控制耳机开机、关机和进入可搜索模式等等。蓝牙耳机给大家的生活带来便利,来讲讲TWS蓝牙耳机的搭档充电仓吧!方便携带:如果耳机单独带着,指定能弄丢一个,有了充电仓就安全多了。收纳保护:把珍爱的耳机放入充电仓里,防止丢失、磕碰、刮花等。给耳机充电:提供电力补给,让耳机持续使用。

改变自己现在能改变的,珍惜自己现在所拥有的 8953

vue移动端实现文件上传、下载、删除

vue项目使用的插件vant,一个开发移动端很好用的组件 这个组件中自带了上传文件的方法,我们直接调用即可。 <!-- 文件上传 --> <van-form @submit="onSubmit" enctype="multipart/form-data"> <van-uploader style="float: left;margin-left: 14px;margin-top: 15px;" v-model="fileList" accept="f

weixin_45956838的博客 1万+

HBM PHY 架构解析:从主控模块到DWORD设计的深度探索

本文深入解析了HBM PHY的完整架构,从作为系统大脑的PUB主控模块出发,详细阐述了其CSR控制、初始化与训练引擎的核心功能。进而剖析了负责命令传输的AWORDX2模块与作为数据高速公路的DWORD模块的设计奥秘,包括其双向数据流、精密时钟对齐与延迟线校准机制。最后,探讨了顶层MASTER PHY的整合作用及从DFI到DRAM的完整数据通路,为理解这一高性能内存接口的关键物理层设计提供了全面视角。

weixin_29306011的博客 296

机械臂TCP标定实战:从四点法到六点法的精度跃迁

本文详细解析机械臂TCP标定技术,从基础的四点法到高精度的六点法实现精度跃迁。通过工具坐标系与基坐标系的转换原理,结合实战案例展示六点法如何将装配合格率提升至99.5%,并分享环境控制、操作技巧等提升标定精度的关键要素。

weixin_29038345的博客 898

[vue移动端项目] 严选商城项目 使用vue+vant做的移动端商城小项目

文章目录项目准备安装 amfe-flexible安装 第三方插件 postcss-pxtorem配置vue.config.jsreset.css 重置样式表安装less 预编译语言安装vant-ui端口配置(可以不做)axios 工具封装下载安装axiosutils/request.jshttps/http.js跨域代理配置 vue.config.js项目路由规划配置下载vue-router在index.js 文件中安装使用vue-routerrouter/index.jsmain.js: router

qq_14993591的博客 8084

包成功安装tiny-cuda-nn,记录安装过程中的问题解决,附带pytorch3d安装【踩坑指南】

该包可以显著提高NeRF训练速度,是和NeRFstudio等框架中,必须使用的。本文提供tiny-cuda-nn可以安装的完整包的下载链接,可以直接上传到项目中安装。附带笔者遇到的问题的解决方案。

zik的博客 7030

vue+vant搭建移动端框架

主要内容 1.vant/rem移动端适配的解决方案 2. vue/cli二次配置及优化处理 3.基于注册动态模式实现loading 4.掌握vuex永久化存储 1 创建一个vue项目 1.1安装vue-cli: npm install -g @vue/cli 1.2初始化项目 vue create vue-vant (1)选择手动配置 空格切换选中状态 插件选择这边选择了(Babel、Router、Vuex、Css预处理器、Linter / Formatter 格式检查) Babel:支持es6

qq_20464593的博客 1万+

ShaderJoy —— 简单又神奇的 “合体” 函数【GLSL】

smin 函数 它实际上有两种常见的实现方式 多项式 指数 多项式 smin 函数图 其对应的代码为 float smin( float a, float b ) { // 多项式 const float k = 0.5; float h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0); return mix(b, a, h) - k * h * (1.0 - h); } 从上图中我们可以很明显的看出有两处不连...

ShaderJoy 的兴趣技术杂货铺 1858

《FPGA接口与协议》专栏的说明与导航

《FPGA接口与协议》专栏的说明与导航(建议阅读)。

孤独的单刀 17万+

vue3+typescript+vite+vant搭建一个移动端项目

本文主要讲解vue3移动端项目如何搭建,在构建项目前请确保已安装node、npm工具,此项目构建主要集成:axios、vant、typescript、vite和vue3,其中还会介绍到如何动态适配尺寸等功能

W_Purplegrape的博客 3757

【数据分析】R语言分段结构方程模型手把手教程(Piecewise Structural Equation Model)

分段结构方程模型(Piecewise Structural Equation Model, SEM)是一种用于分析变量之间因果关系的统计方法。它通过将复杂的因果关系分解为多个简单的线性模型来评估变量之间的直接和间接效应。与传统的结构方程模型(SEM)不同,分段结构方程模型不需要假设数据的多变量正态分布,因此在处理非正态数据时更为灵活。

专注生信领域 2652

vue移动端文件预览

vue移动端文件预览前言:整体思路:具体实现:一、外壳(vViews.vue):二、文件预览:1.图片预览:2.pdf文件预览:3.docx文件预览:4.excel表格预览(xls、xlsx格式表格):5.txt文件预览:三、补充外壳文件css样式: 前言: 最近遇到一个移动端需求,要求在移动端预览上传的附件,在网上找了很多资料,最后参考优快云博主「蛋蛋fighting哈湫」的原创文章实现了功能,并结合自己的项目情况,整理了这份文档。 原文链接:https://blog.youkuaiyun.com/u0124396

weixin_40400844的博客 1万+

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

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

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

Nuxt3哔哩哔哩移动端项目实战

Nuxt 框架提供了一种基于 Node.js 的,可以让 Vue 应用在服务器端进行渲染,从而提高页面的加载速度和 SEO。

u014496893的博客 1767

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

vue+vant创建移动端项目工程

NCCloud1909 自由报表联查单据开发二级目录三级目录 二级目录 三级目录

qq_26313963的博客 2772

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

上一篇: 缓动动画原理
下一篇: Vue父子、兄弟、无关组件传值
小白努力中...
博客等级 码龄6年 10粉丝 12原创
评论 9
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值