diff --git a/.gitignore b/.gitignore index 7f9cbb5..d9a32ae 100644 --- a/.gitignore +++ b/.gitignore @@ -31,3 +31,13 @@ # node_modules/ # build/ # dist/ + +# -- legacy/(OneDrive の原本をそのまま置く場所) -- +# 既定で全部除外し,コードと実験条件の記録だけを Git に入れる(docs/03_PLAN/PLAN_01_要件定義書.md「管理対象」). +# 重み(ckpt・pth・pb・onnx)・result/ の csv と txt(画像のファイル名を含む)・TensorBoard のログ・ +# segmentation_models/(pip で置き換える)は入れない. +legacy/** +!legacy/**/ +!legacy/source/*.py +!legacy/temp/*.py +!legacy/source/lightning_logs/*/hparams.yaml diff --git a/CLAUDE.md b/CLAUDE.md index 634abd7..264b34f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,7 @@ ## 開発進捗 -最新: GUIDE_01 に従いプロジェクト立ち上げ中 +最新: 立ち上げフェーズ 1(方針決定)— 要件定義書を作成 ※ 本欄は**最新ステップ 1 行のみ上書き更新**.詳細な進捗履歴(動機・設計判断・失敗パターン)は [docs/PROGRESS.md](docs/PROGRESS.md) に追記する.運用ルールは `.claude/rules/progress-log.md` を参照(該当ファイル編集時に自動ロードされる). ## 必須ルール(コード実装時) @@ -77,7 +77,7 @@ ### 03_PLAN(計画) - +- 要件定義書: docs/03_PLAN/PLAN_01_要件定義書.md ### 04_SPEC(仕様・設計) diff --git "a/docs/03_PLAN/PLAN_01_\350\246\201\344\273\266\345\256\232\347\276\251\346\233\270.md" "b/docs/03_PLAN/PLAN_01_\350\246\201\344\273\266\345\256\232\347\276\251\346\233\270.md" new file mode 100644 index 0000000..36e125d --- /dev/null +++ "b/docs/03_PLAN/PLAN_01_\350\246\201\344\273\266\345\256\232\347\276\251\346\233\270.md" @@ -0,0 +1,134 @@ +# 要件定義書 (Requirements) + +## プロジェクトの目的 (Purpose) + +舌セグメンテーションモデル(ResUNet)の学習コードを Git で管理し,計算サーバで学習を再現できる状態にする. + +- 学習コードの原本は OneDrive(`OneDrive - 千葉大学\ドキュメント\TongueSegmentation\`)にしか無く,変更履歴が残っていなかった +- 原本のフォルダ全体を本リポジトリの `legacy/` にコピーした(全 331 ファイルのハッシュが原本と一致することを確認済み).以降は `legacy/` を原本とし,OneDrive 側は削除する +- まず原本のコードを**そのまま** Git に入れて出発点を記録し,その上で計算サーバでの再現・TIASDataHub との連携・コード整理を段階的に進める +- 精度の改善(新しいモデルの開発)は本プロジェクトの主目的ではない.再現できる学習基盤を作ることを優先する + +## 対象ユーザー (Target Users) + +- **直接**: 開発者本人(研究用途) +- **間接**: 研究室で舌セグメンテーションを使う人(DeepTIAS・推論サーバーに載せるモデルを再学習する人,後任) + +## 関連するリポジトリ・システム (Related Systems) + +| 名前 | 役割 | 本プロジェクトとの関係 | +| --- | --- | --- | +| OneDrive の原本(`TongueSegmentation\`) | 学習コードの原本(Git 管理なし) | 取り込み元.`legacy/` にコピー済みで,以降は本リポジトリを正とする | +| TIASJudgeModel(`src/tias_judge_model/segmentation/`) | DeepTIAS 2.7 の前処理・後処理の Python 再現と評価(`tias-seg eval`) | 学習したモデルの評価に使う.評価の仕組みは本リポジトリで作り直さない | +| GitBucket `nakaguchi/TongueSegmentation`(中口先生作) | 推論サーバー | 学習したモデル(ONNX)の利用先.本リポジトリでは変更しない | +| DeepTIAS 2.7 | `ResUNet.onnx` を同梱するアプリ | 書き出す ONNX の入出力の形を合わせる相手 | +| TIASDataHub | 臨床データの取り込みとバンドルの作成 | 学習データの受け取り元(今後) | +| 計算サーバ(Newton・Archimedes) | 学習の実行環境 | 学習を再現する場所 | + +## 原本の構成と調査結果 (Survey of the Original) + +原本のコード(.py)と設定(yaml)を読んで分かったこと.データ・重み・`result/` の中身とファイル名は見ていない. +以下のパスは原本のフォルダの中での位置で,本リポジトリでは `legacy/` の下にある(例: `source/main.py` → `legacy/source/main.py`). + +| 場所 | 中身 | 調査結果 | +| --- | --- | --- | +| `source/*.py`(9 個) | 学習・評価・変換のスクリプト | 下表 | +| `source/lightning_logs/version_*/`(43 個) | PyTorch Lightning の実行ログ.`hparams.yaml`・`events.out.tfevents.*`・`checkpoints/`(ckpt) | yaml 43 個は**設定ファイルではなく `Pix2Pix.py` の実行ごとのハイパーパラメータの記録**(`display_step`・`lambda_recon`・`learning_rate` 等).ckpt 20 個もここにある | +| `source/colabs/` | 空 | — | +| `temp/main.py` | `source/main.py` の古い版(PSPNet で学習) | — | +| `segmentation_models/` | segmentation_models_pytorch(smp)0.2.1 のコピー | 公式の 0.2.1 との差分は 2 か所だけ(活性化関数 `clamp` の追加,FPN の `name` を `"FPN-..."` に変更).どちらも本プロジェクトのコードからは使われていないため,**pip の `segmentation-models-pytorch==0.2.1` で置き換えられる** | +| `input/` | 空(0 ファイル) | 学習データは原本のフォルダに無い(研究室 PC にある) | +| `result/`・`output/` | 重み・評価結果・ONNX | 中身は見ていない | + +`source/` の .py の役割: + +| ファイル | 役割 | +| --- | --- | +| `main.py` | 学習と評価を 1 本で行うスクリプト(現状 `UNet_Pruning` を学習.Dice+BCE 損失・Adam・早期終了・テストセットで IoU を計算) | +| `models.py` | モデル定義.`ResNetUNet`(= ResUNet.torchvision の resnet18 を使う),`UNet`・`NestedUNet`・各 `_Pruning` 版・2 タスク版 | +| `losses.py` | 損失関数(Dice・BCE・境界損失の組み合わせ) | +| `utils.py` | 乱数の固定・小領域除去 | +| `evaluation.py` | 学習済みモデルの評価(FPN 等の比較モデル) | +| `pytorchToOnnx.py` | `ResNetUNet` の重みを ONNX(入力 `1×3×256×256`・opset 11)に書き出す | +| `MTL.py` | 2 タスク(セグメンテーション+再構成)の学習・評価 | +| `Pix2Pix.py` | Pix2Pix(PyTorch Lightning)によるセグメンテーション | +| `test.py` | 試し書き(`pandas` の動作確認.このままでは動かない) | + +コードの特徴(計算サーバでの再現・整理で直す対象): + +- データの場所が `..\input\train\{sample,label}`・`..\input\test_extra\cropped\{sample,label}` と相対パス(Windows の区切り文字)で埋め込まれている +- 学習済みの重みの場所が `D:\...\result\CompareModels\<モデル名>\bestModel.pth` と絶対パスで埋め込まれている +- 設定値(バッチサイズ・学習率・エポック数・モデルの種類等)がスクリプトの中に直接書かれている +- `from source.xxx import *` で読み込むため,リポジトリのルートを `sys.path` に入れて実行する前提(PyCharm 等の実行構成) +- 評価結果の `Log_detail.csv` には**画像のファイル名**が 1 行ずつ書かれる(`result/` の csv にファイル名が含まれることをコードで確認した) +- 依存ライブラリのバージョンの記録が無い(smp 0.2.1 が 2021 年 11 月版なので,2021 年末ごろの PyTorch で書かれたと推測) + +## スコープ (Scope) + +### やること (In Scope) + +段階的に進める.各段階の詳細な分割は開発計画(`PLAN_02_開発ステップ.md`)で決める. + +1. **原本の取り込み**: 原本のフォルダを `legacy/` に置き,コードを手を加えずに Git に入れて出発点として記録する(Git に入れる範囲は「管理対象」の表).新しいコードは `legacy/` の外に書き,`legacy/` のコードは書き換えない +2. **計算サーバでの再現**: Newton・Archimedes で学習を再現できるようにする + - 依存ライブラリと Python のバージョンを固定する + - データ・出力・重みの場所を設定ファイルまたは引数で渡せるようにする(埋め込みのパスを無くす) + - `segmentation_models/` のコピーを pip パッケージに置き換える +3. **TIASDataHub との連携**: TIASDataHub が作るバンドルを学習データとして読めるようにする +4. **コード整理**: 学習・評価・ONNX 書き出しを整理し,テストを付ける(挙動は変えない.変える場合は理由を記録する) + +### やらないこと (Out of Scope) + +- 推論サーバー(GitBucket `nakaguchi/TongueSegmentation`)・DeepTIAS の変更 +- DeepTIAS 2.7 の前処理・後処理の再現と評価の作り直し(TIASJudgeModel の `tias-seg eval` を使う) +- 学習データ・正解マスクの管理(研究室 PC と TIASDataHub で管理する) +- 学習済みの重みの管理・配布(研究室 PC・計算サーバに置く) +- 新しいモデル構造の研究開発(必要になったら別途計画する) +- 学習データ・重みを手元 PC に置くこと + +## 管理対象 (What Goes into Git) + +原本のフォルダ全体(重み・結果を含む約 4GB)を `legacy/` に置くが,Git に入れるのは下表の「入れる」だけとする.`.gitignore` で `legacy/` を既定で除外し,入れるものだけを個別に許可している.「入れない」ものは手元 PC の `legacy/` にだけあり,バックアップは別途必要になる. + +| 対象(`legacy/` の下) | 扱い | 理由 | +| --- | --- | --- | +| `source/*.py`(9 個,`test.py` を含む) | 入れる | 学習コードの本体 | +| `temp/main.py` | 入れる | 原本をそのまま残すため(整理の段階で残すか決める) | +| `source/lightning_logs/*/hparams.yaml`(43 個) | 入れる(※ 要確認) | `Pix2Pix.py` の実験条件の記録.ハイパーパラメータの値だけでファイル名・患者情報を含まない | +| `source/lightning_logs/*/events.out.tfevents.*` | 入れない | TensorBoard の実行ログ(バイナリ).ファイル名に実行した PC 名を含む | +| ckpt・pth・pb・onnx(重み) | 入れない | 研究室 PC・計算サーバに置く.配布用の `ResUNet.onnx` も今回は入れない(必要になったら Git LFS を検討する) | +| `result/` の csv・txt | 入れない(ユーザーが中身を確認するまで) | 画像のファイル名(患者 ID の可能性)を含む | +| `segmentation_models/` | 入れない | pip の `segmentation-models-pytorch==0.2.1` で置き換える(差分は使われていない 2 か所のみ) | +| `input/`・`output/` | 入れない | 空のフォルダ・出力(ONNX) | +| `__pycache__/`・`source/colabs/`(空) | 入れない | 生成物・空フォルダ | + +## データの取り扱い (Data Handling) + +- 学習データ(画像・正解マスク)は研究室 PC の `E:\clinical-data\TongueSegmentation\` にある(2390 ファイル.うち `input/` が 1804).**手元 PC には置かない** +- 計算サーバへの受け渡しは,今後 TIASDataHub に取り込んでバンドルで行う(TIASJudgeModel の記録では,同じデータが両サーバの `~/data/TongueSegmentation/input/` に既に置かれている.どちらを正とするかは開発計画で決める) +- Claude はデータの中身・ファイル名を読まない(TIASDataHub のルールと同じ).学習の結果のうちファイル名を含むもの(`Log_detail.csv` 等)も読まない +- 学習で出る結果のファイル(重み・評価結果)はリポジトリの外に出力し,Git に入れない + +## 要件 (Requirements) + +### 機能要件 (Functional Requirements) + +- **R1 原本の記録**: `legacy/` のコードは原本と同じ内容のまま Git に入れる(改行コード以外は変えない).新しいコードは `legacy/` の外に書き,原本のどこを元にしたかを追えるようにする +- **R2 学習の再現**: 計算サーバで,1 つのコマンドと設定ファイルで ResUNet の学習を実行できること(データの場所・出力先・ハイパーパラメータを外から渡す) +- **R3 ONNX の互換性**: 書き出す ONNX が DeepTIAS 2.7 同梱の `ResUNet.onnx` と同じ入出力の形であること(入力 `(1, 3, 256, 256)`・BGR を /255 した値,出力 `(1, 2, 256, 256)`・チャンネル 0 が舌).推論サーバー・DeepTIAS・TIASJudgeModel がそのまま使えるようにするため +- **R4 評価**: 学習したモデルを TIASJudgeModel の `tias-seg eval` で評価できること(本リポジトリでは評価を作り直さない) +- **R5 TIASDataHub の入力**: TIASDataHub のバンドルを学習データとして読めること + +### 非機能要件 (Non-functional Requirements) + +- **再現性**: 乱数の種・依存ライブラリのバージョン・設定ファイルで,同じ条件の学習をやり直せること +- **データの保護**: 学習データ・重み・ファイル名を含む結果がリポジトリに入らないこと(`.gitignore` で防ぐ) +- **挙動の保存**: コード整理で学習の手順(前処理・損失・評価の計算)を変えないこと.変える場合は理由と影響を記録する + +## 未決事項 (Open Questions) + +- `lightning_logs/` の `hparams.yaml` を入れるか(上表では「入れる」とした.Pix2Pix の実験条件の記録としてしか役に立たないため,入れなくてもよい) +- 原作者とライセンス: 原本のコードの作者(埋め込みのパスに前任者の名前がある)と,リポジトリを公開・共有するときの扱い +- 学習データの正: TIASDataHub のバンドルか,計算サーバに既にある `~/data/TongueSegmentation/input/` か +- 原本で最後に配布用 `ResUNet.onnx` を作ったときの学習条件(`main.py` は現状 `UNet_Pruning` を学習する設定になっており,ResUNet の学習条件はコードから確定できない) +- `MTL.py`・`Pix2Pix.py` 等,ResUNet 以外の実験コードを整理の段階で残すか diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 68e9e62..db28cc3 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -9,3 +9,6 @@ - 書式・運用ルールは .claude/rules/progress-log.md を参照 (本ファイルの編集時に自動ロードされる) --> + +- [x] **立ち上げフェーズ 1(方針決定)**: 要件定義書を作成.スコープは原本の取り込み → 計算サーバでの再現 → TIASDataHub 連携 → コード整理の段階式とした.原本のフォルダ全体(約 4GB)は `legacy/` にコピーし(全ファイルのハッシュ一致を確認),Git にはコードと hparams だけを入れる + - 原本の調査: yaml 43 個は設定ではなく `Pix2Pix.py` の lightning_logs の hparams.同梱の smp 0.2.1 は公式との差分が未使用の 2 か所だけで pip に置き換え可能 diff --git a/legacy/source/MTL.py b/legacy/source/MTL.py new file mode 100644 index 0000000..505fe20 --- /dev/null +++ b/legacy/source/MTL.py @@ -0,0 +1,359 @@ +import copy +import datetime +import glob +import os +import time +import cv2 +import matplotlib.pyplot as plt +import torchvision.transforms.functional as TF +import torch +import numpy as np +import pandas as pd +from sklearn.metrics import confusion_matrix +from torch.optim import lr_scheduler +from torch.utils.data import DataLoader +from torchvision import transforms +from tqdm.notebook import tqdm +from source.losses import * +from source.utils import * +from source.models import TwoTaskUNet, TwoTaskResUNet + +class TongueSegAndReconDataset(torch.utils.data.Dataset): + def __init__(self, path_sampleDir, path_labelDir, transform_sample=None, transform_label=None, transform_both=None): + super().__init__() + + self.transform_sample = transform_sample + self.paths_sample = glob.glob(os.path.join(path_sampleDir, '*')) + + self.paths_label_seg = [] + for path_sample in self.paths_sample: + self.paths_label_seg.append(os.path.join(path_labelDir, os.path.basename(path_sample))) + self.transform_label = transform_label + + self.transform_both = transform_both + + def __getitem__(self, index): + + # Load sample + path_sample = self.paths_sample[index] + sample = torch.from_numpy(cv2.imread(path_sample, cv2.IMREAD_COLOR)) / 255.0 + sample = sample.permute(2, 0, 1).float() + if self.transform_sample: + sample = self.transform_sample(sample) + + # Segmentation label + path_label_seg = self.paths_label_seg[index] + label_seg = torch.from_numpy(cv2.imread(path_label_seg, cv2.IMREAD_COLOR)) + label_seg[label_seg <= 128] = 0.0 + label_seg[label_seg > 128] = 1.0 + label_seg = label_seg.permute(2, 0, 1).float() + if self.transform_label: + label_seg = self.transform_label(label_seg) + + if self.transform_both: + for tf, p in self.transform_both: + if random.random() < p: + sample = tf(sample) + label_seg = tf(label_seg) + + label_pos = label_seg[0, :, :] + label_neg = torch.ones(label_pos.shape) - label_seg[0, :, :] + label_pos = label_pos.unsqueeze(0) + label_neg = label_neg.unsqueeze(0) + label_seg = torch.cat([label_pos, label_neg], axis=0) + + # Reconstruction label + label_recon = torch.clone(sample) + + return sample, label_seg, label_recon + + def __len__(self): + return len(self.paths_sample) + +def train(): + # Configs + path_outputDir = os.path.join("..\output", datetime.datetime.now().strftime('%m%d-%H%M%S')) + os.makedirs(path_outputDir) + + # load data train + path_trainSample = os.path.join("..\input", "train", "sample") + path_trainLabel = os.path.join("..\input", "train", "label") + path_testSample = os.path.join("..\input", "test_extra", "cropped", "sample") + path_testLabel = os.path.join("..\input", "test_extra", "cropped", "label") + + # Params + fix_rand(2021) + batch_size = 16 + train_ratio = 2 / 3 + transform_sample = transforms.Compose([transforms.ColorJitter(brightness=0.5, contrast=0.5, saturation=0.5, hue=0.5)]) + transform_label = transforms.Compose([]) + transform_both = [(TF.hflip, 0.5)] + dataset = TongueSegAndReconDataset(path_trainSample, path_trainLabel, transform_sample=transform_sample, + transform_label=transform_label, transform_both=transform_both) + + train_dataset, val_dataset = torch.utils.data.random_split(dataset, + [int(len(dataset) * train_ratio), len(dataset) - int(len(dataset) * train_ratio)]) + data_loader_train = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=0) + data_loader_val = DataLoader(val_dataset, batch_size=batch_size, shuffle=True, num_workers=0) + print("train:", len(train_dataset), " validation:", len(val_dataset)) + + # show + for epoch in range(0, 1): + for inputs, labels_seg, labels_recon in data_loader_train: + input = inputs[0, :, :, :] + label_seg = labels_seg[0, :, :, :] + label_recon = labels_recon[0, :, :, :] + img_input = np.array(input.permute(1, 2, 0)) + plt.imshow(img_input) + plt.show() + img_label_seg = np.array(label_seg[0]) / 255.0 + plt.imshow(img_label_seg) + plt.show() + img_label_recon = np.array(label_recon.permute(1, 2, 0)) + plt.imshow(img_label_recon) + plt.show() + break + + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + learning_rate = 1e-4 + num_epochs = 500 + num_epochsEarlyStop = 30 + + seg_weight = 0.5 + criterion1 = DiceCE(bce_weight=0.5) + criterion2 = nn.MSELoss() + + # create model + fix_rand(2021) + model = TwoTaskResUNet(n_class=2) + model = model.to(device) + optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) + # scheduler = lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.1) # is not used + # パラメータカウント + params = 0 + for p in model.parameters(): + if p.requires_grad: + params += p.numel() + print("params: ", params) + + since = time.time() + best_model_wts = copy.deepcopy(model.state_dict()) + best_model_epochs = 0 + best_loss = 1e5 + losses_train = [] + losses_val = [] + for epoch in tqdm(range(num_epochs)): + print('Epoch {}/{}'.format(epoch + 1, num_epochs)) + print('-' * 10) + + # Each epoch has a training and validation phase + for phase in ['train', 'val']: + + if phase == 'train': + model.train() # Set model to training mode + + # Iterate over data. + running_loss = 0.0 + for inputs, labels_seg, labels_recon in data_loader_train: + inputs = inputs.to(device) + labels_seg = labels_seg.to(device) + labels_recon = labels_recon.to(device) + + # zero the parameter gradients + optimizer.zero_grad() + + # forward + # track history if only in train + with torch.set_grad_enabled(phase == 'train'): + outputs = model(inputs) + loss1 = criterion1(outputs[0], labels_seg) + loss2 = criterion2(outputs[1], labels_recon) + loss = (seg_weight * loss1) + ((1.0 - seg_weight) * loss2) + + loss.backward() + optimizer.step() + + # statistics + running_loss += loss.item() + + epoch_loss = running_loss / len(data_loader_train) + losses_train.append(epoch_loss) + + else: + model.eval() # Set model to evaluate mode + + # Iterate over data. + running_loss = 0.0 + for inputs, labels_seg, labels_recon in data_loader_val: + inputs = inputs.to(device) + labels_seg = labels_seg.to(device) + labels_recon = labels_recon.to(device) + + # zero the parameter gradients + optimizer.zero_grad() + + # forward + # track history if only in train + with torch.set_grad_enabled(phase == 'train'): + outputs = model(inputs) + loss1 = criterion1(outputs[0], labels_seg) + loss2 = criterion2(outputs[1], labels_recon) + loss = (seg_weight * loss1) + ((1.0 - seg_weight) * loss2) + + # statistics + running_loss += loss.item() + + epoch_loss = running_loss / len(data_loader_val) + losses_val.append(epoch_loss) + # scheduler.step() + + print('{} Loss: {:.4f}'.format(phase, epoch_loss)) + + # Todo: early stopping, and metrics + # deep copy the model + if phase == 'val' and epoch_loss < best_loss: + best_loss = epoch_loss + best_model_wts = copy.deepcopy(model.state_dict()) + # torch.save(model.state_dict(), path_outputDir + r"/epoch" + str(epoch) + ".pth") + best_model_epochs = epoch + print("best model saved") + + if (epoch - best_model_epochs) >= num_epochsEarlyStop: + break + + time_elapsed = time.time() - since + print('Training complete in {:.0f}m {:.0f}s'.format( + time_elapsed // 60, time_elapsed % 60)) + print('Best val Loss: {:4f}'.format(best_loss)) + + # load best model weights + model.load_state_dict(best_model_wts) + torch.save(model.state_dict(), path_outputDir + r"/bestModel.pth") + + # lossの可視化 + plt.plot(losses_train, label='training loss') + plt.plot(losses_val, label='validation loss') + plt.ylabel("loss") + plt.xlabel("epoch time") + # plt.ylim(0, 0.35) + plt.savefig(path_outputDir + "/loss.png") + plt.legend() + plt.show() + + # Evaluation + dataset_test = TongueSegAndReconDataset(path_testSample, path_testLabel) + data_loader_test = DataLoader(dataset_test, batch_size=1, shuffle=False) + + model.eval() + shouldShow = True + ious = [] + for i, data in tqdm(enumerate(data_loader_test, 0)): + name = os.path.splitext(os.path.basename(glob.glob(path_testSample + "/*")[i]))[0] + + inputs = data[0].to(device) + labels_seg = data[1] + labels_recon = data[2] + outputs_seg, outputs_recon = model(inputs) + + input = inputs[0].permute(1, 2, 0).cpu().detach().numpy() + label_seg = labels_seg[0].permute(1, 2, 0).detach().numpy() + label_recon = labels_recon[0].permute(1, 2, 0).detach().numpy() + output_seg = outputs_seg[0].sigmoid().permute(1, 2, 0).cpu().detach().numpy() + output_recon = outputs_recon[0].permute(1, 2, 0).cpu().detach().numpy() + if shouldShow and i == 0: + plt.imshow(input) + plt.title("input") + plt.show() + + plt.imshow(label_seg[:, :, 0]) + plt.title("segmentation label") + plt.show() + plt.imshow(output_seg[:, :, 0]) + plt.title("segmentation output") + plt.show() + + plt.imshow(label_recon) + plt.title("reconstruction label") + plt.show() + plt.imshow(output_recon) + plt.title("reconstruction label") + plt.show() + break + +def evaluate(): + fix_rand(2021) + + # load data train + path_model = r"D:\Noguchi\Solution\TongueSegmentation\result\CompareModels\TwoTaskUNet\bestModel.pth" + path_outputDir = os.path.dirname(path_model) + path_testSample = os.path.join("..\input", "test_extra", "cropped", "sample") + path_testLabel = os.path.join("..\input", "test_extra", "cropped", "label") + + # Evaluation + dataset_test = TongueSegAndReconDataset(path_testSample, path_testLabel) + data_loader_test = DataLoader(dataset_test, batch_size=1, shuffle=False) + + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + model = TwoTaskUNet(n_class=2) + model.load_state_dict(torch.load(path_model)) + model = model.to(device) + model.eval() + + shouldShow = True + df = pd.DataFrame() + for i, data in tqdm(enumerate(data_loader_test, 0)): + name = os.path.splitext(os.path.basename(glob.glob(path_testSample + "/*")[i]))[0] + + inputs = data[0].to(device) + labels_seg = data[1] + labels_recon = data[2] + outputs_seg, outputs_recon = model(inputs) + + input = inputs[0].permute(1, 2, 0).cpu().detach().numpy() + label_seg = labels_seg[0].permute(1, 2, 0).detach().numpy()[:, :, 0] + label_recon = labels_recon[0].permute(1, 2, 0).detach().numpy() + output_seg = outputs_seg[0].sigmoid().permute(1, 2, 0).cpu().detach().numpy()[:, :, 0] + output_recon = outputs_recon[0].permute(1, 2, 0).cpu().detach().numpy() + + img_pred = (output_seg * 255).astype(np.uint8) + ret, img_pred = cv2.threshold(img_pred, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) + + # スコア計算 + y_pred = (img_pred / 255).flatten() + y_true = label_seg.flatten() + tn, fp, fn, tp = confusion_matrix(y_pred, y_true).ravel() + iou_tp = tp / (tp + fp + fn) + r = pd.DataFrame([name, tn, fp, fn, tp, iou_tp]).T + df = pd.concat([df, r], axis=0) + + if shouldShow and i == 153: + plt.imshow(input) + plt.title("input") + plt.show() + + plt.imshow(label_seg) + plt.title("segmentation label") + plt.show() + plt.imshow(output_seg) + plt.title("segmentation output") + plt.show() + + plt.imshow(label_recon) + plt.title("reconstruction label") + plt.show() + + plt.imshow(output_recon) + plt.title("reconstruction output") + plt.show() + + df.columns = ["name", "tn", "fp", "fn", "tp", "iou_tp"] + mean = pd.DataFrame(df.mean(axis=0)).T + df = pd.concat([df, mean]) + + df.to_csv(path_outputDir + r'/Log_detail.csv', index=False) + + print("全体平均:", df["iou_tp"].to_numpy()[-1]) +if __name__ == '__main__': + # train() + evaluate() + diff --git a/legacy/source/Pix2Pix.py b/legacy/source/Pix2Pix.py new file mode 100644 index 0000000..bcc1c9a --- /dev/null +++ b/legacy/source/Pix2Pix.py @@ -0,0 +1,353 @@ +import copy +import datetime +import glob +import os +import time +import cv2 +import matplotlib.pyplot as plt +import torchvision.transforms.functional as TF +import torch +import numpy as np +from sklearn.metrics import confusion_matrix +from torch.optim import lr_scheduler +from torch.utils.data import DataLoader +from torchvision import transforms +from tqdm.notebook import tqdm +from source.losses import * +from source.models import * +from source.utils import * +import pytorch_lightning as pl +from pytorch_lightning.callbacks.early_stopping import EarlyStopping +from pytorch_lightning.callbacks.model_checkpoint import ModelCheckpoint +from source.losses import * +import pandas as pd + +class DownSampleConv(nn.Module): + + def __init__(self, in_channels, out_channels, kernel=4, strides=2, padding=1, activation=True, batchnorm=True): + """ + Paper details: + - C64-C128-C256-C512-C512-C512-C512-C512 + - All convolutions are 4×4 spatial filters applied with stride 2 + - Convolutions in the encoder downsample by a factor of 2 + """ + super().__init__() + self.activation = activation + self.batchnorm = batchnorm + + self.conv = nn.Conv2d(in_channels, out_channels, kernel, strides, padding) + + if batchnorm: + self.bn = nn.BatchNorm2d(out_channels) + + if activation: + self.act = nn.LeakyReLU(0.2) + + def forward(self, x): + x = self.conv(x) + if self.batchnorm: + x = self.bn(x) + if self.activation: + x = self.act(x) + return x + +class PatchGAN(nn.Module): + + def __init__(self, input_channels): + super().__init__() + self.d1 = DownSampleConv(input_channels, 64, batchnorm=False) + self.d2 = DownSampleConv(64, 128) + self.d3 = DownSampleConv(128, 256) + self.d4 = DownSampleConv(256, 512) + self.final = nn.Conv2d(512, 1, kernel_size=1) + + def forward(self, x, y): + x = torch.cat([x, y], axis=1) + x0 = self.d1(x) + x1 = self.d2(x0) + x2 = self.d3(x1) + x3 = self.d4(x2) + xn = self.final(x3) + return xn + + +# collapse-hide +# https://stackoverflow.com/questions/49433936/how-to-initialize-weights-in-pytorch + +def _weights_init(m): + if isinstance(m, (nn.Conv2d, nn.ConvTranspose2d)): + torch.nn.init.normal_(m.weight, 0.0, 0.02) + if isinstance(m, nn.BatchNorm2d): + torch.nn.init.normal_(m.weight, 0.0, 0.02) + torch.nn.init.constant_(m.bias, 0) + + +def display_progress(cond, fake, real, figsize=(10, 5)): + cond = cond.detach().cpu().permute(1, 2, 0) + fake = fake.detach().cpu().permute(1, 2, 0) + real = real.detach().cpu().permute(1, 2, 0) + + fig, ax = plt.subplots(1, 3, figsize=figsize) + ax[0].imshow(cond) + ax[1].imshow(real) + ax[2].imshow(fake.sigmoid()) + plt.show() + + +class Pix2Pix(pl.LightningModule): + + def __init__(self, in_channels, out_channels, learning_rate=0.0002, lambda_recon=200, display_step=25, pruning=False): + + super().__init__() + self.save_hyperparameters() + + self.display_step = display_step + if pruning: + self.gen = UNet_Pruning(n_class=out_channels) + else: + self.gen = UNet(n_class=out_channels) + + self.patch_gan = PatchGAN(in_channels + out_channels) + + # intializing weights + self.gen = self.gen.apply(_weights_init) + self.patch_gan = self.patch_gan.apply(_weights_init) + + # self.adversarial_criterion = nn.BCEWithLogitsLoss() + self.adversarial_criterion = DiceCE(bce_weight=0.5) + self.recon_criterion = nn.L1Loss() + + def _gen_step(self, real_images, conditioned_images): + # Pix2Pix has adversarial and a reconstruction loss + # First calculate the adversarial loss + fake_images = self.gen(conditioned_images) + disc_logits = self.patch_gan(fake_images, conditioned_images) + adversarial_loss = self.adversarial_criterion(disc_logits, torch.ones_like(disc_logits)) + + # calculate reconstruction loss + recon_loss = self.recon_criterion(fake_images, real_images) + lambda_recon = self.hparams.lambda_recon + + return adversarial_loss + lambda_recon * recon_loss + + def _disc_step(self, real_images, conditioned_images): + fake_images = self.gen(conditioned_images).detach() + fake_logits = self.patch_gan(fake_images, conditioned_images) + + real_logits = self.patch_gan(real_images, conditioned_images) + + fake_loss = self.adversarial_criterion(fake_logits, torch.zeros_like(fake_logits)) + real_loss = self.adversarial_criterion(real_logits, torch.ones_like(real_logits)) + return (real_loss + fake_loss) / 2 + + def configure_optimizers(self): + lr = self.hparams.learning_rate + gen_opt = torch.optim.Adam(self.gen.parameters(), lr=lr) + disc_opt = torch.optim.Adam(self.patch_gan.parameters(), lr=lr) + return disc_opt, gen_opt + + def training_step(self, batch, batch_idx, optimizer_idx): + condition, real = batch + + loss = None + if optimizer_idx == 0: + loss = self._disc_step(real, condition) + self.log('PatchGAN Loss', loss) + elif optimizer_idx == 1: + loss = self._gen_step(real, condition) + self.log('Generator Loss', loss) + + if self.current_epoch % self.display_step == 0 and batch_idx == 0 and optimizer_idx == 1: + fake = self.gen(condition).detach() + display_progress(condition[0], fake[0], real[0]) + return loss + + +class TongueSegDataset(torch.utils.data.Dataset): + def __init__(self, path_sampleDir, path_labelDir, transform_sample=None, transform_label=None, transform_both=None): + super().__init__() + + self.transform_sample = transform_sample + self.paths_sample = glob.glob(os.path.join(path_sampleDir, '*')) + + self.paths_label = [] + for path_sample in self.paths_sample: + self.paths_label.append(os.path.join(path_labelDir, os.path.basename(path_sample))) + self.transform_label = transform_label + + self.transform_both = transform_both + + def __getitem__(self, index): + + # Load sample + path_sample = self.paths_sample[index] + sample = torch.from_numpy(cv2.imread(path_sample, cv2.IMREAD_COLOR)) / 255.0 + sample = sample.permute(2, 0, 1).float() + if self.transform_sample: + sample = self.transform_sample(sample) + + # Load label + path_label = self.paths_label[index] + label = torch.from_numpy(cv2.imread(path_label, cv2.IMREAD_COLOR)) + label[label <= 128] = 0.0 + label[label > 128] = 1.0 + label = label.permute(2, 0, 1).float() + if self.transform_label: + label = self.transform_label(label) + + if self.transform_both: + for tf, p in self.transform_both: + if random.random() < p: + sample = tf(sample) + label = tf(label) + + # label_pos = label[0, :, :] + # label_neg = torch.ones(label_pos.shape) - label[0, :, :] + # label_pos = label_pos.unsqueeze(0) + # label_neg = label_neg.unsqueeze(0) + # label = torch.cat([label_pos, label_neg], axis=0) + return sample, label + + def __len__(self): + return len(self.paths_sample) + +def train(): + # Configs + path_outputDir = os.path.join("..\output", datetime.datetime.now().strftime('%m%d-%H%M%S')) + os.makedirs(path_outputDir) + + # load data train + path_trainSample = os.path.join("..\input", "train", "sample") + path_trainLabel = os.path.join("..\input", "train", "label") + path_testSample = os.path.join("..\input", "test_extra", "cropped", "sample") + path_testLabel = os.path.join("..\input", "test_extra", "cropped", "label") + + # Params + fix_rand(2021) + train_ratio = 2 / 3 + num_epochs = 300 + num_epochsEarlyStop = 30 + display_step = 5 + lambda_recon = 100 + batch_size = 16 + lr = 0.0001 + target_size = 256 + transform_sample = transforms.Compose([transforms.ColorJitter(brightness=0.5, contrast=0.5, saturation=0.5, hue=0.5)]) + transform_label = transforms.Compose([]) + transform_both = [(TF.hflip, 0.5)] + dataset = TongueSegDataset(path_trainSample, path_trainLabel, transform_sample=transform_sample, + transform_label=transform_label, transform_both=transform_both) + + train_dataset, val_dataset = torch.utils.data.random_split(dataset, + [int(len(dataset) * train_ratio), len(dataset) - int(len(dataset) * train_ratio)]) + data_loader_train = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=0) + data_loader_val = DataLoader(val_dataset, batch_size=batch_size, shuffle=True, num_workers=0) + print("train:", len(train_dataset), " validation:", len(val_dataset)) + + pix2pix = Pix2Pix(3, 3, pruning=True, learning_rate=lr, lambda_recon=lambda_recon, display_step=display_step) + early_stop_callback = EarlyStopping(monitor="PatchGAN Loss", patience=num_epochsEarlyStop) + trainer = pl.Trainer(max_epochs=num_epochs, gpus=1, callbacks=[early_stop_callback], log_every_n_steps=16,) + trainer.fit(pix2pix, train_dataloader=data_loader_train, val_dataloaders=data_loader_val) + torch.save(pix2pix.state_dict(), path_outputDir + r"/bestModel.pth") + +def eval(): + fix_rand(2021) + path_outputDir = os.path.join("..\output", datetime.datetime.now().strftime('%m%d-%H%M%S')) + os.makedirs(path_outputDir) + path_testSample = os.path.join("..\input", "test_extra", "cropped", "sample") + path_testLabel = os.path.join("..\input", "test_extra", "cropped", "label") + dataset_test = TongueSegDataset(path_testSample, path_testLabel) + data_loader_test = DataLoader(dataset_test, batch_size=1, shuffle=False) + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + + path_model = r"D:\Noguchi\Solution\TongueSegmentation\result\CompareModels\Pix2Pix_Pruning\bestModel.pth" + model = Pix2Pix(3, 3, pruning=True) + # パラメータカウント + params = 0 + for p in model.parameters(): + params += p.numel() + print("params: ", params) + model.load_state_dict(torch.load(path_model)) + model = model.gen + model.to(device) + + + + # 推論時間計測 + since = time.perf_counter() + for repeated in range(10): + for i, data in enumerate(data_loader_test, 0): + inputs = data[0].to(device) + labels = data[1].to(device) + outputs = model(inputs).sigmoid() + pred = outputs.permute(0, 2, 3, 1).to('cpu').detach().numpy()[0, :, :, 0] + ret, img_pred = cv2.threshold((pred * 255).astype(np.uint8), 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) + time_elapsed = (time.perf_counter() - since) / 10.0 + print("time: ", time_elapsed) + + with open(path_outputDir + r'/test_time¶ms.csv', 'x', encoding='utf-8') as f: + f.write("time," + str(time_elapsed) + "\n") + f.write("params," + str(params) + "\n") + + # Evaluation + shouldSave = True + shouldShow = False + ious = [] + df = pd.DataFrame() + for i, data in tqdm(enumerate(data_loader_test, 0)): + name = os.path.splitext(os.path.basename(glob.glob(path_testSample + "/*")[i]))[0] + + inputs = data[0].to(device) + labels = data[1].to(device) + outputs = model(inputs).sigmoid() + + pred = outputs.permute(0, 2, 3, 1).to('cpu').detach().numpy()[0, :, :, :] + pred = cv2.cvtColor(pred, cv2.COLOR_BGR2GRAY) + true = labels.permute(0, 2, 3, 1).to('cpu').detach().numpy()[0, :, :, 0] + + img_pred = (pred * 255).astype(np.uint8) + # otsu + ret, img_pred = cv2.threshold(img_pred, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) + + y_pred = (img_pred / 255).flatten() + y_true = true.flatten() + tn, fp, fn, tp = confusion_matrix(y_pred, y_true).ravel() + + iou_tp = tp / (tp + fp + fn) + + ious.append(iou_tp) + + r = pd.DataFrame([name, tn, fp, fn, tp, iou_tp]).T + df = pd.concat([df, r], axis=0) + + if shouldSave and (i >= 175 or i ==153 or i==150): + num_output = outputs.permute(0, 2, 3, 1).to('cpu').detach().numpy()[0, :, :, 0] + plt.axis("off") + plt.imshow(img_pred) + cv2.imwrite(path_outputDir + r"/" + str(i + 1) + ".png", img_pred) + + if os.path.exists(path_outputDir + r'/Log_detail.csv'): + with open(path_outputDir + r'/Log_detail.csv', 'a', encoding='utf-8') as f: + f.write(name + ", " + str(iou_tp) + "\n") + else: + with open(path_outputDir + r'/Log_detail.csv', 'x', encoding='utf-8') as f: + f.write(name + ", " + str(iou_tp) + "\n") + + df.columns = ["name", "tn", "fp", "fn", "tp", "iou_tp"] + mean = pd.DataFrame(df.mean(axis=0)).T + df = pd.concat([df, mean]) + df.to_csv(path_outputDir + r'/Log_detail.csv', index=False) + # + print("全体平均:", np.array(ious).mean()) + if os.path.exists(path_outputDir + r'/Log.txt'): + with open(path_outputDir + r'/Log.txt', 'w', encoding='utf-8') as f: + s = f.write("全体平均:" + str(np.array(ious).mean())) + else: + with open(path_outputDir + r'/Log.txt', 'x', encoding='utf-8') as f: + s = f.write("全体平均:" + str(np.array(ious).mean())) + +# TODO early stoppingした時や,いい感じのlossでモデルを随時保存する +# check point call back で実装できるが,データ構造が嫌いなので,スクラッチで実装したい. +# あと,間違えて出力がカラーになるように構築してしまったが,2 or 1でよい +# train() +eval() diff --git a/legacy/source/evaluation.py b/legacy/source/evaluation.py new file mode 100644 index 0000000..060b66d --- /dev/null +++ b/legacy/source/evaluation.py @@ -0,0 +1,184 @@ +import glob +import time +import cv2 +import matplotlib.pyplot as plt +import pandas as pd +import numpy as np +from sklearn.metrics import confusion_matrix +from torch.utils.data import DataLoader +from tqdm import tqdm +from source.utils import * +from source.models import * +from segmentation_models.segmentation_models_pytorch.pspnet import PSPNet +from segmentation_models.segmentation_models_pytorch.deeplabv3 import DeepLabV3Plus +from segmentation_models.segmentation_models_pytorch.pspnet import PSPNet +from segmentation_models.segmentation_models_pytorch.fpn import FPN + +class TongueSegDataset(torch.utils.data.Dataset): + def __init__(self, path_sampleDir, path_labelDir, transform_sample=None, transform_label=None, transform_both=None): + super().__init__() + + self.transform_sample = transform_sample + self.paths_sample = glob.glob(os.path.join(path_sampleDir, '*')) + + self.paths_label = [] + for path_sample in self.paths_sample: + self.paths_label.append(os.path.join(path_labelDir, os.path.basename(path_sample))) + self.transform_label = transform_label + + self.transform_both = transform_both + + def __getitem__(self, index): + + # Load sample + path_sample = self.paths_sample[index] + sample = torch.from_numpy(cv2.imread(path_sample, cv2.IMREAD_COLOR)) / 255.0 + sample = sample.permute(2, 0, 1).float() + if self.transform_sample: + sample = self.transform_sample(sample) + + # Load label + path_label = self.paths_label[index] + label = torch.from_numpy(cv2.imread(path_label, cv2.IMREAD_COLOR)) + label[label <= 128] = 0.0 + label[label > 128] = 1.0 + label = label.permute(2, 0, 1).float() + if self.transform_label: + label = self.transform_label(label) + + if self.transform_both: + for tf, p in self.transform_both: + if random.random() < p: + sample = tf(sample) + label = tf(label) + + label_pos = label[0, :, :] + label_neg = torch.ones(label_pos.shape) - label[0, :, :] + label_pos = label_pos.unsqueeze(0) + label_neg = label_neg.unsqueeze(0) + label = torch.cat([label_pos, label_neg], axis=0) + return sample, label + + def __len__(self): + return len(self.paths_sample) + +fix_rand(2021) + +# load data train +path_testSample = os.path.join("..\input", "test_extra", "cropped", "sample") +path_testLabel = os.path.join("..\input", "test_extra", "cropped", "label") + +dataset_test = TongueSegDataset(path_testSample, path_testLabel) +data_loader_test = DataLoader(dataset_test, batch_size=1, shuffle=False) + +device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + +# CHANGE THAT +shouldSave = True +model_path = r"D:\Noguchi\Solution\TongueSegmentation\result\CompareModels\FPN\bestModel.pth" +model = FPN(classes=2) + +# outputpath +path_outputDir = os.path.dirname(model_path) + +# model load +model.load_state_dict(torch.load(model_path)) +model = model.to(device) +model.eval() + +# # パラメータカウント +# params = 0 +# for p in model.parameters(): +# params += p.numel() +# print("params: ", params) +# +# # 推論時間計測 +# since = time.perf_counter() +# for repeated in range(10): +# for i, data in enumerate(data_loader_test, 0): +# inputs = data[0].to(device) +# labels = data[1].to(device) +# outputs = model(inputs).sigmoid() +# pred = outputs.permute(0, 2, 3, 1).to('cpu').detach().numpy()[0, :, :, 0] +# ret, img_pred = cv2.threshold((pred * 255).astype(np.uint8), 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) +# time_elapsed = (time.perf_counter() - since) / 10.0 +# print("time: ", time_elapsed) +# +# with open(path_outputDir + r'/test_time¶ms.csv', 'x', encoding='utf-8') as f: +# f.write("time," + str(time_elapsed) + "\n") +# f.write("params," + str(params) + "\n") + + +shouldShow = True +df = pd.DataFrame() +df_refined = pd.DataFrame() +for i, data in tqdm(enumerate(data_loader_test, 0)): + name = os.path.splitext(os.path.basename(glob.glob(path_testSample + "/*")[i]))[0] + + inputs = data[0].to(device) + labels = data[1].to(device) + outputs = model(inputs).sigmoid() + + pred = outputs.permute(0, 2, 3, 1).to('cpu').detach().numpy()[0, :, :, 0] + true = labels.permute(0, 2, 3, 1).to('cpu').detach().numpy()[0, :, :, 0] + + img_pred = (pred * 255).astype(np.uint8) + # otsu + ret, img_pred = cv2.threshold(img_pred, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) + + # スコア計算 + y_pred = (img_pred / 255).flatten() + y_true = true.flatten() + tn, fp, fn, tp = confusion_matrix(y_pred, y_true).ravel() + iou_tp = tp / (tp + fp + fn) + r = pd.DataFrame([name, tn, fp, fn, tp, iou_tp]).T + df = pd.concat([df, r], axis=0) + + # ノイズ除去 Remove small regions + img_pred_refined = img_pred.copy() + contours = cv2.findContours(img_pred_refined, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0] + # 一番面積が大きい輪郭を選択する。 + max_cnt = max(contours, key=lambda x: cv2.contourArea(x)) + # 黒い画像に一番大きい輪郭だけ塗りつぶして描画する。 + img_pred_refined = np.zeros_like(img_pred_refined) + cv2.drawContours(img_pred_refined, [max_cnt], -1, color=255, thickness=-1) + # スコア計算 + y_pred_refined = (img_pred_refined / 255).flatten() + tn, fp, fn, tp = confusion_matrix(y_pred_refined, y_true).ravel() + iou_tp = tp / (tp + fp + fn) + r = pd.DataFrame([name, tn, fp, fn, tp, iou_tp]).T + df_refined = pd.concat([df_refined, r], axis=0) + + if shouldSave and i >= 153: + cv2.imwrite(path_outputDir + r"/" + str(i + 1) + ".png", img_pred) + cv2.imwrite(path_outputDir + r"/" + str(i + 1) + "_refined.png", img_pred_refined) + + if shouldShow and i == 153: + img_input = inputs.permute(0, 2, 3, 1).to('cpu').detach().numpy()[0] + plt.imshow(img_input) + plt.show() + + img_label = labels.permute(0, 2, 3, 1).to('cpu').detach().numpy()[0, :, :, 0] + plt.imshow(img_label) + plt.show() + + plt.imshow(img_pred) + plt.show() + + plt.imshow(img_pred_refined) + plt.show() + +df.columns = ["name", "tn", "fp", "fn", "tp", "iou_tp"] +mean = pd.DataFrame(df.mean(axis=0)).T +df = pd.concat([df, mean]) +if shouldSave: + df.to_csv(path_outputDir + r'/Log_detail.csv', index=False) + +df_refined.columns = ["name", "tn", "fp", "fn", "tp", "iou_tp"] +mean = pd.DataFrame(df_refined.mean(axis=0)).T +df_refined = pd.concat([df_refined, mean]) +if shouldSave: + df_refined.to_csv(path_outputDir + r'/Log_detail_refined.csv', index=False) + +print("全体平均:", df["iou_tp"].to_numpy()[-1]) +print("全体平均 ノイズ除去後:", df_refined["iou_tp"].to_numpy()[-1]) diff --git a/legacy/source/lightning_logs/version_0/hparams.yaml b/legacy/source/lightning_logs/version_0/hparams.yaml new file mode 100644 index 0000000..9887594 --- /dev/null +++ b/legacy/source/lightning_logs/version_0/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 100 +in_channels: 3 +lambda_recon: 200 +learning_rate: 0.0001 +out_channels: 3 diff --git a/legacy/source/lightning_logs/version_1/hparams.yaml b/legacy/source/lightning_logs/version_1/hparams.yaml new file mode 100644 index 0000000..cb2362a --- /dev/null +++ b/legacy/source/lightning_logs/version_1/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 100 +in_channels: 3 +lambda_recon: 200 +learning_rate: 0.0001 +out_channels: 2 diff --git a/legacy/source/lightning_logs/version_10/hparams.yaml b/legacy/source/lightning_logs/version_10/hparams.yaml new file mode 100644 index 0000000..cb2362a --- /dev/null +++ b/legacy/source/lightning_logs/version_10/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 100 +in_channels: 3 +lambda_recon: 200 +learning_rate: 0.0001 +out_channels: 2 diff --git a/legacy/source/lightning_logs/version_11/hparams.yaml b/legacy/source/lightning_logs/version_11/hparams.yaml new file mode 100644 index 0000000..cb2362a --- /dev/null +++ b/legacy/source/lightning_logs/version_11/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 100 +in_channels: 3 +lambda_recon: 200 +learning_rate: 0.0001 +out_channels: 2 diff --git a/legacy/source/lightning_logs/version_12/hparams.yaml b/legacy/source/lightning_logs/version_12/hparams.yaml new file mode 100644 index 0000000..cb2362a --- /dev/null +++ b/legacy/source/lightning_logs/version_12/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 100 +in_channels: 3 +lambda_recon: 200 +learning_rate: 0.0001 +out_channels: 2 diff --git a/legacy/source/lightning_logs/version_13/hparams.yaml b/legacy/source/lightning_logs/version_13/hparams.yaml new file mode 100644 index 0000000..cb2362a --- /dev/null +++ b/legacy/source/lightning_logs/version_13/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 100 +in_channels: 3 +lambda_recon: 200 +learning_rate: 0.0001 +out_channels: 2 diff --git a/legacy/source/lightning_logs/version_14/hparams.yaml b/legacy/source/lightning_logs/version_14/hparams.yaml new file mode 100644 index 0000000..9887594 --- /dev/null +++ b/legacy/source/lightning_logs/version_14/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 100 +in_channels: 3 +lambda_recon: 200 +learning_rate: 0.0001 +out_channels: 3 diff --git a/legacy/source/lightning_logs/version_15/hparams.yaml b/legacy/source/lightning_logs/version_15/hparams.yaml new file mode 100644 index 0000000..9887594 --- /dev/null +++ b/legacy/source/lightning_logs/version_15/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 100 +in_channels: 3 +lambda_recon: 200 +learning_rate: 0.0001 +out_channels: 3 diff --git a/legacy/source/lightning_logs/version_16/hparams.yaml b/legacy/source/lightning_logs/version_16/hparams.yaml new file mode 100644 index 0000000..9887594 --- /dev/null +++ b/legacy/source/lightning_logs/version_16/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 100 +in_channels: 3 +lambda_recon: 200 +learning_rate: 0.0001 +out_channels: 3 diff --git a/legacy/source/lightning_logs/version_17/hparams.yaml b/legacy/source/lightning_logs/version_17/hparams.yaml new file mode 100644 index 0000000..9887594 --- /dev/null +++ b/legacy/source/lightning_logs/version_17/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 100 +in_channels: 3 +lambda_recon: 200 +learning_rate: 0.0001 +out_channels: 3 diff --git a/legacy/source/lightning_logs/version_18/hparams.yaml b/legacy/source/lightning_logs/version_18/hparams.yaml new file mode 100644 index 0000000..3e96dd0 --- /dev/null +++ b/legacy/source/lightning_logs/version_18/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 1 +in_channels: 3 +lambda_recon: 200 +learning_rate: 0.0001 +out_channels: 3 diff --git a/legacy/source/lightning_logs/version_19/hparams.yaml b/legacy/source/lightning_logs/version_19/hparams.yaml new file mode 100644 index 0000000..3e96dd0 --- /dev/null +++ b/legacy/source/lightning_logs/version_19/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 1 +in_channels: 3 +lambda_recon: 200 +learning_rate: 0.0001 +out_channels: 3 diff --git a/legacy/source/lightning_logs/version_2/hparams.yaml b/legacy/source/lightning_logs/version_2/hparams.yaml new file mode 100644 index 0000000..cb2362a --- /dev/null +++ b/legacy/source/lightning_logs/version_2/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 100 +in_channels: 3 +lambda_recon: 200 +learning_rate: 0.0001 +out_channels: 2 diff --git a/legacy/source/lightning_logs/version_20/hparams.yaml b/legacy/source/lightning_logs/version_20/hparams.yaml new file mode 100644 index 0000000..3e96dd0 --- /dev/null +++ b/legacy/source/lightning_logs/version_20/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 1 +in_channels: 3 +lambda_recon: 200 +learning_rate: 0.0001 +out_channels: 3 diff --git a/legacy/source/lightning_logs/version_21/hparams.yaml b/legacy/source/lightning_logs/version_21/hparams.yaml new file mode 100644 index 0000000..3e96dd0 --- /dev/null +++ b/legacy/source/lightning_logs/version_21/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 1 +in_channels: 3 +lambda_recon: 200 +learning_rate: 0.0001 +out_channels: 3 diff --git a/legacy/source/lightning_logs/version_22/hparams.yaml b/legacy/source/lightning_logs/version_22/hparams.yaml new file mode 100644 index 0000000..3e96dd0 --- /dev/null +++ b/legacy/source/lightning_logs/version_22/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 1 +in_channels: 3 +lambda_recon: 200 +learning_rate: 0.0001 +out_channels: 3 diff --git a/legacy/source/lightning_logs/version_23/hparams.yaml b/legacy/source/lightning_logs/version_23/hparams.yaml new file mode 100644 index 0000000..3e96dd0 --- /dev/null +++ b/legacy/source/lightning_logs/version_23/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 1 +in_channels: 3 +lambda_recon: 200 +learning_rate: 0.0001 +out_channels: 3 diff --git a/legacy/source/lightning_logs/version_24/hparams.yaml b/legacy/source/lightning_logs/version_24/hparams.yaml new file mode 100644 index 0000000..3e96dd0 --- /dev/null +++ b/legacy/source/lightning_logs/version_24/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 1 +in_channels: 3 +lambda_recon: 200 +learning_rate: 0.0001 +out_channels: 3 diff --git a/legacy/source/lightning_logs/version_25/hparams.yaml b/legacy/source/lightning_logs/version_25/hparams.yaml new file mode 100644 index 0000000..3e96dd0 --- /dev/null +++ b/legacy/source/lightning_logs/version_25/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 1 +in_channels: 3 +lambda_recon: 200 +learning_rate: 0.0001 +out_channels: 3 diff --git a/legacy/source/lightning_logs/version_26/hparams.yaml b/legacy/source/lightning_logs/version_26/hparams.yaml new file mode 100644 index 0000000..3e96dd0 --- /dev/null +++ b/legacy/source/lightning_logs/version_26/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 1 +in_channels: 3 +lambda_recon: 200 +learning_rate: 0.0001 +out_channels: 3 diff --git a/legacy/source/lightning_logs/version_27/hparams.yaml b/legacy/source/lightning_logs/version_27/hparams.yaml new file mode 100644 index 0000000..3e96dd0 --- /dev/null +++ b/legacy/source/lightning_logs/version_27/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 1 +in_channels: 3 +lambda_recon: 200 +learning_rate: 0.0001 +out_channels: 3 diff --git a/legacy/source/lightning_logs/version_28/hparams.yaml b/legacy/source/lightning_logs/version_28/hparams.yaml new file mode 100644 index 0000000..3e96dd0 --- /dev/null +++ b/legacy/source/lightning_logs/version_28/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 1 +in_channels: 3 +lambda_recon: 200 +learning_rate: 0.0001 +out_channels: 3 diff --git a/legacy/source/lightning_logs/version_29/hparams.yaml b/legacy/source/lightning_logs/version_29/hparams.yaml new file mode 100644 index 0000000..4350dab --- /dev/null +++ b/legacy/source/lightning_logs/version_29/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 10 +in_channels: 3 +lambda_recon: 10 +learning_rate: 0.001 +out_channels: 3 diff --git a/legacy/source/lightning_logs/version_3/hparams.yaml b/legacy/source/lightning_logs/version_3/hparams.yaml new file mode 100644 index 0000000..cb2362a --- /dev/null +++ b/legacy/source/lightning_logs/version_3/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 100 +in_channels: 3 +lambda_recon: 200 +learning_rate: 0.0001 +out_channels: 2 diff --git a/legacy/source/lightning_logs/version_30/hparams.yaml b/legacy/source/lightning_logs/version_30/hparams.yaml new file mode 100644 index 0000000..87b89c7 --- /dev/null +++ b/legacy/source/lightning_logs/version_30/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 5 +in_channels: 3 +lambda_recon: 1 +learning_rate: 0.01 +out_channels: 3 diff --git a/legacy/source/lightning_logs/version_31/hparams.yaml b/legacy/source/lightning_logs/version_31/hparams.yaml new file mode 100644 index 0000000..5cb309a --- /dev/null +++ b/legacy/source/lightning_logs/version_31/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 5 +in_channels: 3 +lambda_recon: 100 +learning_rate: 0.001 +out_channels: 3 diff --git a/legacy/source/lightning_logs/version_32/hparams.yaml b/legacy/source/lightning_logs/version_32/hparams.yaml new file mode 100644 index 0000000..f36d312 --- /dev/null +++ b/legacy/source/lightning_logs/version_32/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 5 +in_channels: 3 +lambda_recon: 100 +learning_rate: 0.0001 +out_channels: 3 diff --git a/legacy/source/lightning_logs/version_33/hparams.yaml b/legacy/source/lightning_logs/version_33/hparams.yaml new file mode 100644 index 0000000..f36d312 --- /dev/null +++ b/legacy/source/lightning_logs/version_33/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 5 +in_channels: 3 +lambda_recon: 100 +learning_rate: 0.0001 +out_channels: 3 diff --git a/legacy/source/lightning_logs/version_34/hparams.yaml b/legacy/source/lightning_logs/version_34/hparams.yaml new file mode 100644 index 0000000..f36d312 --- /dev/null +++ b/legacy/source/lightning_logs/version_34/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 5 +in_channels: 3 +lambda_recon: 100 +learning_rate: 0.0001 +out_channels: 3 diff --git a/legacy/source/lightning_logs/version_35/hparams.yaml b/legacy/source/lightning_logs/version_35/hparams.yaml new file mode 100644 index 0000000..f36d312 --- /dev/null +++ b/legacy/source/lightning_logs/version_35/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 5 +in_channels: 3 +lambda_recon: 100 +learning_rate: 0.0001 +out_channels: 3 diff --git a/legacy/source/lightning_logs/version_36/hparams.yaml b/legacy/source/lightning_logs/version_36/hparams.yaml new file mode 100644 index 0000000..f36d312 --- /dev/null +++ b/legacy/source/lightning_logs/version_36/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 5 +in_channels: 3 +lambda_recon: 100 +learning_rate: 0.0001 +out_channels: 3 diff --git a/legacy/source/lightning_logs/version_37/hparams.yaml b/legacy/source/lightning_logs/version_37/hparams.yaml new file mode 100644 index 0000000..3897421 --- /dev/null +++ b/legacy/source/lightning_logs/version_37/hparams.yaml @@ -0,0 +1,6 @@ +display_step: 5 +in_channels: 3 +lambda_recon: 100 +learning_rate: 0.0001 +out_channels: 3 +pruning: false diff --git a/legacy/source/lightning_logs/version_38/hparams.yaml b/legacy/source/lightning_logs/version_38/hparams.yaml new file mode 100644 index 0000000..3897421 --- /dev/null +++ b/legacy/source/lightning_logs/version_38/hparams.yaml @@ -0,0 +1,6 @@ +display_step: 5 +in_channels: 3 +lambda_recon: 100 +learning_rate: 0.0001 +out_channels: 3 +pruning: false diff --git a/legacy/source/lightning_logs/version_39/hparams.yaml b/legacy/source/lightning_logs/version_39/hparams.yaml new file mode 100644 index 0000000..3897421 --- /dev/null +++ b/legacy/source/lightning_logs/version_39/hparams.yaml @@ -0,0 +1,6 @@ +display_step: 5 +in_channels: 3 +lambda_recon: 100 +learning_rate: 0.0001 +out_channels: 3 +pruning: false diff --git a/legacy/source/lightning_logs/version_4/hparams.yaml b/legacy/source/lightning_logs/version_4/hparams.yaml new file mode 100644 index 0000000..cb2362a --- /dev/null +++ b/legacy/source/lightning_logs/version_4/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 100 +in_channels: 3 +lambda_recon: 200 +learning_rate: 0.0001 +out_channels: 2 diff --git a/legacy/source/lightning_logs/version_40/hparams.yaml b/legacy/source/lightning_logs/version_40/hparams.yaml new file mode 100644 index 0000000..b3d1f5b --- /dev/null +++ b/legacy/source/lightning_logs/version_40/hparams.yaml @@ -0,0 +1,6 @@ +display_step: 5 +in_channels: 3 +lambda_recon: 100 +learning_rate: 0.0001 +out_channels: 3 +pruning: true diff --git a/legacy/source/lightning_logs/version_41/hparams.yaml b/legacy/source/lightning_logs/version_41/hparams.yaml new file mode 100644 index 0000000..b3d1f5b --- /dev/null +++ b/legacy/source/lightning_logs/version_41/hparams.yaml @@ -0,0 +1,6 @@ +display_step: 5 +in_channels: 3 +lambda_recon: 100 +learning_rate: 0.0001 +out_channels: 3 +pruning: true diff --git a/legacy/source/lightning_logs/version_42/hparams.yaml b/legacy/source/lightning_logs/version_42/hparams.yaml new file mode 100644 index 0000000..b3d1f5b --- /dev/null +++ b/legacy/source/lightning_logs/version_42/hparams.yaml @@ -0,0 +1,6 @@ +display_step: 5 +in_channels: 3 +lambda_recon: 100 +learning_rate: 0.0001 +out_channels: 3 +pruning: true diff --git a/legacy/source/lightning_logs/version_5/hparams.yaml b/legacy/source/lightning_logs/version_5/hparams.yaml new file mode 100644 index 0000000..e1eac18 --- /dev/null +++ b/legacy/source/lightning_logs/version_5/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 100 +in_channels: 2 +lambda_recon: 200 +learning_rate: 0.0001 +out_channels: 2 diff --git a/legacy/source/lightning_logs/version_6/hparams.yaml b/legacy/source/lightning_logs/version_6/hparams.yaml new file mode 100644 index 0000000..441af43 --- /dev/null +++ b/legacy/source/lightning_logs/version_6/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 100 +in_channels: 3 +lambda_recon: 200 +learning_rate: 0.0001 +out_channels: 1 diff --git a/legacy/source/lightning_logs/version_7/hparams.yaml b/legacy/source/lightning_logs/version_7/hparams.yaml new file mode 100644 index 0000000..cb2362a --- /dev/null +++ b/legacy/source/lightning_logs/version_7/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 100 +in_channels: 3 +lambda_recon: 200 +learning_rate: 0.0001 +out_channels: 2 diff --git a/legacy/source/lightning_logs/version_8/hparams.yaml b/legacy/source/lightning_logs/version_8/hparams.yaml new file mode 100644 index 0000000..cb2362a --- /dev/null +++ b/legacy/source/lightning_logs/version_8/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 100 +in_channels: 3 +lambda_recon: 200 +learning_rate: 0.0001 +out_channels: 2 diff --git a/legacy/source/lightning_logs/version_9/hparams.yaml b/legacy/source/lightning_logs/version_9/hparams.yaml new file mode 100644 index 0000000..cb2362a --- /dev/null +++ b/legacy/source/lightning_logs/version_9/hparams.yaml @@ -0,0 +1,5 @@ +display_step: 100 +in_channels: 3 +lambda_recon: 200 +learning_rate: 0.0001 +out_channels: 2 diff --git a/legacy/source/losses.py b/legacy/source/losses.py new file mode 100644 index 0000000..79f5530 --- /dev/null +++ b/legacy/source/losses.py @@ -0,0 +1,158 @@ +from scipy.ndimage.morphology import distance_transform_edt +from skimage import segmentation as skimage_seg +from torch.nn import functional as F +import torch.nn as nn +import torch + +def dice_loss(pred, target, smooth=1.): + pred = pred.contiguous() + target = target.contiguous() + + intersection = (pred * target).sum(dim=2).sum(dim=2) + + loss = (1 - ((2. * intersection + smooth) / (pred.sum(dim=2).sum(dim=2) + target.sum(dim=2).sum(dim=2) + smooth))) + + return loss.mean() + + +class BDLoss(nn.Module): + def __init__(self): + # ref: https://github.com/LIVIAETS/surface-loss/blob/108bd9892adca476e6cdf424124bc6268707498e/losses.py#L74 + super().__init__() + + def forward(self, pred, target): + """ + pred: (batch_size, class, x,y) + target: ground truth, shape: (batch_size, class, x,y) + bound: precomputed distance map, shape (batch_size, class, x,y) + """ + + img_gt_p = target.to(torch.bool)[:, 0, :, :].cpu() + img_gt_n = ~img_gt_p + posdis = distance_transform_edt(img_gt_p) + negdis = distance_transform_edt(img_gt_n) + boundary = skimage_seg.find_boundaries(img_gt_p.numpy(), mode='inner') + sdf = negdis - posdis + sdf[boundary == 1.0] = 0 + + # pred = pred[:, 0, :, :].cpu().detach().numpy() + # pred[pred[:, :, :] < 0.5] = 0.0 + # pred[pred[:, :, :] >= 0.5] = 1.0 + # plt.imshow(pred[0]) + # plt.show() + # plt.imshow(sdf[0]) + # plt.show() + + pc = pred[:, 0, :, :] + dc = torch.tensor(sdf).to(device) + + multipled = torch.einsum("bxy,bxy->bxy", pc, dc) + bd_loss = multipled.mean() + + return bd_loss + + +def dice_loss(pred, target, smooth=1.): + pred = pred.contiguous() + target = target.contiguous() + + intersection = (pred * target).sum(dim=2).sum(dim=2) + + loss = (1 - ((2. * intersection + smooth) / (pred.sum(dim=2).sum(dim=2) + target.sum(dim=2).sum(dim=2) + smooth))) + + return loss.mean() + + +class MyBDLoss(nn.Module): + def __init__(self): + # ref: https://github.com/LIVIAETS/surface-loss/blob/108bd9892adca476e6cdf424124bc6268707498e/losses.py#L74 + super().__init__() + + def forward(self, pred, target): + """ + pred: (batch_size, class, x,y) + target: ground truth, shape: (batch_size, class, x,y) + bound: precomputed distance map, shape (batch_size, class, x,y) + """ + + img_gt_p = target.to(torch.bool)[:, 0, :, :].cpu() + img_gt_n = ~img_gt_p + posdis = distance_transform_edt(img_gt_p) + negdis = distance_transform_edt(img_gt_n) + boundary = skimage_seg.find_boundaries(img_gt_p.numpy(), mode='inner').astype(np.uint8) + sdf = negdis + posdis + sdf[boundary == 1] = 0 + sdf = sdf * sdf + + pred = pred[:, 0, :, :].cpu().detach().numpy() + pred[pred[:, :, :] < 0.5] = 0.0 + pred[pred[:, :, :] >= 0.5] = 1.0 + + boundary_pc = skimage_seg.find_boundaries(pred, mode='inner') * 255.0 + pc = torch.tensor(boundary_pc).to(device) + dc = torch.tensor(sdf).to(device) + + multipled = torch.einsum("bxy,bxy->bxy", pc, dc) + bd_loss = multipled.mean() + + return bd_loss + + +class DiceCE(nn.Module): + def __init__(self, bce_weight=0.5): + super().__init__() + self.bce_weight = bce_weight + # self.bd = DC_and_HD_loss({'batch_dice': False, 'smooth': 1e-5, 'do_bg': False, 'square': False},{}) + + def forward(self, pred, target): + pred = torch.sigmoid(pred) + bce = F.binary_cross_entropy_with_logits(pred, target, reduction='mean') + dice = dice_loss(pred, target) + + loss = (bce * self.bce_weight) + ((1.0 - self.bce_weight) * dice) + return loss + + +class DiceBD(nn.Module): + def __init__(self, BD_weight=0.5): + super().__init__() + self.BD_weight = BD_weight + self.bd = BDLoss() + + def forward(self, pred, target): + pred = torch.sigmoid(pred) + dice = dice_loss(pred, target) + bd = self.bd(pred, target) + + loss = (bd * self.BD_weight) + ((1.0 - self.BD_weight) * dice) + return loss + + +class MyDiceBD(nn.Module): + def __init__(self, BD_weight=0.5): + super().__init__() + self.BD_weight = BD_weight + self.bd = MyBDLoss() + + def forward(self, pred, target): + pred = torch.sigmoid(pred) + dice = dice_loss(pred, target) + bd = self.bd(pred, target) + + loss = (bd * self.BD_weight) + ((1.0 - self.BD_weight) * dice) + return loss + + +class MyCEBD(nn.Module): + def __init__(self, BD_weight=0.5): + super().__init__() + self.BD_weight = BD_weight + self.bd = MyBDLoss() + + def forward(self, pred, target): + pred = torch.sigmoid(pred) + bce = F.binary_cross_entropy_with_logits(pred, target, reduction='mean') + bd = self.bd(pred, target) + + loss = (bd * self.BD_weight) + ((1.0 - self.BD_weight) * bce) + return loss \ No newline at end of file diff --git a/legacy/source/main.py b/legacy/source/main.py new file mode 100644 index 0000000..0dc9656 --- /dev/null +++ b/legacy/source/main.py @@ -0,0 +1,304 @@ +import copy +import datetime +import glob +import os +import time +import cv2 +import matplotlib.pyplot as plt +import torchvision.transforms.functional as TF +import torch +import numpy as np +from sklearn.metrics import confusion_matrix +from torch.optim import lr_scheduler +from torch.utils.data import DataLoader +from torchvision import transforms +from tqdm.notebook import tqdm +from source.losses import * +from source.models import * +from source.utils import * +from segmentation_models.segmentation_models_pytorch.pspnet import PSPNet +from segmentation_models.segmentation_models_pytorch.deeplabv3 import DeepLabV3Plus +from segmentation_models.segmentation_models_pytorch.pspnet import PSPNet +from segmentation_models.segmentation_models_pytorch.fpn import FPN + +class TongueSegDataset(torch.utils.data.Dataset): + def __init__(self, path_sampleDir, path_labelDir, transform_sample=None, transform_label=None, transform_both=None): + super().__init__() + + self.transform_sample = transform_sample + self.paths_sample = glob.glob(os.path.join(path_sampleDir, '*')) + + self.paths_label = [] + for path_sample in self.paths_sample: + self.paths_label.append(os.path.join(path_labelDir, os.path.basename(path_sample))) + self.transform_label = transform_label + + self.transform_both = transform_both + + def __getitem__(self, index): + + # Load sample + path_sample = self.paths_sample[index] + sample = torch.from_numpy(cv2.imread(path_sample, cv2.IMREAD_COLOR)) / 255.0 + sample = sample.permute(2, 0, 1).float() + if self.transform_sample: + sample = self.transform_sample(sample) + + # Load label + path_label = self.paths_label[index] + label = torch.from_numpy(cv2.imread(path_label, cv2.IMREAD_COLOR)) + label[label <= 128] = 0.0 + label[label > 128] = 1.0 + label = label.permute(2, 0, 1).float() + if self.transform_label: + label = self.transform_label(label) + + if self.transform_both: + for tf, p in self.transform_both: + if random.random() < p: + sample = tf(sample) + label = tf(label) + + label_pos = label[0, :, :] + label_neg = torch.ones(label_pos.shape) - label[0, :, :] + label_pos = label_pos.unsqueeze(0) + label_neg = label_neg.unsqueeze(0) + label = torch.cat([label_pos, label_neg], axis=0) + return sample, label + + def __len__(self): + return len(self.paths_sample) + + +# Configs +path_outputDir = os.path.join("..\output", datetime.datetime.now().strftime('%m%d-%H%M%S')) +os.makedirs(path_outputDir) + +# load data train +path_trainSample = os.path.join("..\input", "train", "sample") +path_trainLabel = os.path.join("..\input", "train", "label") +path_testSample = os.path.join("..\input", "test_extra", "cropped", "sample") +path_testLabel = os.path.join("..\input", "test_extra", "cropped", "label") + +# Params +fix_rand(2021) +batch_size = 16 +train_ratio = 2 / 3 +transform_sample = transforms.Compose([transforms.ColorJitter(brightness=0.5, contrast=0.5, saturation=0.5, hue=0.5)]) +transform_label = transforms.Compose([]) +transform_both = [(TF.hflip, 0.5)] +dataset = TongueSegDataset(path_trainSample, path_trainLabel, transform_sample=transform_sample, + transform_label=transform_label, transform_both=transform_both) + +train_dataset, val_dataset = torch.utils.data.random_split(dataset, + [int(len(dataset) * train_ratio), len(dataset) - int(len(dataset) * train_ratio)]) +data_loader_train = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=0) +data_loader_val = DataLoader(val_dataset, batch_size=batch_size, shuffle=True, num_workers=0) +print("train:", len(train_dataset), " validation:", len(val_dataset)) + +# show +for epoch in range(0, 1): + for inputs, labels in data_loader_train: + input = inputs[0, :, :, :] + label = labels[0, :, :, :] + img_input = np.array(input.permute(1, 2, 0)) + plt.imshow(img_input) + plt.show() + img_label = np.array(label[0]) / 255.0 + plt.imshow(img_label) + plt.show() + break + +device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') +learning_rate = 1e-4 +num_epochs = 300 +num_epochsEarlyStop = 30 +criterion = DiceCE(bce_weight=0.5) + +# create model +fix_rand(2021) +model = UNet_Pruning(n_class=2) +model = model.to(device) +optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) +# scheduler = lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.1) # is not used +# パラメータカウント +params = 0 +for p in model.parameters(): + if p.requires_grad: + params += p.numel() +print("params: ", params) + +since = time.time() +best_model_wts = copy.deepcopy(model.state_dict()) +best_model_epochs = 0 +best_loss = 1e5 +losses_train = [] +losses_val = [] +for epoch in tqdm(range(num_epochs)): + print('Epoch {}/{}'.format(epoch + 1, num_epochs)) + print('-' * 10) + + # Each epoch has a training and validation phase + for phase in ['train', 'val']: + + if phase == 'train': + model.train() # Set model to training mode + + # Iterate over data. + running_loss = 0.0 + for inputs, labels in data_loader_train: + inputs = inputs.to(device) + labels = labels.to(device) + + # zero the parameter gradients + optimizer.zero_grad() + + # forward + # track history if only in train + with torch.set_grad_enabled(phase == 'train'): + outputs = model(inputs) + loss = criterion(outputs, labels) + + loss.backward() + optimizer.step() + + # statistics + running_loss += loss.item() + + epoch_loss = running_loss / len(data_loader_train) + losses_train.append(epoch_loss) + + else: + model.eval() # Set model to evaluate mode + + # Iterate over data. + running_loss = 0.0 + for inputs, labels in data_loader_val: + inputs = inputs.to(device) + labels = labels.to(device) + + # zero the parameter gradients + optimizer.zero_grad() + + # forward + # track history if only in train + with torch.set_grad_enabled(phase == 'train'): + outputs = model(inputs) + loss = criterion(outputs, labels) + + # statistics + running_loss += loss.item() + + epoch_loss = running_loss / len(data_loader_val) + losses_val.append(epoch_loss) + # scheduler.step() + + print('{} Loss: {:.4f}'.format(phase, epoch_loss)) + + # Todo: early stopping, and metrics + # deep copy the model + if phase == 'val' and epoch_loss < best_loss: + best_loss = epoch_loss + best_model_wts = copy.deepcopy(model.state_dict()) + torch.save(model.state_dict(), path_outputDir + r"/epoch" + str(epoch) + ".pth") + best_model_epochs = epoch + print("best model saved") + + if (epoch - best_model_epochs) >= num_epochsEarlyStop: + break + +time_elapsed = time.time() - since +print('Training complete in {:.0f}m {:.0f}s'.format( + time_elapsed // 60, time_elapsed % 60)) +print('Best val Loss: {:4f}'.format(best_loss)) + +# load best model weights +model.load_state_dict(best_model_wts) +torch.save(model.state_dict(), path_outputDir + r"/bestModel.pth") + +# lossの可視化 +plt.plot(losses_train, label='training loss') +plt.plot(losses_val, label='validation loss') +plt.ylabel("loss") +plt.xlabel("epoch time") +# plt.ylim(0, 0.35) +plt.savefig(path_outputDir + "/loss.png") +plt.legend() +plt.show() + +# Evaluation +dataset_test = TongueSegDataset(path_testSample, path_testLabel) +data_loader_test = DataLoader(dataset_test, batch_size=1, shuffle=False) + +# device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') +# model = ResNetUNet(n_class=2) +# model = model.to(device) +# model_path = r"D:\Noguchi\Solution\Tang's\output\1014-091351\epoch21.pth" +# # model_ = torch.load(model_path) +# model.load_state_dict(torch.load(model_path)) +model.eval() +shouldSave = False +shouldShow = False +ious = [] +for i, data in tqdm(enumerate(data_loader_test, 0)): + name = os.path.splitext(os.path.basename(glob.glob(path_testSample + "/*")[i]))[0] + + inputs = data[0].to(device) + labels = data[1].to(device) + outputs = model(inputs).sigmoid() + + pred = outputs.permute(0, 2, 3, 1).to('cpu').detach().numpy()[0, :, :, 0] + true = labels.permute(0, 2, 3, 1).to('cpu').detach().numpy()[0, :, :, 0] + + img_pred = (pred * 255).astype(np.uint8) + # otsu + ret, img_pred = cv2.threshold(img_pred, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) + + if shouldShow: + print("img") + img_input = inputs.permute(0, 2, 3, 1).to('cpu').detach().numpy()[0] / 255.0 + plt.imshow(img_input) + plt.show() + + print("label") + img_label = labels.permute(0, 2, 3, 1).to('cpu').detach().numpy()[0, :, :, 0] + plt.imshow(img_label) + plt.show() + + print("output") + plt.imshow(img_pred) + plt.show() + + print("output_refined") + dst = img_pred.copy() + plt.imshow(dst) + plt.show() + + y_pred = (img_pred / 255).flatten() + y_true = true.flatten() + tn, fp, fn, tp = confusion_matrix(y_pred, y_true).ravel() + + iou_tp = tp / (tp + fp + fn) + + ious.append(iou_tp) + + if shouldSave: + num_output = outputs.permute(0, 2, 3, 1).to('cpu').detach().numpy()[0, :, :, 0] + plt.axis("off") + plt.imshow(img_pred) + plt.savefig(path_outputDir + r"/" + str(i + 1) + ".jpg", bbox_inches='tight') + + if os.path.exists(path_outputDir + r'/Log_detail.csv'): + with open(path_outputDir + r'/Log_detail.csv', 'a', encoding='utf-8') as f: + f.write(name + ", " + str(iou_tp) + "\n") + else: + with open(path_outputDir + r'/Log_detail.csv', 'x', encoding='utf-8') as f: + f.write(name + ", " + str(iou_tp) + "\n") + +print("全体平均:", np.array(ious).mean()) +if os.path.exists(path_outputDir + r'/Log.txt'): + with open(path_outputDir + r'/Log.txt', 'w', encoding='utf-8') as f: + s = f.write("全体平均:" + str(np.array(ious).mean())) +else: + with open(path_outputDir + r'/Log.txt', 'x', encoding='utf-8') as f: + s = f.write("全体平均:" + str(np.array(ious).mean())) diff --git a/legacy/source/models.py b/legacy/source/models.py new file mode 100644 index 0000000..453b842 --- /dev/null +++ b/legacy/source/models.py @@ -0,0 +1,455 @@ +import torch.nn as nn +import torch +from torchvision import models + + + +def convrelu(in_channels, out_channels, kernel, padding): + return nn.Sequential( + nn.Conv2d(in_channels, out_channels, kernel, padding=padding), + nn.ReLU(inplace=True), + ) + + +class ResNetUNet(nn.Module): + def __init__(self, n_class): + super().__init__() + + self.base_model = models.resnet18(pretrained=True) + self.base_layers = list(self.base_model.children()) + + self.layer0 = nn.Sequential(*self.base_layers[:3]) # size=(N, 64, x.H/2, x.W/2) + self.layer0_1x1 = convrelu(64, 64, 1, 0) + self.layer1 = nn.Sequential(*self.base_layers[3:5]) # size=(N, 64, x.H/4, x.W/4) + self.layer1_1x1 = convrelu(64, 64, 1, 0) + self.layer2 = self.base_layers[5] # size=(N, 128, x.H/8, x.W/8) + self.layer2_1x1 = convrelu(128, 128, 1, 0) + self.layer3 = self.base_layers[6] # size=(N, 256, x.H/16, x.W/16) + self.layer3_1x1 = convrelu(256, 256, 1, 0) + self.layer4 = self.base_layers[7] # size=(N, 512, x.H/32, x.W/32) + self.layer4_1x1 = convrelu(512, 512, 1, 0) + + self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True) + + self.conv_up3 = convrelu(256 + 512, 512, 3, 1) + self.conv_up2 = convrelu(128 + 512, 256, 3, 1) + self.conv_up1 = convrelu(64 + 256, 256, 3, 1) + self.conv_up0 = convrelu(64 + 256, 128, 3, 1) + + self.conv_original_size0 = convrelu(3, 64, 3, 1) + self.conv_original_size1 = convrelu(64, 64, 3, 1) + self.conv_original_size2 = convrelu(64 + 128, 64, 3, 1) + + self.conv_last = nn.Conv2d(64, n_class, 1) + + def forward(self, input): + x_original = self.conv_original_size0(input) + x_original = self.conv_original_size1(x_original) + + layer0 = self.layer0(input) + layer1 = self.layer1(layer0) + layer2 = self.layer2(layer1) + layer3 = self.layer3(layer2) + layer4 = self.layer4(layer3) + + layer4 = self.layer4_1x1(layer4) + x = self.upsample(layer4) + layer3 = self.layer3_1x1(layer3) + x = torch.cat([x, layer3], dim=1) + x = self.conv_up3(x) + + x = self.upsample(x) + layer2 = self.layer2_1x1(layer2) + x = torch.cat([x, layer2], dim=1) + x = self.conv_up2(x) + + x = self.upsample(x) + layer1 = self.layer1_1x1(layer1) + x = torch.cat([x, layer1], dim=1) + x = self.conv_up1(x) + + x = self.upsample(x) + layer0 = self.layer0_1x1(layer0) + x = torch.cat([x, layer0], dim=1) + x = self.conv_up0(x) + + x = self.upsample(x) + x = torch.cat([x, x_original], dim=1) + x = self.conv_original_size2(x) + + out = self.conv_last(x) + + return out + + +class ResNetUNet_Pruning(nn.Module): + def __init__(self, n_class): + super().__init__() + + self.base_model = models.resnet18(pretrained=True) + self.base_layers = list(self.base_model.children()) + + self.layer0 = nn.Sequential(*self.base_layers[:3]) # size=(N, 64, x.H/2, x.W/2) + self.layer0_1x1 = convrelu(64, 64, 1, 0) + self.layer1 = nn.Sequential(*self.base_layers[3:5]) # size=(N, 64, x.H/4, x.W/4) + self.layer1_1x1 = convrelu(64, 64, 1, 0) + self.layer2 = self.base_layers[5] # size=(N, 128, x.H/8, x.W/8) + self.layer2_1x1 = convrelu(128, 128, 1, 0) + self.layer3 = self.base_layers[6] # size=(N, 256, x.H/16, x.W/16) + self.layer3_1x1 = convrelu(256, 256, 1, 0) + self.layer4 = self.base_layers[7] # size=(N, 512, x.H/32, x.W/32) + self.layer4_1x1 = convrelu(512, 512, 1, 0) + + self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True) + + self.conv_up3 = convrelu(256 + 512, 512, 3, 1) + self.conv_up2 = convrelu(128 + 512, 256, 3, 1) + self.conv_up1 = convrelu(64 + 256, 256, 3, 1) + # self.conv_up0 = convrelu(64 + 256, 128, 3, 1) + self.conv_up0 = convrelu(256, 64, 3, 1) + + self.conv_original_size0 = convrelu(3, 64, 3, 1) + self.conv_original_size1 = convrelu(64, 64, 3, 1) + # self.conv_original_size2 = convrelu(64 + 128, 64, 3, 1) + self.conv_original_size2 = convrelu(64, 64, 3, 1) + + self.conv_last = nn.Conv2d(64, n_class, 1) + + def forward(self, input): + x_original = self.conv_original_size0(input) + x_original = self.conv_original_size1(x_original) + + layer0 = self.layer0(input) # 実質,0, 1, 2 層 + layer1 = self.layer1(layer0) + layer2 = self.layer2(layer1) + layer3 = self.layer3(layer2) + layer4 = self.layer4(layer3) + + layer4 = self.layer4_1x1(layer4) + x = self.upsample(layer4) + layer3 = self.layer3_1x1(layer3) + x = torch.cat([x, layer3], dim=1) + x = self.conv_up3(x) + + x = self.upsample(x) + layer2 = self.layer2_1x1(layer2) + x = torch.cat([x, layer2], dim=1) + x = self.conv_up2(x) + + x = self.upsample(x) + layer1 = self.layer1_1x1(layer1) + x = torch.cat([x, layer1], dim=1) + x = self.conv_up1(x) + + x = self.upsample(x) + layer0 = self.layer0_1x1(layer0) + # x = torch.cat([x, layer0], dim=1) + x = self.conv_up0(x) + + x = self.upsample(x) + # x = torch.cat([x, x_original], dim=1) + x = self.conv_original_size2(x) + + out = self.conv_last(x) + + return out + + +class VGGBlock(nn.Module): + def __init__(self, in_channels, middle_channels, out_channels): + super().__init__() + self.relu = nn.ReLU(inplace=True) + self.conv1 = nn.Conv2d(in_channels, middle_channels, 3, padding=1) + self.bn1 = nn.BatchNorm2d(middle_channels) + self.conv2 = nn.Conv2d(middle_channels, out_channels, 3, padding=1) + self.bn2 = nn.BatchNorm2d(out_channels) + + def forward(self, x): + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + out = self.relu(out) + + return out + + +class UNet(nn.Module): + def __init__(self, n_class, input_channels=3, **kwargs): + super().__init__() + + nb_filter = [32, 64, 128, 256, 512] + + self.pool = nn.MaxPool2d(2, 2) + self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True) + + self.conv0_0 = VGGBlock(input_channels, nb_filter[0], nb_filter[0]) + self.conv1_0 = VGGBlock(nb_filter[0], nb_filter[1], nb_filter[1]) + self.conv2_0 = VGGBlock(nb_filter[1], nb_filter[2], nb_filter[2]) + self.conv3_0 = VGGBlock(nb_filter[2], nb_filter[3], nb_filter[3]) + self.conv4_0 = VGGBlock(nb_filter[3], nb_filter[4], nb_filter[4]) + + self.conv3_1 = VGGBlock(nb_filter[3]+nb_filter[4], nb_filter[3], nb_filter[3]) + self.conv2_2 = VGGBlock(nb_filter[2]+nb_filter[3], nb_filter[2], nb_filter[2]) + self.conv1_3 = VGGBlock(nb_filter[1]+nb_filter[2], nb_filter[1], nb_filter[1]) + self.conv0_4 = VGGBlock(nb_filter[0]+nb_filter[1], nb_filter[0], nb_filter[0]) + + self.final = nn.Conv2d(nb_filter[0], n_class, kernel_size=1) + + + def forward(self, input): + x0_0 = self.conv0_0(input) + x1_0 = self.conv1_0(self.pool(x0_0)) + x2_0 = self.conv2_0(self.pool(x1_0)) + x3_0 = self.conv3_0(self.pool(x2_0)) + x4_0 = self.conv4_0(self.pool(x3_0)) + + x3_1 = self.conv3_1(torch.cat([x3_0, self.up(x4_0)], 1)) + x2_2 = self.conv2_2(torch.cat([x2_0, self.up(x3_1)], 1)) + x1_3 = self.conv1_3(torch.cat([x1_0, self.up(x2_2)], 1)) + x0_4 = self.conv0_4(torch.cat([x0_0, self.up(x1_3)], 1)) + + output = self.final(x0_4) + return output + + +class UNet_Pruning(nn.Module): + def __init__(self, n_class, input_channels=3, **kwargs): + super().__init__() + + nb_filter = [32, 64, 128, 256, 512] + + self.pool = nn.MaxPool2d(2, 2) + self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True) + + self.conv0_0 = VGGBlock(input_channels, nb_filter[0], nb_filter[0]) + self.conv1_0 = VGGBlock(nb_filter[0], nb_filter[1], nb_filter[1]) + self.conv2_0 = VGGBlock(nb_filter[1], nb_filter[2], nb_filter[2]) + self.conv3_0 = VGGBlock(nb_filter[2], nb_filter[3], nb_filter[3]) + self.conv4_0 = VGGBlock(nb_filter[3], nb_filter[4], nb_filter[4]) + + self.conv3_1 = VGGBlock(nb_filter[3]+nb_filter[4], nb_filter[3], nb_filter[3]) + self.conv2_2 = VGGBlock(nb_filter[2]+nb_filter[3], nb_filter[2], nb_filter[2]) + self.conv1_3 = VGGBlock(nb_filter[2], nb_filter[1], nb_filter[1]) + self.conv0_4 = VGGBlock(nb_filter[1], nb_filter[0], nb_filter[0]) + + self.final = nn.Conv2d(nb_filter[0], n_class, kernel_size=1) + + + def forward(self, input): + x0_0 = self.conv0_0(input) + x1_0 = self.conv1_0(self.pool(x0_0)) + x2_0 = self.conv2_0(self.pool(x1_0)) + x3_0 = self.conv3_0(self.pool(x2_0)) + x4_0 = self.conv4_0(self.pool(x3_0)) + + x3_1 = self.conv3_1(torch.cat([x3_0, self.up(x4_0)], 1)) + x2_2 = self.conv2_2(torch.cat([x2_0, self.up(x3_1)], 1)) + # x1_3 = self.conv1_3(torch.cat([x1_0, self.up(x2_2)], 1)) + # x0_4 = self.conv0_4(torch.cat([x0_0, self.up(x1_3)], 1)) + x1_3 = self.conv1_3(torch.cat([self.up(x2_2)], 1)) + x0_4 = self.conv0_4(torch.cat([self.up(x1_3)], 1)) + + output = self.final(x0_4) + return output + +class NestedUNet(nn.Module): + def __init__(self, n_class, input_channels=3, deep_supervision=False, **kwargs): + super().__init__() + + nb_filter = [32, 64, 128, 256, 512] + + self.deep_supervision = deep_supervision + + self.pool = nn.MaxPool2d(2, 2) + self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True) + + self.conv0_0 = VGGBlock(input_channels, nb_filter[0], nb_filter[0]) + self.conv1_0 = VGGBlock(nb_filter[0], nb_filter[1], nb_filter[1]) + self.conv2_0 = VGGBlock(nb_filter[1], nb_filter[2], nb_filter[2]) + self.conv3_0 = VGGBlock(nb_filter[2], nb_filter[3], nb_filter[3]) + self.conv4_0 = VGGBlock(nb_filter[3], nb_filter[4], nb_filter[4]) + + self.conv0_1 = VGGBlock(nb_filter[0]+nb_filter[1], nb_filter[0], nb_filter[0]) + self.conv1_1 = VGGBlock(nb_filter[1]+nb_filter[2], nb_filter[1], nb_filter[1]) + self.conv2_1 = VGGBlock(nb_filter[2]+nb_filter[3], nb_filter[2], nb_filter[2]) + self.conv3_1 = VGGBlock(nb_filter[3]+nb_filter[4], nb_filter[3], nb_filter[3]) + + self.conv0_2 = VGGBlock(nb_filter[0]*2+nb_filter[1], nb_filter[0], nb_filter[0]) + self.conv1_2 = VGGBlock(nb_filter[1]*2+nb_filter[2], nb_filter[1], nb_filter[1]) + self.conv2_2 = VGGBlock(nb_filter[2]*2+nb_filter[3], nb_filter[2], nb_filter[2]) + + self.conv0_3 = VGGBlock(nb_filter[0]*3+nb_filter[1], nb_filter[0], nb_filter[0]) + self.conv1_3 = VGGBlock(nb_filter[1]*3+nb_filter[2], nb_filter[1], nb_filter[1]) + + self.conv0_4 = VGGBlock(nb_filter[0]*4+nb_filter[1], nb_filter[0], nb_filter[0]) + + if self.deep_supervision: + self.final1 = nn.Conv2d(nb_filter[0], n_class, kernel_size=1) + self.final2 = nn.Conv2d(nb_filter[0], n_class, kernel_size=1) + self.final3 = nn.Conv2d(nb_filter[0], n_class, kernel_size=1) + self.final4 = nn.Conv2d(nb_filter[0], n_class, kernel_size=1) + else: + self.final = nn.Conv2d(nb_filter[0], n_class, kernel_size=1) + + + def forward(self, input): + x0_0 = self.conv0_0(input) + x1_0 = self.conv1_0(self.pool(x0_0)) + x0_1 = self.conv0_1(torch.cat([x0_0, self.up(x1_0)], 1)) + + x2_0 = self.conv2_0(self.pool(x1_0)) + x1_1 = self.conv1_1(torch.cat([x1_0, self.up(x2_0)], 1)) + x0_2 = self.conv0_2(torch.cat([x0_0, x0_1, self.up(x1_1)], 1)) + + x3_0 = self.conv3_0(self.pool(x2_0)) + x2_1 = self.conv2_1(torch.cat([x2_0, self.up(x3_0)], 1)) + x1_2 = self.conv1_2(torch.cat([x1_0, x1_1, self.up(x2_1)], 1)) + x0_3 = self.conv0_3(torch.cat([x0_0, x0_1, x0_2, self.up(x1_2)], 1)) + + x4_0 = self.conv4_0(self.pool(x3_0)) + x3_1 = self.conv3_1(torch.cat([x3_0, self.up(x4_0)], 1)) + x2_2 = self.conv2_2(torch.cat([x2_0, x2_1, self.up(x3_1)], 1)) + x1_3 = self.conv1_3(torch.cat([x1_0, x1_1, x1_2, self.up(x2_2)], 1)) + x0_4 = self.conv0_4(torch.cat([x0_0, x0_1, x0_2, x0_3, self.up(x1_3)], 1)) + + if self.deep_supervision: + output1 = self.final1(x0_1) + output2 = self.final2(x0_2) + output3 = self.final3(x0_3) + output4 = self.final4(x0_4) + return [output1, output2, output3, output4] + + else: + output = self.final(x0_4) + return output + + +class TwoTaskUNet(nn.Module): + def __init__(self, n_class): + super().__init__() + + nb_filter = [32, 64, 128, 256, 512] + + self.downsample = nn.MaxPool2d(2, 2) + self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True) + + self.conv0 = VGGBlock(3, nb_filter[0], nb_filter[0]) + self.conv1 = VGGBlock(nb_filter[0], nb_filter[1], nb_filter[1]) + self.conv2 = VGGBlock(nb_filter[1], nb_filter[2], nb_filter[2]) + self.conv3 = VGGBlock(nb_filter[2], nb_filter[3], nb_filter[3]) + self.conv4 = VGGBlock(nb_filter[3], nb_filter[4], nb_filter[4]) + + self.conv3_1 = VGGBlock(nb_filter[3] + nb_filter[4], nb_filter[3], nb_filter[3]) + self.conv2_1 = VGGBlock(nb_filter[2] + nb_filter[3], nb_filter[2], nb_filter[2]) + self.conv1_1 = VGGBlock(nb_filter[1] + nb_filter[2], nb_filter[1], nb_filter[1]) + self.conv0_1 = VGGBlock(nb_filter[0] + nb_filter[1], nb_filter[0], nb_filter[0]) + self.final_1 = nn.Conv2d(nb_filter[0], n_class, kernel_size=1) + + self.conv3_2 = VGGBlock(nb_filter[3] + nb_filter[4], nb_filter[3], nb_filter[3]) + self.conv2_2 = VGGBlock(nb_filter[2] + nb_filter[3], nb_filter[2], nb_filter[2]) + self.conv1_2 = VGGBlock(nb_filter[1] + nb_filter[2], nb_filter[1], nb_filter[1]) + self.conv0_2 = VGGBlock(nb_filter[0] + nb_filter[1], nb_filter[0], nb_filter[0]) + self.final_2 = nn.Conv2d(nb_filter[0], 3, kernel_size=1) + + def forward(self, input): + # Shared Encoder + x0 = self.conv0(input) + x1 = self.conv1(self.downsample(x0)) + x2 = self.conv2(self.downsample(x1)) + x3 = self.conv3(self.downsample(x2)) + encoderOutput = self.conv4(self.downsample(x3)) + # Decoder 1 for segmentation + x3_1 = self.conv3_1(torch.cat([x3, self.upsample(encoderOutput)], 1)) + x2_1 = self.conv2_1(torch.cat([x2, self.upsample(x3_1)], 1)) + x1_1 = self.conv1_1(torch.cat([x1, self.upsample(x2_1)], 1)) + x0_1 = self.conv0_1(torch.cat([x0, self.upsample(x1_1)], 1)) + segmentation = self.final_1(x0_1) + # Decoder 2 for reconstruction + x3_2 = self.conv3_2(torch.cat([x3, self.upsample(encoderOutput)], 1)) + x2_2 = self.conv2_2(torch.cat([x2, self.upsample(x3_2)], 1)) + x1_2 = self.conv1_2(torch.cat([x1, self.upsample(x2_2)], 1)) + x0_2 = self.conv0_2(torch.cat([x0, self.upsample(x1_2)], 1)) + reconstruction = self.final_2(x0_2) + return segmentation, reconstruction + + +class TwoTaskResUNet(nn.Module): + def __init__(self, n_class): + super().__init__() + + self.base_model = models.resnet18(pretrained=True) + self.base_layers = list(self.base_model.children()) + + self.layer0 = nn.Sequential(*self.base_layers[:3]) # size=(N, 64, x.H/2, x.W/2) + self.layer1 = nn.Sequential(*self.base_layers[3:5]) # size=(N, 64, x.H/4, x.W/4) + self.layer2 = self.base_layers[5] # size=(N, 128, x.H/8, x.W/8) + self.layer3 = self.base_layers[6] # size=(N, 256, x.H/16, x.W/16) + self.layer4 = self.base_layers[7] # size=(N, 512, x.H/32, x.W/32) + + self.layer0_1x1_1 = convrelu(64, 64, 1, 0) + self.layer1_1x1_1 = convrelu(64, 64, 1, 0) + self.layer2_1x1_1 = convrelu(128, 128, 1, 0) + self.layer3_1x1_1 = convrelu(256, 256, 1, 0) + self.layer4_1x1_1 = convrelu(512, 512, 1, 0) + + self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True) + + self.conv_original_size0 = convrelu(3, 64, 3, 1) + self.conv_original_size1 = convrelu(64, 64, 3, 1) + + # Segmentation + self.conv_up3_1 = convrelu(256 + 512, 512, 3, 1) + self.conv_up2_1 = convrelu(128 + 512, 256, 3, 1) + self.conv_up1_1 = convrelu(64 + 256, 256, 3, 1) + self.conv_up0_1 = convrelu(64 + 256, 128, 3, 1) + self.conv_original_size2_1 = convrelu(64 + 128, 64, 3, 1) + self.conv_last_1 = nn.Conv2d(64, n_class, 1) + # Reconstruction + self.conv_up3_2 = convrelu(256 + 512, 512, 3, 1) + self.conv_up2_2 = convrelu(128 + 512, 256, 3, 1) + self.conv_up1_2 = convrelu(64 + 256, 256, 3, 1) + self.conv_up0_2 = convrelu(64 + 256, 128, 3, 1) + self.conv_original_size2_2 = convrelu(64 + 128, 64, 3, 1) + self.conv_last_2 = nn.Conv2d(64, 3, 1) + + def forward(self, input): + x_original = self.conv_original_size0(input) + x_original = self.conv_original_size1(x_original) + + layer0 = self.layer0(input) + layer1 = self.layer1(layer0) + layer2 = self.layer2(layer1) + layer3 = self.layer3(layer2) + encoderOutput = self.layer4(layer3) + + # Decoder 1 for segmentation + x = self.layer4_1x1_1(encoderOutput) + x = self.upsample(x) + x = self.conv_up3_1(torch.cat([x, self.layer3_1x1_1(layer3)], dim=1)) + x = self.upsample(x) + x = self.conv_up2_1(torch.cat([x, self.layer2_1x1_1(layer2)], dim=1)) + x = self.upsample(x) + x = self.conv_up1_1(torch.cat([x, self.layer1_1x1_1(layer1)], dim=1)) + x = self.upsample(x) + x = self.conv_up0_1(torch.cat([x, self.layer0_1x1_1(layer0)], dim=1)) + x = self.upsample(x) + x = self.conv_original_size2_1(torch.cat([x, x_original], dim=1)) + segmentation = self.conv_last_1(x) + # Decoder 2 for reconstruction + x = self.layer4_1x1_1(encoderOutput) + x = self.upsample(x) + x = self.conv_up3_2(torch.cat([x, self.layer3_1x1_1(layer3)], dim=1)) + x = self.upsample(x) + x = self.conv_up2_2(torch.cat([x, self.layer2_1x1_1(layer2)], dim=1)) + x = self.upsample(x) + x = self.conv_up1_2(torch.cat([x, self.layer1_1x1_1(layer1)], dim=1)) + x = self.upsample(x) + x = self.conv_up0_2(torch.cat([x, self.layer0_1x1_1(layer0)], dim=1)) + x = self.upsample(x) + x = self.conv_original_size2_2(torch.cat([x, x_original], dim=1)) + reconstruction = self.conv_last_2(x) + return segmentation, reconstruction + diff --git a/legacy/source/pytorchToOnnx.py b/legacy/source/pytorchToOnnx.py new file mode 100644 index 0000000..369ff6e --- /dev/null +++ b/legacy/source/pytorchToOnnx.py @@ -0,0 +1,80 @@ +import copy +import datetime +import glob +import os +import time +import cv2 +import matplotlib.pyplot as plt +import torchvision.transforms.functional as TF +import torch +import numpy as np +from sklearn.metrics import confusion_matrix +from torch.optim import lr_scheduler +from torch.utils.data import DataLoader +from torchvision import transforms +from tqdm.notebook import tqdm +from source.losses import * +from source.models import * +from source.utils import * + +class TongueSegDataset(torch.utils.data.Dataset): + def __init__(self, path_sampleDir, path_labelDir, transform_sample=None, transform_label=None, transform_both=None): + super().__init__() + + self.transform_sample = transform_sample + self.paths_sample = glob.glob(os.path.join(path_sampleDir, '*')) + + self.paths_label = [] + for path_sample in self.paths_sample: + self.paths_label.append(os.path.join(path_labelDir, os.path.basename(path_sample))) + self.transform_label = transform_label + + self.transform_both = transform_both + + def __getitem__(self, index): + + # Load sample + path_sample = self.paths_sample[index] + sample = torch.from_numpy(cv2.imread(path_sample, cv2.IMREAD_COLOR)) / 255.0 + sample = sample.permute(2, 0, 1).float() + if self.transform_sample: + sample = self.transform_sample(sample) + + # Load label + path_label = self.paths_label[index] + label = torch.from_numpy(cv2.imread(path_label, cv2.IMREAD_COLOR)) + label[label <= 128] = 0.0 + label[label > 128] = 1.0 + label = label.permute(2, 0, 1).float() + if self.transform_label: + label = self.transform_label(label) + + if self.transform_both: + for tf, p in self.transform_both: + if random.random() < p: + sample = tf(sample) + label = tf(label) + + label_pos = label[0, :, :] + label_neg = torch.ones(label_pos.shape) - label[0, :, :] + label_pos = label_pos.unsqueeze(0) + label_neg = label_neg.unsqueeze(0) + label = torch.cat([label_pos, label_neg], axis=0) + return sample, label + + def __len__(self): + return len(self.paths_sample) + +# Configs + +# load data train +fix_rand(2021) +path_model = r"D:\Noguchi\Solution\TongueSegmentation\result\CompareModels\ResUNet\bestModel.pth" +path_outputDir = os.path.join("..\output", datetime.datetime.now().strftime('%m%d-%H%M%S')) +os.makedirs(path_outputDir) + +model = ResNetUNet(n_class=2) +model.load_state_dict(torch.load(path_model)) +model.eval() +path_outputONNX = path_outputDir + r"\ResUNet.onnx" +torch.onnx.export(model, torch.zeros([1, 3, 256, 256]), path_outputONNX, opset_version=11) diff --git a/legacy/source/test.py b/legacy/source/test.py new file mode 100644 index 0000000..34307e5 --- /dev/null +++ b/legacy/source/test.py @@ -0,0 +1,8 @@ +import pandas as pd + +df = pd.DataFrame([[1, 2, 3, 4], [1, 2, 3, 5]]) + + +print(mean) +df = pd.concat([df, mean]) +print(df) \ No newline at end of file diff --git a/legacy/source/utils.py b/legacy/source/utils.py new file mode 100644 index 0000000..71c7de3 --- /dev/null +++ b/legacy/source/utils.py @@ -0,0 +1,90 @@ +import os +import random +import numpy as np +import torch + + +# define +def fix_rand(seed=2021): + np.random.seed(seed) + random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + torch.backends.cudnn.deterministic = True + torch.backends.cudnn.benchmark = False + os.environ["PYTHONHASHSEED"] = str(seed) + torch.use_deterministic_algorithms(False) + # torch.use_deterministic_algorithms(True) + + + +def RemoveSmallRegion(Src, Dst, AreaLimit, CheckMode, NeihborMode): + RemoveCount = 0 + PointLabel = np.zeros((Src.shape), np.uint8) + if CheckMode == 1: # mode1 小さい領域(白飛び)の削除 + for i in range(0, Src.shape[0]): + for j in range(0, Src.shape[1]): + if Src[i][j] < 128: + PointLabel[i][j] = 3 + else: # mode0 穴(黒飛び)の削除 + for i in range(0, Src.shape[0]): + for j in range(0, Src.shape[1]): + if Src[i][j] >= 128: + PointLabel[i][j] = 3 + + NeihborPos = list() + NeihborPos.append([-1, 0]) + NeihborPos.append([1, 0]) + NeihborPos.append([0, -1]) + NeihborPos.append([0, 1]) + + if NeihborMode == 1: + NeihborPos.append([-1, -1]) + NeihborPos.append([-1, 1]) + NeihborPos.append([1, -1]) + NeihborPos.append([1, 1]) + + NeihborCount = 4 + 4 * NeihborMode + CurrX = 0 + CurrY = 0 + + for i in range(0, Src.shape[0]): + for j in range(0, Src.shape[1]): + + if PointLabel[i][j] == 0: + GrowBuffer = list() + GrowBuffer.append([i, j]) + PointLabel[i][j] = 1 + CheckResult = 0 + + z = 0 + while z < len(GrowBuffer): + for q in range(0, NeihborCount): + CurrY = GrowBuffer[z][0] + NeihborPos[q][0] + CurrX = GrowBuffer[z][1] + NeihborPos[q][1] + if CurrX >= 0 and CurrX < Src.shape[1] and CurrY >= 0 and CurrY < Src.shape[0]: + if PointLabel[CurrY][CurrX] == 0: + GrowBuffer.append([CurrY, CurrX]) + PointLabel[CurrY][CurrX] = 1 + z = z + 1 + + if len(GrowBuffer) > AreaLimit: + CheckResult = 2 + else: + CheckResult = 1 + RemoveCount = RemoveCount + 1 + + for z in range(0, len(GrowBuffer)): + CurrX = GrowBuffer[z][1] + CurrY = GrowBuffer[z][0] + PointLabel[CurrY][CurrX] += CheckResult + + CheckMode = 255 * (1 - CheckMode) + for i in range(0, Src.shape[0]): + for j in range(0, Src.shape[1]): + if PointLabel[i][j] == 2: + Dst[i][j] = CheckMode + + elif PointLabel[i][j] == 3: + Dst[i][j] = Src[i][j] \ No newline at end of file diff --git a/legacy/temp/main.py b/legacy/temp/main.py new file mode 100644 index 0000000..bff2a8f --- /dev/null +++ b/legacy/temp/main.py @@ -0,0 +1,296 @@ +from segmentation_models.segmentation_models_pytorch.pspnet import PSPNet +import copy +import datetime +import glob +import os +import time +import cv2 +import matplotlib.pyplot as plt +import torchvision.transforms.functional as TF +import torch +import numpy as np +from sklearn.metrics import confusion_matrix +from torch.optim import lr_scheduler +from torch.utils.data import DataLoader +from torchvision import transforms +from tqdm.notebook import tqdm +from source.losses import * +from source.models import * +from source.utils import * + + +class TongueSegDataset(torch.utils.data.Dataset): + def __init__(self, path_sampleDir, path_labelDir, transform_sample=None, transform_label=None, transform_both=None): + super().__init__() + + self.transform_sample = transform_sample + self.paths_sample = glob.glob(os.path.join(path_sampleDir, '*')) + + self.paths_label = [] + for path_sample in self.paths_sample: + self.paths_label.append(os.path.join(path_labelDir, os.path.basename(path_sample))) + self.transform_label = transform_label + + self.transform_both = transform_both + + def __getitem__(self, index): + + # Load sample + path_sample = self.paths_sample[index] + sample = torch.from_numpy(cv2.imread(path_sample, cv2.IMREAD_COLOR)) / 255.0 + sample = sample.permute(2, 0, 1).float() + if self.transform_sample: + sample = self.transform_sample(sample) + + # Load label + path_label = self.paths_label[index] + label = torch.from_numpy(cv2.imread(path_label, cv2.IMREAD_COLOR)) + label[label <= 128] = 0.0 + label[label > 128] = 1.0 + label = label.permute(2, 0, 1).float() + if self.transform_label: + label = self.transform_label(label) + + if self.transform_both: + for tf, p in self.transform_both: + if random.random() < p: + sample = tf(sample) + label = tf(label) + + label_pos = label[0, :, :] + label_neg = torch.ones(label_pos.shape) - label[0, :, :] + label_pos = label_pos.unsqueeze(0) + label_neg = label_neg.unsqueeze(0) + label = torch.cat([label_pos, label_neg], axis=0) + return sample, label + + def __len__(self): + return len(self.paths_sample) + + +# Configs +path_outputDir = os.path.join("../output", datetime.datetime.now().strftime('%m%d-%H%M%S')) +os.makedirs(path_outputDir) + +# load data train +path_trainSample = os.path.join("../input", "train", "sample") +path_trainLabel = os.path.join("../input", "train", "label") +path_testSample = os.path.join("../input", "test_extra", "cropped", "sample") +path_testLabel = os.path.join("../input", "test_extra", "cropped", "label") + +# Params +fix_rand(2021) +batch_size = 16 +train_ratio = 2 / 3 +transform_sample = transforms.Compose([transforms.ColorJitter(brightness=0.5, contrast=0.5, saturation=0.5, hue=0.5)]) +transform_label = transforms.Compose([]) +transform_both = [(TF.hflip, 0.5)] +dataset = TongueSegDataset(path_trainSample, path_trainLabel, transform_sample=transform_sample, + transform_label=transform_label, transform_both=transform_both) + +train_dataset, val_dataset = torch.utils.data.random_split(dataset, + [int(len(dataset) * train_ratio), len(dataset) - int(len(dataset) * train_ratio)]) +data_loader_train = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=0) +data_loader_val = DataLoader(val_dataset, batch_size=batch_size, shuffle=True, num_workers=0) +print("train:", len(train_dataset), " validation:", len(val_dataset)) + +# show +for epoch in range(0, 1): + for inputs, labels in data_loader_train: + input = inputs[0, :, :, :] + label = labels[0, :, :, :] + img_input = np.array(input.permute(1, 2, 0)) + plt.imshow(img_input) + plt.show() + img_label = np.array(label[0]) / 255.0 + plt.imshow(img_label) + plt.show() + break + +device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') +learning_rate = 1e-4 +num_epochs = 300 +num_epochsEarlyStop = 30 +criterion = DiceCE(bce_weight=0.5) + +# create model +fix_rand(2021) +model = PSPNet(classes=2) +model = model.to(device) +optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) +# scheduler = lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.1) # is not used + +since = time.time() +best_model_wts = copy.deepcopy(model.state_dict()) +best_model_epochs = 0 +best_loss = 1e5 +losses_train = [] +losses_val = [] +for epoch in tqdm(range(num_epochs)): + print('Epoch {}/{}'.format(epoch + 1, num_epochs)) + print('-' * 10) + + # Each epoch has a training and validation phase + for phase in ['train', 'val']: + + if phase == 'train': + model.train() # Set model to training mode + + # Iterate over data. + running_loss = 0.0 + for inputs, labels in data_loader_train: + inputs = inputs.to(device) + labels = labels.to(device) + + # zero the parameter gradients + optimizer.zero_grad() + + # forward + # track history if only in train + with torch.set_grad_enabled(phase == 'train'): + outputs = model(inputs) + loss = criterion(outputs, labels) + + loss.backward() + optimizer.step() + + # statistics + running_loss += loss.item() + + epoch_loss = running_loss / len(data_loader_train) + losses_train.append(epoch_loss) + + else: + model.eval() # Set model to evaluate mode + + # Iterate over data. + running_loss = 0.0 + for inputs, labels in data_loader_val: + inputs = inputs.to(device) + labels = labels.to(device) + + # zero the parameter gradients + optimizer.zero_grad() + + # forward + # track history if only in train + with torch.set_grad_enabled(phase == 'train'): + outputs = model(inputs) + loss = criterion(outputs, labels) + + # statistics + running_loss += loss.item() + + epoch_loss = running_loss / len(data_loader_val) + losses_val.append(epoch_loss) + # scheduler.step() + + print('{} Loss: {:.4f}'.format(phase, epoch_loss)) + + # Todo: early stopping, and metrics + # deep copy the model + if phase == 'val' and epoch_loss < best_loss: + best_loss = epoch_loss + best_model_wts = copy.deepcopy(model.state_dict()) + torch.save(model.state_dict(), path_outputDir + r"/epoch" + str(epoch) + ".pth") + best_model_epochs = epoch + print("best model saved") + + if (epoch - best_model_epochs) >= num_epochsEarlyStop: + break + +time_elapsed = time.time() - since +print('Training complete in {:.0f}m {:.0f}s'.format( + time_elapsed // 60, time_elapsed % 60)) +print('Best val Loss: {:4f}'.format(best_loss)) + +# load best model weights +model.load_state_dict(best_model_wts) +torch.save(model.state_dict(), path_outputDir + r"/bestModel.pth") + +# lossの可視化 +plt.plot(losses_train, label='training loss') +plt.plot(losses_val, label='validation loss') +plt.ylabel("loss") +plt.xlabel("epoch time") +# plt.ylim(0, 0.35) +plt.savefig(path_outputDir + "/loss.png") +plt.legend() +plt.show() + +# Evaluation +dataset_test = TongueSegDataset(path_testSample, path_testLabel) +data_loader_test = DataLoader(dataset_test, batch_size=1, shuffle=False) + +# device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') +# model = ResNetUNet(n_class=2) +# model = model.to(device) +# model_path = r"D:\Noguchi\Solution\Tang's\output\1014-091351\epoch21.pth" +# # model_ = torch.load(model_path) +# model.load_state_dict(torch.load(model_path)) +model.eval() +shouldSave = False +shouldShow = False +ious = [] +for i, data in tqdm(enumerate(data_loader_test, 0)): + name = os.path.splitext(os.path.basename(glob.glob(path_testSample + "/*")[i]))[0] + + inputs = data[0].to(device) + labels = data[1].to(device) + outputs = model(inputs).sigmoid() + + pred = outputs.permute(0, 2, 3, 1).to('cpu').detach().numpy()[0, :, :, 0] + true = labels.permute(0, 2, 3, 1).to('cpu').detach().numpy()[0, :, :, 0] + + img_pred = (pred * 255).astype(np.uint8) + # otsu + ret, img_pred = cv2.threshold(img_pred, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) + + if shouldShow: + print("img") + img_input = inputs.permute(0, 2, 3, 1).to('cpu').detach().numpy()[0] / 255.0 + plt.imshow(img_input) + plt.show() + + print("label") + img_label = labels.permute(0, 2, 3, 1).to('cpu').detach().numpy()[0, :, :, 0] + plt.imshow(img_label) + plt.show() + + print("output") + plt.imshow(img_pred) + plt.show() + + print("output_refined") + dst = img_pred.copy() + plt.imshow(dst) + plt.show() + + y_pred = (img_pred / 255).flatten() + y_true = true.flatten() + tn, fp, fn, tp = confusion_matrix(y_pred, y_true).ravel() + + iou_tp = tp / (tp + fp + fn) + + ious.append(iou_tp) + + if shouldSave: + num_output = outputs.permute(0, 2, 3, 1).to('cpu').detach().numpy()[0, :, :, 0] + plt.axis("off") + plt.imshow(img_pred) + plt.savefig(path_outputDir + r"/" + str(i + 1) + ".jpg", bbox_inches='tight') + + if os.path.exists(path_outputDir + r'/Log_detail.txt'): + with open(path_outputDir + r'/Log_detail.txt', 'a', encoding='utf-8') as f: + f.write(name + ", " + str(iou_tp) + "\n") + else: + with open(path_outputDir + r'/Log_detail.txt', 'x', encoding='utf-8') as f: + f.write(name + ", " + str(iou_tp) + "\n") + +print("全体平均:", np.array(ious).mean()) +if os.path.exists(path_outputDir + r'/Log.txt'): + with open(path_outputDir + r'/Log.txt', 'w', encoding='utf-8') as f: + s = f.write("全体平均:" + str(np.array(ious).mean())) +else: + with open(path_outputDir + r'/Log.txt', 'x', encoding='utf-8') as f: + s = f.write("全体平均:" + str(np.array(ious).mean()))