Kerasを用いてMNISTの深層学習を行っているのですが、エラーが出て困っています。
バージョンは
keras 2.2.4
tensorflow 1.14.0
tensorboard 1.14.0
です
python
1import os 2import numpy as np 3import matplotlib.pyplot as plt 4 5from keras.datasets import mnist 6from keras.models import Sequential 7from keras.layers import Dense, Dropout, Activation, Flatten 8from keras.layers import Convolution2D, MaxPooling2D 9from keras.optimizers import Adam 10from keras.callbacks import EarlyStopping 11from keras.utils import np_utils 12from keras import backend as K 13from keras.utils.vis_utils import plot_model 14 15from sklearn.preprocessing import MinMaxScaler 16 17# MNISTの数字分類 18# 参考: https://github.com/fchollet/keras/blob/master/examples/mnist_cnn.py 19 20 21def build_cnn(input_shape, nb_filters, filter_size, pool_size): 22 model = Sequential() 23 24 model.add(Convolution2D(nb_filters, 25 filter_size[0], filter_size[1], 26 border_mode='valid', 27 input_shape=input_shape)) 28 model.add(Activation('relu')) 29 30 model.add(Convolution2D(nb_filters, filter_size[0], filter_size[1])) 31 model.add(Activation('relu')) 32 33 model.add(MaxPooling2D(pool_size=pool_size)) 34 model.add(Dropout(0.25)) 35 36 model.add(Flatten()) 37 38 model.add(Dense(128)) 39 model.add(Activation('relu')) 40 model.add(Dropout(0.5)) 41 42 model.add(Dense(nb_classes)) 43 model.add(Activation('softmax')) 44 45 return model 46 47 48def plot_history(history, outdir): 49 # 精度の履歴をプロット 50 plt.figure() 51 plt.plot_model(history.history['acc'], marker='.') 52 plt.plot_model(history.history['val_acc'], marker='.') 53 plt.title('model accuracy') 54 plt.xlabel('epoch') 55 plt.ylabel('accuracy') 56 plt.grid() 57 plt.legend(['train', 'test'], loc='upper left') 58 plt.savefig(os.path.join(outdir, 'acc.png')) 59 60 # 損失の履歴をプロット 61 plt.figure() 62 plt.plot_model(history.history['loss'], marker='.') 63 plt.plot_model(history.history['val_loss'], marker='.') 64 plt.title('model loss') 65 plt.xlabel('epoch') 66 plt.ylabel('loss') 67 plt.grid() 68 plt.legend(['train', 'test'], loc='upper left') 69 plt.savefig(os.path.join(outdir, 'loss.png')) 70 71 72def visualize_filter(model): 73 # 最初の畳み込み層の重みを取得 74 # tf => (nb_row, nb_col, nb_channel, nb_filter) 75 # th => (nb_filter, nb_channel, nb_row, nb_col) 76 W = model.layers[0].get_weights()[0] 77 78 # 次元を並べ替え 79 if K.backend.image_data_format()== 'tf': 80 # (nb_filter, nb_channel, nb_row, nb_col) 81 W = W.transpose(3, 2, 0, 1) 82 83 nb_filter, nb_channel, nb_row, nb_col = W.shape 84 85 # 32個(手抜きで固定)のフィルタの重みを描画 86 plt.figure() 87 for i in range(nb_filters): 88 # フィルタの画像 89 im = W[i, 0] 90 91 # 重みを0-255のスケールに変換 92 scaler = MinMaxScaler(feature_range=(0, 255)) 93 im = scaler.fit_transform(im) 94 95 plt.subplot(4, 8, i + 1) 96 plt.axis('off') 97 plt.imshow(im, cmap="gray") 98 plt.show() 99 100 101if __name__ == "__main__": 102 batch_size = 128 103 nb_classes = 10 104 nb_epoch = 100 105 106 img_rows, img_cols = 28, 28 107 nb_filters = 32 108 filter_size = (5, 5) 109 pool_size = (2, 2) 110 111 # MNISTデータのロード 112 (X_train, y_train), (X_test, y_test) = mnist.load_data() 113 114 # 画像集合を表す4次元テンソルに変形 115 # keras.jsonのimage_dim_orderingがthのときはチャネルが2次元目、tfのときはチャネルが4次元目にくる 116 if K.keras.backend.image_data_format() == 'th': 117 X_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols) 118 X_test = X_test.reshape(X_test.shape[0], 1, img_rows, img_cols) 119 input_shape = (1, img_rows, img_cols) 120 else: 121 X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1) 122 X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1) 123 input_shape = (img_rows, img_cols, 1) 124 125 # 画素を0.0-1.0の範囲に変換 126 X_train = X_train.astype('float32') 127 X_test = X_test.astype('float32') 128 X_train /= 255 129 X_test /= 255 130 131 print(X_train.shape[0], 'train samples') 132 print(X_test.shape[0], 'test samples') 133 134 # one-hot-encoding 135 Y_train = np_utils.to_categorical(y_train, nb_classes) 136 Y_test = np_utils.to_categorical(y_test, nb_classes) 137 138 # 畳み込みニューラルネットワークを構築 139 model = build_cnn(input_shape, nb_filters, filter_size, pool_size) 140 141 # モデルのサマリを表示 142 model.summary() 143 plot_model(model, show_shapes=True, to_file='result_mnist/model.png') 144 145 # モデルをコンパイル 146 model.compile(loss='categorical_crossentropy', 147 optimizer='adam', 148 metrics=['accuracy']) 149 150 # 学習前の1層目のフィルタを可視化 151 visualize_filter(model) 152 153 # Early-stopping 154 early_stopping = EarlyStopping() 155 156 # モデルの訓練 157 history = model.fit(X_train, Y_train, 158 batch_size=batch_size, 159 nb_epoch=nb_epoch, 160 verbose=1, 161 validation_split=0.1, 162 callbacks=[early_stopping]) 163 164 # 学習後の1層目のフィルタを可視化 165 visualize_filter(model) 166 167 # 学習履歴をプロット 168 plot_history(history, 'result_mnist') 169 170 # モデルの評価 171 loss, acc = model.evaluate(X_test, Y_test, verbose=0) 172 173 print('Test loss:', loss) 174 print('Test acc:', acc) 175
##エラーコード
runfile('C:/Users/mlab/.spyder-py3/work/keras-examples-master/keras-examples-master/cnn/mnist/mnist.py', wdir='C:/Users/mlab/.spyder-py3/work/keras-examples-master/keras-examples-master/cnn/mnist') Traceback (most recent call last): File "<ipython-input-13-be7b81a67ff3>", line 1, in <module> runfile('C:/Users/mlab/.spyder-py3/work/keras-examples-master/keras-examples-master/cnn/mnist/mnist.py', wdir='C:/Users/mlab/.spyder-py3/work/keras-examples-master/keras-examples-master/cnn/mnist') File "C:\Users\mlab\Anaconda3\envs\py3.7\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile execfile(filename, namespace) File "C:\Users\mlab\Anaconda3\envs\py3.7\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/mlab/.spyder-py3/work/keras-examples-master/keras-examples-master/cnn/mnist/mnist.py", line 116, in <module> if K.keras.backend.image_data_format() == 'th': AttributeError: module 'keras.backend' has no attribute 'keras'