質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

機械学習

機械学習は、データからパターンを自動的に発見し、そこから知能的な判断を下すためのコンピューターアルゴリズムを指します。人工知能における課題のひとつです。

Q&A

解決済

1回答

459閲覧

pythonでRuntimeErrorがでてしまいます

yep

総合スコア45

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

機械学習

機械学習は、データからパターンを自動的に発見し、そこから知能的な判断を下すためのコンピューターアルゴリズムを指します。人工知能における課題のひとつです。

0グッド

0クリップ

投稿2018/10/19 01:25

編集2018/10/19 06:47

以下のコードを動かそうと思っているのですが、
エラーが出力されてしまいます。
もしよろしければ、ご教授よろしくお願いいたします
何卒、よろしくお願いいたします。

python3 '/home/hoge/train.py'

Traceback (most recent call last):
File "/home/hoge/train.py", line 56, in <module>
model = RNN(n_vocab, embedding_dim, hidden_dim)
File "/home/hoge/train.py", line 24, in init
self.decoder = nn.Linear(hidden_dim, n_vocab)
File "/home/hoge/.local/lib/python3.6/site-packages/torch/nn/modules/linear.py", line 44, in init
self.reset_parameters()
File "/home/hoge/.local/lib/python3.6/site-packages/torch/nn/modules/linear.py", line 47, in reset_parameters
stdv = 1. / math.sqrt(self.weight.size(1))
RuntimeError: invalid argument 2: dimension 1 out of range of 0D tensor at /pytorch/torch/lib/TH/generic/THTensor.c:24

get_data.py

python

1import time 2from urllib import request 3from bs4 import BeautifulSoup 4import MeCab 5 6 7def get_data(url): 8 req = request.urlopen(url) 9 soup = BeautifulSoup(req.read(), 'html.parser') 10 11 # 俳句 12 poem_elem = soup.select('td[height=40] b')[0] 13 poem = poem_elem.text.replace('*', '').strip() # サニタイズ 14 if not poem: 15 return False # 存在しないID 16 return {'poem': poem} 17 18 19def write2file(i, morphemes): 20 with open('poem.txt', 'a', encoding="utf-8") as f: 21 f.write(morphemes + '\n') 22 23def get_morphemes(sentences): 24 temp = tagger.parse(sentences).split() 25 return " ".join(temp) 26 27tagger = MeCab.Tagger("-Owakati") 28MAX_ID = 10 # 登録されているIDの最大値 29for i in range(1, MAX_ID): 30 url = 'http://www.haiku-data.jp/work_detail.php?cd={id}'.format(id=i) 31 print('fetching data... ' + url, end=' ') 32 d = get_data(url) 33 if d: 34 print('result: SUCCESS') 35 morphemes = get_morphemes(d['poem']) 36 write2file(i, morphemes) 37 else: 38 print('result: MISSING') 39 40 time.sleep(1)

data_util.py

python

1# -*- coding: utf-8 -*- 2import codecs 3 4 5def read_file(fname): 6 """ Read file 7 :param fname: file name 8 :return: word list in the file 9 """ 10 with codecs.open('poem.txt', 'a', encoding='utf-8') as f: 11 return f.read().splitlines() 12 13def select_sentences(sentences): 14 dataset = [] 15 for sent in sentences: 16 morphemes = sent.split() 17 if len(morphemes) > 30: 18 continue 19 for i in range(len(morphemes)-2): 20 if morphemes[i] == morphemes[i+1]: 21 break 22 if morphemes[i] == morphemes[i+2]: 23 break 24 else: 25 dataset.append(sent) 26 return dataset 27 28def make_vocab(sentences): 29 """ make dictionary 30 :param sentences: word list ex. ["I", "am", "stupid"] 31 """ 32 global word2id 33 34 for sent in sentences: 35 for morpheme in sent.split(): 36 if morpheme in word2id: 37 continue 38 word2id[morpheme] = len(word2id) 39 40def sent2id(sentences): 41 id_list = [] 42 for sent in sentences: 43 temp = [] 44 for morpheme in sent.split(): 45 temp.append(word2id[morpheme]) 46 id_list.append(temp) 47 return id_list 48 49def get_dataset(): 50 fname_list = [] 51 dataset = [] 52 # make dictionary 53 for fname in fname_list: 54 sentences = read_file(fname) 55 sentences = select_sentences(sentences) 56 make_vocab(sentences) 57 dataset = dataset + sentences 58 id2sent = sent2id(dataset) 59 return word2id, id2sent, dataset 60 61 62word2id = {}

train.py

python

1import random 2import data_util as U 3import torch 4import torch.nn as nn 5import torch.nn.functional as F 6import torch.optim as O 7from torch.autograd import Variable 8 9### Prepare data ### 10word2id, id2sent, dataset = U.get_dataset() 11 12USE_CUDA = False 13FloatTensor = torch.cuda.FloatTensor if USE_CUDA else torch.FloatTensor 14LongTensor = torch.cuda.LongTensor if USE_CUDA else torch.LongTensor 15class RNN(nn.Module): 16 def __init__(self, n_vocab, embedding_dim, hidden_dim): 17 super(RNN, self).__init__() 18 self.encoder = nn.Embedding(n_vocab, embedding_dim) 19 self.gru = nn.GRU(embedding_dim, hidden_dim) 20 self.decoder = nn.Linear(hidden_dim, n_vocab) 21 self.embedding_dim = embedding_dim 22 self.num_layers = 1 23 self.dropout = nn.Dropout(0.1) 24 self.init_hidden() 25 26 def init_hidden(self): 27 self.hidden = Variable(\ 28 FloatTensor(self.num_layers, 1, self.embedding_dim).fill_(0)) 29 if USE_CUDA: 30 self.hidden.cuda() 31 32 def forward(self, x): 33 x = self.encoder(x.view(1, -1)) 34 x = self.dropout(x) 35 y, self.hidden = self.gru(x.view(1, 1, -1), self.hidden) 36 y = self.decoder(y.view(1, -1)) 37 return y 38 39def variable(index): 40 tensor = LongTensor(index) 41 if USE_CUDA: 42 return Variable(tensor).cuda() 43 return Variable(tensor) 44 45### Training ### 46n_epochs = 10 47n_vocab = len(word2id) 48embedding_dim = 128 49hidden_dim = 128 50learning_rate = 0.01 51 52model = RNN(n_vocab, embedding_dim, hidden_dim) 53if USE_CUDA: 54 model.cuda() 55criterion = nn.CrossEntropyLoss() 56optimizer = O.Adam(model.parameters(), lr=learning_rate) 57 58print("USE_CUDA: {}\nn_epochs: {}\nn_vocab: {}\n".format(USE_CUDA, n_epochs, n_vocab)) 59 60for epoch in range(n_epochs): 61 if (epoch+1) % 1 == 0: 62 print("Epoch {}".format(epoch+1)) 63 random.shuffle(id2sent) 64 for indices in id2sent: 65 model.init_hidden() 66 model.zero_grad() 67 source = variable(indices[:-1]) 68 target = variable(indices[1:]) 69 loss = 0 70 for x, t in zip(source, target): 71 y = model(x) 72 loss += criterion(y, t) 73 loss.backward() 74 optimizer.step() 75#model_name = "/output/example_gpu.model" if USE_CUDA else "/output/example.model" 76model_name = "example_gpu.model" if USE_CUDA else "example.model" 77torch.save(model.state_dict(), model_name)

Ubuntu 18.04

Python 3.6.6
torch (0.2.0.post2)
mecab-python3 (0.7)

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

このソースコードでは

get_dataset()

の時に fname_listが空のままなので
word2idも空のままです。

n_vocab = len(word2id)

とした値をその後も使うので、元のコードに何か記述が足りないのではないかと思います。

投稿2018/11/22 06:46

tak__tak

総合スコア78

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問