Kaggle competition: Aerial Cactus Identification
<SOS> metric: AUC Kaggle data source: aerial-cactus-identification<predict_on_test>
%matplotlib inline
q=GBoost.predict(test)
 q=np.expm1(q )<predict_on_test>
labels = pd.read_csv('.. /input/train.csv')
 sub = pd.read_csv('.. /input/sample_submission.csv')
 train_path = '.. /input/train/train/'
test_path = '.. /input/test/test/'
w=KRR.predict(test)
 w=np.expm1(w )<predict_on_test>
print('Num train samples:{0}'.format(len(os.listdir(train_path))))
print('Num test samples:{0}'.format(len(os.listdir(test_path))))
e=ENet.predict(test)
 e=np.expm1(e )<define_variables>
labels['has_cactus'].value_counts()
x=(0.15*x+0.15*z)+0.7*(q+e+w)/3 
<save_to_csv>
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import TensorDataset, DataLoader, Dataset
import torchvision
import torchvision.transforms as transforms
from sklearn.model_selection import train_test_split
output = pd.DataFrame({'Id': test_ID,
'SalePrice': x})
 output.to_csv('submission.csv', index=False )<train_model>
num_epochs = 25
num_classes = 2
batch_size = 128
learning_rate = 0.002
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu' )
print("That's all Folks !" )<set_options>
train, val = train_test_split(labels, stratify=labels.has_cactus, test_size=0.1)
 train.shape, val.shape
%matplotlib inline<set_options>
train['has_cactus'].value_counts()
warnings.filterwarnings('ignore' )<load_from_csv>
val['has_cactus'].value_counts()
train = pd.read_csv('.. /input/titanic/train.csv')
 test = pd.read_csv('.. /input/titanic/test.csv')
 IDtest = test["PassengerId"]<concatenate>
class MyDataset(Dataset):
def __init__(self, df_data, data_dir = './', transform=None):
super().__init__()
self.df = df_data.values
self.data_dir = data_dir
self.transform = transform
def __len__(self):
return len(self.df)
 def __getitem__(self, index):
img_name,label = self.df[index]
img_path = os.path.join(self.data_dir, img_name)
 image = cv2.imread(img_path)
 if self.transform is not None:
image = self.transform(image)
 return image, label
dataset = pd.concat(objs=[train, test], axis=0 ).reset_index(drop=True)
 len(dataset )<define_variables>
trans_train = transforms.Compose([transforms.ToPILImage() ,
transforms.Pad(32, padding_mode='reflect'),
transforms.ToTensor() ,
transforms.Normalize(mean=[0.5, 0.5, 0.5],std=[0.5, 0.5, 0.5])])
 trans_valid = transforms.Compose([transforms.ToPILImage() ,
transforms.Pad(32, padding_mode='reflect'),
transforms.ToTensor() ,
transforms.Normalize(mean=[0.5, 0.5, 0.5],std=[0.5, 0.5, 0.5])])
 dataset_train = MyDataset(df_data=train, data_dir=train_path, transform=trans_train)
 dataset_valid = MyDataset(df_data=val, data_dir=train_path, transform=trans_valid)
 loader_train = DataLoader(dataset = dataset_train, batch_size=batch_size, shuffle=True, num_workers=0)
 loader_valid = DataLoader(dataset = dataset_valid, batch_size=batch_size//2, shuffle=False, num_workers=0 )
train_len = len(train )<count_missing_values>
class SimpleCNN(nn.Module):
def __init__(self):
super(SimpleCNN, self ).__init__()
self.conv1 = nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, padding=2)
 self.conv2 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, padding=2)
 self.conv3 = nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, padding=2)
 self.conv4 = nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, padding=2)
 self.conv5 = nn.Conv2d(in_channels=256, out_channels=512, kernel_size=3, padding=2)
 self.bn1 = nn.BatchNorm2d(32)
 self.bn2 = nn.BatchNorm2d(64)
 self.bn3 = nn.BatchNorm2d(128)
 self.bn4 = nn.BatchNorm2d(256)
 self.bn5 = nn.BatchNorm2d(512)
 self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
 self.avg = nn.AvgPool2d(4)
 self.fc = nn.Linear(512 * 1 * 1, 2)
 def forward(self, x):
x = self.pool(F.leaky_relu(self.bn1(self.conv1(x))))
x = self.pool(F.leaky_relu(self.bn2(self.conv2(x))))
x = self.pool(F.leaky_relu(self.bn3(self.conv3(x))))
x = self.pool(F.leaky_relu(self.bn4(self.conv4(x))))
x = self.pool(F.leaky_relu(self.bn5(self.conv5(x))))
x = self.avg(x)
 x = x.view(-1, 512 * 1 * 1)
 x = self.fc(x)
 return x
dataset.isnull().sum()<feature_engineering>
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adamax(model.parameters() , lr=learning_rate )
sex_survived = pd.DataFrame(columns=['Total', 'Survived', 'Survived Ratio'])
 sex_survived['Total'] = train['Sex'].value_counts()
sex_survived['Survived'] = train[train['Survived']==1].groupby(['Sex'] ).apply(lambda x: x.shape[0])
 sex_survived['Survived Ratio'] = sex_survived['Survived'] / sex_survived['Total']
sex_survived<feature_engineering>
total_step = len(loader_train)
 for epoch in range(num_epochs):
for i,(images, labels)in enumerate(loader_train):
images = images.to(device)
 labels = labels.to(device)
 outputs = model(images)
 loss = criterion(outputs, labels)
 optimizer.zero_grad()
loss.backward()
optimizer.step()
if(i+1)% 100 == 0:
print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}' 
.format(epoch+1, num_epochs, i+1, total_step, loss.item()))
dataset['Sex'] = dataset['Sex'].map(lambda s: 1 if s == 'male' else 0 )<filter>
model.eval()
with torch.no_grad() :
correct = 0
total = 0
for images, labels in loader_valid:
images = images.to(device)
 labels = labels.to(device)
 outputs = model(images)
 _, predicted = torch.max(outputs.data, 1)
 total += labels.size(0)
 correct +=(predicted == labels ).sum().item()
print('Test Accuracy of the model on the 1750 validation images: {} %'.format(100 * correct / total))
torch.save(model.state_dict() , 'model.ckpt' )
dataset['Age'][dataset['Age'].isnull() == True] = dataset[dataset['Age'].isnull() == False].median() [0]<feature_engineering>
dataset_valid = MyDataset(df_data=sub, data_dir=test_path, transform=trans_valid)
 loader_test = DataLoader(dataset = dataset_valid, batch_size=32, shuffle=False, num_workers=0 )
<create_dataframe><EOS> 
model.eval()
preds = []
for batch_i,(data, target)in enumerate(loader_test):
data, target = data.cuda() , target.cuda()
output = model(data)
 pr = output[:,1].detach().cpu().numpy()
for i in pr:
preds.append(i)
 sub['has_cactus'] = preds
sub.to_csv('sub.csv', index=False )