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

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

新規登録して質問してみよう
ただいま回答率
85.50%
機械学習

機械学習は、データからパターンを自動的に発見し、そこから知能的な判断を下すためのコンピューターアルゴリズムを指します。人工知能における課題のひとつです。

Python

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

Q&A

解決済

4回答

5408閲覧

TypeError: unsupported operand type(s) for %: 'builtin_function_or_method' and 'int'の原因と解消方法を教えて下さい。

ganase

総合スコア4

機械学習

機械学習は、データからパターンを自動的に発見し、そこから知能的な判断を下すためのコンピューターアルゴリズムを指します。人工知能における課題のひとつです。

Python

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

0グッド

0クリップ

投稿2020/06/18 15:32

編集2020/06/19 02:26

前提・実現したいこと

下記urlにある、ベアリングの異常検知をする、機械学習のサンプルコードを実行しようとしています。
https://github.com/BLarzalere/LSTM-Autoencoder-for-Anomaly-Detection
データや判定手法が実際に使えるものかを判断するのが目的です。
したがって、コードを一通り試して、内容を理解したいです。
しかしながら、環境の違いなのかエラーが出てしまいます。
初歩的で恐縮ですがご教示頂ければ幸いです。

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

TypeError: unsupported operand type(s) for %: 'builtin_function_or_method' and 'int' TypeError Traceback (most recent call last) <ipython-input-50-4fa0c8e38f05> in <module>() 1 # create the autoencoder model ----> 2 model = autoencoder_model(X_train) 12 frames /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/random_seed.py in _truncate_seed(seed) 36 37 def _truncate_seed(seed): ---> 38 return seed % _MAXINT32 # Truncate to fit into 32-bit integer 39 40 TypeError: unsupported operand type(s) for %: 'builtin_function_or_method' and 'int'

該当のソースコード ★印

Python

1# import libraries 2import os 3import pandas as pd 4import numpy as np 5from sklearn.preprocessing import MinMaxScaler 6from sklearn.externals import joblib 7import seaborn as sns 8sns.set(color_codes=True) 9import matplotlib.pyplot as plt 10%matplotlib inline 11from numpy.random import seed 12import tensorflow as tf 13tf.random.set_seed(seed) 14from keras.layers import Input, Dropout, Dense, LSTM, TimeDistributed, RepeatVector 15from keras.models import Model 16from keras import regularizers 17 18# set random seed 19seed(10) 20from google import colab 21colab.drive.mount('/content/gdrive') 22 23# load, average and merge sensor samples 24data_dir = 'gdrive/My Drive/data/bearing_data' 25!ls 'gdrive/My Drive/data/bearing_data' 26merged_data = pd.DataFrame() 27for filename in os.listdir(data_dir): 28 dataset = pd.read_csv(os.path.join(data_dir, filename), sep='\t', engine='python') 29 dataset_mean_abs = np.array(dataset.abs().mean()) 30 dataset_mean_abs = pd.DataFrame(dataset_mean_abs.reshape(1,4)) 31 dataset_mean_abs.index = [filename] 32 merged_data = merged_data.append(dataset_mean_abs) 33merged_data.columns = ['Bearing 1', 'Bearing 2', 'Bearing 3', 'Bearing 4'] 34 35# transform data file index to datetime and sort in chronological order 36merged_data.index = pd.to_datetime(merged_data.index, format='%Y.%m.%d.%H.%M.%S') 37merged_data = merged_data.sort_index() 38merged_data.to_csv('Averaged_BearingTest_Dataset.csv') 39print("Dataset shape:", merged_data.shape) 40merged_data.head() 41train = merged_data['2004-02-12 10:52:39': '2004-02-15 12:52:39'] 42test = merged_data['2004-02-15 12:52:39':] 43print("Training dataset shape:", train.shape) 44print("Test dataset shape:", test.shape) 45 46# Train データをプロット 47fig, ax = plt.subplots(figsize=(14, 6), dpi=80) 48ax.plot(train['Bearing 1'], label='Bearing 1', color='blue', animated = True, linewidth=1) 49ax.plot(train['Bearing 2'], label='Bearing 2', color='red', animated = True, linewidth=1) 50ax.plot(train['Bearing 3'], label='Bearing 3', color='green', animated = True, linewidth=1) 51ax.plot(train['Bearing 4'], label='Bearing 4', color='black', animated = True, linewidth=1) 52plt.legend(loc='lower left') 53ax.set_title('Bearing Sensor Training Data', fontsize=16) 54plt.show() 55 56# transforming data from the time domain to the frequency domain using fast Fourier transform 57# 高速フーリエ変換を使用して、時間領域から周波数領域にデータを変換する 58train_fft = np.fft.fft(train) 59test_fft = np.fft.fft(test) 60 61# frequencies of the healthy sensor signal 62# 正常なセンサー信号の周波数 63fig, ax = plt.subplots(figsize=(14, 6), dpi=80) 64ax.plot(train_fft[:,0].real, label='Bearing 1', color='blue', animated = True, linewidth=1) 65ax.plot(train_fft[:,1].imag, label='Bearing 2', color='red', animated = True, linewidth=1) 66ax.plot(train_fft[:,2].real, label='Bearing 3', color='green', animated = True, linewidth=1) 67ax.plot(train_fft[:,3].real, label='Bearing 4', color='black', animated = True, linewidth=1) 68plt.legend(loc='center') 69ax.set_title('Bearing Sensor Training Frequency Data', fontsize=16) 70plt.show() 71 72# frequencies of the degrading sensor signal 73# 劣化センサー信号の周波数 74fig, ax = plt.subplots(figsize=(14, 6), dpi=80) 75ax.plot(test_fft[:,0].real, label='Bearing 1', color='blue', animated = True, linewidth=1) 76ax.plot(test_fft[:,1].imag, label='Bearing 2', color='red', animated = True, linewidth=1) 77ax.plot(test_fft[:,2].real, label='Bearing 3', color='green', animated = True, linewidth=1) 78ax.plot(test_fft[:,3].real, label='Bearing 4', color='black', animated = True, linewidth=1) 79plt.legend(loc='upper left') 80ax.set_title('Bearing Sensor Test Frequency Data', fontsize=16) 81plt.show() 82 83# normalize the data 84# データを正規化する 85scaler = MinMaxScaler() 86X_train = scaler.fit_transform(train) 87X_test = scaler.transform(test) 88scaler_filename = "scaler_data" 89joblib.dump(scaler, scaler_filename) 90 91# reshape inputs for LSTM [samples, timesteps, features] 92X_train = X_train.reshape(X_train.shape[0], 1, X_train.shape[1]) 93print("Training data shape:", X_train.shape) 94X_test = X_test.reshape(X_test.shape[0], 1, X_test.shape[1]) 95print("Test data shape:", X_test.shape) 96 97# define the autoencoder network model 98def autoencoder_model(X): 99 inputs = Input(shape=(X.shape[1], X.shape[2])) 100 L1 = LSTM(16, activation='relu', return_sequences=True, 101 kernel_regularizer=regularizers.l2(0.00))(inputs) 102 L2 = LSTM(4, activation='relu', return_sequences=False)(L1) 103 L3 = RepeatVector(X.shape[1])(L2) 104 L4 = LSTM(4, activation='relu', return_sequences=True)(L3) 105 L5 = LSTM(16, activation='relu', return_sequences=True)(L4) 106 output = TimeDistributed(Dense(X.shape[2]))(L5) 107 model = Model(inputs=inputs, outputs=output) 108 return model 109 110# create the autoencoder model  111model = autoencoder_model(X_train) #★この行でエラーです。 112model.compile(optimizer='adam', loss='mae') 113model.summary()

試したこと

built in functionが何を指すのか分からないのですが、int、つまり被演算の数値のデータ形式のエラーと思われました。そこで、データファイルを3つに絞り込んで実行しましたが、同じエラーが出ます。データではなく、functionが原因だと思われますが、それ以上のヒントが無く困っております。

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

Google colabを利用しています。
元データはすべてまとめて、自分のGoogle drive にdata\bearing_data というディレクトリを作って保存しています。

Pythonや機械学習は素人で、特に関数定義の# define the autoencoder network modelの内容は理解できていません。

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

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

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

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

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

meg_

2020/06/18 22:12 編集

autoencoder_model(X)のどこでエラーが発生しているかについて、エラーメッセージに書いてありませんか? エラーメッセージは省略せずに掲載ください。 ----------------------------------------------------------------- コードの中に書いてありましたね。今、気が付きました。分かりにくいので、エラーメッセージは独立して記述してくださいね。 ----------------------------------------------------------------- エラー発生箇所は何処ですか? エラーメッセージは全文掲載してください。(ユーザー名等は隠してもらって構いません)
ganase

2020/06/19 02:26

ご指摘ありがとうございます。改定を行いましたのでご確認頂ければ幸いです。
ganase

2020/06/21 02:42

tensorflowのバージョンダウンしてスッキリ解決しました。 アドバイスありがとうございました。
guest

回答4

0

!pip install tensorflow==1.14.0
上記コマンドでtensorflowのバージョンダウンしてスッキリ解決しました。

投稿2020/06/21 02:43

ganase

総合スコア4

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

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

0

!pip install tensorflow==1.14.0

上記コマンドでtensorflowのバージョンダウンして解決しました。

投稿2020/06/21 02:39

ganase

総合スコア4

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

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

0

自己解決

!pip install tensorflow==1.14.0

上記コマンドでtensorflowのバージョンダウンして解決しました。

投稿2020/06/21 02:24

ganase

総合スコア4

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

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

0

https://www.tensorflow.org/api_docs/python/tf/random/set_seed
のサンプル

tf.random.set_seed(1234)

あたりを参考にしてください。

その関数の引数seedにはなにかの整数を渡すのですよ。

投稿2020/06/19 05:04

quickquip

総合スコア11029

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

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

ganase

2020/06/21 02:41 編集

アドバイスありがとうございます。 tensorflowのバージョンダウンしてスッキリ解決しました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問