PyTorch实战:Seq2seq模型完成机器翻译任务(详细注释版)

简要

本博客以《PyTorch自然语言处理入门与实战》第九章的Seq2seq模型处理英译中翻译任务作为基础,给出自己的理解及代码的详细注释。

数据预处理

在数据预处理中,用到了train.tags.zh-en.en和train.tags.zh-en.zh两个文件,第一个文件包含英译中任务的英文内容,第二个文件包含英译中任务的中文内容(数据集下载链接)。

两个文件来自IWSLT 2015数据集(提供了一些TED演讲的多种语言和英语之间的翻译)。

代码如下:

# step1: 从文件所包含的众多信息中筛选出演讲内容
fen = open('train.tags.zh-en.en', encoding='utf8')  # 演讲稿的英文内容
fzh = open('train.tags.zh-en.zh', encoding='utf8')  # 演讲稿的中文内容
en_zh = []
while True:
    lz = fzh.readline()  # 每次执行依次读取中文文件中的一行内容
    le = fen.readline()  #  每次执行依次读取英文文件中的一行内容
    # 判断是否读完文件
    if not lz:
        assert not le  # 如果读完,两个文件的结果都应该是空行  not lz == not le == True
        break
    lz, le = lz.strip(), le.strip()  # 返回删除首尾空白字符(换行符也能删除)的字符串副本
    # 筛选出需要的演讲内容部分
    if lz.startswith(''):
        assert le.startswith('')
        lz = fzh.readline()
        le = fen.readline()
        # 关键词部分
        assert lz.startswith('')
        assert le.startswith('')
        lz = fzh.readline()
        le = fen.readline()
        # 演讲人部分
        assert lz.startswith('')
        assert le.startswith('')
        lz = fzh.readline()
        le = fen.readline()
        # 演讲 ID
        assert lz.startswith('')
        assert le.startswith('')
        lz = fzh.readline()
        le = fen.readline()
        # 标题部分
        assert lz.startswith(''</span><span class="token punctuation">)</span>
        <span class="token keyword">assert</span> le<span class="token punctuation">.</span>startswith<span class="token punctuation">(</span><span class="token string">'<title>'</span><span class="token punctuation">)</span>
        lz <span class="token operator">=</span> fzh<span class="token punctuation">.</span>readline<span class="token punctuation">(</span><span class="token punctuation">)</span>
        le <span class="token operator">=</span> fen<span class="token punctuation">.</span>readline<span class="token punctuation">(</span><span class="token punctuation">)</span>
        <span class="token comment"># 描述部分</span>
        <span class="token keyword">assert</span> lz<span class="token punctuation">.</span>startswith<span class="token punctuation">(</span><span class="token string">'<description>'</span><span class="token punctuation">)</span>
        <span class="token keyword">assert</span> le<span class="token punctuation">.</span>startswith<span class="token punctuation">(</span><span class="token string">'<description>'</span><span class="token punctuation">)</span>
    <span class="token keyword">else</span><span class="token punctuation">:</span>  <span class="token comment"># 演讲内容部分</span>
        <span class="token keyword">if</span> <span class="token keyword">not</span> lz<span class="token punctuation">:</span>
            <span class="token keyword">assert</span> <span class="token keyword">not</span> le
            <span class="token keyword">break</span>
    <span class="token comment"># step2: 定位到演讲内容部分后,进行分词</span>
    <span class="token comment"># 对于中文内容, 我们把每个字当成一个词,因此list(lz)就实现分词</span>
    <span class="token comment"># 对于英文内容,我们把每个单词当成一个词,因此用空格字符“ ”进行分词</span>
        new_le <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span>
        <span class="token keyword">for</span> w <span class="token keyword">in</span> le<span class="token punctuation">.</span>split<span class="token punctuation">(</span><span class="token string">' '</span><span class="token punctuation">)</span><span class="token punctuation">:</span>  <span class="token comment"># 英文内容按照空格字符进行分词</span>
            <span class="token comment"># 按照空格进行分词后,某些单词后面会跟着标点符号 "." 和 “,”</span>
            w <span class="token operator">=</span> w<span class="token punctuation">.</span>replace<span class="token punctuation">(</span><span class="token string">'.'</span><span class="token punctuation">,</span> <span class="token string">''</span><span class="token punctuation">)</span><span class="token punctuation">.</span>replace<span class="token punctuation">(</span><span class="token string">','</span><span class="token punctuation">,</span> <span class="token string">''</span><span class="token punctuation">)</span>  <span class="token comment"># 去掉跟单词连着的标点符号</span>
            w <span class="token operator">=</span> w<span class="token punctuation">.</span>lower<span class="token punctuation">(</span><span class="token punctuation">)</span>  <span class="token comment"># 统一单词大小写</span>
            <span class="token keyword">if</span> w<span class="token punctuation">:</span>
                new_le<span class="token punctuation">.</span>append<span class="token punctuation">(</span>w<span class="token punctuation">)</span>
        en_zh<span class="token punctuation">.</span>append<span class="token punctuation">(</span><span class="token punctuation">[</span>new_le<span class="token punctuation">,</span> <span class="token builtin">list</span><span class="token punctuation">(</span>lz<span class="token punctuation">)</span><span class="token punctuation">]</span><span class="token punctuation">)</span> 


<span class="token comment"># step3 分别统计中英文内容数据中出现的词的数量</span>
<span class="token keyword">from</span> tqdm <span class="token keyword">import</span> tqdm  <span class="token comment"># 利用进度条直观展示处理进度</span>
en_words <span class="token operator">=</span> <span class="token builtin">set</span><span class="token punctuation">(</span><span class="token punctuation">)</span>  <span class="token comment"># 初始化集合对象  自动去重</span>
zh_words <span class="token operator">=</span> <span class="token builtin">set</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">for</span> s <span class="token keyword">in</span> tqdm<span class="token punctuation">(</span>en_zh<span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">for</span> w <span class="token keyword">in</span> s<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">:</span> <span class="token comment"># 统计英文</span>
        w <span class="token operator">=</span> w<span class="token punctuation">.</span>replace<span class="token punctuation">(</span><span class="token string">'.'</span><span class="token punctuation">,</span> <span class="token string">''</span><span class="token punctuation">)</span><span class="token punctuation">.</span>replace<span class="token punctuation">(</span><span class="token string">','</span><span class="token punctuation">,</span> <span class="token string">''</span><span class="token punctuation">)</span><span class="token punctuation">.</span>lower<span class="token punctuation">(</span><span class="token punctuation">)</span>
        <span class="token keyword">if</span> w<span class="token punctuation">:</span>
            en_words<span class="token punctuation">.</span>add<span class="token punctuation">(</span>w<span class="token punctuation">)</span>
    <span class="token keyword">for</span> w <span class="token keyword">in</span> s<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">:</span> <span class="token comment"># 统计中文</span>
        <span class="token keyword">if</span> w<span class="token punctuation">:</span>
            zh_words<span class="token punctuation">.</span>add<span class="token punctuation">(</span>w<span class="token punctuation">)</span>
            
<span class="token comment"># step4 将集合对象转换为列表对象后,添加三个标识符'<sos>', '<eos>', '<pad>'</span>
<span class="token comment"># sos ---> start of sentence 句子开头  	索引:0</span>
<span class="token comment"># eos ---> end of sentence	 句子结尾	索引:1</span>
<span class="token comment"># pad ---> 填充标识符	索引:2</span>
en_wl <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">'<sos>'</span><span class="token punctuation">,</span> <span class="token string">'<eos>'</span><span class="token punctuation">,</span> <span class="token string">'<pad>'</span><span class="token punctuation">]</span> <span class="token operator">+</span> <span class="token builtin">list</span><span class="token punctuation">(</span>en_words<span class="token punctuation">)</span>
zh_wl <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">'<sos>'</span><span class="token punctuation">,</span> <span class="token string">'<eos>'</span><span class="token punctuation">,</span> <span class="token string">'<pad>'</span><span class="token punctuation">]</span> <span class="token operator">+</span> <span class="token builtin">list</span><span class="token punctuation">(</span>zh_words<span class="token punctuation">)</span>
pad_id <span class="token operator">=</span> <span class="token number">2</span>

<span class="token comment"># step5 利用字典对象存储词和索引的对应关系</span>
en2id <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
zh2id <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
<span class="token keyword">for</span> i<span class="token punctuation">,</span> w <span class="token keyword">in</span> <span class="token builtin">enumerate</span><span class="token punctuation">(</span>en_wl<span class="token punctuation">)</span><span class="token punctuation">:</span>  <span class="token comment"># 遍历枚举类型对象实现此功能</span>
    en2id<span class="token punctuation">[</span>w<span class="token punctuation">]</span> <span class="token operator">=</span> i
<span class="token keyword">for</span> i<span class="token punctuation">,</span> w <span class="token keyword">in</span> <span class="token builtin">enumerate</span><span class="token punctuation">(</span>zh_wl<span class="token punctuation">)</span><span class="token punctuation">:</span>
    zh2id<span class="token punctuation">[</span>w<span class="token punctuation">]</span> <span class="token operator">=</span> i            
    
</code></pre> 
  <h3>运行结果</h3> 
  <p><a href="http://img.e-com-net.com/image/info8/bea31a59818c47eb97e1db6df07b3ab6.jpg" target="_blank"><img src="http://img.e-com-net.com/image/info8/bea31a59818c47eb97e1db6df07b3ab6.jpg" alt="运行结果" width="650" height="77"></a></p> 
  <h2>随机划分训练集和测试集</h2> 
  <p>使用80%数据作为训练集,20%数据作为测试集,代码如下:</p> 
  <pre><code class="prism language-python"><span class="token keyword">import</span> random

random<span class="token punctuation">.</span>shuffle<span class="token punctuation">(</span>en_zh<span class="token punctuation">)</span>  <span class="token comment"># 随机打乱全部数据</span>
train_num <span class="token operator">=</span> <span class="token builtin">len</span><span class="token punctuation">(</span>en_zh<span class="token punctuation">)</span> <span class="token operator">*</span> <span class="token number">0.8</span>
train_set <span class="token operator">=</span> en_zh<span class="token punctuation">[</span><span class="token punctuation">:</span>train_num<span class="token punctuation">]</span>  <span class="token comment"># 8成用于训练</span>
dev_set <span class="token operator">=</span> en_zh<span class="token punctuation">[</span>train_num<span class="token punctuation">:</span><span class="token punctuation">]</span>  <span class="token comment"># 2成用于测试</span>
</code></pre> 
  <h2>创建训练集和测试集</h2> 
  <p>利用<code>torch.utils.data.dataset</code>和<code>torch.utils.data.DataLoader</code>创建训练集和测试集以及它们的数据加载器</p> 
  <h3>torch.utils.data.dataset(存放中英文内容,为遍历数据做准备)</h3> 
  <pre><code class="prism language-python"><span class="token keyword">import</span> torch

batch_size <span class="token operator">=</span> <span class="token number">16</span>
data_workers <span class="token operator">=</span> <span class="token number">0</span>  <span class="token comment"># 子进程数 </span>

<span class="token keyword">class</span> <span class="token class-name">MyDataSet</span><span class="token punctuation">(</span>torch<span class="token punctuation">.</span>utils<span class="token punctuation">.</span>data<span class="token punctuation">.</span>Dataset<span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> examples<span class="token punctuation">)</span><span class="token punctuation">:</span>
        self<span class="token punctuation">.</span>examples <span class="token operator">=</span> examples

    <span class="token keyword">def</span> <span class="token function">__len__</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">return</span> <span class="token builtin">len</span><span class="token punctuation">(</span>self<span class="token punctuation">.</span>examples<span class="token punctuation">)</span>

    <span class="token keyword">def</span> <span class="token function">__getitem__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> index<span class="token punctuation">)</span><span class="token punctuation">:</span>
        example <span class="token operator">=</span> self<span class="token punctuation">.</span>examples<span class="token punctuation">[</span>index<span class="token punctuation">]</span>
        s1 <span class="token operator">=</span> example<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span>
        s2 <span class="token operator">=</span> example<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span>
        l1 <span class="token operator">=</span> <span class="token builtin">len</span><span class="token punctuation">(</span>s1<span class="token punctuation">)</span>
        l2 <span class="token operator">=</span> <span class="token builtin">len</span><span class="token punctuation">(</span>s2<span class="token punctuation">)</span>
        <span class="token keyword">return</span> s1<span class="token punctuation">,</span> l1<span class="token punctuation">,</span> s2<span class="token punctuation">,</span> l2<span class="token punctuation">,</span> index  <span class="token comment"># 英文句子  英文句子长度  中文句子  中文句子长度 当前数据在数据集中的索引</span>

<span class="token comment"># batch_size = 16 是全局变量</span>
<span class="token keyword">def</span> <span class="token function">the_collate_fn</span><span class="token punctuation">(</span>batch<span class="token punctuation">)</span><span class="token punctuation">:</span>
    src <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">*</span> batch_size<span class="token punctuation">]</span>  <span class="token comment"># src ---> source 缩写   该任务中 源句子指的是英文句子  # 每个样本的开头都是0(起始标识符的编码)</span>
    tar <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">*</span> batch_size<span class="token punctuation">]</span>  <span class="token comment"># tar ---> target 缩写           目标句子指的是中文句子</span>
    src_max_l <span class="token operator">=</span> <span class="token number">0</span>  <span class="token comment"># 初始化英文句子最大长度  方便计算需要填充的个数</span>
    <span class="token keyword">for</span> b <span class="token keyword">in</span> batch<span class="token punctuation">:</span> <span class="token comment"># 每个batch的数据有五个信息 分别是: 英文句子  英文句子长度  中文句子  中文句子长度 当前数据在数据集中的索引</span>
        src_max_l <span class="token operator">=</span> <span class="token builtin">max</span><span class="token punctuation">(</span>src_max_l<span class="token punctuation">,</span> b<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span>  <span class="token comment"># b[1] 即英文句子的长度</span>
    tar_max_l <span class="token operator">=</span> <span class="token number">0</span>
    <span class="token keyword">for</span> b <span class="token keyword">in</span> batch<span class="token punctuation">:</span>
        tar_max_l <span class="token operator">=</span> <span class="token builtin">max</span><span class="token punctuation">(</span>tar_max_l<span class="token punctuation">,</span> b<span class="token punctuation">[</span><span class="token number">3</span><span class="token punctuation">]</span><span class="token punctuation">)</span>  <span class="token comment"># b[3] 即中文句子的长度</span>
    <span class="token keyword">for</span> i <span class="token keyword">in</span> <span class="token builtin">range</span><span class="token punctuation">(</span>src_max_l<span class="token punctuation">)</span><span class="token punctuation">:</span>
        l <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span>
        <span class="token keyword">for</span> x <span class="token keyword">in</span> batch<span class="token punctuation">:</span>
            <span class="token keyword">if</span> i <span class="token operator"><</span> x<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">:</span>
                l<span class="token punctuation">.</span>append<span class="token punctuation">(</span>en2id<span class="token punctuation">[</span>x<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">]</span><span class="token punctuation">)</span>
            <span class="token keyword">else</span><span class="token punctuation">:</span>
                l<span class="token punctuation">.</span>append<span class="token punctuation">(</span>pad_id<span class="token punctuation">)</span>  <span class="token comment"># 如果句子长度小于最大句子长度,进行填充</span>
        src<span class="token punctuation">.</span>append<span class="token punctuation">(</span>l<span class="token punctuation">)</span>
        <span class="token comment"># l记录的是每个句子的第 i 个词  有多少个句子? batch size个,因此len(l) == batch_size == 句子的数量</span>
        <span class="token comment"># src记录的是每个 l  总共多少个l? src_max_l个,因此len(src) == src_max_l == 句子的最大长度</span>
        <span class="token comment"># len(src) == 句子的最大长度    len(src[0]) == 句子的数量</span>
        <span class="token comment"># [len(src), len(src[0])] ==> [src len, batch size]</span>

    <span class="token keyword">for</span> i <span class="token keyword">in</span> <span class="token builtin">range</span><span class="token punctuation">(</span>tar_max_l<span class="token punctuation">)</span><span class="token punctuation">:</span>  <span class="token comment"># 注释参考上面</span>
        l <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span>
        <span class="token keyword">for</span> x <span class="token keyword">in</span> batch<span class="token punctuation">:</span>
            <span class="token keyword">if</span> i <span class="token operator"><</span> x<span class="token punctuation">[</span><span class="token number">3</span><span class="token punctuation">]</span><span class="token punctuation">:</span>
                l<span class="token punctuation">.</span>append<span class="token punctuation">(</span>zh2id<span class="token punctuation">[</span>x<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">]</span><span class="token punctuation">)</span>
            <span class="token keyword">else</span><span class="token punctuation">:</span>
                l<span class="token punctuation">.</span>append<span class="token punctuation">(</span>pad_id<span class="token punctuation">)</span>  <span class="token comment"># 如果句子长度小于最大句子长度,进行填充</span>
        tar<span class="token punctuation">.</span>append<span class="token punctuation">(</span>l<span class="token punctuation">)</span>
    indexs <span class="token operator">=</span> <span class="token punctuation">[</span>b<span class="token punctuation">[</span><span class="token number">4</span><span class="token punctuation">]</span> <span class="token keyword">for</span> b <span class="token keyword">in</span> batch<span class="token punctuation">]</span>  <span class="token comment"># b[4] 记录的是 当前数据在数据集中的索引</span>
    src<span class="token punctuation">.</span>append<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span> <span class="token operator">*</span> batch_size<span class="token punctuation">)</span>  <span class="token comment"># 终止标识符的编码为1 所以src和tar在句子的最后把终止符加上</span>
    tar<span class="token punctuation">.</span>append<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span> <span class="token operator">*</span> batch_size<span class="token punctuation">)</span>
    s1 <span class="token operator">=</span> torch<span class="token punctuation">.</span>LongTensor<span class="token punctuation">(</span>src<span class="token punctuation">)</span> 
    s2 <span class="token operator">=</span> torch<span class="token punctuation">.</span>LongTensor<span class="token punctuation">(</span>tar<span class="token punctuation">)</span>
    <span class="token keyword">return</span> s1<span class="token punctuation">,</span> s2<span class="token punctuation">,</span> indexs
</code></pre> 
  <pre><code class="prism language-python"><span class="token comment"># 构建训练集 </span>
train_dataset <span class="token operator">=</span> MyDataSet<span class="token punctuation">(</span>train_set<span class="token punctuation">)</span>
dev_dataset <span class="token operator">=</span> MyDataSet<span class="token punctuation">(</span>dev_set<span class="token punctuation">)</span>
</code></pre> 
  <h3>torch.utils.data.DataLoader</h3> 
  <pre><code class="prism language-python"><span class="token comment"># 定义训练集数据加载器和验证集数据加载器</span>
train_data_loader <span class="token operator">=</span> torch<span class="token punctuation">.</span>utils<span class="token punctuation">.</span>data<span class="token punctuation">.</span>DataLoader<span class="token punctuation">(</span>
    train_dataset<span class="token punctuation">,</span>
    batch_size<span class="token operator">=</span>batch_size<span class="token punctuation">,</span>
    shuffle<span class="token operator">=</span><span class="token boolean">True</span><span class="token punctuation">,</span>
    num_workers<span class="token operator">=</span>data_workers<span class="token punctuation">,</span>
    collate_fn<span class="token operator">=</span>the_collate_fn<span class="token punctuation">,</span>
<span class="token punctuation">)</span>

dev_data_loader <span class="token operator">=</span> torch<span class="token punctuation">.</span>utils<span class="token punctuation">.</span>data<span class="token punctuation">.</span>DataLoader<span class="token punctuation">(</span>
    dev_dataset<span class="token punctuation">,</span>
    batch_size<span class="token operator">=</span>batch_size<span class="token punctuation">,</span>
    shuffle<span class="token operator">=</span><span class="token boolean">True</span><span class="token punctuation">,</span>
    num_workers<span class="token operator">=</span>data_workers<span class="token punctuation">,</span>
    collate_fn<span class="token operator">=</span>the_collate_fn<span class="token punctuation">,</span>
<span class="token punctuation">)</span>
</code></pre> 
  <h2>定义Seq2Seq模型</h2> 
  <p>代码如下:</p> 
  <pre><code class="prism language-python"><span class="token keyword">import</span> torch<span class="token punctuation">.</span>nn <span class="token keyword">as</span> nn


<span class="token keyword">class</span> <span class="token class-name">Encoder</span><span class="token punctuation">(</span>nn<span class="token punctuation">.</span>Module<span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> input_dim<span class="token punctuation">,</span> emb_dim<span class="token punctuation">,</span> hid_dim<span class="token punctuation">,</span> n_layers<span class="token punctuation">,</span> dropout<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token builtin">super</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span>__init__<span class="token punctuation">(</span><span class="token punctuation">)</span>
        self<span class="token punctuation">.</span>hid_dim <span class="token operator">=</span> hid_dim
        self<span class="token punctuation">.</span>n_layers <span class="token operator">=</span> n_layers
        self<span class="token punctuation">.</span>embedding <span class="token operator">=</span> nn<span class="token punctuation">.</span>Embedding<span class="token punctuation">(</span>input_dim<span class="token punctuation">,</span> emb_dim<span class="token punctuation">)</span>  <span class="token comment"># 词嵌入</span>
        self<span class="token punctuation">.</span>rnn <span class="token operator">=</span> nn<span class="token punctuation">.</span>LSTM<span class="token punctuation">(</span>emb_dim<span class="token punctuation">,</span> hid_dim<span class="token punctuation">,</span> n_layers<span class="token punctuation">,</span> dropout<span class="token operator">=</span>dropout<span class="token punctuation">)</span>
        self<span class="token punctuation">.</span>dropout <span class="token operator">=</span> nn<span class="token punctuation">.</span>Dropout<span class="token punctuation">(</span>dropout<span class="token punctuation">)</span>

    <span class="token keyword">def</span> <span class="token function">forward</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> src<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token comment"># src = (src len, batch size)</span>
        embedded <span class="token operator">=</span> self<span class="token punctuation">.</span>dropout<span class="token punctuation">(</span>self<span class="token punctuation">.</span>embedding<span class="token punctuation">(</span>src<span class="token punctuation">)</span><span class="token punctuation">)</span>
        <span class="token comment"># embedded = (src len, batch size, emb dim)</span>
        outputs<span class="token punctuation">,</span> <span class="token punctuation">(</span>hidden<span class="token punctuation">,</span> cell<span class="token punctuation">)</span> <span class="token operator">=</span> self<span class="token punctuation">.</span>rnn<span class="token punctuation">(</span>embedded<span class="token punctuation">)</span>
        <span class="token comment"># outputs = (src len, batch size, hid dim * n directions)</span>
        <span class="token comment"># hidden = (n layers * n directions, batch size, hid dim)</span>
        <span class="token comment"># cell = (n layers * n directions, batch size, hid dim)</span>
        <span class="token comment"># rnn的输出总是来自顶部的隐藏层</span>
        <span class="token keyword">return</span> hidden<span class="token punctuation">,</span> cell


<span class="token keyword">class</span> <span class="token class-name">Decoder</span><span class="token punctuation">(</span>nn<span class="token punctuation">.</span>Module<span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> output_dim<span class="token punctuation">,</span> emb_dim<span class="token punctuation">,</span> hid_dim<span class="token punctuation">,</span> n_layers<span class="token punctuation">,</span> dropout<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token builtin">super</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span>__init__<span class="token punctuation">(</span><span class="token punctuation">)</span>
        self<span class="token punctuation">.</span>output_dim <span class="token operator">=</span> output_dim
        self<span class="token punctuation">.</span>hid_dim <span class="token operator">=</span> hid_dim
        self<span class="token punctuation">.</span>n_layers <span class="token operator">=</span> n_layers
        self<span class="token punctuation">.</span>embedding <span class="token operator">=</span> nn<span class="token punctuation">.</span>Embedding<span class="token punctuation">(</span>output_dim<span class="token punctuation">,</span> emb_dim<span class="token punctuation">)</span>
        self<span class="token punctuation">.</span>rnn <span class="token operator">=</span> nn<span class="token punctuation">.</span>LSTM<span class="token punctuation">(</span>emb_dim<span class="token punctuation">,</span> hid_dim<span class="token punctuation">,</span> n_layers<span class="token punctuation">,</span> dropout<span class="token operator">=</span>dropout<span class="token punctuation">)</span>
        self<span class="token punctuation">.</span>fc_out <span class="token operator">=</span> nn<span class="token punctuation">.</span>Linear<span class="token punctuation">(</span>hid_dim<span class="token punctuation">,</span> output_dim<span class="token punctuation">)</span>
        self<span class="token punctuation">.</span>dropout <span class="token operator">=</span> nn<span class="token punctuation">.</span>Dropout<span class="token punctuation">(</span>dropout<span class="token punctuation">)</span>

    <span class="token keyword">def</span> <span class="token function">forward</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> <span class="token builtin">input</span><span class="token punctuation">,</span> hidden<span class="token punctuation">,</span> cell<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token comment"># 各输入的形状</span>
        <span class="token comment"># input = (batch size)</span>
        <span class="token comment"># hidden = (n layers * n directions, batch size, hid dim)</span>
        <span class="token comment"># cell = (n layers * n directions, batch size, hid dim)</span>

        <span class="token comment"># LSTM是单向的  ==> n directions == 1</span>
        <span class="token comment"># hidden = (n layers, batch size, hid dim)</span>
        <span class="token comment"># cell = (n layers, batch size, hid dim)</span>

        <span class="token builtin">input</span> <span class="token operator">=</span> <span class="token builtin">input</span><span class="token punctuation">.</span>unsqueeze<span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span>  <span class="token comment"># (batch size)  --> [1, batch size)</span>

        embedded <span class="token operator">=</span> self<span class="token punctuation">.</span>dropout<span class="token punctuation">(</span>self<span class="token punctuation">.</span>embedding<span class="token punctuation">(</span><span class="token builtin">input</span><span class="token punctuation">)</span><span class="token punctuation">)</span>  <span class="token comment"># (1, batch size, emb dim)</span>

        output<span class="token punctuation">,</span> <span class="token punctuation">(</span>hidden<span class="token punctuation">,</span> cell<span class="token punctuation">)</span> <span class="token operator">=</span> self<span class="token punctuation">.</span>rnn<span class="token punctuation">(</span>embedded<span class="token punctuation">,</span> <span class="token punctuation">(</span>hidden<span class="token punctuation">,</span> cell<span class="token punctuation">)</span><span class="token punctuation">)</span>
        <span class="token comment"># LSTM理论上的输出形状</span>
        <span class="token comment"># output = (seq len, batch size, hid dim * n directions)</span>
        <span class="token comment"># hidden = (n layers * n directions, batch size, hid dim)</span>
        <span class="token comment"># cell = (n layers * n directions, batch size, hid dim)</span>

        <span class="token comment"># 解码器中的序列长度 seq len == 1</span>
        <span class="token comment"># 解码器的LSTM是单向的 n directions == 1 则实际上</span>
        <span class="token comment"># output = (1, batch size, hid dim)</span>
        <span class="token comment"># hidden = (n layers, batch size, hid dim)</span>
        <span class="token comment"># cell = (n layers, batch size, hid dim)</span>

        prediction <span class="token operator">=</span> self<span class="token punctuation">.</span>fc_out<span class="token punctuation">(</span>output<span class="token punctuation">.</span>squeeze<span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">)</span>

        <span class="token comment"># prediction = (batch size, output dim)</span>

        <span class="token keyword">return</span> prediction<span class="token punctuation">,</span> hidden<span class="token punctuation">,</span> cell


<span class="token keyword">class</span> <span class="token class-name">Seq2Seq</span><span class="token punctuation">(</span>nn<span class="token punctuation">.</span>Module<span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> input_word_count<span class="token punctuation">,</span> output_word_count<span class="token punctuation">,</span> encode_dim<span class="token punctuation">,</span> decode_dim<span class="token punctuation">,</span> hidden_dim<span class="token punctuation">,</span> n_layers<span class="token punctuation">,</span>
                 encode_dropout<span class="token punctuation">,</span> decode_dropout<span class="token punctuation">,</span> device<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token triple-quoted-string string">"""

        :param input_word_count:    英文词表的长度     34737
        :param output_word_count:   中文词表的长度     4015
        :param encode_dim:          编码器的词嵌入维度
        :param decode_dim:          解码器的词嵌入维度
        :param hidden_dim:          LSTM的隐藏层维度
        :param n_layers:            采用n层LSTM
        :param encode_dropout:      编码器的dropout概率
        :param decode_dropout:      编码器的dropout概率
        :param device:              cuda / cpu
        """</span>
        <span class="token builtin">super</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span>__init__<span class="token punctuation">(</span><span class="token punctuation">)</span>
        self<span class="token punctuation">.</span>encoder <span class="token operator">=</span> Encoder<span class="token punctuation">(</span>input_word_count<span class="token punctuation">,</span> encode_dim<span class="token punctuation">,</span> hidden_dim<span class="token punctuation">,</span> n_layers<span class="token punctuation">,</span> encode_dropout<span class="token punctuation">)</span>
        self<span class="token punctuation">.</span>decoder <span class="token operator">=</span> Decoder<span class="token punctuation">(</span>output_word_count<span class="token punctuation">,</span> decode_dim<span class="token punctuation">,</span> hidden_dim<span class="token punctuation">,</span> n_layers<span class="token punctuation">,</span> decode_dropout<span class="token punctuation">)</span>
        self<span class="token punctuation">.</span>device <span class="token operator">=</span> device

    <span class="token keyword">def</span> <span class="token function">forward</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> src<span class="token punctuation">,</span> trg<span class="token punctuation">,</span> teacher_forcing_ratio<span class="token operator">=</span><span class="token number">0.5</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token comment"># src = (src len, batch size)</span>
        <span class="token comment"># trg = (trg len, batch size)</span>
        <span class="token comment"># teacher_forcing_ratio 定义使用Teacher Forcing的比例</span>
        <span class="token comment"># 例如 if teacher_forcing_ratio is 0.75 we use ground-truth inputs 75% of the time</span>
        batch_size <span class="token operator">=</span> trg<span class="token punctuation">.</span>shape<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span>
        trg_len <span class="token operator">=</span> trg<span class="token punctuation">.</span>shape<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span>
        trg_vocab_size <span class="token operator">=</span> self<span class="token punctuation">.</span>decoder<span class="token punctuation">.</span>output_dim  <span class="token comment"># 实际上就是中文词表的长度</span>
        <span class="token comment"># 初始化保存解码器输出的Tensor</span>
        outputs <span class="token operator">=</span> torch<span class="token punctuation">.</span>zeros<span class="token punctuation">(</span>trg_len<span class="token punctuation">,</span> batch_size<span class="token punctuation">,</span> trg_vocab_size<span class="token punctuation">)</span><span class="token punctuation">.</span>to<span class="token punctuation">(</span>self<span class="token punctuation">.</span>device<span class="token punctuation">)</span>

        <span class="token comment"># 编码器的隐藏层输出将作为i解码器的第一个隐藏层输入</span>
        hidden<span class="token punctuation">,</span> cell <span class="token operator">=</span> self<span class="token punctuation">.</span>encoder<span class="token punctuation">(</span>src<span class="token punctuation">)</span>

        <span class="token comment"># 解码器的第一个输入应该是起始标识符<sos></span>
        <span class="token builtin">input</span> <span class="token operator">=</span> trg<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token punctuation">:</span><span class="token punctuation">]</span>  <span class="token comment"># 取trg的第“0”行所有列  “0”指的是索引</span>
        <span class="token comment"># 从the_collate_fn函数中可以看出trg的第“0”行全是0,也就是起始标识符对应的ID</span>

        <span class="token keyword">for</span> t <span class="token keyword">in</span> <span class="token builtin">range</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> trg_len<span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token comment"># 从 trg的第"1"行开始遍历</span>
            <span class="token comment"># 解码器的输入包括:起始标识符的词嵌入input; 编码器输出的 hidden and cell states</span>
            <span class="token comment"># 解码器的输出包括:输出张量(predictions) and new hidden and cell states</span>
            output<span class="token punctuation">,</span> hidden<span class="token punctuation">,</span> cell <span class="token operator">=</span> self<span class="token punctuation">.</span>decoder<span class="token punctuation">(</span><span class="token builtin">input</span><span class="token punctuation">,</span> hidden<span class="token punctuation">,</span> cell<span class="token punctuation">)</span>

            <span class="token comment"># 保存每次预测结果于outputs</span>
            <span class="token comment"># outputs (trg_len, batch_size, trg_vocab_size)</span>
            <span class="token comment"># output  (batch size, trg_vocab_size)</span>
            outputs<span class="token punctuation">[</span>t<span class="token punctuation">]</span> <span class="token operator">=</span> output

            <span class="token comment"># 随机决定是否使用Teacher Forcing</span>
            teacher_force <span class="token operator">=</span> random<span class="token punctuation">.</span>random<span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator"><</span> teacher_forcing_ratio

            <span class="token comment"># output  (batch size, trg_vocab_size)  沿dim=1取最大值索引</span>
            top1 <span class="token operator">=</span> output<span class="token punctuation">.</span>argmax<span class="token punctuation">(</span>dim<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">)</span>  <span class="token comment"># (batch size, )</span>

            <span class="token comment"># if teacher forcing, 以真实值作为下一个输入 否则 使用预测值</span>
            <span class="token builtin">input</span> <span class="token operator">=</span> trg<span class="token punctuation">[</span>t<span class="token punctuation">]</span> <span class="token keyword">if</span> teacher_force <span class="token keyword">else</span> top1

        <span class="token keyword">return</span> outputs


source_word_count <span class="token operator">=</span> <span class="token builtin">len</span><span class="token punctuation">(</span>en_wl<span class="token punctuation">)</span>  <span class="token comment"># 英文词表的长度     34737</span>
target_word_count <span class="token operator">=</span> <span class="token builtin">len</span><span class="token punctuation">(</span>zh_wl<span class="token punctuation">)</span>  <span class="token comment"># 中文词表的长度     4015</span>
encode_dim <span class="token operator">=</span> <span class="token number">256</span>    <span class="token comment"># 编码器的词嵌入维度</span>
decode_dim <span class="token operator">=</span> <span class="token number">256</span>    <span class="token comment"># 解码器的词嵌入维度</span>
hidden_dim <span class="token operator">=</span> <span class="token number">512</span>    <span class="token comment"># LSTM的隐藏层维度</span>
n_layers <span class="token operator">=</span> <span class="token number">2</span>        <span class="token comment"># 采用n层LSTM</span>
encode_dropout <span class="token operator">=</span> <span class="token number">0.5</span>    <span class="token comment"># 编码器的dropout概率</span>
decode_dropout <span class="token operator">=</span> <span class="token number">0.5</span>    <span class="token comment"># 编码器的dropout概率</span>
device <span class="token operator">=</span> torch<span class="token punctuation">.</span>device<span class="token punctuation">(</span><span class="token string">'cuda'</span><span class="token punctuation">)</span> <span class="token keyword">if</span> torch<span class="token punctuation">.</span>cuda<span class="token punctuation">.</span>is_available<span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">else</span> torch<span class="token punctuation">.</span>device<span class="token punctuation">(</span><span class="token string">'cpu'</span><span class="token punctuation">)</span>  <span class="token comment"># GPU可用 用GPU</span>
<span class="token comment"># Seq2Seq模型实例化</span>
model <span class="token operator">=</span> Seq2Seq<span class="token punctuation">(</span>source_word_count<span class="token punctuation">,</span> target_word_count<span class="token punctuation">,</span> encode_dim<span class="token punctuation">,</span> decode_dim<span class="token punctuation">,</span> hidden_dim<span class="token punctuation">,</span> n_layers<span class="token punctuation">,</span> encode_dropout<span class="token punctuation">,</span>
                decode_dropout<span class="token punctuation">,</span> device<span class="token punctuation">)</span><span class="token punctuation">.</span>to<span class="token punctuation">(</span>device<span class="token punctuation">)</span>

<span class="token comment"># 初始化模型参数</span>
<span class="token keyword">def</span> <span class="token function">init_weights</span><span class="token punctuation">(</span>m<span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">for</span> name<span class="token punctuation">,</span> param <span class="token keyword">in</span> m<span class="token punctuation">.</span>named_parameters<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
        nn<span class="token punctuation">.</span>init<span class="token punctuation">.</span>uniform_<span class="token punctuation">(</span>param<span class="token punctuation">.</span>data<span class="token punctuation">,</span> <span class="token operator">-</span><span class="token number">0.08</span><span class="token punctuation">,</span> <span class="token number">0.08</span><span class="token punctuation">)</span>

model<span class="token punctuation">.</span><span class="token builtin">apply</span><span class="token punctuation">(</span>init_weights<span class="token punctuation">)</span>  

<span class="token comment"># 统计Seq2Seq模型中可训练的参数个数</span>
<span class="token keyword">def</span> <span class="token function">count_parameters</span><span class="token punctuation">(</span>model<span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">return</span> <span class="token builtin">sum</span><span class="token punctuation">(</span>p<span class="token punctuation">.</span>numel<span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">for</span> p <span class="token keyword">in</span> model<span class="token punctuation">.</span>parameters<span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">if</span> p<span class="token punctuation">.</span>requires_grad<span class="token punctuation">)</span>

<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string-interpolation"><span class="token string">f'The model has </span><span class="token interpolation"><span class="token punctuation">{</span>count_parameters<span class="token punctuation">(</span>model<span class="token punctuation">)</span><span class="token punctuation">:</span><span class="token format-spec">,</span><span class="token punctuation">}</span></span><span class="token string"> trainable parameters'</span></span><span class="token punctuation">)</span>

<span class="token keyword">import</span> torch<span class="token punctuation">.</span>optim <span class="token keyword">as</span> optim

<span class="token comment"># 定义优化器</span>
optimizer <span class="token operator">=</span> optim<span class="token punctuation">.</span>Adam<span class="token punctuation">(</span>model<span class="token punctuation">.</span>parameters<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>

<span class="token comment"># 定义损失函数</span>
criterion <span class="token operator">=</span> nn<span class="token punctuation">.</span>CrossEntropyLoss<span class="token punctuation">(</span>ignore_index<span class="token operator">=</span>pad_id<span class="token punctuation">)</span><span class="token punctuation">.</span>to<span class="token punctuation">(</span>device<span class="token punctuation">)</span>  <span class="token comment"># 忽略填充标识符的索引</span>
</code></pre> 
  <h2>模型的训练和评估</h2> 
  <pre><code class="prism language-python"><span class="token comment"># 训练策略</span>
<span class="token keyword">def</span> <span class="token function">train</span><span class="token punctuation">(</span>model<span class="token punctuation">,</span> iterator<span class="token punctuation">,</span> optimizer<span class="token punctuation">,</span> criterion<span class="token punctuation">,</span> clip<span class="token punctuation">)</span><span class="token punctuation">:</span>
    model<span class="token punctuation">.</span>train<span class="token punctuation">(</span><span class="token punctuation">)</span>  <span class="token comment"># 切换到训练模式</span>
    epoch_loss <span class="token operator">=</span> <span class="token number">0</span>

    <span class="token keyword">for</span> i<span class="token punctuation">,</span> batch <span class="token keyword">in</span> <span class="token builtin">enumerate</span><span class="token punctuation">(</span>iterator<span class="token punctuation">)</span><span class="token punctuation">:</span>
        src <span class="token operator">=</span> batch<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">.</span>to<span class="token punctuation">(</span>device<span class="token punctuation">)</span>
        trg <span class="token operator">=</span> batch<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">.</span>to<span class="token punctuation">(</span>device<span class="token punctuation">)</span>

        optimizer<span class="token punctuation">.</span>zero_grad<span class="token punctuation">(</span><span class="token punctuation">)</span>  <span class="token comment"># 梯度清零</span>

        output <span class="token operator">=</span> model<span class="token punctuation">(</span>src<span class="token punctuation">,</span> trg<span class="token punctuation">)</span>  <span class="token comment"># 前向传播</span>

        <span class="token comment"># trg = [trg len, batch size]</span>
        <span class="token comment"># output = [trg len, batch size, output dim]</span>

        output_dim <span class="token operator">=</span> output<span class="token punctuation">.</span>shape<span class="token punctuation">[</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">]</span>

        output <span class="token operator">=</span> output<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">:</span><span class="token punctuation">]</span><span class="token punctuation">.</span>view<span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">,</span> output_dim<span class="token punctuation">)</span>
        trg <span class="token operator">=</span> trg<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">:</span><span class="token punctuation">]</span><span class="token punctuation">.</span>view<span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span>

        <span class="token comment"># trg = [(trg len - 1) * batch size]</span>
        <span class="token comment"># output = [(trg len - 1) * batch size, output dim]</span>

        loss <span class="token operator">=</span> criterion<span class="token punctuation">(</span>output<span class="token punctuation">,</span> trg<span class="token punctuation">)</span> <span class="token comment"># 计算损失</span>

        loss<span class="token punctuation">.</span>backward<span class="token punctuation">(</span><span class="token punctuation">)</span>  <span class="token comment"># 反向传播</span>

        torch<span class="token punctuation">.</span>nn<span class="token punctuation">.</span>utils<span class="token punctuation">.</span>clip_grad_norm_<span class="token punctuation">(</span>model<span class="token punctuation">.</span>parameters<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> clip<span class="token punctuation">)</span>

        optimizer<span class="token punctuation">.</span>step<span class="token punctuation">(</span><span class="token punctuation">)</span>  <span class="token comment"># 更新参数</span>

        epoch_loss <span class="token operator">+=</span> loss<span class="token punctuation">.</span>item<span class="token punctuation">(</span><span class="token punctuation">)</span>

    <span class="token keyword">return</span> epoch_loss <span class="token operator">/</span> <span class="token builtin">len</span><span class="token punctuation">(</span>iterator<span class="token punctuation">)</span>

<span class="token comment"># 验证策略</span>
<span class="token keyword">def</span> <span class="token function">evaluate</span><span class="token punctuation">(</span>model<span class="token punctuation">,</span> iterator<span class="token punctuation">,</span> criterion<span class="token punctuation">)</span><span class="token punctuation">:</span>
    model<span class="token punctuation">.</span><span class="token builtin">eval</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment"># 切换到验证模式</span>

    epoch_loss <span class="token operator">=</span> <span class="token number">0</span>

    <span class="token keyword">with</span> torch<span class="token punctuation">.</span>no_grad<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>  <span class="token comment"># 不计算梯度</span>
        <span class="token keyword">for</span> i<span class="token punctuation">,</span> batch <span class="token keyword">in</span> <span class="token builtin">enumerate</span><span class="token punctuation">(</span>iterator<span class="token punctuation">)</span><span class="token punctuation">:</span>
            src <span class="token operator">=</span> batch<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">.</span>to<span class="token punctuation">(</span>device<span class="token punctuation">)</span>
            trg <span class="token operator">=</span> batch<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">.</span>to<span class="token punctuation">(</span>device<span class="token punctuation">)</span>

            output <span class="token operator">=</span> model<span class="token punctuation">(</span>src<span class="token punctuation">,</span> trg<span class="token punctuation">,</span> teacher_forcing_ratio<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">)</span>  <span class="token comment"># 验证时禁用Teacher Forcing</span>

            <span class="token comment"># trg = [trg len, batch size]</span>
            <span class="token comment"># output = [trg len, batch size, output dim]</span>

            output_dim <span class="token operator">=</span> output<span class="token punctuation">.</span>shape<span class="token punctuation">[</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">]</span>

            output <span class="token operator">=</span> output<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">:</span><span class="token punctuation">]</span><span class="token punctuation">.</span>view<span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">,</span> output_dim<span class="token punctuation">)</span>
            trg <span class="token operator">=</span> trg<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">:</span><span class="token punctuation">]</span><span class="token punctuation">.</span>view<span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span>

            <span class="token comment"># trg = [(trg len - 1) * batch size]</span>
            <span class="token comment"># output = [(trg len - 1) * batch size, output dim]</span>

            loss <span class="token operator">=</span> criterion<span class="token punctuation">(</span>output<span class="token punctuation">,</span> trg<span class="token punctuation">)</span>

            epoch_loss <span class="token operator">+=</span> loss<span class="token punctuation">.</span>item<span class="token punctuation">(</span><span class="token punctuation">)</span>

    <span class="token keyword">return</span> epoch_loss <span class="token operator">/</span> <span class="token builtin">len</span><span class="token punctuation">(</span>iterator<span class="token punctuation">)</span>

<span class="token comment"># 记录每个epoch的用时</span>
<span class="token keyword">def</span> <span class="token function">epoch_time</span><span class="token punctuation">(</span>start_time<span class="token punctuation">,</span> end_time<span class="token punctuation">)</span><span class="token punctuation">:</span>
    elapsed_time <span class="token operator">=</span> end_time <span class="token operator">-</span> start_time
    elapsed_mins <span class="token operator">=</span> <span class="token builtin">int</span><span class="token punctuation">(</span>elapsed_time <span class="token operator">/</span> <span class="token number">60</span><span class="token punctuation">)</span>
    elapsed_secs <span class="token operator">=</span> <span class="token builtin">int</span><span class="token punctuation">(</span>elapsed_time <span class="token operator">-</span> <span class="token punctuation">(</span>elapsed_mins <span class="token operator">*</span> <span class="token number">60</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token keyword">return</span> elapsed_mins<span class="token punctuation">,</span> elapsed_secs


<span class="token keyword">import</span> math
<span class="token keyword">import</span> time

N_EPOCHS <span class="token operator">=</span> <span class="token number">10</span>  <span class="token comment"># 训练轮次</span>
CLIP <span class="token operator">=</span> <span class="token number">1</span>

best_valid_loss <span class="token operator">=</span> <span class="token builtin">float</span><span class="token punctuation">(</span><span class="token string">'inf'</span><span class="token punctuation">)</span>

<span class="token comment"># 开始训练</span>
<span class="token keyword">for</span> epoch <span class="token keyword">in</span> <span class="token builtin">range</span><span class="token punctuation">(</span>N_EPOCHS<span class="token punctuation">)</span><span class="token punctuation">:</span>

    start_time <span class="token operator">=</span> time<span class="token punctuation">.</span>time<span class="token punctuation">(</span><span class="token punctuation">)</span>

    train_loss <span class="token operator">=</span> train<span class="token punctuation">(</span>model<span class="token punctuation">,</span> train_data_loader<span class="token punctuation">,</span> optimizer<span class="token punctuation">,</span> criterion<span class="token punctuation">,</span> CLIP<span class="token punctuation">)</span>
    <span class="token comment"># 每训练一个轮次,测试一次</span>
    valid_loss <span class="token operator">=</span> evaluate<span class="token punctuation">(</span>model<span class="token punctuation">,</span> dev_data_loader<span class="token punctuation">,</span> criterion<span class="token punctuation">)</span>

    end_time <span class="token operator">=</span> time<span class="token punctuation">.</span>time<span class="token punctuation">(</span><span class="token punctuation">)</span>

    epoch_mins<span class="token punctuation">,</span> epoch_secs <span class="token operator">=</span> epoch_time<span class="token punctuation">(</span>start_time<span class="token punctuation">,</span> end_time<span class="token punctuation">)</span>

    <span class="token keyword">if</span> valid_loss <span class="token operator"><</span> best_valid_loss<span class="token punctuation">:</span> <span class="token comment"># 保存最优模型(验证loss阶段性最低时)</span>
        best_valid_loss <span class="token operator">=</span> valid_loss
        torch<span class="token punctuation">.</span>save<span class="token punctuation">(</span>model<span class="token punctuation">.</span>state_dict<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token string">'best_model.pth'</span><span class="token punctuation">)</span>
	
	<span class="token comment"># 打印相关指标</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string-interpolation"><span class="token string">f'Epoch: </span><span class="token interpolation"><span class="token punctuation">{</span>epoch <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">:</span><span class="token format-spec">02</span><span class="token punctuation">}</span></span><span class="token string"> | Time: </span><span class="token interpolation"><span class="token punctuation">{</span>epoch_mins<span class="token punctuation">}</span></span><span class="token string">m </span><span class="token interpolation"><span class="token punctuation">{</span>epoch_secs<span class="token punctuation">}</span></span><span class="token string">s'</span></span><span class="token punctuation">)</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string-interpolation"><span class="token string">f'\tTrain Loss: </span><span class="token interpolation"><span class="token punctuation">{</span>train_loss<span class="token punctuation">:</span><span class="token format-spec">.3f</span><span class="token punctuation">}</span></span><span class="token string"> | Train PPL: </span><span class="token interpolation"><span class="token punctuation">{</span>math<span class="token punctuation">.</span>exp<span class="token punctuation">(</span>train_loss<span class="token punctuation">)</span><span class="token punctuation">:</span><span class="token format-spec">7.3f</span><span class="token punctuation">}</span></span><span class="token string">'</span></span><span class="token punctuation">)</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string-interpolation"><span class="token string">f'\t Val. Loss: </span><span class="token interpolation"><span class="token punctuation">{</span>valid_loss<span class="token punctuation">:</span><span class="token format-spec">.3f</span><span class="token punctuation">}</span></span><span class="token string"> |  Val. PPL: </span><span class="token interpolation"><span class="token punctuation">{</span>math<span class="token punctuation">.</span>exp<span class="token punctuation">(</span>valid_loss<span class="token punctuation">)</span><span class="token punctuation">:</span><span class="token format-spec">7.3f</span><span class="token punctuation">}</span></span><span class="token string">'</span></span><span class="token punctuation">)</span>
</code></pre> 
  <h1>如果你有任何疑问或者更好的建议,欢迎评论区留言~</h1> 
 </div> 
</div>
                            </div>
                        </div>
                    </div>
                    <!--PC和WAP自适应版-->
                    <div id="SOHUCS" sid="1681327141796524032"></div>
                    <script type="text/javascript" src="/views/front/js/chanyan.js"></script>
                    <!-- 文章页-底部 动态广告位 -->
                    <div class="youdao-fixed-ad" id="detail_ad_bottom"></div>
                </div>
                <div class="col-md-3">
                    <div class="row" id="ad">
                        <!-- 文章页-右侧1 动态广告位 -->
                        <div id="right-1" class="col-lg-12 col-md-12 col-sm-4 col-xs-4 ad">
                            <div class="youdao-fixed-ad" id="detail_ad_1"> </div>
                        </div>
                        <!-- 文章页-右侧2 动态广告位 -->
                        <div id="right-2" class="col-lg-12 col-md-12 col-sm-4 col-xs-4 ad">
                            <div class="youdao-fixed-ad" id="detail_ad_2"></div>
                        </div>
                        <!-- 文章页-右侧3 动态广告位 -->
                        <div id="right-3" class="col-lg-12 col-md-12 col-sm-4 col-xs-4 ad">
                            <div class="youdao-fixed-ad" id="detail_ad_3"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="container">
        <h4 class="pt20 mb15 mt0 border-top">你可能感兴趣的:(PyTorch实战,深度学习,PyTorch,pytorch,机器翻译,python)</h4>
        <div id="paradigm-article-related">
            <div class="recommend-post mb30">
                <ul class="widget-links">
                    <li><a href="/article/1835513803861749760.htm"
                           title="机器学习与深度学习间关系与区别" target="_blank">机器学习与深度学习间关系与区别</a>
                        <span class="text-muted">ℒℴѵℯ心·动ꦿ໊ོ꫞</span>
<a class="tag" taget="_blank" href="/search/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/1.htm">人工智能</a><a class="tag" taget="_blank" href="/search/%E5%AD%A6%E4%B9%A0/1.htm">学习</a><a class="tag" taget="_blank" href="/search/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/1.htm">深度学习</a><a class="tag" taget="_blank" href="/search/python/1.htm">python</a>
                        <div>一、机器学习概述定义机器学习(MachineLearning,ML)是一种通过数据驱动的方法,利用统计学和计算算法来训练模型,使计算机能够从数据中学习并自动进行预测或决策。机器学习通过分析大量数据样本,识别其中的模式和规律,从而对新的数据进行判断。其核心在于通过训练过程,让模型不断优化和提升其预测准确性。主要类型1.监督学习(SupervisedLearning)监督学习是指在训练数据集中包含输入</div>
                    </li>
                    <li><a href="/article/1835511912843014144.htm"
                           title="理解Gunicorn:Python WSGI服务器的基石" target="_blank">理解Gunicorn:Python WSGI服务器的基石</a>
                        <span class="text-muted">范范0825</span>
<a class="tag" taget="_blank" href="/search/ipython/1.htm">ipython</a><a class="tag" taget="_blank" href="/search/linux/1.htm">linux</a><a class="tag" taget="_blank" href="/search/%E8%BF%90%E7%BB%B4/1.htm">运维</a>
                        <div>理解Gunicorn:PythonWSGI服务器的基石介绍Gunicorn,全称GreenUnicorn,是一个为PythonWSGI(WebServerGatewayInterface)应用设计的高效、轻量级HTTP服务器。作为PythonWeb应用部署的常用工具,Gunicorn以其高性能和易用性著称。本文将介绍Gunicorn的基本概念、安装和配置,帮助初学者快速上手。1.什么是Gunico</div>
                    </li>
                    <li><a href="/article/1835506869838376960.htm"
                           title="Python数据分析与可视化实战指南" target="_blank">Python数据分析与可视化实战指南</a>
                        <span class="text-muted">William数据分析</span>
<a class="tag" taget="_blank" href="/search/python/1.htm">python</a><a class="tag" taget="_blank" href="/search/python/1.htm">python</a><a class="tag" taget="_blank" href="/search/%E6%95%B0%E6%8D%AE/1.htm">数据</a>
                        <div>在数据驱动的时代,Python因其简洁的语法、强大的库生态系统以及活跃的社区,成为了数据分析与可视化的首选语言。本文将通过一个详细的案例,带领大家学习如何使用Python进行数据分析,并通过可视化来直观呈现分析结果。一、环境准备1.1安装必要库在开始数据分析和可视化之前,我们需要安装一些常用的库。主要包括pandas、numpy、matplotlib和seaborn等。这些库分别用于数据处理、数学</div>
                    </li>
                    <li><a href="/article/1835505858939809792.htm"
                           title="python os.environ" target="_blank">python os.environ</a>
                        <span class="text-muted">江湖偌大</span>
<a class="tag" taget="_blank" href="/search/python/1.htm">python</a><a class="tag" taget="_blank" href="/search/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/1.htm">深度学习</a>
                        <div>os.environ['TF_CPP_MIN_LOG_LEVEL']='0'#默认值,输出所有信息os.environ['TF_CPP_MIN_LOG_LEVEL']='1'#屏蔽通知信息(INFO)os.environ['TF_CPP_MIN_LOG_LEVEL']='2'#屏蔽通知信息和警告信息(INFO\WARNING)os.environ['TF_CPP_MIN_LOG_LEVEL']='</div>
                    </li>
                    <li><a href="/article/1835505606245576704.htm"
                           title="Python中os.environ基本介绍及使用方法" target="_blank">Python中os.environ基本介绍及使用方法</a>
                        <span class="text-muted">鹤冲天Pro</span>
<a class="tag" taget="_blank" href="/search/%23/1.htm">#</a><a class="tag" taget="_blank" href="/search/Python/1.htm">Python</a><a class="tag" taget="_blank" href="/search/python/1.htm">python</a><a class="tag" taget="_blank" href="/search/%E6%9C%8D%E5%8A%A1%E5%99%A8/1.htm">服务器</a><a class="tag" taget="_blank" href="/search/%E5%BC%80%E5%8F%91%E8%AF%AD%E8%A8%80/1.htm">开发语言</a>
                        <div>文章目录python中os.environos.environ简介os.environ进行环境变量的增删改查python中os.environ的使用详解1.简介2.key字段详解2.1常见key字段3.os.environ.get()用法4.环境变量的增删改查和判断是否存在4.1新增环境变量4.2更新环境变量4.3获取环境变量4.4删除环境变量4.5判断环境变量是否存在python中os.envi</div>
                    </li>
                    <li><a href="/article/1835505226933694464.htm"
                           title="Pyecharts数据可视化大屏:打造沉浸式数据分析体验" target="_blank">Pyecharts数据可视化大屏:打造沉浸式数据分析体验</a>
                        <span class="text-muted">我的运维人生</span>
<a class="tag" taget="_blank" href="/search/%E4%BF%A1%E6%81%AF%E5%8F%AF%E8%A7%86%E5%8C%96/1.htm">信息可视化</a><a class="tag" taget="_blank" href="/search/%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90/1.htm">数据分析</a><a class="tag" taget="_blank" href="/search/%E6%95%B0%E6%8D%AE%E6%8C%96%E6%8E%98/1.htm">数据挖掘</a><a class="tag" taget="_blank" href="/search/%E8%BF%90%E7%BB%B4%E5%BC%80%E5%8F%91/1.htm">运维开发</a><a class="tag" taget="_blank" href="/search/%E6%8A%80%E6%9C%AF%E5%85%B1%E4%BA%AB/1.htm">技术共享</a>
                        <div>Pyecharts数据可视化大屏:打造沉浸式数据分析体验在当今这个数据驱动的时代,如何将海量数据以直观、生动的方式展现出来,成为了数据分析师和企业决策者关注的焦点。Pyecharts,作为一款基于Python的开源数据可视化库,凭借其丰富的图表类型、灵活的配置选项以及高度的定制化能力,成为了构建数据可视化大屏的理想选择。本文将深入探讨如何利用Pyecharts打造数据可视化大屏,并通过实际代码案例</div>
                    </li>
                    <li><a href="/article/1835504217729626112.htm"
                           title="Python教程:一文了解使用Python处理XPath" target="_blank">Python教程:一文了解使用Python处理XPath</a>
                        <span class="text-muted">旦莫</span>
<a class="tag" taget="_blank" href="/search/Python%E8%BF%9B%E9%98%B6/1.htm">Python进阶</a><a class="tag" taget="_blank" href="/search/python/1.htm">python</a><a class="tag" taget="_blank" href="/search/%E5%BC%80%E5%8F%91%E8%AF%AD%E8%A8%80/1.htm">开发语言</a>
                        <div>目录1.环境准备1.1安装lxml1.2验证安装2.XPath基础2.1什么是XPath?2.2XPath语法2.3示例XML文档3.使用lxml解析XML3.1解析XML文档3.2查看解析结果4.XPath查询4.1基本路径查询4.2使用属性查询4.3查询多个节点5.XPath的高级用法5.1使用逻辑运算符5.2使用函数6.实战案例6.1从网页抓取数据6.1.1安装Requests库6.1.2代</div>
                    </li>
                    <li><a href="/article/1835503965563875328.htm"
                           title="python os.environ_python os.environ 读取和设置环境变量" target="_blank">python os.environ_python os.environ 读取和设置环境变量</a>
                        <span class="text-muted">weixin_39605414</span>
<a class="tag" taget="_blank" href="/search/python/1.htm">python</a><a class="tag" taget="_blank" href="/search/os.environ/1.htm">os.environ</a>
                        <div>>>>importos>>>os.environ.keys()['LC_NUMERIC','GOPATH','GOROOT','GOBIN','LESSOPEN','SSH_CLIENT','LOGNAME','USER','HOME','LC_PAPER','PATH','DISPLAY','LANG','TERM','SHELL','J2REDIR','LC_MONETARY','QT_QPA</div>
                    </li>
                    <li><a href="/article/1835502704827396096.htm"
                           title="将cmd中命令输出保存为txt文本文件" target="_blank">将cmd中命令输出保存为txt文本文件</a>
                        <span class="text-muted">落难Coder</span>
<a class="tag" taget="_blank" href="/search/Windows/1.htm">Windows</a><a class="tag" taget="_blank" href="/search/cmd/1.htm">cmd</a><a class="tag" taget="_blank" href="/search/window/1.htm">window</a>
                        <div>最近深度学习本地的训练中我们常常要在命令行中运行自己的代码,无可厚非,我们有必要保存我们的炼丹结果,但是复制命令行输出到txt是非常麻烦的,其实Windows下的命令行为我们提供了相应的操作。其基本的调用格式就是:运行指令>输出到的文件名称或者具体保存路径测试下,我打开cmd并且ping一下百度:pingwww.baidu.com>./data.txt看下相同目录下data.txt的输出:如果你再</div>
                    </li>
                    <li><a href="/article/1835497664922349568.htm"
                           title="使用Faiss进行高效相似度搜索" target="_blank">使用Faiss进行高效相似度搜索</a>
                        <span class="text-muted">llzwxh888</span>
<a class="tag" taget="_blank" href="/search/faiss/1.htm">faiss</a><a class="tag" taget="_blank" href="/search/python/1.htm">python</a>
                        <div>在现代AI应用中,快速和高效的相似度搜索是至关重要的。Faiss(FacebookAISimilaritySearch)是一个专门用于快速相似度搜索和聚类的库,特别适用于高维向量。本文将介绍如何使用Faiss来进行相似度搜索,并结合Python代码演示其基本用法。什么是Faiss?Faiss是一个由FacebookAIResearch团队开发的开源库,主要用于高维向量的相似性搜索和聚类。Faiss</div>
                    </li>
                    <li><a href="/article/1835497665853485056.htm"
                           title="python是什么意思中文-在python中%是什么意思" target="_blank">python是什么意思中文-在python中%是什么意思</a>
                        <span class="text-muted">编程大乐趣</span>

                        <div>Python中%有两种:1、数值运算:%代表取模,返回除法的余数。如:>>>7%212、%操作符(字符串格式化,stringformatting),说明如下:%[(name)][flags][width].[precision]typecode(name)为命名flags可以有+,-,''或0。+表示右对齐。-表示左对齐。''为一个空格,表示在正数的左侧填充一个空格,从而与负数对齐。0表示使用0填</div>
                    </li>
                    <li><a href="/article/1835495644123459584.htm"
                           title="Day1笔记-Python简介&标识符和关键字&输入输出" target="_blank">Day1笔记-Python简介&标识符和关键字&输入输出</a>
                        <span class="text-muted">~在杰难逃~</span>
<a class="tag" taget="_blank" href="/search/Python/1.htm">Python</a><a class="tag" taget="_blank" href="/search/python/1.htm">python</a><a class="tag" taget="_blank" href="/search/%E5%BC%80%E5%8F%91%E8%AF%AD%E8%A8%80/1.htm">开发语言</a><a class="tag" taget="_blank" href="/search/%E5%A4%A7%E6%95%B0%E6%8D%AE/1.htm">大数据</a><a class="tag" taget="_blank" href="/search/%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90/1.htm">数据分析</a><a class="tag" taget="_blank" href="/search/%E6%95%B0%E6%8D%AE%E6%8C%96%E6%8E%98/1.htm">数据挖掘</a>
                        <div>大家好,从今天开始呢,杰哥开展一个新的专栏,当然,数据分析部分也会不定时更新的,这个新的专栏主要是讲解一些Python的基础语法和知识,帮助0基础的小伙伴入门和学习Python,感兴趣的小伙伴可以开始认真学习啦!一、Python简介【了解】1.计算机工作原理编程语言就是用来定义计算机程序的形式语言。我们通过编程语言来编写程序代码,再通过语言处理程序执行向计算机发送指令,让计算机完成对应的工作,编程</div>
                    </li>
                    <li><a href="/article/1835495517774245888.htm"
                           title="python八股文面试题分享及解析(1)" target="_blank">python八股文面试题分享及解析(1)</a>
                        <span class="text-muted">Shawn________</span>
<a class="tag" taget="_blank" href="/search/python/1.htm">python</a>
                        <div>#1.'''a=1b=2不用中间变量交换a和b'''#1.a=1b=2a,b=b,aprint(a)print(b)结果:21#2.ll=[]foriinrange(3):ll.append({'num':i})print(11)结果:#[{'num':0},{'num':1},{'num':2}]#3.kk=[]a={'num':0}foriinrange(3):#0,12#可变类型,不仅仅改变</div>
                    </li>
                    <li><a href="/article/1835493753557708800.htm"
                           title="每日算法&面试题,大厂特训二十八天——第二十天(树)" target="_blank">每日算法&面试题,大厂特训二十八天——第二十天(树)</a>
                        <span class="text-muted">肥学</span>
<a class="tag" taget="_blank" href="/search/%E2%9A%A1%E7%AE%97%E6%B3%95%E9%A2%98%E2%9A%A1%E9%9D%A2%E8%AF%95%E9%A2%98%E6%AF%8F%E6%97%A5%E7%B2%BE%E8%BF%9B/1.htm">⚡算法题⚡面试题每日精进</a><a class="tag" taget="_blank" href="/search/java/1.htm">java</a><a class="tag" taget="_blank" href="/search/%E7%AE%97%E6%B3%95/1.htm">算法</a><a class="tag" taget="_blank" href="/search/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/1.htm">数据结构</a>
                        <div>目录标题导读算法特训二十八天面试题点击直接资料领取导读肥友们为了更好的去帮助新同学适应算法和面试题,最近我们开始进行专项突击一步一步来。上一期我们完成了动态规划二十一天现在我们进行下一项对各类算法进行二十八天的一个小总结。还在等什么快来一起肥学进行二十八天挑战吧!!特别介绍小白练手专栏,适合刚入手的新人欢迎订阅编程小白进阶python有趣练手项目里面包括了像《机器人尬聊》《恶搞程序》这样的有趣文章</div>
                    </li>
                    <li><a href="/article/1835493626688401408.htm"
                           title="Python快速入门 —— 第三节:类与对象" target="_blank">Python快速入门 —— 第三节:类与对象</a>
                        <span class="text-muted">孤华暗香</span>
<a class="tag" taget="_blank" href="/search/Python%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8/1.htm">Python快速入门</a><a class="tag" taget="_blank" href="/search/python/1.htm">python</a><a class="tag" taget="_blank" href="/search/%E5%BC%80%E5%8F%91%E8%AF%AD%E8%A8%80/1.htm">开发语言</a>
                        <div>第三节:类与对象目标:了解面向对象编程的基础概念,并学会如何定义类和创建对象。内容:类与对象:定义类:class关键字。类的构造函数:__init__()。类的属性和方法。对象的创建与使用。示例:classStudent:def__init__(self,name,age,major):self.name&#</div>
                    </li>
                    <li><a href="/article/1835492869062881280.htm"
                           title="pyecharts——绘制柱形图折线图" target="_blank">pyecharts——绘制柱形图折线图</a>
                        <span class="text-muted">2224070247</span>
<a class="tag" taget="_blank" href="/search/%E4%BF%A1%E6%81%AF%E5%8F%AF%E8%A7%86%E5%8C%96/1.htm">信息可视化</a><a class="tag" taget="_blank" href="/search/python/1.htm">python</a><a class="tag" taget="_blank" href="/search/java/1.htm">java</a><a class="tag" taget="_blank" href="/search/%E6%95%B0%E6%8D%AE%E5%8F%AF%E8%A7%86%E5%8C%96/1.htm">数据可视化</a>
                        <div>一、pyecharts概述自2013年6月百度EFE(ExcellentFrontEnd)数据可视化团队研发的ECharts1.0发布到GitHub网站以来,ECharts一直备受业界权威的关注并获得广泛好评,成为目前成熟且流行的数据可视化图表工具,被应用到诸多数据可视化的开发领域。Python作为数据分析领域最受欢迎的语言,也加入ECharts的使用行列,并研发出方便Python开发者使用的数据</div>
                    </li>
                    <li><a href="/article/1835491859351302144.htm"
                           title="Python 实现图片裁剪(附代码) | Python工具" target="_blank">Python 实现图片裁剪(附代码) | Python工具</a>
                        <span class="text-muted">剑客阿良_ALiang</span>

                        <div>前言本文提供将图片按照自定义尺寸进行裁剪的工具方法,一如既往的实用主义。环境依赖ffmpeg环境安装,可以参考我的另一篇文章:windowsffmpeg安装部署_阿良的博客-CSDN博客本文主要使用到的不是ffmpeg,而是ffprobe也在上面这篇文章中的zip包中。ffmpy安装:pipinstallffmpy-ihttps://pypi.douban.com/simple代码不废话了,上代码</div>
                    </li>
                    <li><a href="/article/1835491353451130880.htm"
                           title="【华为OD技术面试真题 - 技术面】- python八股文真题题库(4)" target="_blank">【华为OD技术面试真题 - 技术面】- python八股文真题题库(4)</a>
                        <span class="text-muted">算法大师</span>
<a class="tag" taget="_blank" href="/search/%E5%8D%8E%E4%B8%BAod/1.htm">华为od</a><a class="tag" taget="_blank" href="/search/%E9%9D%A2%E8%AF%95/1.htm">面试</a><a class="tag" taget="_blank" href="/search/python/1.htm">python</a>
                        <div>华为OD面试真题精选专栏:华为OD面试真题精选目录:2024华为OD面试手撕代码真题目录以及八股文真题目录文章目录华为OD面试真题精选**1.Python中的`with`**用途和功能自动资源管理示例:文件操作上下文管理协议示例代码工作流程解析优点2.\_\_new\_\_和**\_\_init\_\_**区别__new____init__区别总结3.**切片(Slicing)操作**基本切片语法</div>
                    </li>
                    <li><a href="/article/1835490974911000576.htm"
                           title="python os 环境变量" target="_blank">python os 环境变量</a>
                        <span class="text-muted">CV矿工</span>
<a class="tag" taget="_blank" href="/search/python/1.htm">python</a><a class="tag" taget="_blank" href="/search/%E5%BC%80%E5%8F%91%E8%AF%AD%E8%A8%80/1.htm">开发语言</a><a class="tag" taget="_blank" href="/search/numpy/1.htm">numpy</a>
                        <div>环境变量:环境变量是程序和操作系统之间的通信方式。有些字符不宜明文写进代码里,比如数据库密码,个人账户密码,如果写进自己本机的环境变量里,程序用的时候通过os.environ.get()取出来就行了。os.environ是一个环境变量的字典。环境变量的相关操作importos"""设置/修改环境变量:os.environ[‘环境变量名称’]=‘环境变量值’#其中key和value均为string类</div>
                    </li>
                    <li><a href="/article/1835490218845761536.htm"
                           title="Python爬虫解析工具之xpath使用详解" target="_blank">Python爬虫解析工具之xpath使用详解</a>
                        <span class="text-muted">eqa11</span>
<a class="tag" taget="_blank" href="/search/python/1.htm">python</a><a class="tag" taget="_blank" href="/search/%E7%88%AC%E8%99%AB/1.htm">爬虫</a><a class="tag" taget="_blank" href="/search/%E5%BC%80%E5%8F%91%E8%AF%AD%E8%A8%80/1.htm">开发语言</a>
                        <div>文章目录Python爬虫解析工具之xpath使用详解一、引言二、环境准备1、插件安装2、依赖库安装三、xpath语法详解1、路径表达式2、通配符3、谓语4、常用函数四、xpath在Python代码中的使用1、文档树的创建2、使用xpath表达式3、获取元素内容和属性五、总结Python爬虫解析工具之xpath使用详解一、引言在Python爬虫开发中,数据提取是一个至关重要的环节。xpath作为一门</div>
                    </li>
                    <li><a href="/article/1835483915071090688.htm"
                           title="【华为OD技术面试真题 - 技术面】- python八股文真题题库(1)" target="_blank">【华为OD技术面试真题 - 技术面】- python八股文真题题库(1)</a>
                        <span class="text-muted">算法大师</span>
<a class="tag" taget="_blank" href="/search/%E5%8D%8E%E4%B8%BAod/1.htm">华为od</a><a class="tag" taget="_blank" href="/search/%E9%9D%A2%E8%AF%95/1.htm">面试</a><a class="tag" taget="_blank" href="/search/python/1.htm">python</a>
                        <div>华为OD面试真题精选专栏:华为OD面试真题精选目录:2024华为OD面试手撕代码真题目录以及八股文真题目录文章目录华为OD面试真题精选1.数据预处理流程数据预处理的主要步骤工具和库2.介绍线性回归、逻辑回归模型线性回归(LinearRegression)模型形式:关键点:逻辑回归(LogisticRegression)模型形式:关键点:参数估计与评估:3.python浅拷贝及深拷贝浅拷贝(Shal</div>
                    </li>
                    <li><a href="/article/1835483159630802944.htm"
                           title="nosql数据库技术与应用知识点" target="_blank">nosql数据库技术与应用知识点</a>
                        <span class="text-muted">皆过客,揽星河</span>
<a class="tag" taget="_blank" href="/search/NoSQL/1.htm">NoSQL</a><a class="tag" taget="_blank" href="/search/nosql/1.htm">nosql</a><a class="tag" taget="_blank" href="/search/%E6%95%B0%E6%8D%AE%E5%BA%93/1.htm">数据库</a><a class="tag" taget="_blank" href="/search/%E5%A4%A7%E6%95%B0%E6%8D%AE/1.htm">大数据</a><a class="tag" taget="_blank" href="/search/%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90/1.htm">数据分析</a><a class="tag" taget="_blank" href="/search/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/1.htm">数据结构</a><a class="tag" taget="_blank" href="/search/%E9%9D%9E%E5%85%B3%E7%B3%BB%E5%9E%8B%E6%95%B0%E6%8D%AE%E5%BA%93/1.htm">非关系型数据库</a>
                        <div>Nosql知识回顾大数据处理流程数据采集(flume、爬虫、传感器)数据存储(本门课程NoSQL所处的阶段)Hdfs、MongoDB、HBase等数据清洗(入仓)Hive等数据处理、分析(Spark、Flink等)数据可视化数据挖掘、机器学习应用(Python、SparkMLlib等)大数据时代存储的挑战(三高)高并发(同一时间很多人访问)高扩展(要求随时根据需求扩展存储)高效率(要求读写速度快)</div>
                    </li>
                    <li><a href="/article/1835481269690003456.htm"
                           title="《Python数据分析实战终极指南》" target="_blank">《Python数据分析实战终极指南》</a>
                        <span class="text-muted">xjt921122</span>
<a class="tag" taget="_blank" href="/search/python/1.htm">python</a><a class="tag" taget="_blank" href="/search/%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90/1.htm">数据分析</a><a class="tag" taget="_blank" href="/search/%E5%BC%80%E5%8F%91%E8%AF%AD%E8%A8%80/1.htm">开发语言</a>
                        <div>对于分析师来说,大家在学习Python数据分析的路上,多多少少都遇到过很多大坑**,有关于技能和思维的**:Excel已经没办法处理现有的数据量了,应该学Python吗?找了一大堆Python和Pandas的资料来学习,为什么自己动手就懵了?跟着比赛类公开数据分析案例练了很久,为什么当自己面对数据需求还是只会数据处理而没有分析思路?学了对比、细分、聚类分析,也会用PEST、波特五力这类分析法,为啥</div>
                    </li>
                    <li><a href="/article/1835477362700021760.htm"
                           title="Python中深拷贝与浅拷贝的区别" target="_blank">Python中深拷贝与浅拷贝的区别</a>
                        <span class="text-muted">yuxiaoyu.</span>

                        <div>转自:http://blog.csdn.net/u014745194/article/details/70271868定义:在Python中对象的赋值其实就是对象的引用。当创建一个对象,把它赋值给另一个变量的时候,python并没有拷贝这个对象,只是拷贝了这个对象的引用而已。浅拷贝:拷贝了最外围的对象本身,内部的元素都只是拷贝了一个引用而已。也就是,把对象复制一遍,但是该对象中引用的其他对象我不复</div>
                    </li>
                    <li><a href="/article/1835476983614631936.htm"
                           title="Python开发常用的三方模块如下:" target="_blank">Python开发常用的三方模块如下:</a>
                        <span class="text-muted">换个网名有点难</span>
<a class="tag" taget="_blank" href="/search/python/1.htm">python</a><a class="tag" taget="_blank" href="/search/%E5%BC%80%E5%8F%91%E8%AF%AD%E8%A8%80/1.htm">开发语言</a>
                        <div>Python是一门功能强大的编程语言,拥有丰富的第三方库,这些库为开发者提供了极大的便利。以下是100个常用的Python库,涵盖了多个领域:1、NumPy,用于科学计算的基础库。2、Pandas,提供数据结构和数据分析工具。3、Matplotlib,一个绘图库。4、Scikit-learn,机器学习库。5、SciPy,用于数学、科学和工程的库。6、TensorFlow,由Google开发的开源机</div>
                    </li>
                    <li><a href="/article/1835473704432267264.htm"
                           title="Python编译器" target="_blank">Python编译器</a>
                        <span class="text-muted">鹿鹿~</span>
<a class="tag" taget="_blank" href="/search/Python%E7%BC%96%E8%AF%91%E5%99%A8/1.htm">Python编译器</a><a class="tag" taget="_blank" href="/search/Python/1.htm">Python</a><a class="tag" taget="_blank" href="/search/python/1.htm">python</a><a class="tag" taget="_blank" href="/search/%E5%BC%80%E5%8F%91%E8%AF%AD%E8%A8%80/1.htm">开发语言</a><a class="tag" taget="_blank" href="/search/%E5%90%8E%E7%AB%AF/1.htm">后端</a>
                        <div>嘿嘿嘿我又来了啊有些小盆友可能不知道Python其实是有编译器的,也就是PyCharm。你们可能会问到这个是干嘛的又不可以吃也不可以穿好像没有什么用,其实你还说对了这个还真的不可以吃也不可以穿,但是它用来干嘛的呢。用来编译你所打出的代码进行运行(可能这里说的有点不对但是只是个人认为)现在我们来说说PyCharm是用来干嘛的。PyCharm是一种PythonIDE,带有一整套可以帮助用户在使用Pyt</div>
                    </li>
                    <li><a href="/article/1835471437754888192.htm"
                           title="一文掌握python面向对象魔术方法(二)" target="_blank">一文掌握python面向对象魔术方法(二)</a>
                        <span class="text-muted">程序员neil</span>
<a class="tag" taget="_blank" href="/search/python/1.htm">python</a><a class="tag" taget="_blank" href="/search/python/1.htm">python</a><a class="tag" taget="_blank" href="/search/%E5%BC%80%E5%8F%91%E8%AF%AD%E8%A8%80/1.htm">开发语言</a>
                        <div>接上篇:一文掌握python面向对象魔术方法(一)-CSDN博客目录六、迭代和序列化:1、__iter__(self):定义迭代器,使得类可以被for循环迭代。2、__getitem__(self,key):定义索引操作,如obj[key]。3、__setitem__(self,key,value):定义赋值操作,如obj[key]=value。4、__delitem__(self,key):定义</div>
                    </li>
                    <li><a href="/article/1835471185589137408.htm"
                           title="一文掌握python常用的list(列表)操作" target="_blank">一文掌握python常用的list(列表)操作</a>
                        <span class="text-muted">程序员neil</span>
<a class="tag" taget="_blank" href="/search/python/1.htm">python</a><a class="tag" taget="_blank" href="/search/python/1.htm">python</a><a class="tag" taget="_blank" href="/search/%E5%BC%80%E5%8F%91%E8%AF%AD%E8%A8%80/1.htm">开发语言</a>
                        <div>目录一、创建列表1.直接创建列表:2.使用list()构造器3.使用列表推导式4.创建空列表二、访问列表元素1.列表支持通过索引访问元素,索引从0开始:2.还可以使用切片操作访问列表的一部分:三、修改列表元素四、添加元素1.append():在末尾添加元素2.insert():在指定位置插入元素五、删除元素1.del:删除指定位置的元素2.remove():删除指定值的第一个匹配项3.pop():</div>
                    </li>
                    <li><a href="/article/1835469798838988800.htm"
                           title="Python实现简单的机器学习算法" target="_blank">Python实现简单的机器学习算法</a>
                        <span class="text-muted">master_chenchengg</span>
<a class="tag" taget="_blank" href="/search/python/1.htm">python</a><a class="tag" taget="_blank" href="/search/python/1.htm">python</a><a class="tag" taget="_blank" href="/search/%E5%8A%9E%E5%85%AC%E6%95%88%E7%8E%87/1.htm">办公效率</a><a class="tag" taget="_blank" href="/search/python%E5%BC%80%E5%8F%91/1.htm">python开发</a><a class="tag" taget="_blank" href="/search/IT/1.htm">IT</a>
                        <div>Python实现简单的机器学习算法开篇:初探机器学习的奇妙之旅搭建环境:一切从安装开始必备工具箱第一步:安装Anaconda和JupyterNotebook小贴士:如何配置Python环境变量算法初体验:从零开始的Python机器学习线性回归:让数据说话数据准备:从哪里找数据编码实战:Python实现线性回归模型评估:如何判断模型好坏逻辑回归:从分类开始理论入门:什么是逻辑回归代码实现:使用skl</div>
                    </li>
                    <li><a href="/article/1835465134710026240.htm"
                           title="python中的深拷贝与浅拷贝" target="_blank">python中的深拷贝与浅拷贝</a>
                        <span class="text-muted">anshejd70787</span>
<a class="tag" taget="_blank" href="/search/python/1.htm">python</a>
                        <div>深拷贝和浅拷贝浅拷贝的时候,修改原来的对象,浅拷贝的对象不会发生改变。1、对象的赋值对象的赋值实际上是对象之间的引用:当创建一个对象,然后将这个对象赋值给另外一个变量的时候,python并没有拷贝这个对象,而只是拷贝了这个对象的引用。当对对象做赋值或者是参数传递或者作为返回值的时候,总是传递原始对象的引用,而不是一个副本。如下所示:>>>aList=["kel","abc",123]>>>bLis</div>
                    </li>
                                <li><a href="/article/54.htm"
                                       title="JAVA中的Enum" target="_blank">JAVA中的Enum</a>
                                    <span class="text-muted">周凡杨</span>
<a class="tag" taget="_blank" href="/search/java/1.htm">java</a><a class="tag" taget="_blank" href="/search/enum/1.htm">enum</a><a class="tag" taget="_blank" href="/search/%E6%9E%9A%E4%B8%BE/1.htm">枚举</a>
                                    <div>Enum是计算机编程语言中的一种数据类型---枚举类型。 在实际问题中,有些变量的取值被限定在一个有限的范围内。       例如,一个星期内只有七天 我们通常这样实现上面的定义: 
public String monday;
public String tuesday;
public String wensday;
public String thursday</div>
                                </li>
                                <li><a href="/article/181.htm"
                                       title="赶集网mysql开发36条军规" target="_blank">赶集网mysql开发36条军规</a>
                                    <span class="text-muted">Bill_chen</span>
<a class="tag" taget="_blank" href="/search/mysql/1.htm">mysql</a><a class="tag" taget="_blank" href="/search/%E4%B8%9A%E5%8A%A1%E6%9E%B6%E6%9E%84%E8%AE%BE%E8%AE%A1/1.htm">业务架构设计</a><a class="tag" taget="_blank" href="/search/mysql%E8%B0%83%E4%BC%98/1.htm">mysql调优</a><a class="tag" taget="_blank" href="/search/mysql%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/1.htm">mysql性能优化</a>
                                    <div>(一)核心军规   (1)不在数据库做运算      cpu计算务必移至业务层;   (2)控制单表数据量      int型不超过1000w,含char则不超过500w;      合理分表;      限制单库表数量在300以内;   (3)控制列数量      字段少而精,字段数建议在20以内</div>
                                </li>
                                <li><a href="/article/308.htm"
                                       title="Shell test命令" target="_blank">Shell test命令</a>
                                    <span class="text-muted">daizj</span>
<a class="tag" taget="_blank" href="/search/shell/1.htm">shell</a><a class="tag" taget="_blank" href="/search/%E5%AD%97%E7%AC%A6%E4%B8%B2/1.htm">字符串</a><a class="tag" taget="_blank" href="/search/test/1.htm">test</a><a class="tag" taget="_blank" href="/search/%E6%95%B0%E5%AD%97/1.htm">数字</a><a class="tag" taget="_blank" href="/search/%E6%96%87%E4%BB%B6%E6%AF%94%E8%BE%83/1.htm">文件比较</a>
                                    <div>Shell test命令 
Shell中的 test 命令用于检查某个条件是否成立,它可以进行数值、字符和文件三个方面的测试。  数值测试    参数 说明   -eq 等于则为真   -ne 不等于则为真   -gt 大于则为真   -ge 大于等于则为真   -lt 小于则为真   -le 小于等于则为真    
实例演示: 
num1=100
num2=100if test $[num1]</div>
                                </li>
                                <li><a href="/article/435.htm"
                                       title="XFire框架实现WebService(二)" target="_blank">XFire框架实现WebService(二)</a>
                                    <span class="text-muted">周凡杨</span>
<a class="tag" taget="_blank" href="/search/java/1.htm">java</a><a class="tag" taget="_blank" href="/search/webservice/1.htm">webservice</a>
                                    <div>   有了XFire框架实现WebService(一),就可以继续开发WebService的简单应用。 
Webservice的服务端(WEB工程): 
两个java bean类: 
Course.java 
   package cn.com.bean; 
public class Course { 
    private </div>
                                </li>
                                <li><a href="/article/562.htm"
                                       title="重绘之画图板" target="_blank">重绘之画图板</a>
                                    <span class="text-muted">朱辉辉33</span>
<a class="tag" taget="_blank" href="/search/%E7%94%BB%E5%9B%BE%E6%9D%BF/1.htm">画图板</a>
                                    <div>       上次博客讲的五子棋重绘比较简单,因为只要在重写系统重绘方法paint()时加入棋盘和棋子的绘制。这次我想说说画图板的重绘。 
       画图板重绘难在需要重绘的类型很多,比如说里面有矩形,园,直线之类的,所以我们要想办法将里面的图形加入一个队列中,这样在重绘时就</div>
                                </li>
                                <li><a href="/article/689.htm"
                                       title="Java的IO流" target="_blank">Java的IO流</a>
                                    <span class="text-muted">西蜀石兰</span>
<a class="tag" taget="_blank" href="/search/java/1.htm">java</a>
                                    <div>刚学Java的IO流时,被各种inputStream流弄的很迷糊,看老罗视频时说想象成插在文件上的一根管道,当初听时觉得自己很明白,可到自己用时,有不知道怎么代码了。。。 
每当遇到这种问题时,我习惯性的从头开始理逻辑,会问自己一些很简单的问题,把这些简单的问题想明白了,再看代码时才不会迷糊。 
 
IO流作用是什么? 
答:实现对文件的读写,这里的文件是广义的; 
 
Java如何实现程序到文件</div>
                                </li>
                                <li><a href="/article/816.htm"
                                       title="No matching PlatformTransactionManager bean found for qualifier 'add' - neither" target="_blank">No matching PlatformTransactionManager bean found for qualifier 'add' - neither</a>
                                    <span class="text-muted">林鹤霄</span>

                                    <div>java.lang.IllegalStateException: No matching PlatformTransactionManager bean found for qualifier 'add' - neither qualifier match nor bean name match! 
  
网上找了好多的资料没能解决,后来发现:项目中使用的是xml配置的方式配置事务,但是</div>
                                </li>
                                <li><a href="/article/943.htm"
                                       title="Row size too large (> 8126). Changing some columns to TEXT or BLOB" target="_blank">Row size too large (> 8126). Changing some columns to TEXT or BLOB</a>
                                    <span class="text-muted">aigo</span>
<a class="tag" taget="_blank" href="/search/column/1.htm">column</a>
                                    <div>原文:http://stackoverflow.com/questions/15585602/change-limit-for-mysql-row-size-too-large 
  
异常信息: 
Row size too large (> 8126). Changing some columns to TEXT or BLOB or using ROW_FORMAT=DYNAM</div>
                                </li>
                                <li><a href="/article/1070.htm"
                                       title="JS 格式化时间" target="_blank">JS 格式化时间</a>
                                    <span class="text-muted">alxw4616</span>
<a class="tag" taget="_blank" href="/search/JavaScript/1.htm">JavaScript</a>
                                    <div>/**
 * 格式化时间 2013/6/13 by 半仙 alxw4616@msn.com
 * 需要 pad 函数
 * 接收可用的时间值.
 * 返回替换时间占位符后的字符串
 *
 * 时间占位符:年 Y 月 M 日 D 小时 h 分 m 秒 s 重复次数表示占位数
 * 如 YYYY 4占4位 YY 占2位<p></p>
 * MM DD hh mm</div>
                                </li>
                                <li><a href="/article/1197.htm"
                                       title="队列中数据的移除问题" target="_blank">队列中数据的移除问题</a>
                                    <span class="text-muted">百合不是茶</span>
<a class="tag" taget="_blank" href="/search/%E9%98%9F%E5%88%97%E7%A7%BB%E9%99%A4/1.htm">队列移除</a>
                                    <div>  
   队列的移除一般都是使用的remov();都可以移除的,但是在昨天做线程移除的时候出现了点问题,没有将遍历出来的全部移除,  代码如下; 
  
   // 
package com.Thread0715.com;

import java.util.ArrayList;

public class Threa</div>
                                </li>
                                <li><a href="/article/1324.htm"
                                       title="Runnable接口使用实例" target="_blank">Runnable接口使用实例</a>
                                    <span class="text-muted">bijian1013</span>
<a class="tag" taget="_blank" href="/search/java/1.htm">java</a><a class="tag" taget="_blank" href="/search/thread/1.htm">thread</a><a class="tag" taget="_blank" href="/search/Runnable/1.htm">Runnable</a><a class="tag" taget="_blank" href="/search/java%E5%A4%9A%E7%BA%BF%E7%A8%8B/1.htm">java多线程</a>
                                    <div>Runnable接口 
a.       该接口只有一个方法:public void run(); 
b.       实现该接口的类必须覆盖该run方法 
c.       实现了Runnable接口的类并不具有任何天</div>
                                </li>
                                <li><a href="/article/1451.htm"
                                       title="oracle里的extend详解" target="_blank">oracle里的extend详解</a>
                                    <span class="text-muted">bijian1013</span>
<a class="tag" taget="_blank" href="/search/oracle/1.htm">oracle</a><a class="tag" taget="_blank" href="/search/%E6%95%B0%E6%8D%AE%E5%BA%93/1.htm">数据库</a><a class="tag" taget="_blank" href="/search/extend/1.htm">extend</a>
                                    <div>扩展已知的数组空间,例: 
DECLARE
  TYPE CourseList IS TABLE OF VARCHAR2(10);
  courses CourseList;
BEGIN
  --   初始化数组元素,大小为3
  courses := CourseList('Biol   4412 ', 'Psyc   3112 ', 'Anth   3001 ');
  --   </div>
                                </li>
                                <li><a href="/article/1578.htm"
                                       title="【httpclient】httpclient发送表单POST请求" target="_blank">【httpclient】httpclient发送表单POST请求</a>
                                    <span class="text-muted">bit1129</span>
<a class="tag" taget="_blank" href="/search/httpclient/1.htm">httpclient</a>
                                    <div>浏览器Form Post请求 
浏览器可以通过提交表单的方式向服务器发起POST请求,这种形式的POST请求不同于一般的POST请求 
1. 一般的POST请求,将请求数据放置于请求体中,服务器端以二进制流的方式读取数据,HttpServletRequest.getInputStream()。这种方式的请求可以处理任意数据形式的POST请求,比如请求数据是字符串或者是二进制数据 
2. Form </div>
                                </li>
                                <li><a href="/article/1705.htm"
                                       title="【Hive十三】Hive读写Avro格式的数据" target="_blank">【Hive十三】Hive读写Avro格式的数据</a>
                                    <span class="text-muted">bit1129</span>
<a class="tag" taget="_blank" href="/search/hive/1.htm">hive</a>
                                    <div> 1. 原始数据 
hive> select * from word; 
OK
1	MSN  
10	QQ  
100	Gtalk  
1000	Skype  
  
  
 2. 创建avro格式的数据表 
  
hive> CREATE TABLE avro_table(age INT, name STRING)STORE</div>
                                </li>
                                <li><a href="/article/1832.htm"
                                       title="nginx+lua+redis自动识别封解禁频繁访问IP" target="_blank">nginx+lua+redis自动识别封解禁频繁访问IP</a>
                                    <span class="text-muted">ronin47</span>

                                    <div>在站点遇到攻击且无明显攻击特征,造成站点访问慢,nginx不断返回502等错误时,可利用nginx+lua+redis实现在指定的时间段 内,若单IP的请求量达到指定的数量后对该IP进行封禁,nginx返回403禁止访问。利用redis的expire命令设置封禁IP的过期时间达到在 指定的封禁时间后实行自动解封的目的。 
一、安装环境: 
 
 CentOS x64 release 6.4(Fin</div>
                                </li>
                                <li><a href="/article/1959.htm"
                                       title="java-二叉树的遍历-先序、中序、后序(递归和非递归)、层次遍历" target="_blank">java-二叉树的遍历-先序、中序、后序(递归和非递归)、层次遍历</a>
                                    <span class="text-muted">bylijinnan</span>
<a class="tag" taget="_blank" href="/search/java/1.htm">java</a>
                                    <div>
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;


public class BinTreeTraverse {
	//private int[] array={ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	private int[] array={ 10,6,</div>
                                </li>
                                <li><a href="/article/2086.htm"
                                       title="Spring源码学习-XML 配置方式的IoC容器启动过程分析" target="_blank">Spring源码学习-XML 配置方式的IoC容器启动过程分析</a>
                                    <span class="text-muted">bylijinnan</span>
<a class="tag" taget="_blank" href="/search/java/1.htm">java</a><a class="tag" taget="_blank" href="/search/spring/1.htm">spring</a><a class="tag" taget="_blank" href="/search/IOC/1.htm">IOC</a>
                                    <div>以FileSystemXmlApplicationContext为例,把Spring IoC容器的初始化流程走一遍: 
 

ApplicationContext context = new FileSystemXmlApplicationContext
            ("C:/Users/ZARA/workspace/HelloSpring/src/Beans.xml&q</div>
                                </li>
                                <li><a href="/article/2213.htm"
                                       title="[科研与项目]民营企业请慎重参与军事科技工程" target="_blank">[科研与项目]民营企业请慎重参与军事科技工程</a>
                                    <span class="text-muted">comsci</span>
<a class="tag" taget="_blank" href="/search/%E4%BC%81%E4%B8%9A/1.htm">企业</a>
                                    <div> 
 
     军事科研工程和项目 并非要用最先进,最时髦的技术,而是要做到“万无一失” 
 
   而民营科技企业在搞科技创新工程的时候,往往考虑的是技术的先进性,而对先进技术带来的风险考虑得不够,在今天提倡军民融合发展的大环境下,这种“万无一失”和“时髦性”的矛盾会日益凸显。。。。。。所以请大家在参与任何重大的军事和政府项目之前,对</div>
                                </li>
                                <li><a href="/article/2340.htm"
                                       title="spring 定时器-两种方式" target="_blank">spring 定时器-两种方式</a>
                                    <span class="text-muted">cuityang</span>
<a class="tag" taget="_blank" href="/search/spring/1.htm">spring</a><a class="tag" taget="_blank" href="/search/quartz/1.htm">quartz</a><a class="tag" taget="_blank" href="/search/%E5%AE%9A%E6%97%B6%E5%99%A8/1.htm">定时器</a>
                                    <div>方式一: 
间隔一定时间 运行 
 
<bean id="updateSessionIdTask" class="com.yang.iprms.common.UpdateSessionTask" autowire="byName" /> 
 
 <bean id="updateSessionIdSchedule</div>
                                </li>
                                <li><a href="/article/2467.htm"
                                       title="简述一下关于BroadView站点的相关设计" target="_blank">简述一下关于BroadView站点的相关设计</a>
                                    <span class="text-muted">damoqiongqiu</span>
<a class="tag" taget="_blank" href="/search/view/1.htm">view</a>
                                    <div>终于弄上线了,累趴,戳这里http://www.broadview.com.cn 
  
简述一下相关的技术点 
  
前端:jQuery+BootStrap3.2+HandleBars,全站Ajax(貌似对SEO的影响很大啊!怎么破?),用Grunt对全部JS做了压缩处理,对部分JS和CSS做了合并(模块间存在很多依赖,全部合并比较繁琐,待完善)。 
  
后端:U</div>
                                </li>
                                <li><a href="/article/2594.htm"
                                       title="运维 PHP问题汇总" target="_blank">运维 PHP问题汇总</a>
                                    <span class="text-muted">dcj3sjt126com</span>
<a class="tag" taget="_blank" href="/search/windows2003/1.htm">windows2003</a>
                                    <div>1、Dede(织梦)发表文章时,内容自动添加关键字显示空白页 
解决方法: 
后台>系统>系统基本参数>核心设置>关键字替换(是/否),这里选择“是”。 
后台>系统>系统基本参数>其他选项>自动提取关键字,这里选择“是”。 
  
2、解决PHP168超级管理员上传图片提示你的空间不足 
网站是用PHP168做的,反映使用管理员在后台无法</div>
                                </li>
                                <li><a href="/article/2721.htm"
                                       title="mac 下 安装php扩展 - mcrypt" target="_blank">mac 下 安装php扩展 - mcrypt</a>
                                    <span class="text-muted">dcj3sjt126com</span>
<a class="tag" taget="_blank" href="/search/PHP/1.htm">PHP</a>
                                    <div>MCrypt是一个功能强大的加密算法扩展库,它包括有22种算法,phpMyAdmin依赖这个PHP扩展,具体如下: 
 
  
  下载并解压libmcrypt-2.5.8.tar.gz。 
  在终端执行如下命令:  tar zxvf libmcrypt-2.5.8.tar.gz cd libmcrypt-2.5.8/ ./configure --disable-posix-threads --</div>
                                </li>
                                <li><a href="/article/2848.htm"
                                       title="MongoDB更新文档 [四]" target="_blank">MongoDB更新文档 [四]</a>
                                    <span class="text-muted">eksliang</span>
<a class="tag" taget="_blank" href="/search/mongodb/1.htm">mongodb</a><a class="tag" taget="_blank" href="/search/Mongodb%E6%9B%B4%E6%96%B0%E6%96%87%E6%A1%A3/1.htm">Mongodb更新文档</a>
                                    <div>MongoDB更新文档 
转载请出自出处:http://eksliang.iteye.com/blog/2174104 
MongoDB对文档的CURD,前面的博客简单介绍了,但是对文档更新篇幅比较大,所以这里单独拿出来。 
语法结构如下: 
db.collection.update( criteria, objNew, upsert, multi) 
参数含义    参数   </div>
                                </li>
                                <li><a href="/article/2975.htm"
                                       title="Linux下的解压,移除,复制,查看tomcat命令" target="_blank">Linux下的解压,移除,复制,查看tomcat命令</a>
                                    <span class="text-muted">y806839048</span>
<a class="tag" taget="_blank" href="/search/tomcat/1.htm">tomcat</a>
                                    <div>重复myeclipse生成webservice有问题删除以前的,干净 
 
 1、先切换到:cd usr/local/tomcat5/logs 
 
2、tail -f catalina.out 
 
3、这样运行时就可以实时查看运行日志了 
 
 
 
 
Ctrl+c 是退出tail命令。 
 有问题不明的先注掉 
   cp /opt/tomcat-6.0.44/webapps/g</div>
                                </li>
                                <li><a href="/article/3102.htm"
                                       title="Spring之使用事务缘由(3-XML实现)" target="_blank">Spring之使用事务缘由(3-XML实现)</a>
                                    <span class="text-muted">ihuning</span>
<a class="tag" taget="_blank" href="/search/spring/1.htm">spring</a>
                                    <div>  
用事务通知声明式地管理事务 
  
事务管理是一种横切关注点。为了在 Spring 2.x 中启用声明式事务管理,可以通过 tx Schema 中定义的 <tx:advice> 元素声明事务通知,为此必须事先将这个 Schema 定义添加到 <beans> 根元素中去。声明了事务通知后,就需要将它与切入点关联起来。由于事务通知是在 <aop:</div>
                                </li>
                                <li><a href="/article/3229.htm"
                                       title="GCD使用经验与技巧浅谈" target="_blank">GCD使用经验与技巧浅谈</a>
                                    <span class="text-muted">啸笑天</span>
<a class="tag" taget="_blank" href="/search/GC/1.htm">GC</a>
                                    <div>前言 
GCD(Grand Central Dispatch)可以说是Mac、iOS开发中的一大“利器”,本文就总结一些有关使用GCD的经验与技巧。 
dispatch_once_t必须是全局或static变量 
这一条算是“老生常谈”了,但我认为还是有必要强调一次,毕竟非全局或非static的dispatch_once_t变量在使用时会导致非常不好排查的bug,正确的如下:        1  </div>
                                </li>
                                <li><a href="/article/3356.htm"
                                       title="linux(Ubuntu)下常用命令备忘录1" target="_blank">linux(Ubuntu)下常用命令备忘录1</a>
                                    <span class="text-muted">macroli</span>
<a class="tag" taget="_blank" href="/search/linux/1.htm">linux</a><a class="tag" taget="_blank" href="/search/%E5%B7%A5%E4%BD%9C/1.htm">工作</a><a class="tag" taget="_blank" href="/search/ubuntu/1.htm">ubuntu</a>
                                    <div>在使用下面的命令是可以通过--help来获取更多的信息1,查询当前目录文件列表:ls 
 
 ls命令默认状态下将按首字母升序列出你当前文件夹下面的所有内容,但这样直接运行所得到的信息也是比较少的,通常它可以结合以下这些参数运行以查询更多的信息:  
 ls / 显示/.下的所有文件和目录  
 ls -l 给出文件或者文件夹的详细信息 
 ls -a 显示所有文件,包括隐藏文</div>
                                </li>
                                <li><a href="/article/3483.htm"
                                       title="nodejs同步操作mysql" target="_blank">nodejs同步操作mysql</a>
                                    <span class="text-muted">qiaolevip</span>
<a class="tag" taget="_blank" href="/search/%E5%AD%A6%E4%B9%A0%E6%B0%B8%E6%97%A0%E6%AD%A2%E5%A2%83/1.htm">学习永无止境</a><a class="tag" taget="_blank" href="/search/%E6%AF%8F%E5%A4%A9%E8%BF%9B%E6%AD%A5%E4%B8%80%E7%82%B9%E7%82%B9/1.htm">每天进步一点点</a><a class="tag" taget="_blank" href="/search/mysql/1.htm">mysql</a><a class="tag" taget="_blank" href="/search/nodejs/1.htm">nodejs</a>
                                    <div>// db-util.js
var mysql = require('mysql');
var pool = mysql.createPool({
  connectionLimit : 10,
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'test',
  port: 3306
});

</div>
                                </li>
                                <li><a href="/article/3610.htm"
                                       title="一起学Hive系列文章" target="_blank">一起学Hive系列文章</a>
                                    <span class="text-muted">superlxw1234</span>
<a class="tag" taget="_blank" href="/search/hive/1.htm">hive</a><a class="tag" taget="_blank" href="/search/Hive%E5%85%A5%E9%97%A8/1.htm">Hive入门</a>
                                    <div>  
[一起学Hive]系列文章 目录贴,入门Hive,持续更新中。 
  
[一起学Hive]之一—Hive概述,Hive是什么 
[一起学Hive]之二—Hive函数大全-完整版 
[一起学Hive]之三—Hive中的数据库(Database)和表(Table) 
[一起学Hive]之四-Hive的安装配置 
[一起学Hive]之五-Hive的视图和分区 
[一起学Hive</div>
                                </li>
                                <li><a href="/article/3737.htm"
                                       title="Spring开发利器:Spring Tool Suite 3.7.0 发布" target="_blank">Spring开发利器:Spring Tool Suite 3.7.0 发布</a>
                                    <span class="text-muted">wiselyman</span>
<a class="tag" taget="_blank" href="/search/spring/1.htm">spring</a>
                                    <div>Spring Tool Suite(简称STS)是基于Eclipse,专门针对Spring开发者提供大量的便捷功能的优秀开发工具。 
  
在3.7.0版本主要做了如下的更新: 
  
 
 将eclipse版本更新至Eclipse Mars 4.5 GA 
 Spring Boot(JavaEE开发的颠覆者集大成者,推荐大家学习)的配置语言YAML编辑器的支持(包含自动提示,</div>
                                </li>
                </ul>
            </div>
        </div>
    </div>

<div>
    <div class="container">
        <div class="indexes">
            <strong>按字母分类:</strong>
            <a href="/tags/A/1.htm" target="_blank">A</a><a href="/tags/B/1.htm" target="_blank">B</a><a href="/tags/C/1.htm" target="_blank">C</a><a
                href="/tags/D/1.htm" target="_blank">D</a><a href="/tags/E/1.htm" target="_blank">E</a><a href="/tags/F/1.htm" target="_blank">F</a><a
                href="/tags/G/1.htm" target="_blank">G</a><a href="/tags/H/1.htm" target="_blank">H</a><a href="/tags/I/1.htm" target="_blank">I</a><a
                href="/tags/J/1.htm" target="_blank">J</a><a href="/tags/K/1.htm" target="_blank">K</a><a href="/tags/L/1.htm" target="_blank">L</a><a
                href="/tags/M/1.htm" target="_blank">M</a><a href="/tags/N/1.htm" target="_blank">N</a><a href="/tags/O/1.htm" target="_blank">O</a><a
                href="/tags/P/1.htm" target="_blank">P</a><a href="/tags/Q/1.htm" target="_blank">Q</a><a href="/tags/R/1.htm" target="_blank">R</a><a
                href="/tags/S/1.htm" target="_blank">S</a><a href="/tags/T/1.htm" target="_blank">T</a><a href="/tags/U/1.htm" target="_blank">U</a><a
                href="/tags/V/1.htm" target="_blank">V</a><a href="/tags/W/1.htm" target="_blank">W</a><a href="/tags/X/1.htm" target="_blank">X</a><a
                href="/tags/Y/1.htm" target="_blank">Y</a><a href="/tags/Z/1.htm" target="_blank">Z</a><a href="/tags/0/1.htm" target="_blank">其他</a>
        </div>
    </div>
</div>
<footer id="footer" class="mb30 mt30">
    <div class="container">
        <div class="footBglm">
            <a target="_blank" href="/">首页</a> -
            <a target="_blank" href="/custom/about.htm">关于我们</a> -
            <a target="_blank" href="/search/Java/1.htm">站内搜索</a> -
            <a target="_blank" href="/sitemap.txt">Sitemap</a> -
            <a target="_blank" href="/custom/delete.htm">侵权投诉</a>
        </div>
        <div class="copyright">版权所有 IT知识库 CopyRight © 2000-2050 E-COM-NET.COM , All Rights Reserved.
<!--            <a href="https://beian.miit.gov.cn/" rel="nofollow" target="_blank">京ICP备09083238号</a><br>-->
        </div>
    </div>
</footer>
<!-- 代码高亮 -->
<script type="text/javascript" src="/static/syntaxhighlighter/scripts/shCore.js"></script>
<script type="text/javascript" src="/static/syntaxhighlighter/scripts/shLegacy.js"></script>
<script type="text/javascript" src="/static/syntaxhighlighter/scripts/shAutoloader.js"></script>
<link type="text/css" rel="stylesheet" href="/static/syntaxhighlighter/styles/shCoreDefault.css"/>
<script type="text/javascript" src="/static/syntaxhighlighter/src/my_start_1.js"></script>





</body>

</html>