Kaggle competition: Cassava Leaf Disease Classification
submission.to_csv('submission.csv', index=False )<save_to_csv>
!mkdir -p /tmp/pip/cache/
!cp.. /input/omegaconf/PyYAML-5.4b2-cp38-cp38-manylinux1_x86_64.whl /tmp/pip/cache/
!cp.. /input/omegaconf/omegaconf-2.0.5-py3-none-any.whl /tmp/pip/cache/
!cp.. /input/omegaconf/typing_extensions-3.7.4.3-py3-none-any.whl /tmp/pip/cache/
!pip install --no-index --find-links /tmp/pip/cache/ omegaconf > /dev/null
submission.to_csv('submission.csv', index=False )<load_from_csv>
sys.path.append('.. /input/timm-pytorch-image-models/pytorch-image-models-master')
 sys.path.append(".. /input/cleanlab/")
 warnings.filterwarnings('ignore')
pd.read_csv('submission.csv' )<import_modules>
mean, std =(0.485, 0.456, 0.406),(0.229, 0.224, 0.225)
 def get_transforms(img_size=(512, 512)) :
transformations = Compose([
PadIfNeeded(min_height=img_size[0], min_width=img_size[1]),
CenterCrop(img_size[0], img_size[1]),
Normalize(mean=mean, std=std, max_pixel_value=255.0, p=1.0),
ToTensorV2(p=1.0),
], p=1.0)
 return transformations
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from mlxtend.feature_selection import SequentialFeatureSelector as SFS<load_from_csv>
def create_model(model_name: str,
pretrained: bool,
num_classes: int,
in_chans: int):
model = timm.create_model(model_name=model_name,
pretrained=pretrained,
num_classes=num_classes,
in_chans=in_chans)
 return model
train_data = pd.read_csv("/kaggle/input/titanic/train.csv")
 train_data.head()<load_from_csv>
def get_state_dict_from_checkpoint(log_dir, fold_num):
ckpt_path = glob(os.path.join(log_dir, f'checkpoints/*fold{fold_num}*.ckpt')) [0]
state_dict = pl_load(ckpt_path, map_location='cpu')
 if 'state_dict' in state_dict:
state_dict = state_dict['state_dict']
did_distillation = False
state_dict = OrderedDict(( k.replace('model.', '')
 if 'model.' in k else k, v)for k, v in
state_dict.items())
 return state_dict
test_data = pd.read_csv("/kaggle/input/titanic/test.csv")
 test_data.head()<data_type_conversions>
class LitTester(pl.LightningModule):
def __init__(self, network_cfg, state_dict):
super(LitTester, self ).__init__()
self.model = create_model(**network_cfg)
 self.model.load_state_dict(state_dict)
 self.model.eval()
def forward(self, x):
x = self.model(x)
 return x
def test_step(self, batch, batch_idx):
score = torch.nn.functional.softmax(self(batch), dim=1)
 score2 = torch.nn.functional.softmax(self(torch.flip(batch, [-1])) , dim=1)
 score3 = torch.nn.functional.softmax(self(torch.flip(batch, [-2])) , dim=1)
 out =(score + score2 + score3)/ 3.0
return {"pred": out}
def test_epoch_end(self, output_results):
all_outputs = torch.cat([out["pred"] for out in output_results], dim=0)
 all_outputs = all_outputs.cpu().numpy()
return {'prob': all_outputs}
train_data['Age'] = train_data['Age'].fillna(train_data.Age.mean())
 test_data['Age'] = test_data['Age'].fillna(test_data.Age.mean())
 test_data['Fare'] = test_data['Fare'].fillna(test_data.Fare.mean() )<count_values>
eff_b0_cfg_s =
eff_b0_cfg = OmegaConf.create(eff_b0_cfg_s )
train_data["Embarked"].value_counts()<categorify>
name = '14-10-36'
cfg = eff_b0_cfg
do_predict = True
do_submit = False
img_dir = '.. /input/cassava-leaf-disease-merged/train/'
label_path = '.. /input/cassava-leaf-disease-merged/merged.csv'
log_dir = os.path.join('.. /input/cassava-public-ckpt', name)
 n_folds = len(glob(os.path.join(log_dir, 'checkpoints/*.ckpt')))
 num2class = ["Cassava Bacterial Blight(CBB)", "Cassava Brown Streak Disease(CBSD)", "Cassava Green Mottle(CGM)", "Cassava Mosaic Disease(CMD)", "Healthy"]
train_data = train_data.fillna({"Embarked": "S"} )<drop_column>
seed_everything(42)
 label_df = pd.read_csv(label_path)
 if 'fold' not in label_df.columns:
skf = StratifiedKFold(n_splits=5, shuffle=True)
 label_df.loc[:, 'fold'] = 0
for fold_num,(train_index, val_index)in enumerate(skf.split(X=label_df.index, y=label_df.label.values)) :
label_df.loc[label_df.iloc[val_index].index, 'fold'] = fold_num
if do_predict:
infer = pl.Trainer(gpus=1)
 oof_dict = {'image_id': [], 'label': [], 'fold': []}
for fold_num in range(n_folds):
val_df = label_df[label_df.fold == fold_num]
test_dataset = TestDataset(img_dir, val_df, img_size=cfg.img_size)
 test_dataloader = DataLoader(test_dataset,
batch_size=cfg.batch_size,
num_workers=4,
shuffle=False)
 state_dict = get_state_dict_from_checkpoint(log_dir, fold_num)
 model = LitTester(cfg.network, state_dict)
 pred = infer.test(model, test_dataloaders=test_dataloader, verbose=False)[0]
oof_dict['image_id'].extend(val_df.image_id.values)
 oof_dict['label'].extend(pred['prob'].tolist())
 oof_dict['fold'].extend([fold_num] * len(pred['prob']))
pred_df = pd.DataFrame(oof_dict)
 pred_df.to_csv('oof.csv', index=False)
 else:
pred_df = pd.read_csv(os.path.join(log_dir, 'oof.csv'))
train_data.drop(['Name','Ticket','Cabin'], axis = 1, inplace = True)
 test_data.drop(['Name','Ticket','Cabin'], axis = 1, inplace = True )<count_missing_values>
if do_submit:
sub = pd.read_csv('.. /input/cassava-leaf-disease-classification/sample_submission.csv')
 infer = pl.Trainer(gpus=1)
 test_dataset = TestDataset('.. /input/cassava-leaf-disease-classification/test_images',
sub,
img_size=cfg.img_size)
 test_dataloader = DataLoader(test_dataset,
batch_size=cfg.batch_size,
num_workers=4,
shuffle=False)
 preds = []
for fold_num in range(n_folds):
state_dict = get_state_dict_from_checkpoint(log_dir, fold_num)
 model = LitTester(cfg.network, state_dict)
 pred = infer.test(model, test_dataloaders=test_dataloader, verbose=False)[0]
preds.append(pred['prob'])
 sub['label'] = np.argmax(np.mean(preds, axis=0), axis=1)
 sub.to_csv(os.path.join(os.getcwd() , 'submission.csv'), index=False )
train_data.isnull().sum()
test_data.isnull().sum()<categorify>
label_df = label_df.sort_values(by='image_id', ascending=1)
 pred_df = pred_df.sort_values(by='image_id', ascending=1)
 ids, labels = label_df.image_id.values, label_df.label.values
preds = np.array([literal_eval(pred)if isinstance(pred, str)else pred for pred in pred_df.label.values])
 print(f'total {len(ids)} images')
 print(f'prediction shape: {preds.shape}, label shape: {labels.shape}' )
train_data = pd.get_dummies(train_data, columns=["Sex"])
 train_data = pd.get_dummies(train_data, columns=["Embarked"])
 test_data = pd.get_dummies(test_data, columns=["Sex"])
 test_data = pd.get_dummies(test_data, columns=["Embarked"] )<prepare_x_and_y>
s = labels
psx = preds
K = len(np.unique(s))
thresholds = [np.mean(psx[:,k][s == k])for k in range(K)]
thresholds = np.asarray(thresholds)
 confident_joint = np.zeros(( K, K), dtype = int)
 for i, row in enumerate(psx):
s_label = s[i]
confident_bins = row >= thresholds - 1e-6
num_confident_bins = sum(confident_bins)
 if num_confident_bins == 1:
confident_joint[s_label][np.argmax(confident_bins)] += 1
elif num_confident_bins > 1:
confident_joint[s_label][np.argmax(row)] += 1
confident_joint = cleanlab.latent_estimation.calibrate_confident_joint(
 confident_joint, s)
 cleanlab.util.print_joint_matrix(confident_joint)
 MIN_NUM_PER_CLASS = 5
prune_count_matrix = cleanlab.pruning.keep_at_least_n_per_class(
 prune_count_matrix=confident_joint.T,
n=MIN_NUM_PER_CLASS, 
)
 s_counts = np.bincount(s)
 noise_masks_per_class = []
for k in range(K):
noise_mask = np.zeros(len(psx), dtype=bool)
 psx_k = psx[:, k]
if s_counts[k] > MIN_NUM_PER_CLASS:
for j in range(K):
if k != j:
num2prune = prune_count_matrix[k][j]
if num2prune > 0:
margin = psx_k - psx[:, j]
s_filter = s == j
threshold = -np.partition(
 -margin[s_filter], num2prune - 1 
)[num2prune - 1]
noise_mask = noise_mask |(s_filter &(margin >= threshold))
noise_masks_per_class.append(noise_mask)
 else:
noise_masks_per_class.append(np.zeros(len(s), dtype=bool))
label_errors_bool = np.stack(noise_masks_per_class ).any(axis=0)
 for i, pred_label in enumerate(psx.argmax(axis=1)) :
if label_errors_bool[i] and np.all(pred_label == s[i]):
label_errors_bool[i] = False
label_errors_idx = np.arange(len(s)) [label_errors_bool]
self_confidence = np.array(
 [np.mean(psx[i][s[i]])for i in label_errors_idx] 
)
 margin = self_confidence - psx[label_errors_bool].max(axis=1)
 label_errors_idx = label_errors_idx[np.argsort(margin)]
X = train_data
X = train_data.drop("Survived",axis=1)
 y = train_data["Survived"]<split>
total_idx = np.arange(len(ids))
clean_idx = np.array([idx for idx in total_idx if idx not in label_errors_idx])
 guesses = np.stack(noise_masks_per_class ).argmax(axis=0)
 guesses[clean_idx] = labels[clean_idx]
clean_ids = ids[clean_idx]
clean_labels = labels[clean_idx]
clean_guesses = guesses[clean_idx]
noisy_ids = ids[label_errors_idx]
noisy_labels = labels[label_errors_idx]
noisy_guesses = guesses[label_errors_idx]
print(f'[clean ratio] \t {len(clean_idx)/ len(total_idx)* 100:.2f}%')
 print(f'[noise ratio] \t {len(noisy_ids)/ len(total_idx)* 100:.2f}%' )
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 1)
 X_train.shape, X_test.shape<train_model>
all_data = pd.DataFrame({'image_id': ids,
'given_label': labels,
'guess_label': guesses})
 all_data['is_noisy'] =(all_data.given_label != all_data.guess_label)
 all_data['max_prob'] = preds.max(axis=1 )
<compute_test_metric><EOS> 
class_colors = np.array(['
num2class = [f'{idx}-{elem}' for idx, elem in enumerate(num2class)]