👋
pytorchコードサンプル テンソル化編
インストール
pip install torch
他にもインストールするパッケージはあります
サンプル
文字単位でテンソル化
import torch
char_to_idx = {ch: i for i, ch in enumerate(sorted(set("hello")))}
text = "hello,keita"
indices = [char_to_idx[ch] for ch in text]
tensor = torch.tensor(indices, dtype=torch.long)
print(tensor)
単語単位(スペース区切り)でテンソル化
text = "hello keita keita hello"
words = text.split()
word_to_idx = {word: i for i, word in enumerate(set(words))}
indices = [word_to_idx[word] for word in words]
tensor = torch.tensor(indices, dtype=torch.long)
print(tensor)
janomeを使う
from janome.tokenizer import Tokenizer
tokenizer = Tokenizer()
text = "こんにちはkeitaです"
tokens = [token.surface for token in tokenizer.tokenize(text)]
word_to_idx = {word: i for i, word in enumerate(set(tokens))}
indices = [word_to_idx[word] for word in tokens]
tensor = torch.tensor(indices, dtype=torch.long)
print(tensor)
Discussion