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

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

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

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

Anaconda

Anacondaは、Python本体とPythonで利用されるライブラリを一括でインストールできるパッケージです。環境構築が容易になるため、Python開発者間ではよく利用されており、商用目的としても利用できます。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

1回答

3727閲覧

「AttributeError: module 'keras.backend' has no attribute 'image_dim_ordering'」の解消方法

mnmnmmmn

総合スコア18

Keras

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

Anaconda

Anacondaは、Python本体とPythonで利用されるライブラリを一括でインストールできるパッケージです。環境構築が容易になるため、Python開発者間ではよく利用されており、商用目的としても利用できます。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2021/01/13 07:45

編集2021/01/13 07:48

前提・実現したいこと

下記URLのコードを参考に、手書き文字認識プログラムを作成したいです。
https://github.com/yukoba/CnnJapaneseCharacter
(紹介記事:https://qiita.com/yukoba/items/7a687e44395783eb32b1)

conda環境にて「learn.py」を実行したところ、以下のエラーメッセージが発生しました。

発生している問題・エラーメッセージ

Traceback (most recent call last): File "learn.py", line 32, in <module> if K.image_dim_ordering() == 'th': AttributeError: module 'keras.backend' has no attribute 'image_dim_ordering'

該当のソースコード

# This code is based on # https://github.com/fchollet/keras/blob/master/examples/mnist_cnn.py # https://github.com/fchollet/keras/blob/master/examples/cifar10_cnn.py import numpy as np #import scipy.misc from PIL import Image from keras import backend as K from keras import initializers from keras.layers import Convolution2D, MaxPooling2D from keras.layers import Dense, Dropout, Activation, Flatten from keras.models import Sequential from keras.preprocessing.image import ImageDataGenerator from keras.utils import np_utils from sklearn.model_selection import train_test_split nb_classes = 72 # input image dimensions img_rows, img_cols = 32, 32 # img_rows, img_cols = 127, 128 ary = np.load("hiragana.npz")['arr_0'].reshape([-1, 127, 128]).astype(np.float32) / 15 X_train = np.zeros([nb_classes * 160, img_rows, img_cols], dtype=np.float32) for i in range(nb_classes * 160): X_train[i] = np.array(Image.fromarray(ary[i]).resize((img_cols,img_rows))) # X_train[i] = scipy.misc.imresize(ary[i], (img_rows, img_cols), mode='F') # X_train[i] = ary[i] Y_train = np.repeat(np.arange(nb_classes), 160) X_train, X_test, Y_train, Y_test = train_test_split(X_train, Y_train, test_size=0.2) if K.image_dim_ordering() == 'th': X_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols) X_test = X_test.reshape(X_test.shape[0], 1, img_rows, img_cols) input_shape = (1, img_rows, img_cols) else: X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1) X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1) input_shape = (img_rows, img_cols, 1) # convert class vectors to binary class matrices Y_train = np_utils.to_categorical(Y_train, nb_classes) Y_test = np_utils.to_categorical(Y_test, nb_classes) datagen = ImageDataGenerator(rotation_range=15, zoom_range=0.20) datagen.fit(X_train) model = Sequential() def my_init(shape, name=None): return initializers.normal(shape, scale=0.1, name=name) # Best val_loss: 0.0205 - val_acc: 0.9978 (just tried only once) # 30 minutes on Amazon EC2 g2.2xlarge (NVIDIA GRID K520) def m6_1(): model.add(Convolution2D(32, 3, 3, init=my_init, input_shape=input_shape)) model.add(Activation('relu')) model.add(Convolution2D(32, 3, 3, init=my_init)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.5)) model.add(Convolution2D(64, 3, 3, init=my_init)) model.add(Activation('relu')) model.add(Convolution2D(64, 3, 3, init=my_init)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.5)) model.add(Flatten()) model.add(Dense(256, init=my_init)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(nb_classes)) model.add(Activation('softmax')) def classic_neural(): model.add(Flatten(input_shape=input_shape)) model.add(Dense(256)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(nb_classes)) model.add(Activation('softmax')) m6_1() # classic_neural() model.summary() model.compile(loss='categorical_crossentropy', optimizer='adadelta', metrics=['accuracy']) model.fit_generator(datagen.flow(X_train, Y_train, batch_size=16), samples_per_epoch=X_train.shape[0], nb_epoch=400, validation_data=(X_test, Y_test))

試したこと

①32行目「K.image_dim_ordering()」を「K.image_data_format()」に置換
TypeError: ('Keyword argument not understood:', 'init')が発生
参考URL:https://github.com/keras-team/keras/issues/12649

②kerasのバージョンを2.2.4にダウン
AttributeError: module 'tensorflow' has no attribute 'get_default_graph'が発生
参考URL:https://qiita.com/ryoo/items/89e29ec4cfb956e7af9c

③②のバージョン状態で下記参考URLの①~⑤を実行
→①~③:ImportError: cannot import name 'np_utils' from 'tensorflow.keras.utils'が発生
④:Could not find a version that satisfies the requirement keras==1.4 が発生
⑤:AttributeError: module 'keras.backend' has no attribute 'image_dim_ordering'が発生(振出しに戻る)
参考URL:https://qiita.com/white1107/items/67ec0826a07a84442d31

お答えいただける範囲でアドバイスいただければ幸いです。
追加すべき情報等ありましたらご指摘ください。

補足情報(FW/ツールのバージョンなど)

conda 4.9.2
keras 2.3.1
※※同プログラムについて以下URLにて質問させていただきました。当該エラーは解消できたのですが、新たにエラーが発生したため、改めて質問させていただいた次第です。ソースコードからの変更箇所等は下記URLもご参照いただければ幸いです※※
https://teratail.com/questions/315642

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

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

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

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

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

guest

回答1

0

ベストアンサー

既に解決策が判明しているかもしれませんが、、
keras 2.3.1 では keras.backend.image_dim_ordering() がなく、代わりに keras.backend.image_data_format() が使用できるようです。

そこで以下のように keras.backend.image_data_format() を使用すれば該当エラーが解消されるかと思います:

Python

1if K.image_data_format() == 'channels_first': # <- ココを変更 2 X_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols) 3 X_test = X_test.reshape(X_test.shape[0], 1, img_rows, img_cols) 4 input_shape = (1, img_rows, img_cols) 5else: 6 X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1) 7 X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1) 8 input_shape = (img_rows, img_cols, 1)

このことに関しては以下の Issue の一連が多少参考になるかと思います。
https://github.com/keras-team/keras/issues/12649
関数が返す値の対応関係については、上記 Issue の TheHugeManatee commented on 7 Apr 2020 をご参考ください:

# TheHugeManatee commented on 7 Apr 2020 The way I understand it, with the new API: setting: K.set_image_dim_ordering('tf') --> K.set_image_data_format('channels_last') K.set_image_dim_ordering('th') --> K.set_image_data_format('channels_first') checking: K.image_dim_ordering() == 'tf' --> K.image_data_format() == 'channels_last' K.image_dim_ordering() == 'th' --> K.image_data_format() == 'channels_first' I'm not very familiar with it so there might be other edge cases. [Edited: Corrected the order as per @CarMiranda 's comment below]

また、上記 Issue の aclex commented on 20 Sep 2019 によれば v2.2.4 -> v2.2.5 のタイミングで関数の変更が入ったようです:

# aclex commented on 20 Sep 2019 From my little version-wise research, this attribute disappears in 2.2.4 -> 2.2.5 version change. So in my case everything still works fine with 2.2.4. Thanks everyone for suggestions to fix it!

投稿2021/01/13 14:54

編集2021/01/13 14:58
Surpris

総合スコア106

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

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

mnmnmmmn

2021/01/14 05:50

ご回答ありがとうございます。いただいた情報で解決できました!image_dim_ordering()だけでなく右辺も修正する必要が合ったのですね。勉強になりました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問