1. 程式人生 > 實用技巧 >深度學習與Pytorch入門實戰(十六)情感分類實戰(基於IMDB資料集)

深度學習與Pytorch入門實戰(十六)情感分類實戰(基於IMDB資料集)

筆記摘抄

提前安裝torchtext和scapy,執行下面語句(壓縮包地址連結:https://pan.baidu.com/s/1_syic9B-SXKQvkvHlEf78w 提取碼:ahh3):

pip install torchtext

pip install scapy

pip install 你的地址\en_core_web_md-2.2.5.tar.gz  
  • 在torchtext中使用spacy時,由於field的預設屬性是tokenizer_language='en'

  • 當使用 en_core_web_md 時要改 field.py檔案中 建立的field屬性為tokenizer_language='en_core_web_md'

    ,且data.Field()中的引數也要改為tokenizer_language='en_core_web_md'

1. 載入資料

import numpy as np
import torch
from torch import nn, optim
from torchtext import data, datasets

# 為CPU設定隨機種子
torch.manual_seed(123)

# 兩個Field物件定義欄位的處理方法(文字欄位、標籤欄位)
TEXT = data.Field(tokenize='spacy', tokenizer_language='en_core_web_md')
LABEL = data.LabelField(dtype=torch.float)

# IMDB共50000影評,包含正面和負面兩個類別。資料被前面的Field處理
train_data, test_data = datasets.IMDB.splits(TEXT, LABEL)

print('len of train data:', len(train_data))        # 25000
print('len of test data:', len(test_data))          # 25000

print(train_data.examples[15].text)                 # 文字:句子的單詞列表
print(train_data.examples[15].label)                # 標籤: 積極
len of train data: 25000
len of test data: 25000
['Like', 'one', 'of', 'the', 'previous', 'commenters', 'said', ',', 'this', 'had', 'the', 'foundations', 'of', 'a', 'great', 'movie', 'but', 'something', 'happened', 'on', 'the', 'way', 'to', 'delivery', '.', 'Such', 'a', 'waste', 'because', 'Collette', "'s", 'performance', 'was', 'eerie', 'and', 'Williams', 'was', 'believable', '.', 'I', 'just', 'kept', 'waiting', 'for', 'it', 'to', 'get', 'better', '.', 'I', 'do', "n't", 'think', 'it', 'was', 'bad', 'editing', 'or', 'needed', 'another', 'director', ',', 'it', 'could', 'have', 'just', 'been', 'the', 'film', '.', 'It', 'came', 'across', 'as', 'a', 'Canadian', 'movie', ',', 'something', 'like', 'the', 'first', 'few', 'seasons', 'of', 'X', '-', 'Files', '.', 'Not', 'cheap', ',', 'just', 'hokey', '.', 'Also', ',', 'it', 'needed', 'a', 'little', 'more', 'suspense', '.', 'Something', 'that', 'makes', 'you', 'jump', 'off', 'your', 'seat', '.', 'The', 'movie', 'reached', 'that', 'moment', 'then', 'faded', 'away', ';', 'kind', 'of', 'like', 'a', 'false', 'climax', '.', 'I', 'can', 'see', 'how', 'being', 'too', 'suspenseful', 'would', 'have', 'taken', 'away', 'from', 'the', '"', 'reality', '"', 'of', 'the', 'story', 'but', 'I', 'thought', 'that', 'part', 'was', 'reached', 'when', 'Gabriel', 'was', 'in', 'the', 'hospital', 'looking', 'for', 'the', 'boy', '.', 'This', 'movie', 'needs', 'to', 'have', 'a', 'Director', "'s", 'cut', 'that', 'tries', 'to', 'fix', 'these', 'problems', '.']
pos