13. if(path1[-1]=="/"):
path1=path1[:-1]
for file in glob.glob(path1+"/*.tif"):
idx = file.rfind("/") # use "" for windows or "/" for mac
filename = file[idx+1:-4]
print("------Processing {}------".format(filename))
Tiff_to_BMP(file,filename,path2)
print("------All done------")
いよいよ画像の切り出しを実行します。
セルを実行すると、進行状況(読み込んだファイル名と切り出した画像数)が表示されます。
path1に保存されているTIFFファイルを全て処理し、“All done”と表示されたら終了です。
path2で指定したフォルダ内を確認して画像が保存されていれば成功です。
処理が実行されているにも関わらず画像が保存されていない場合は、ディレクトリの指定に失敗
している可能性があります。
特に、上記セルの4行目、”/”の部分が使用しているシステムに合っていないためによくエラーが
発生します。Google Colabを使う場合は”/”に書き換える必要があります。
“/”に書き換える。
17. # parameter settings
path = "/content/drive/My Drive/Colab Notebooks/CellCycle" # root directory
groups = ["G2", "notG2"] # class name
if(path[-1]!="/"):
path=path + "/"
root_dir = path
train_dir =path + "image/train/"
test_dir = path + "image/test/"
export_dir = path+"/data" # directory for data export
from google.colab import drive
drive.mount('/content/drive')
“2_ImageToArray.ipynb”を開いたら冒頭にセルを追加してドライブをマウントしましょう。
画像切り出しからそのまま続けて作業する場合は省略できます。
必要なモジュールをインポートしてください。特に追加インストールの必要はないと思います。
次に、ディレクトリを指定します。
pathの部分は状況に合わせて必ず書き換えてください。
その他の部分は、あらかじめ指定通りにフォルダを作成した場合はそのまま使えます。
自分のデータを使う際にフォルダの構造や名前を変えた場合は、ここの設定も更新してください。
18. # split files into train and test
for i, group in enumerate(groups):
print("----Processing {}----".format(group))
image_dir = root_dir + "image/" + group # original images
move_train_dir = train_dir + group # destination; training data
move_test_dir = test_dir + group # destination; test data
files = list(glob.glob(image_dir+"/*.bmp"))
print("Files detected:")
print(len(files))
# 20% of data will be moved to "test"
th = math.floor(len(files)*0.2)
random.shuffle(files)
for i in range(th):
shutil.move(files[i],move_test_dir)
# move rest of data to "train"
files = glob.glob(image_dir+"/*.bmp")
for file in files:
shutil.move(file, move_train_dir)
print("----All done----")
次のセルで画像ファイルを訓練データとテストデータに振り分けます。
実行すると、G2とnotG2それぞれのフォルダに入った画像ファイルの中からランダムに20%を選び、
testフォルダ内のサブフォルダG2およびnotG2に移動します。
残りの画像ファイルをtrainフォルダ内に同様に移動します。これで訓練/テストデータを振り分けます。
注意すべきは、元の画像ファイルが全て移動してしまうことです。
やり直す場合は手動で画像ファイルを元の場所に戻す必要があります。
ファイルは動かさずにインデックスだけ取得して振り分けるなどした方がスマートですね。
ここはぜひ自分で改善してみてください。
21. !pip install bayesian-optimization
from google.colab import drive
drive.mount('/content/drive')
path = "/content/drive/My Drive/Colab Notebooks/CellCycle" # root directory
groups = ["G2","notG2"] # class name
title="Results1" # name of bayesian optimization result file w/o extension
nb_ch = 2 # number of input image channels (1 or 2)
single_ch = 0 # if number of channel is 1, choose channel #0 or 1
nb_classes = len(groups)
if(path[-1]=="/"):
path=path[:-1]
Google Colabで”3_BayesianOptimization.ipynb”を開きます。
bayesian-optimizationをインストールして、ドライブをマウントします(順不同)。
モジュールをインポートしたらディレクトリなどのパラメータを設定します。
pathは必ず正しく書き換えてください。
titleで出力ファイル名を指定します。拡張子はつけないでください(自動的に”.csv”が付加されます)。
画像のチャンネル数も指定します。
今回練習用に使う画像はHoechst+GM130の2チャンネルです。
せっかくなのでnb_ch=2にして2チャンネルとも使いましょう。その場合、single_chの値は無視されます。
もし1チャンネルで試す場合はnb_ch=1にした上で、single_chの値は0 (Hoechst)もしくは1 (GM130)を
選択してください。
※ややこしいのですが、チャンネルの並び順はBGRで(RGBではない!)、Pythonでは最初の要素は0番目とカウントされるのでこうなります。
22. # load training and test data sets
x_train = np.load(path+"/data/x_train.npy")
y_train = np.load(path+"/data/y_train.npy")
x_test = np.load(path +"/data/X_test.npy")
y_test = np.load(path +"/data/Y_test.npy")
# normalize
x_train = x_train/255
x_test = x_test/255
y_train = np_utils.to_categorical(y_train,nb_classes)
y_test = np_utils.to_categorical(y_test,nb_classes)
# shuffle sequence of data
index=list(range(x_train.shape[0]))
index=random.sample(index,len(index))
x_train = x_train[index]
y_train = y_train[index]
# pick color channels
if nb_ch == 2:
x_train=x_train[...,:2]
x_test=x_test[...,:2]
else:
x_train=x_train[...,single_ch]
x_test=x_test[...,single_ch]
x_train=x_train[...,None]
x_test=x_test[...,None]
print(x_train.shape)
print(x_test.shape)
次のセルを実行しnp.array形式で保存された画像データおよびラベルデータを読み込んで調整します。
訓練・テストデータそれぞれについて(画像数, 画像サイズx, y, チャンネル数)が表示されます。
26. # save results
all_params=[]
target=[]
for i in range(len(result.res)):
all_params.append(result.res[i]["params"])
target.append(result.res[i]["target"])
print("all_params:")
print(all_params)
print("target:")
print(target)
params_name=list(all_params[0].keys())
with open(path+'/'+title+'.csv', 'w') as f:
label=["acc","target(loss)"]+params_name
writer = csv.writer(f)
writer.writerow(label)
for i in range(len(all_params)):
eachparams=[acc[i],target[i]]+list(all_params[i].values())
writer.writerow(eachparams)
次のセルを実行し、ベイズ最適化の実行結果のログをCSVファイルで保存します。
28. from google.colab import drive
drive.mount('/content/drive')
Google Colabで”4_FunctionalModel.ipynb”を開いてドライブをマウントします。
モジュールをインポートしたらディレクトリなどのパラメータを設定します。
pathは必ず正しく書き換えてください。
model_nameで出力ファイル名を指定します。拡張子はつけないでください。
画像のチャンネル数の指定はベイズ最適化の時と同じです。
path = "/content/drive/My Drive/Colab Notebooks/CellCycle" # root directory
groups = ["G2","notG2"] # class name
model_name = "Model1" # name of output model w/o extension
nb_ch = 2 # number of input image channels (1 or 2)
single_ch = 0 # if number of channel is 1, choose channel #0 or 1
nb_classes = len(groups)
if(path[-1]=="/"):
path=path[:-1]
from bayes_opt import BayesianOptimization
ここではBayesianOptimizationは使用しないので、モジュールをインポートする際に以下の行は
削除してください(BayesianOptimizationがインストールされていない環境ではエラーになって
しまうので)。
29. # load training and test data sets
x_train = np.load(path+"/data/x_train.npy")
y_train = np.load(path+"/data/y_train.npy")
x_test = np.load(path +"/data/X_test.npy")
y_test = np.load(path +"/data/Y_test.npy")
# normalize
x_train = x_train/255
x_test = x_test/255
y_train = np_utils.to_categorical(y_train,nb_classes)
y_test = np_utils.to_categorical(y_test,nb_classes)
# shuffle sequence of data
index=list(range(x_train.shape[0]))
index=random.sample(index,len(index))
x_train = x_train[index]
y_train = y_train[index]
# pick color channels
if nb_ch == 2:
x_train=x_train[...,:2]
x_test=x_test[...,:2]
else:
x_train=x_train[...,single_ch]
x_test=x_test[...,single_ch]
x_train=x_train[...,None]
x_test=x_test[...,None]
print(x_train.shape)
print(x_test.shape)
画像データの読み込みもベイズ最適化の時と同じです。
35. # load saved model
with open(path+"/model/"+model_name+".json", "r") as f:
model = model_from_json(f.read())
model.load_weights(path+"/model/"+model_name+".hdf5")
model.summary()
保存したモデルを読み込んで構造を確認することもできます。
Grad-CAM解析などの時にも同様にモデルを読み込むことができます。
36. 以下のコードを新しいセルで実行(※)すると、読み込んだモデルの判定結果を表示できます。
※公開しているコードには含まれていないのでコピペで追加してください。
テストデータの中から読み込む画像の数を1行目のnumberで指定して実行するだけです。
保存したモデルを読み込んだ後で実行してください(実行結果は次のスライド)。
number=15 # number of images to show
input_model=model
plt.figure(figsize=(14,number*1.5),facecolor="w")
for i, idx in enumerate(np.random.choice(y_test.shape[0],size=number,replace=False)): # y_test.shape[0]=nu
mber of test images
# test images
plt.subplot(number/2, 6, 2*i+1, xticks=[], yticks=[])
img=x_test[idx,:,:,:]
if nb_ch==2:
zero=np.zeros(img.shape[:2])
raw_img=np.stack([zero,img[:,:,1],img[:,:,0]],axis=2)
plt.imshow(raw_img)
else:
zero=np.zeros(img.shape[:2])
raw_img=np.stack([zero,zero,img[:,:,single_ch]],axis=2)
plt.imshow(raw_img)
# predict class of input image
img = img[None,:,:,:]
predictions = input_model.predict(img)
predictions = np.asarray(predictions)
predictions=np.round(predictions,3)
class_idx = np.argmax(predictions[0])
true_idx = np.argmax(y_test[idx])
plt.title("#{}, {}(label.{}), {}".format(idx,groups[class_idx],groups[true_idx],str(predictions)))
if class_idx == true_idx:
plt.xlabel("correct",color="green")
else:
plt.xlabel("incorrect",color="red")