李沐动手学深度学习V2-LeNet模型和代码实现

人工智能25
  1. LeNet

LeNet是最早发布的卷积神经网络之一,因其在计算机视觉任务中的高效性能而受到广泛关注。 这个模型是由AT&T贝尔实验室的研究员Yann LeCun在1989年提出的(并以其命名),目的是识别图像中的手写数字。

1.1 LeNet架构:

总体来看,LeNet由两个部分组成:卷积块(有两个卷积层组成)和全连接块(由三个全连接层组成),架构如下图所示。
每个卷积块中的基本单元是一个卷积层、一个sigmoid激活函数和平均汇聚层。请注意,虽然ReLU和最大汇聚层更有效,但它们在20世纪90年代还没有出现。每个卷积层使用 5×5 卷积核和一个sigmoid激活函数。这些层将输入映射到多个二维特征输出,并且同时增加通道的数量。第一卷积层有6个输出通道,而第二个卷积层有16个输出通道。每个 2×2 池操作通过空间下采样将维数减少4倍。 卷积的输出形状由批量大小、通道数、高度、宽度决定。
为了将卷积块的输出传递给全连接稠密块,我们必须在小批量中展平每个样本。换言之,我们将这个四维输入转换成全连接层所期望的二维输入。这里的二维表示的第一个维度索引小批量中的样本,第二个维度给出每个样本的平面向量特征表示。LeNet的全连接稠密块有三个全连接层,分别有120、84和10个输出。因为我们在执行分类任务,所以输出层的10维对应于最后输出结果的分类数量。
李沐动手学深度学习V2-LeNet模型和代码实现

; 1.2 LeNet模型定义

通过将一个大小为 28×28 的单通道(黑白)图像通过LeNet。通过在每一层打印输出的形状,我们可以检查模型,以确保其操作与我们期望的输出形状大小一致,如下图模型每层结构所示。
在整个卷积块中,与上一层相比,每一层特征的高度和宽度都减小了。 第一个卷积层使用2个像素的填充,来补偿 5×5 卷积核导致的特征减少。 相反,第二个卷积层没有填充,因此高度和宽度都减少了4个像素。 随着层叠的上升,通道的数量从输入时的1个,增加到第一个卷积层之后的6个,再到第二个卷积层之后的16个。 同时,每个汇聚层的高度和宽度都减半。最后,每个全连接层减少维数,最终输出一个维数与结果分类数相匹配的输出。
李沐动手学深度学习V2-LeNet模型和代码实现
LeNet模型定义代码:

import d2l.torch
import torch
from torch import nn

LeNet = nn.Sequential(nn.Conv2d(in_channels=1,out_channels=6,kernel_size=5,padding=2,stride=1),nn.Sigmoid(),
                      nn.AvgPool2d(kernel_size=2,stride=2),
                      nn.Conv2d(in_channels=6,out_channels=16,kernel_size=5,padding=0,stride=1),nn.Sigmoid(),
                      nn.AvgPool2d(kernel_size=2,stride=2),
                      nn.Flatten(),
                      nn.Linear(in_features=16*5*5,out_features=120),nn.Sigmoid(),
                      nn.Linear(in_features=120,out_features=84),nn.Sigmoid(),
                      nn.Linear(in_features=84,out_features=10))
print(LeNet)
X = torch.randn(size=(1,1,28,28))
for layer in LeNet:
    X = layer(X)
    print(layer.__class__.__name__,'output layer shape:\t',X.shape)
输出结果:
Sequential(
  (0): Conv2d(1, 6, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))
  (1): Sigmoid()
  (2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (3): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))
  (4): Sigmoid()
  (5): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (6): Flatten(start_dim=1, end_dim=-1)
  (7): Linear(in_features=400, out_features=120, bias=True)
  (8): Sigmoid()
  (9): Linear(in_features=120, out_features=84, bias=True)
  (10): Sigmoid()
  (11): Linear(in_features=84, out_features=10, bias=True)
)
Conv2d output layer shape:   torch.Size([1, 6, 28, 28])
Sigmoid output layer shape:  torch.Size([1, 6, 28, 28])
MaxPool2d output layer shape:    torch.Size([1, 6, 14, 14])
Conv2d output layer shape:   torch.Size([1, 16, 10, 10])
Sigmoid output layer shape:  torch.Size([1, 16, 10, 10])
MaxPool2d output layer shape:    torch.Size([1, 16, 5, 5])
Flatten output layer shape:  torch.Size([1, 400])
Linear output layer shape:   torch.Size([1, 120])
Sigmoid output layer shape:  torch.Size([1, 120])
Linear output layer shape:   torch.Size([1, 84])
Sigmoid output layer shape:  torch.Size([1, 84])
Linear output layer shape:   torch.Size([1, 10])

1.3 模型训练

使用Xavier_uniform分布随机初始化网络模型参数,与全连接层一样,使用交叉熵损失函数和小批量随机梯度下降。
模型训练代码如下:


def evaluate_accuracy_gpu(net,data_iter,device=None):
    if isinstance(net,nn.Module):
        net.eval()
        if not device:
            device = next(iter(net.parameters())).device
    accumulator = d2l.torch.Accumulator(2)
    for X,y in data_iter:
        if isinstance(X,list):
            X = [x.to(device) for x in X]
        else:
            X = X.to(device)
        y = y.to(device)
        accumulator.add(d2l.torch.accuracy(net(X),y),y.numel())
    return accumulator[0]/accumulator[1]

batch_size = 256
train_iter,test_iter = d2l.torch.load_data_fashion_mnist(batch_size=batch_size)
def train_LeNet(net,train_iter,test_iter,lr,num_epochs,device):
    def init_weights(m):
        if type(m) == nn.Linear or type(m) == nn.Conv2d:
            nn.init.xavier_uniform_(m.weight)
    net.apply(init_weights)
    net.to(device)
    loss = nn.CrossEntropyLoss()
    optim = torch.optim.SGD(net.parameters(),lr=lr)
    animator = d2l.torch.Animator(xlabel='epoch',xlim=[1,num_epochs],legend=['train_loss','train_acc','test_acc'])
    timer = d2l.torch.Timer()
    num_batches = len(train_iter)
    for epoch in range(num_epochs):
        net.train()
        accumulator = d2l.torch.Accumulator(3)
        for i,(X,y) in enumerate(train_iter):
           timer.start()
           optim.zero_grad()
           X = X.to(device)
           y = y.to(device)
           y_hat = net(X)
           l = loss(y_hat,y)
           l.backward()
           optim.step()
           with torch.no_grad():
               accumulator.add(l*X.shape[0],d2l.torch.accuracy(y_hat,y),X.shape[0])
           timer.stop()
           train_loss = accumulator[0]/accumulator[2]
           train_acc = accumulator[1]/accumulator[2]
           if (i+1) % (num_batches // 5) == 0 or i == num_batches-1:
               animator.add(epoch+(i+1)/num_batches,(train_loss,train_acc,None))
        test_accuracy = evaluate_accuracy_gpu(net,test_iter)
        animator.add(epoch+1,(None,None,test_accuracy))
    print(f'模型训练完最后一轮时 train_loss:{train_loss},train_acc:{train_acc},test_acc:{test_accuracy}')
    print(f'{num_epochs*accumulator[2]/timer.sum()}examples/second on {str(device)}')

lr,num_epochs= 0.9,10
train_LeNet(net=LeNet,train_iter=train_iter,test_iter=test_iter,lr=lr,num_epochs=num_epochs,device=d2l.torch.try_gpu())
'''
输出结果:
模型训练完最后一轮时 train_loss:0.4322478462855021,train_acc:0.8396666666666667,test_acc:0.8163
55954.65804440994examples/second on cuda:0
'''

1.4 小结

  1. 卷积神经网络(LeNet)是一类使用卷积层的网络。
  2. 在卷积神经网络中,我们组合使用卷积层、非线性激活函数和汇聚层(池化层)。
  3. 为了构造高性能的(更大更深)卷积神经网络,我们通常对卷积层进行排列,逐渐降低其表示的空间分辨率(输出尺寸形状(高和宽)大小),同时增加通道数。
  4. 在传统的卷积神经网络中,卷积块编码得到的表征在输出之前需由一个或多个全连接层进行处理(通常需要由一个Flatten()层将卷积块的输出铺平,然后再作为输入到全连接层中。
  5. LeNet是最早发布的卷积神经网络之一。

2.全部源代码

2.1 原始LeNet模型源代码(模型使用AvgPool2d池化层,Sigmoid()非线性激活函数,lr =0.9学习率,epochs = 10轮)


import d2l.torch
import torch
from torch import nn

LeNet = nn.Sequential(nn.Conv2d(in_channels=1,out_channels=6,kernel_size=5,padding=2,stride=1),nn.Sigmoid(),
                      nn.AvgPool2d(kernel_size=2,stride=2),
                      nn.Conv2d(in_channels=6,out_channels=16,kernel_size=5,padding=0,stride=1),nn.Sigmoid(),
                      nn.AvgPool2d(kernel_size=2,stride=2),
                      nn.Flatten(),
                      nn.Linear(in_features=16*5*5,out_features=120),nn.Sigmoid(),
                      nn.Linear(in_features=120,out_features=84),nn.Sigmoid(),
                      nn.Linear(in_features=84,out_features=10))
print(LeNet)
X = torch.randn(size=(1,1,28,28))
for layer in LeNet:
    X = layer(X)
    print(layer.__class__.__name__,'output layer shape:\t',X.shape)

def evaluate_accuracy_gpu(net,data_iter,device=None):
    if isinstance(net,nn.Module):
        net.eval()
        if not device:
            device = next(iter(net.parameters())).device
    accumulator = d2l.torch.Accumulator(2)
    for X,y in data_iter:
        if isinstance(X,list):
            X = [x.to(device) for x in X]
        else:
            X = X.to(device)
        y = y.to(device)
        accumulator.add(d2l.torch.accuracy(net(X),y),y.numel())
    return accumulator[0]/accumulator[1]

batch_size = 256
train_iter,test_iter = d2l.torch.load_data_fashion_mnist(batch_size=batch_size)
def train_LeNet(net,train_iter,test_iter,lr,num_epochs,device):
    def init_weights(m):
        if type(m) == nn.Linear or type(m) == nn.Conv2d:
            nn.init.xavier_uniform_(m.weight)
    net.apply(init_weights)
    net.to(device)
    loss = nn.CrossEntropyLoss()
    optim = torch.optim.SGD(net.parameters(),lr=lr)
    animator = d2l.torch.Animator(xlabel='epoch',xlim=[1,num_epochs],legend=['train_loss','train_acc','test_acc'])
    timer = d2l.torch.Timer()
    num_batches = len(train_iter)
    for epoch in range(num_epochs):
        net.train()
        accumulator = d2l.torch.Accumulator(3)
        for i,(X,y) in enumerate(train_iter):
           timer.start()
           optim.zero_grad()
           X = X.to(device)
           y = y.to(device)
           y_hat = net(X)
           l = loss(y_hat,y)
           l.backward()
           optim.step()
           with torch.no_grad():
               accumulator.add(l*X.shape[0],d2l.torch.accuracy(y_hat,y),X.shape[0])
           timer.stop()
           train_loss = accumulator[0]/accumulator[2]
           train_acc = accumulator[1]/accumulator[2]
           if (i+1) % (num_batches // 5) == 0 or i == num_batches-1:
               animator.add(epoch+(i+1)/num_batches,(train_loss,train_acc,None))
        test_accuracy = evaluate_accuracy_gpu(net,test_iter)
        animator.add(epoch+1,(None,None,test_accuracy))
    print(f'模型训练完最后一轮时 train_loss:{train_loss},train_acc:{train_acc},test_acc:{test_accuracy}')
    print(f'{num_epochs*accumulator[2]/timer.sum()}examples/second on {str(device)}')

lr,num_epochs= 0.9,10
train_LeNet(net=LeNet,train_iter=train_iter,test_iter=test_iter,lr=lr,num_epochs=num_epochs,device=d2l.torch.try_gpu())

原始LeNet模型训练结果输出如下图所示:
李沐动手学深度学习V2-LeNet模型和代码实现

2.2 改进后的LeNet模型(模型使用MaxPool2d池化层,ReLU()非线性激活函数,lr =0.03学习率,epochs = 150轮,batch_size = 256)


import d2l.torch
import torch
from torch import nn

LeNet = nn.Sequential(nn.Conv2d(in_channels=1,out_channels=6,kernel_size=5,padding=2,stride=1),nn.ReLU(),
                      nn.MaxPool2d(kernel_size=2,stride=2),
                      nn.Conv2d(in_channels=6,out_channels=16,kernel_size=5,padding=0,stride=1),nn.ReLU(),
                      nn.MaxPool2d(kernel_size=2,stride=2),
                      nn.Flatten(),
                      nn.Linear(in_features=16*5*5,out_features=120),nn.ReLU(),
                      nn.Linear(in_features=120,out_features=84),nn.ReLU(),
                      nn.Linear(in_features=84,out_features=10))
print(LeNet)
X = torch.randn(size=(1,1,28,28))
for layer in LeNet:
    X = layer(X)
    print(layer.__class__.__name__,'output layer shape:\t',X.shape)

def evaluate_accuracy_gpu(net,data_iter,device=None):
    if isinstance(net,nn.Module):
        net.eval()
        if not device:
            device = next(iter(net.parameters())).device
    accumulator = d2l.torch.Accumulator(2)
    for X,y in data_iter:
        if isinstance(X,list):
            X = [x.to(device) for x in X]
        else:
            X = X.to(device)
        y = y.to(device)
        accumulator.add(d2l.torch.accuracy(net(X),y),y.numel())
    return accumulator[0]/accumulator[1]

batch_size = 256
train_iter,test_iter = d2l.torch.load_data_fashion_mnist(batch_size=batch_size)
def train_LeNet(net,train_iter,test_iter,lr,num_epochs,device):
    def init_weights(m):
        if type(m) == nn.Linear or type(m) == nn.Conv2d:
            nn.init.xavier_uniform_(m.weight)
    net.apply(init_weights)
    net.to(device)
    loss = nn.CrossEntropyLoss()
    optim = torch.optim.SGD(net.parameters(),lr=lr)
    animator = d2l.torch.Animator(xlabel='epoch',xlim=[1,num_epochs],legend=['train_loss','train_acc','test_acc'])
    timer = d2l.torch.Timer()
    num_batches = len(train_iter)
    for epoch in range(num_epochs):
        net.train()
        accumulator = d2l.torch.Accumulator(3)
        for i,(X,y) in enumerate(train_iter):
           timer.start()
           optim.zero_grad()
           X = X.to(device)
           y = y.to(device)
           y_hat = net(X)
           l = loss(y_hat,y)
           l.backward()
           optim.step()
           with torch.no_grad():
               accumulator.add(l*X.shape[0],d2l.torch.accuracy(y_hat,y),X.shape[0])
           timer.stop()
           train_loss = accumulator[0]/accumulator[2]
           train_acc = accumulator[1]/accumulator[2]
           if (i+1) % (num_batches // 5) == 0 or i == num_batches-1:
               animator.add(epoch+(i+1)/num_batches,(train_loss,train_acc,None))
        test_accuracy = evaluate_accuracy_gpu(net,test_iter,device)
        animator.add(epoch+1,(None,None,test_accuracy))
    print(f'模型训练完最后一轮时 train_loss:{train_loss},train_acc:{train_acc},test_acc:{test_accuracy}')
    print(f'{num_epochs*accumulator[2]/timer.sum()}examples/second on {str(device)}')

lr,num_epochs= 0.03,150
train_LeNet(net=LeNet,train_iter=train_iter,test_iter=test_iter,lr=lr,num_epochs=num_epochs,device=d2l.torch.try_gpu())

改进后的LeNet模型训练结果输出如下图所示:
李沐动手学深度学习V2-LeNet模型和代码实现
从上面两个图可以看出,ReLU非线性函数和最大汇聚层(池化层)对于卷积神经网络更有效

Original: https://blog.csdn.net/flyingluohaipeng/article/details/124529913
Author: cv_lhp
Title: 李沐动手学深度学习V2-LeNet模型和代码实现



相关阅读1

Title: 安装tensorflow-gpu

安装tensorflow,主要是关于GPU

一、写在前面

我安装了三天,看了n+篇博客,写的很好,但是跟我不搭边。
因此,我的enter键已经被我蓄力冲击不知道多少次了。
所以,我只能回归最简单的安装了。
电脑耐操的话可以试一试我的方法。

二、两个XPU的区别

CPU:计算精准,但是速度不快,好比大脑,精细活
GPU:速度快,但是只能做简单计算,好比四肢,流水线
(不知道这么比喻恰不恰当,大部分是这个意思)

三、前提

如果不需要anaconda来隔离环境,就直接安装在系统Python就好了
否则,需要安装好anaconda。

安装在C盘和安装在其他盘的anaconda有一些不一样。 按我实际情况,我将anaconda安装在其他盘,出现安装路径的envs没有虚环境,反而是在C盘找到了(C:\Users\Hsu.conda\envs)。这个有点意外
还有一个比较重要的情况,安装在其他盘的时候,anaconda自带的命令行界面没有识别出安装好的cuda版本,提示没有这个nvcc -V这个命令。这也是第二个意外。

但是我安装在C盘的时候没有出现这些状况。

4、安装版本须知

4.1、CUDA和CUDNN

这个安装cuda和cudnn需要你去找其他博主的博客
可以告诉你的是,需要GPU驱动版本,python版本,pytorch版本,tensorflow-gpu版本都符合才可以成功安装cuda和cudnn,你可以不着急安装,先找这些版本。

4.2 编辑系统环境变量

第一步,设置自定义变量
李沐动手学深度学习V2-LeNet模型和代码实现
第二步、在Path设置
李沐动手学深度学习V2-LeNet模型和代码实现
这里是方便观看,实际上我是将四条语句写在一起,在Path我只写了%MYCUDA%;(当然了,每次cuda安装时都会自己注册一个变量名

我这么设置是因为经常修改cuda的版本,你可以直接将这四个文件夹路径都写入一个变量值,用英文分号隔开。(设置一个变量值等价于设置四个变量值)

; 4.3、安装版本(个人版本)

1、GPU驱动版本
显卡
李沐动手学深度学习V2-LeNet模型和代码实现
驱动版本:516.40
李沐动手学深度学习V2-LeNet模型和代码实现
在组件中还会有一个cuda版本,可以理解为是自带的,现在安装的是自己需要的
2、Python
李沐动手学深度学习V2-LeNet模型和代码实现
3、cuda和cudnn
cuda
李沐动手学深度学习V2-LeNet模型和代码实现

安装完了之后打开bandwidthTest.exe和deviceQuery.exe

C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.1\extras\demo_suite

如果直接打开的话,会出现闪退;需要在命令行打开。如果打开后两个的最后几行都出现Result=PASS,则证明成功了

4、PyTorch
李沐动手学深度学习V2-LeNet模型和代码实现
5、tensorflow-gpu
李沐动手学深度学习V2-LeNet模型和代码实现

4.4、表格查看版本

两个版本目前的区别在于tensorflow的函数调用
10.2版本

名称版本驱动版本516.40python3.7.13cuda10.2cudnn7.6tensorflow-gpu2.1pytorch1.10+cu102

11.3版本

名称版本驱动版本516.40python3.9.12cuda11.3cudnn8.2.1tensorflow-gpu2.6pytorch1.12.1+cu113

5、安装库

只有装好cuda和cudnn才可以看这里。

5.1、安装tensorlfow-gpu

conda create -n tf tensorflow-gpu=2.1

在acaconda官方文档中,上面的语句是:如果你符合gpu版本的环境,系统自动帮你安装gpu版本,否则还是安装cpu
这句话的意思:创建一个虚环境tf,并且安装tensorflow-gpu=2.1

5.2、安装pytorch

pip install torch==1.10.0+cu102 torchvision==0.11.0+cu102 torchaudio==0.10.0 -f https://download.pytorch.org/whl/torch_stable.html

这个很大,需要等很久。可以提前下载wheel文件

5.3、11.3版本

我用yolov5的依赖来安装,将里面的内容复制在一个txt文件中,在该文件路径的命令行中输入 pip install -r requirements.txt,即可安装


matplotlib>=3.2.2
numpy>=1.18.5
opencv-python>=4.1.1
Pillow>=7.1.2
PyYAML>=5.3.1
requests>=2.23.0
scipy>=1.4.1
torch>=1.7.0
torchvision>=0.8.1
tqdm>=4.41.0
protobuf3.20.1

tensorboard>=2.4.1

pandas>=1.1.4
seaborn>=0.11.0

ipython
psutil
thop

torch:我用conda的cudatoolkit安装一直不成功,各位可以试一试
pip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu113

tensorflow-gpu:
pip install tensorflow-gpu=2.6 -i  https://storage.googleapis.com/tensorflow/windows/gpu/tensorflow_gpu-2.6.0-cp39-cp39-win_amd64.whl

6、测试

1、点击,并且激活环境 tf
李沐动手学深度学习V2-LeNet模型和代码实现
输入测试代码,返回两个True可能还不行。最好去找个模型去运行一下。
李沐动手学深度学习V2-LeNet模型和代码实现

; 7、建议

软件版本能安装更高等级的就最好,因为2.5之后的tensorflow的部分api有所变化。11.3的搭配可以运行yolov5来训练自己的数据集

Original: https://blog.csdn.net/weixin_46107120/article/details/123433598
Author: 徐子元竟然被占了!!
Title: 安装tensorflow-gpu

相关阅读2

Title: 语音识别与转换小试牛刀(1)

前言

这几天突然觉得语音有点儿意思。想探索一些用一些库来实现下。

看见这篇推文: 这段AI的深情告白在外网爆火:我并非真实,从未出生,永不死亡,你能爱我吗?, 觉得语音合成的声音也可以很有感情。

语音合成

Text-to-Speech, 简称TTS
之前有一篇记录 语音合成模型小抄(1)

pyttsx3

首先, 下载好pyttsx, 由于我看的 文档 是2.6的,所以这里我就下载2.6版本的pyttsx3

pip install pyttsx3==2.6

直接读出来

import pyttsx3

zh_voice_id = 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_ZH-CN_HUIHUI_11.0'

en_engine = pyttsx3.init()
zh_engine = pyttsx3.init()
zh_engine.setProperty('voice', zh_voice_id)

def say_text(engine, text):
    show_engine_info(engine)
    engine.say(text)
    engine.runAndWait()

def show_engine_info(engine):
    voices = engine.getProperty('voices')
    for voice in voices:
        print("Voice:")
        print(" - ID: %s" % voice.id)
        print(" - Name: %s" % voice.name)
        print(" - Languages: %s" % voice.languages)
        print(" - Gender: %s" % voice.gender)
        print(" - Age: %s" % voice.age)

if __name__ == '__main__':
    say_text(en_engine, 'I will study hard. Only in this way can I get a good remark.')

转存为文件。发现: 'Engine' object has no attribute 'save_to_file'
等我有空看看这个版本下的源码...

FastSpeech2

项目链接 https://github.com/ming024/FastSpeech2

我是在colab上跑的,修改notebook为GPU加速
需要把作者的ckpt(当然自己训练也可以, 就直接放到指定地方即可)加载到google网盘中

def copy_pretrained_weight(ckpt_name, ckpt_share_path):
  assert ckpt_name in ['LJSpeech', 'AISHELL3', 'LibriTTS']

  if not os.path.exists('output'):
    os.mkdir('output')
  if not os.path.exists('output/ckpt'):
    os.mkdir('output/ckpt')
  dir_path = 'output/ckpt/{}'.format(ckpt_name)
  if not os.path.exists(dir_path):
    os.mkdir(dir_path)
  shutil.copy(ckpt_share_path, dir_path)

copy_pretrained_weight('LibriTTS', '/content/drive/MyDrive/share/FastSpeech2/LibriTTS_800000.pth.tar')

改一下pretrained名字

os.rename('/content/FastSpeech2/output/ckpt/LibriTTS/LibriTTS_800000.pth.tar',
          '/content/FastSpeech2/output/ckpt/LibriTTS/800000.pth.tar')

我这里是跑 LibriTTS 的版本,多人英文语音合成,其实还有中文的版本AISHELL3, 看一下readme.md就懂了,这里就不说了。
然后需要安装一下requirements.txt中的库,解压一下 HiFiGAN, 这里hifigan是decoder.

!unzip -d /content/FastSpeech2/hifigan /content/FastSpeech2/hifigan/generator_universal.pth.tar.zip

跑起来

!python3 synthesize.py --text "Want the stars and the sun, want the world to surrender, and want you by your side."\
  --speaker_id 0 --restore_step 800000 --mode single -p config/LibriTTS/preprocess.yaml -m config/LibriTTS/model.yaml -t config/LibriTTS/train.yaml

输出信息:
Removing weight norm...

Raw Text Sequence: Want the stars and the sun, want the world to surrender, and want you by your side
Phoneme Sequence: {W AA1 N T DH AH0 S T AA1 R Z AE1 N D DH AH0 S AH1 N sp W AA1 N T DH AH0 W ER1 L D T AH0 S ER0 EH1 N D ER0 sp AE1 N D W AA1 N T Y UW1 B AY1 Y AO1 R S AY1 D}

同时还输出了两个文件
李沐动手学深度学习V2-LeNet模型和代码实现

下载到本地后,look一下.这句话生成的梅尔谱。另外.wav文件直接点击就可以播放啦。(该wav文件我会拿来做ASR的例子hh)
李沐动手学深度学习V2-LeNet模型和代码实现

语音识别

Automatic Speech Recognition 简称 ASR

pocketSphinx

本来想安装的,结果报错了,看其他博客好像要安装其他东西,先做罢

wenet

https://github.com/wenet-e2e/wenet

pip install wenet

可以先去下载 https://github.com/wenet-e2e/wenet/releases/download/
这些文件,当然也可以直接不指定model_dir,它会自己下载到 C:/Users/Administrator/.wenet/
李沐动手学深度学习V2-LeNet模型和代码实现

import sys
import wave
import wenet

def wav2text(test_wav, only_last=True):
    with wave.open(test_wav, 'rb') as fin:
        assert fin.getnchannels() == 1
        wav = fin.readframes(fin.getnframes())

    decoder = wenet.Decoder(lang='en', model_dir='.wenet/en')

    interval = int(0.5 * 16000) * 2
    result = []
    for i in range(0, len(wav), interval):
        last = False if i + interval < len(wav) else True
        chunk_wav = wav[i: min(i + interval, len(wav))]
        ans = decoder.decode(chunk_wav, last)
        result.append(ans)
    if only_last:
        return result[-1]
    return result

if __name__ == '__main__':
    test_wav = 'demo/demo.wav'
    text = wav2text(test_wav)
    print(text)

{
"nbest" : [{
"sentence" : "want the stars and the sun want the world to surrender and want you by your side"
}],
"type" : "final_result"
}

看了一下输出内容就是 (没有标点符号...是个问题)
want the stars and the sun want the world to surrender and want you by your side

原文:
Want the stars and the sun, want the world to surrender, and want you by your side

Original: https://blog.csdn.net/weixin_43850253/article/details/126187251
Author: Andy Dennis
Title: 语音识别与转换小试牛刀(1)

相关阅读3

Title: Keras安装

keras安装

文章目录

*
- keras安装
* 前言
* 一、安装Keras前提
*
- 1.安装Anaconda
- 2.安装tensorflow
- 如果像我一样点背,出现了如下问题
* 二、Keras安装步骤
* 总结

前言

本次安装基于Python

一、安装Keras前提

1.安装Anaconda

直接从网址https://www.anaconda.com/products/individual#download-section点击Download,选择对应版本下载。安装过程一路next,在Select Installation Type 中两个都勾选,如图1
李沐动手学深度学习V2-LeNet模型和代码实现

图1
然后点击install就安装好了。接着验证是否安装成功,win+R输入cmd,打开命令窗口,输入 conda --version,出现版本表示安装成功,如图2。
李沐动手学深度学习V2-LeNet模型和代码实现图2

; 2.安装tensorflow

先打开我们刚安装好的Anaconda中的 Anaconda Prompt(开始->Anaconda->Anaconda Prompt),如图3:
李沐动手学深度学习V2-LeNet模型和代码实现图3
然后输入:(复制过去就好了)

conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/

再接着输入:

conda config --set show_channel_urls yes

安装Tensorflow时,需要从Anaconda仓库中下载,一般默认链接的都是国外镜像地址,要变成国内的需要改一下链接镜像的地址(跨国比较慢)。上述两行代码是用来改镜像代码的。

接下来安装Tensorflow,在Anaconda Prompt中输入:

conda create -n tensorflow python=3.5.2

出现图4
李沐动手学深度学习V2-LeNet模型和代码实现图4
输入y,顺利的话就完成了tensorflow的安装。如果自己已有tensorflow请跳过上述步骤

如果像我一样点背,出现了如下问题

李沐动手学深度学习V2-LeNet模型和代码实现图5
开始解决(我也是上网查的)
首先切换镜像

conda config --add channels https://mirrors.ustc.edu.cn/anaconda/pkgs/free/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config --set show_channel_urls yes

这四条依次输进去,然后找到c盘user文件里的.condarc,把里面的https 修改为 http
,删除 defaul那行,改后的文件如下
李沐动手学深度学习V2-LeNet模型和代码实现图6
回来运行一下

李沐动手学深度学习V2-LeNet模型和代码实现图7
我还是错了,我气死...

然后,然后我以管理员的身份进入 Anaconda Prompt,再重新按装,命令行同上为conda create -n tensorflow python=3.5.2,继续y,居然成功了,啊这...就这啊...我刚才干嘛呢

李沐动手学深度学习V2-LeNet模型和代码实现图8
下载tensorflow
pip install tensorflow,然后我就莫名其妙满江红了,不着急看一下问题在哪
李沐动手学深度学习V2-LeNet模型和代码实现图9
版本有点问题,先 pip --version一下,然后

python -m pip install --upgrade pip

就是这了,成功!!!

激活下吧,输入activate tensorflow,OK这一进程结束。

二、Keras安装步骤

还是管理员身份,在Anaconda prompt,依次输入

conda install mingw libpython

继续输入y,等他装好。

pip install theano

一样等着装好就行了

pip install keras

一样一样

然后我到这又又又满江红了???他又出错了
李沐动手学深度学习V2-LeNet模型和代码实现图10
再输入pip --default-timeout=1000 install keras尝试一下,没有报错。

测试Keras安装是否成功:
输入python,再输入import keras,如果没有报错,恭喜你安装成功了!!!!!!!!!

总结

也没啥总结的,本人菜鸡一只,欢迎各位大佬批评指正!!!

Original: https://blog.csdn.net/weixin_45822156/article/details/115732039
Author: weixin_45822156
Title: Keras安装

相关文章
C# 使用DirectX.DirectSound播放语音 人工智能

C# 使用DirectX.DirectSound播放语音

最近在做项目时,需要进行音频文件的即时播放,并且要求同时播放多条语音,之前C#程序中语音播放一直使用System.Media类库的SoundPlayer类进行播放,但是这个播放类有个弊端,就是在播放时...
n-gram语言模型LM 人工智能

n-gram语言模型LM

感谢阅读,笔者能力有限,有错误请指正! 为什么要加入语音模型? 对于连续语音识别,可能有上万个词,解码过程是复杂的,识别结果组合很多,只使用声学模型是不够的,需要引入语言模型来约束识别结果。 统计语言...
从 jQuery 到 Vue3 的快捷通道 人工智能

从 jQuery 到 Vue3 的快捷通道

当初使用 jQuery 做了几个简单的项目,算是有一点点了解,现在学习Vue3,发现了一个可以快速转换思维的通道 —— 使用CDN的方式模拟 Vite 建立的项目! CDN方式 jQuery的使用非常...
opencv-python安装 人工智能

opencv-python安装

文章目录 前言 一、安装opencv-python库 二、opencv模块架构 * 1.模块 2.实例运行 总结 前言 OpenCV就是学习计算机视觉的过程中经常用到的工具,opencv降低了计算机视...