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

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

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

Kerasは、TheanoやTensorFlow/CNTK対応のラッパーライブラリです。DeepLearningの数学的部分を短いコードでネットワークとして表現することが可能。DeepLearningの最新手法を迅速に試すことができます。

Python 3.x

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

Q&A

解決済

1回答

793閲覧

lstmのサンプルコードを書き換えるとValueErrorが出てくる

退会済みユーザー

退会済みユーザー

総合スコア0

Keras

Kerasは、TheanoやTensorFlow/CNTK対応のラッパーライブラリです。DeepLearningの数学的部分を短いコードでネットワークとして表現することが可能。DeepLearningの最新手法を迅速に試すことができます。

Python 3.x

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

0グッド

0クリップ

投稿2019/02/03 02:22

編集2019/02/03 02:41

やりたいこと

python初心者です。
Kerasのlstmサンプルコード[https://github.com/keras-team/keras/blob/master/examples/lstm_text_generation.py]を参考に、diversityの値を一部変更し、複数ファイルを読み込めるように書き換えようとしています。

## ソースコード

'''Example script to generate text from Nietzsche's writings. At least 20 epochs are required before the generated text starts sounding coherent. It is recommended to run this script on GPU, as recurrent networks are quite computationally intensive. If you try this script on new data, make sure your corpus has at least ~100k characters. ~1M is better. ''' from __future__ import print_function from keras.callbacks import LambdaCallback from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from keras.optimizers import RMSprop from keras.utils.data_utils import get_file import numpy as np import random import sys import io data = [None] * 100 for i in range(100): with open('Data Folder/data001.txt'.format(i + 1), mode='r', encoding='utf-8') as f: data[i] = f.read() print('corpus length:', len(data)) chars = sorted(list(set(data))) print('total chars:', len(chars)) char_indices = dict((c, i) for i, c in enumerate(chars)) indices_char = dict((i, c) for i, c in enumerate(chars)) maxlen = 7 step = 3 sentences = [] next_chars = [] for i in range(0, len(data) - maxlen, step): sentences.append(data[i: i + maxlen]) next_chars.append(data[i + maxlen]) print('nb sequences:', len(sentences)) print('Vectorization...') x = np.zeros((len(sentences), maxlen, len(chars)), dtype=np.bool) y = np.zeros((len(sentences), len(chars)), dtype=np.bool) for i, sentence in enumerate(sentences): for t, char in enumerate(sentence): x[i, t, char_indices[char]] = 1 y[i, char_indices[next_chars[i]]] = 1 print('Build model...') model = Sequential() model.add(LSTM(128, input_shape=(maxlen, len(chars)))) model.add(Dense(len(chars), activation='softmax')) optimizer = RMSprop(lr=0.01) model.compile(loss='categorical_crossentropy', optimizer=optimizer) def sample(preds, temperature=1.0): # helper function to sample an index from a probability array preds = np.asarray(preds).astype('float64') preds = np.log(preds) / temperature exp_preds = np.exp(preds) preds = exp_preds / np.sum(exp_preds) probas = np.random.multinomial(1, preds, 1) return np.argmax(probas) def on_epoch_end(epoch, _): # Function invoked at end of each epoch. Prints generated text. print() print('----- Generating text after Epoch: %d' % epoch) start_index = random.randint(0, len(data) - maxlen - 1) for diversity in [0.2, 0.5, 0.8, 1.0]: print('----- diversity:', diversity) generated = '' sentence = data[start_index: start_index + maxlen] generated += sentence print('----- Generating with seed: "' + sentence + '"') sys.stdout.write(generated) for i in range(300): x_pred = np.zeros((1, maxlen, len(chars))) for t, char in enumerate(sentence): x_pred[0, t, char_indices[char]] = 1. preds = model.predict(x_pred, verbose=0)[0] next_index = sample(preds, diversity) next_char = indices_char[next_index] generated += next_char sentence = sentence[1:] + next_char sys.stdout.write(next_char) sys.stdout.flush() print() print_callback = LambdaCallback(on_epoch_end=on_epoch_end) model.fit(x, y, batch_size=128, epochs=60, callbacks=[print_callback]) ``` ## エラーコード ``` ValueError Traceback (most recent call last) <ipython-input-7-5103855688dc> in <module> 107 batch_size=128, 108 epochs=60, --> 109 callbacks=[print_callback]) ~\Anaconda3\envs\tensorflow16\lib\site-packages\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs) 950 sample_weight=sample_weight, 951 class_weight=class_weight, --> 952 batch_size=batch_size) 953 # Prepare validation data. 954 do_validation = False ~\Anaconda3\envs\tensorflow16\lib\site-packages\keras\engine\training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_array_lengths, batch_size) 807 # using improper loss fns. 808 check_loss_and_target_compatibility( --> 809 y, self._feed_loss_fns, feed_output_shapes) 810 else: 811 y = [] ~\Anaconda3\envs\tensorflow16\lib\site-packages\keras\engine\training_utils.py in check_loss_and_target_compatibility(targets, loss_fns, output_shapes) 271 raise ValueError( 272 'You are passing a target array of shape ' + str(y.shape) + --> 273 ' while using as loss `categorical_crossentropy`. ' 274 '`categorical_crossentropy` expects ' 275 'targets to be binary matrices (1s and 0s) ' ValueError: You are passing a target array of shape (31, 1) while using as loss `categorical_crossentropy`. `categorical_crossentropy` expects targets to be binary matrices (1s and 0s) of shape (samples, classes). If your targets are integer classes, you can convert them to the expected format via:   from keras.utils import to_categorical   y_binary = to_categorical(y_int) Alternatively, you can use the loss function `sparse_categorical_crossentropy` instead, which does expect integer targets. ``` ## 分からないこと エラーコード内の ``` from keras.utils import to_categorical y_binary = to_categorical(y_int) ``` このコードを改良すれば治る、ということなのでしょうか。 エラーが何を指してのものかすら分かっていない状態です。 このValueErrorの原因と対処法について、教えてください。

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

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

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

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

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

guest

回答1

0

ベストアンサー

If your targets are integer classes, you can convert them to the expected format via:   from keras.utils import to_categorical   y_binary = to_categorical(y_int)

イメージ説明

出力の次元が正しくないので、エラーメッセージ内のヒントを参考にしてください。

投稿2019/02/03 07:14

mkgrei

総合スコア8560

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

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

退会済みユーザー

退会済みユーザー

2019/02/03 08:23

載せてくださった画像の訳の元の文はどこのものでしょうか(エラーメッセージ欄でしょうか……?)、つまらないことを聞いてしまいすみません。
mkgrei

2019/02/03 08:42

エラーメッセージ欄の下から3と2番目のブロックです。 文を検索してみると引っかかるはずです。
退会済みユーザー

退会済みユーザー

2019/02/03 09:24

ありがとうございます。 from keras.utils import to_categorical y_binary = to_categorical(data) として、コードに挿入してみましたが、ValueError: invalid literal for int() with base 10が出てきました。 調べると、10進書式以外の文字列をint型に変換しようとした可能性があるようなのですが、このエラーを解決するためにどのようにアプローチすればよいでしょうか。
mkgrei

2019/02/03 22:14

ちなみですが、yの中身は何ですか? そうですね、今までの話を一度忘れていただいて、yの中身について考えてみてはいかがでしょうか? y = np.zeros((len(sentences), len(chars)), dtype=np.bool) からみるに、yのshapeは(len(sentences), len(chars))になっているはずです。 You are passing a target array of shape (31, 1) をみると、1次元になっていることがわかります。 すると、結果は全て同じものになり、予測すべきものはないことになります。 with open('Data Folder/data001.txt'.format(i + 1), mode='r', encoding='utf-8') as f: をみると、iが渡されているにもかかわらず、同じファイルを読み続けていることがわかります。 ですので、data001をdata{0:0>3}に変えてみてはいかがでしょう。
退会済みユーザー

退会済みユーザー

2019/02/04 11:09

yの大元は5万字程度の日本語のテキストです。答えになっているでしょうか。 data001をdata{0:0>3}に変更すると、再びValueError: invalid literal for int() with base 10が出てきました。(現在用意している読み込み用のファイルが3つしかないため、以下のようにwith open('Data Folder/data001.txt'.format(i + 1), mode='r', encoding='utf-8') as f:の箇所を変えました。) data = [None] * 3 for i in range(3): with open('Data Folder/da_ta{0:0>3}.txt'.format(i + 1), mode='r', encoding='utf-8') as f: data[i] = f.read() f.close()
mkgrei

2019/02/05 22:43

ちなみにyのあるべき形は理解している前提でよろしいでしょうか。 print('total chars:', len(chars)) の結果は何になっていますか?
退会済みユーザー

退会済みユーザー

2019/02/06 10:35

指定されたshapeを持った0を要素とするN次元配列がyのあるべき形ということだと調べたのですが、十分理解しているとは言えません。 print('total chars:', len(chars))の結果ですが、今度は違うValueErrorが出てきてしまいました。 ValueError: operator __getitem__ cannot be overwritten again on class <class 'tensorflow.python.framework.ops.Tensor'>. インデクシングに問題があるのでしょうか。
mkgrei

2019/02/06 22:44

とりあえずColabに入れてみたら走らせることができました。 どのようなデータを想定しているのか不明ですが、dataは文字列であることを想定しています。 いまリストになっているので、エラーになっています。 data = '\n'.join(data) と最初にすることでエラーは消えるはずです。 Noneのせいでエラーになるかもしれませんが、その場合は最初の初期化を、 data = [''] * 100
退会済みユーザー

退会済みユーザー

2019/02/07 05:27

data = '\n'.join(data)とdata = [''] * 100を加えることで動きました。 丁寧な回答本当にありがとうございました!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問