前提・実現したいこと
以下のエラーの解消方法について教えていただきたいです。
調べると、ローカル変数内でcallbackを定義していることが影響しているようなのですが、どのように修正すればよいか分からず、こちらに質問をさせていただきました。
お手数をおかけいたしますがどうぞよろしくお願い致します。
発生している問題・エラーメッセージ
UnboundLocalError: local variable 'callbacks' referenced before assignment
該当のソースコード
Python
1import keras 2from keras.applications.inception_v3 import InceptionV3 3from keras.optimizers import Adam, SGD 4from keras.models import Model 5from keras.layers import GlobalAveragePooling2D, Dense 6from keras import backend as K 7from keras.callbacks import CSVLogger,EarlyStopping, ModelCheckpoint 8from sklearn.neighbors import LocalOutlierFactor 9from sklearn import metrics 10from sklearn.preprocessing import MinMaxScaler 11 12 13input_shape = (299, 299, 3) 14classes = 4#10 15batchsize = 12#128 16 17def train_and_evaluate(number):#, anomaly=True): 18 print("Model build...") 19 20 model = InceptionV3(include_top=True, input_shape=input_shape, weights='imagenet') 21 22 # 最終層削除 23 model.layers.pop() 24 model = Model(inputs=model.input,outputs=model.layers[-1].output) 25 26 # L2層と全結合層を付ける 27 c = keras.layers.Lambda(lambda xx: 5*(xx)/K.sqrt(K.sum(xx**2)))(model.output) #metric learning 28 c = Dense(classes, activation='softmax')(c) 29 model = Model(inputs=model.input,outputs=c) 30 31 #model.summary() 32 33 model.compile(loss='categorical_crossentropy', 34 optimizer=Adam(lr=0.0001, amsgrad=True), 35 metrics=['accuracy']) 36 37 print(number,"training...") 38 39 callbacks = callbacks.ModelCheckpoint(filepath="model.ep{epoch:02d}.h5",save_best_only=True)#, 40 41 hist = model.fit_generator(train_generator, steps_per_epoch=8072, epochs=1, 42 validation_steps=952, validation_data=validation_generator, callbacks=callbacks) 43 44 # 最終層削除 45 model.layers.pop() 46 model = Model(inputs=model.input,outputs=model.layers[-1].output) 47 48 train = model.predict(train_generator[57173:]) 49 test_normal = model.predict(x_test_normal) 50 test_anomaly = model.predict(x_test_anomaly) 51 52 train = train.reshape((len(train),-1)) 53 test_normal = test_normal.reshape((len(x_test_normal),-1)) 54 test_anomaly = test_anomaly.reshape((len(x_test_anomaly),-1)) 55 56 #0-1変換 57 ms = MinMaxScaler() 58 train = ms.fit_transform(train) 59 test_normal = ms.transform(test_normal) 60 test_anomaly = ms.transform(test_anomaly) 61 62 # LOF 63 clf = LocalOutlierFactor(n_neighbors=5) 64 y_pred = clf.fit(train) 65 66 # plot the level sets of the decision function 67 Z1 = -clf._decision_function(test_normal) 68 Z2 = -clf._decision_function(test_anomaly) 69 70 #ROC曲線の描画 71 y_true = np.zeros(len(test_normal)+len(test_anomaly)) 72 y_true[len(test_normal):] = 1#0:正常、1:異常 73 74 # FPR, TPR(, しきい値) を算出 75 fpr, tpr, _ = metrics.roc_curve(y_true, np.hstack((Z1, Z2))) 76 77 # AUC 78 auc = metrics.auc(fpr, tpr) 79 80 # ROC曲線をプロット 81 plt.plot(fpr, tpr, label='metric learning(AUC = %.2f)'%auc) 82 plt.legend() 83 plt.title(str(number)+'ROC curve') 84 plt.xlabel('False Positive Rate') 85 plt.ylabel('True Positive Rate') 86 plt.grid(True) 87 plt.show() 88 89for i in range(10): 90 train_and_evaluate(i+1)
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/08/22 09:09