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

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

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

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

Q&A

解決済

1回答

737閲覧

Python3 scikit-learnのMSE関数使用時のエラー解消方法について

SuzuAya

総合スコア71

Python 3.x

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

0グッド

0クリップ

投稿2019/05/24 01:43

前提・実現したいこと

Kerasのサンプルコードを使ってオリジナルのデータセットでVAEを実装したのですが、ROC曲線とAUCを表示させる部分でつまづいています。
初めはscikit-learnのMSE関数でy_true(元画像)とy_pred(復元画像)の平均二乗誤差を出そうとしたのですが、どうやらこちらの関数は2次元までしか対応していないようで(画像は4次元)、うまくいかなかったため、tensoflowで実装したところ、やはりエラーが出てしまいました。

・Scikit-learnのMSE関数で4次元のy_trueとy_predの平均二乗誤差を算出する方法
・tensorflowのMSE関数で4次元のy_trueとy_predの平均二乗誤差を算出する方法

上記2点のいずれかをご教示いただけますと幸いです。
お手数をお掛けしますがどうぞよろしくお願いいたします。

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

TypeError Traceback (most recent call last) /usr/local/lib/python3.6/dist-packages/numpy/core/fromnumeric.py in _wrapfunc(obj, method, *args, **kwds) 55 try: ---> 56 return getattr(obj, method)(*args, **kwds) 57 7 frames TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed. Use `if t is not None:` instead of `if t:` to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor. During handling of the above exception, another exception occurred: TypeError Traceback (most recent call last) /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py in __bool__(self) 651 `TypeError`. 652 """ --> 653 raise TypeError("Using a `tf.Tensor` as a Python `bool` is not allowed. " 654 "Use `if t is not None:` instead of `if t:` to test if a " 655 "tensor is defined, and use TensorFlow ops such as " TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed. Use `if t is not None:` instead of `if t:` to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor.

該当のソースコード

#ROC曲線とAUCスコアの表示 #from sklearn.metrics import mean_squared_error from sklearn.metrics import roc_curve from sklearn.metrics import roc_auc_score import tensorflow as tf test_normal_pred = vae.predict(test_normal, verbose=1) test_anomaly_pred = vae.predict(test_anomaly, verbose=1) score = [] for i in range(len(test_normal)): squared_error_normal = tf.reduce_mean(tf.square(test_normal_pred[i,:,:,:] -test_normal[i,:,:,:]))# mean_squared_error(test_normal[i,:,:,:], test_normal_pred[i,:,:,:]) score.append(squared_error_normal) for i in range(len(test_anomaly)): squared_error_anomaly = tf.reduce_mean(tf.square(test_anomaly_pred[i,:,:,:] - test_anomaly[i,:,:,:]))# mean_squared_error(test_anomaly[i,:,:,:], test_anomaly_pred[i,:,:,:]) score.append(squared_error_anomaly) score = np.array(score) #print(score.shape) #print(score) #ROC曲線の描画 y_true = np.zeros(len(test_normal)+len(test_anomaly)) y_true[len(test_normal):] = 1#0:正常、1:異常 #print(y_true.shape) #print(score.shape) #print(score) # FPR, TPR(, しきい値) を算出 fpr, tpr, thresholds = roc_curve(y_true, score) # AUC auc = roc_auc_score(y_true, score) # ROC曲線をプロット plt.figure plt.plot(fpr, tpr, label='VAE method (area = %.2f)'%auc, c="r") plt.legend() plt.title('ROC curve') plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.grid(True) plt.savefig("./ROC curve.png") plt.show()

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

学習の部分のコードは省略させていただいております。
Google Colabを使っています。

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

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

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

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

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

guest

回答1

0

自己解決

こちらのサイトを参考に、次元を4次元から2次元に削減したところ、うまくいきましたので共有させていただきます。
https://stackoverflow.com/questions/33162871/python-scikit-learn-svm-classifier-valueerror-found-array-with-dim-3-expected

#ROC曲線とAUCスコアの表示 from sklearn.metrics import mean_squared_error from sklearn.metrics import roc_curve from sklearn.metrics import roc_auc_score import tensorflow as tf test_normal_pred = vae.predict(test_normal, verbose=1) test_anomaly_pred = vae.predict(test_anomaly, verbose=1) #4次元から2次元にreshape test_normal_size = len(test_normal) test_normal_pred_size = len(test_normal_pred) test_anomaly_size = len(test_anomaly) test_anomaly_pred_size = len(test_anomaly_pred) twodim_test_normal = test_normal.reshape(test_normal_size,-2) twodim_test_normal_pred = test_normal_pred.reshape(test_normal_pred_size,-2) twodim_test_anomaly = test_anomaly.reshape(test_anomaly_size,-2) twodim_test_anomaly_pred = test_anomaly_pred.reshape(test_anomaly_pred_size,-2) score = [] for i in range(len(test_normal)): squared_error_normal = mean_squared_error(twodim_test_normal[i,:], twodim_test_normal_pred[i,:])#squared_error_normal = tf.reduce_mean(tf.square(test_normal_pred[i,:,:,:] -test_normal[i,:,:,:])) score.append(squared_error_normal) for i in range(len(test_anomaly)): squared_error_anomaly = mean_squared_error(twodim_test_anomaly[i,:], twodim_test_anomaly_pred[i,:])# squared_error_anomaly = tf.reduce_mean(tf.square(test_anomaly_pred[i,:,:,:] - test_anomaly[i,:,:,:])) score.append(squared_error_anomaly) score = np.array(score) #print(score.shape) #print(score) #ROC曲線の描画 y_true = np.zeros(len(test_normal)+len(test_anomaly)) y_true[len(test_normal):] = 1#0:正常、1:異常 #print(y_true.shape) #print(score.shape) #print(score) # FPR, TPR(, しきい値) を算出 fpr, tpr, thresholds = roc_curve(y_true, score) # AUC auc = roc_auc_score(y_true, score) # ROC曲線をプロット plt.figure plt.plot(fpr, tpr, label='VAE method (area = %.2f)'%auc, c="r") plt.legend() plt.title('ROC curve') plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.grid(True) plt.savefig("./ROC curve.png") plt.show()

投稿2019/05/24 08:29

SuzuAya

総合スコア71

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

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

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問