Kaggle competition: COVID19 Global Forecasting (Week 2)
submission.iloc[np.where(mask)[0], 1:] = total_results<save_to_csv>
plt.style.use('ggplot')
 font = {'family' : 'meiryo'}
plt.rc('font', **font )
submission.to_csv("submission.csv", index=None, float_format='%.7f' )<set_options>
train_df = pd.read_csv(".. /input/covid19-global-forecasting-week-2/train.csv" )
%%HTML
<style type="text/css">
div.h1 {
background-color:
color: white;
padding: 8px;
padding-right: 300px;
font-size: 35px;
max-width: 1500px;
margin: auto;
margin-top: 50px;
}
div.h2 {
background-color:
color: white;
padding: 8px;
padding-right: 300px;
font-size: 35px;
max-width: 1500px;
margin: auto;
margin-top: 50px;
}
</style><set_options>
train_df = train_df[train_df["Date"] < "2020-03-19"]
train_df = train_df.fillna("No State" )
warnings.filterwarnings('ignore' )<set_options>
test_rate = 0.05
maxlen = 20
train_date_count = len(set(train_df["Date"]))
X, Y = [],[]
scaler = StandardScaler()
train_df["ConfirmedCases_std"] = scaler.fit_transform(train_df["ConfirmedCases"].values.reshape(len(train_df["ConfirmedCases"].values),1))
for state,country in train_df.groupby(["Province_State","Country_Region"] ).sum().index:
df = train_df[(train_df["Country_Region"] == country)&(train_df["Province_State"] == state)]
if df["ConfirmedCases"].sum() != 0:
for i in range(len(df)- maxlen):
if df[['ConfirmedCases']].iloc[i+maxlen].values != 0:
X.append(df[['ConfirmedCases_std']].iloc[i:(i+maxlen)].values)
 Y.append(df[['ConfirmedCases_std']].iloc[i+maxlen].values)
 X=np.array(X)
 Y=np.array(Y)
 X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=test_rate, shuffle = True ,random_state = 0 )
def seed_everything(seed=1903):
random.seed(seed)
 os.environ['PYTHONHASHSEED'] = str(seed)
 np.random.seed(seed)
 torch.manual_seed(seed)
 torch.cuda.manual_seed(seed)
 torch.backends.cudnn.deterministic = True
seed_everything(seed=42 )<load_from_csv>
def huber_loss(y_true, y_pred, clip_delta=1.0):
error = y_true - y_pred
cond = tf.keras.backend.abs(error)< clip_delta
squared_loss = 0.5 * tf.keras.backend.square(error)
 linear_loss = clip_delta *(tf.keras.backend.abs(error)- 0.5 * clip_delta)
 return tf.where(cond, squared_loss, linear_loss)
 def huber_loss_mean(y_true, y_pred, clip_delta=1.0):
return tf.keras.backend.mean(huber_loss(y_true, y_pred, clip_delta))
def rmsle(y, y_pred):
assert len(y)== len(y_pred)
 terms_to_sum = [(math.log(y_pred[i] + 1)- math.log(y[i] + 1)) ** 2.0 for i,pred in enumerate(y_pred)]
return(sum(terms_to_sum)*(1.0/len(y)))** 0.5
train_features = pd.read_csv('.. /input/lish-moa/train_features.csv')
 train_targets_scored = pd.read_csv('.. /input/lish-moa/train_targets_scored.csv')
 train_targets_nonscored = pd.read_csv('.. /input/lish-moa/train_targets_nonscored.csv')
 test_features = pd.read_csv('.. /input/lish-moa/test_features.csv')
 sample_submission = pd.read_csv('.. /input/lish-moa/sample_submission.csv' )<define_variables>
epochs_num = 20
n_hidden = 300
n_in = 1
model = Sequential()
model.add(GRU(n_hidden,
batch_input_shape=(None, maxlen, n_in),
kernel_initializer='random_uniform',
return_sequences=False))
model.add(Dense(n_in, kernel_initializer='random_uniform'))
model.add(Activation("linear"))
opt = Adagrad(lr=0.01, epsilon=1e-08, decay=1e-4)
 model.compile(loss = huber_loss_mean, optimizer=opt )
GENES = [col for col in train_features.columns if col.startswith('g-')]
CELLS = [col for col in train_features.columns if col.startswith('c-')]<concatenate>
early_stopping = EarlyStopping(monitor='loss', patience=5, verbose=1)
 hist = model.fit(X_train, Y_train, batch_size=10, epochs=epochs_num,
callbacks=[early_stopping],shuffle=False )
n_comp = 28
data = pd.concat([pd.DataFrame(train_features[GENES]), pd.DataFrame(test_features[GENES])])
 data2 =(PCA(n_components=n_comp, random_state=1903 ).fit_transform(data[GENES]))
train2 = data2[:train_features.shape[0]]; test2 = data2[-test_features.shape[0]:]
train2 = pd.DataFrame(train2, columns=[f'pca_G-{i}' for i in range(n_comp)])
 test2 = pd.DataFrame(test2, columns=[f'pca_G-{i}' for i in range(n_comp)])
 train_features = pd.concat(( train_features, train2), axis=1)
 test_features = pd.concat(( test_features, test2), axis=1)
 n_comp = 5
data = pd.concat([pd.DataFrame(train_features[CELLS]), pd.DataFrame(test_features[CELLS])])
 data2 =(PCA(n_components=n_comp, random_state=1903 ).fit_transform(data[CELLS]))
train2 = data2[:train_features.shape[0]]; test2 = data2[-test_features.shape[0]:]
train2 = pd.DataFrame(train2, columns=[f'pca_C-{i}' for i in range(n_comp)])
 test2 = pd.DataFrame(test2, columns=[f'pca_C-{i}' for i in range(n_comp)])
 train_features = pd.concat(( train_features, train2), axis=1)
 test_features = pd.concat(( test_features, test2), axis=1 )<create_dataframe>
predicted_std = model.predict(X_test)
 result_std= pd.DataFrame(predicted_std)
 result_std.columns = ['predict']
result_std['actual'] = Y_test
var_thresh = VarianceThreshold(threshold=0.4)
 data = train_features.append(test_features)
 data_transformed = var_thresh.fit_transform(data.iloc[:, 4:])
 train_features_transformed = data_transformed[ : train_features.shape[0]]
test_features_transformed = data_transformed[-test_features.shape[0] : ]
train_features = pd.DataFrame(train_features[['sig_id','cp_type','cp_time','cp_dose']].values.reshape(-1, 4),\
columns=['sig_id','cp_type','cp_time','cp_dose'])
 train_features = pd.concat([train_features, pd.DataFrame(train_features_transformed)], axis=1)
 test_features = pd.DataFrame(test_features[['sig_id','cp_type','cp_time','cp_dose']].values.reshape(-1, 4),\
columns=['sig_id','cp_type','cp_time','cp_dose'])
 test_features = pd.concat([test_features, pd.DataFrame(test_features_transformed)], axis=1)
 train_features<merge>
predicted = scaler.inverse_transform(predicted_std)
 Y_test = scaler.inverse_transform(Y_test )
train = train_features.merge(train_targets_scored, on='sig_id')
 train = train[train['cp_type']!='ctl_vehicle'].reset_index(drop=True)
 test = test_features[test_features['cp_type']!='ctl_vehicle'].reset_index(drop=True)
 target = train[train_targets_scored.columns]
train = train.drop('cp_type', axis=1)
 test = test.drop('cp_type', axis=1 )<drop_column>
result= pd.DataFrame(predicted)
 result.columns = ['predict']
result['actual'] = Y_test
result.plot(figsize=(25,6))
plt.show()
target_cols = target.drop('sig_id', axis=1 ).columns.values.tolist()<split>
test_df = pd.read_csv(".. /input/covid19-global-forecasting-week-2/test.csv")
 test_df
folds = train.copy()
mskf = MultilabelStratifiedKFold(n_splits=7)
 for f,(t_idx, v_idx)in enumerate(mskf.split(X=train, y=target)) :
folds.loc[v_idx, 'kfold'] = int(f)
 folds['kfold'] = folds['kfold'].astype(int )<feature_engineering>
submission_c = pd.read_csv(".. /input/covid19-global-forecasting-week-2/submission.csv" )
def process_data(df):
df['time_dose'] = df['cp_time'].astype(str)+df['cp_dose']
df = pd.get_dummies(df, columns=['cp_time','cp_dose','time_dose'])
 features_g = list(df.columns[4:776])
 features_c = list(df.columns[776:876])
 df['g_sum'] = df[features_g].sum(axis = 1)
 df['g_mean'] = df[features_g].mean(axis = 1)
 df['g_std'] = df[features_g].std(axis = 1)
 df['g_kurt'] = df[features_g].kurtosis(axis = 1)
 df['g_skew'] = df[features_g].skew(axis = 1)
 df['c_sum'] = df[features_c].sum(axis = 1)
 df['c_mean'] = df[features_c].mean(axis = 1)
 df['c_std'] = df[features_c].std(axis = 1)
 df['c_kurt'] = df[features_c].kurtosis(axis = 1)
 df['c_skew'] = df[features_c].skew(axis = 1)
 df['gc_sum'] = df[features_g + features_c].sum(axis = 1)
 df['gc_mean'] = df[features_g + features_c].mean(axis = 1)
 df['gc_std'] = df[features_g + features_c].std(axis = 1)
 df['gc_kurt'] = df[features_g + features_c].kurtosis(axis = 1)
 df['gc_skew'] = df[features_g + features_c].skew(axis = 1)
 features_c = list(df.columns[776:876])
 for feature in features_c:
df[f'{feature}_squared'] = df[feature] ** 2
return df<define_variables>
temp =(datetime.datetime.strptime("2020-03-18", '%Y-%m-%d')- datetime.timedelta(days=maxlen)).strftime('%Y-%m-%d')
 test_df = train_df[train_df["Date"] > temp]
feature_cols = [c for c in process_data(folds ).columns if c not in target_cols]
feature_cols = [c for c in feature_cols if c not in ['kfold','sig_id']]
len(feature_cols )<categorify>
check_df = pd.read_csv(".. /input/covid19-global-forecasting-week-2/train.csv" ).query("Date>'2020-03-18'and Date<='2020-03-31'")
 check_df["ConfirmedCases_std"] = scaler.transform(check_df["ConfirmedCases"].values.reshape(len(check_df["ConfirmedCases"].values),1))
class MoADataset:
def __init__(self, features, targets):
self.features = features
self.targets = targets
def __len__(self):
return(self.features.shape[0])
 def __getitem__(self, idx):
dct = {
'x' : torch.tensor(self.features[idx, :], dtype=torch.float),
'y' : torch.tensor(self.targets[idx, :], dtype=torch.float)
 }
return dct
class TestDataset:
def __init__(self, features):
self.features = features
def __len__(self):
return(self.features.shape[0])
 def __getitem__(self, idx):
dct = {
'x' : torch.tensor(self.features[idx, :], dtype=torch.float)
 }
return dct<train_model>
confirmedCases_pred = []
for i in range(0,294*maxlen,maxlen):
temp_array = np.array(test_df["ConfirmedCases_std"][i:i+maxlen])
 for j in range(43):
if j<13:
temp_array = np.append(temp_array,np.array(check_df["ConfirmedCases_std"])[int(i*13/maxlen)+j])
 elif np.array(test_df["ConfirmedCases"][i:i+maxlen] ).sum() == 0:
temp_array = np.append(temp_array,temp_array[-1])
 else:
temp_array = np.append(temp_array,model.predict(temp_array[-maxlen:].reshape(1,maxlen,1)))
 confirmedCases_pred.append(temp_array[-43:] )
def train_fn(model, optimizer, scheduler, loss_fn, dataloader, device):
model.train()
final_loss = 0
for data in dataloader:
optimizer.zero_grad()
inputs, targets = data['x'].to(device), data['y'].to(device)
 outputs = model(inputs)
 loss = loss_fn(outputs, targets)
 loss.backward()
optimizer.step()
scheduler.step()
final_loss += loss.item()
final_loss /= len(dataloader)
 return final_loss
def valid_fn(model, loss_fn, dataloader, device):
model.eval()
final_loss = 0
valid_preds = []
for data in dataloader:
inputs, targets = data['x'].to(device), data['y'].to(device)
 outputs = model(inputs)
 loss = loss_fn(outputs, targets)
 final_loss += loss.item()
valid_preds.append(outputs.sigmoid().detach().cpu().numpy())
 final_loss /= len(dataloader)
 valid_preds = np.concatenate(valid_preds)
 return final_loss, valid_preds
def inference_fn(model, dataloader, device):
model.eval()
preds = []
for data in dataloader:
inputs = data['x'].to(device)
 with torch.no_grad() :
outputs = model(inputs)
 preds.append(outputs.sigmoid().detach().cpu().numpy())
 preds = np.concatenate(preds)
 return preds 
<normalization>
submission_c["ConfirmedCases"] = np.abs(scaler.inverse_transform(np.array(confirmedCases_pred ).reshape(294*43)))
 submission_c["ConfirmedCases_std"] = np.array(confirmedCases_pred ).reshape(294*43)
 submission_c
class Model(nn.Module):
def __init__(self, num_features, num_targets, hidden_size):
super(Model, self ).__init__()
self.batch_norm1 = nn.BatchNorm1d(num_features)
 self.dropout1 = nn.Dropout(0.2)
 self.dense1 = nn.utils.weight_norm(nn.Linear(num_features, hidden_size))
self.batch_norm2 = nn.BatchNorm1d(hidden_size)
 self.dropout2 = nn.Dropout(0.2)
 self.dense2 = nn.utils.weight_norm(nn.Linear(hidden_size, hidden_size))
self.batch_norm3 = nn.BatchNorm1d(hidden_size)
 self.dropout3 = nn.Dropout(0.2)
 self.dense3 = nn.utils.weight_norm(nn.Linear(hidden_size, num_targets))
def forward(self, x):
x = self.batch_norm1(x)
 x = self.dropout1(x)
 x = F.leaky_relu(self.dense1(x), 1e-3)
 x = self.batch_norm2(x)
 x = self.dropout2(x)
 x = F.relu(self.dense2(x))
x = self.batch_norm3(x)
 x = self.dropout3(x)
 x = self.dense3(x)
 return x<define_variables>
submission_c.to_csv('./submission_c.csv')
 submission_c.to_csv('.. \output\kaggle\working\submission_c.csv' )
DEVICE =('cuda' if torch.cuda.is_available() else 'cpu')
 EPOCHS = 26
BATCH_SIZE = 256
LEARNING_RATE = 6e-4
WEIGHT_DECAY = 1e-5
NFOLDS = 7
EARLY_STOPPING_STEPS = 10
EARLY_STOP = True
num_features=len(feature_cols)
 num_targets=len(target_cols)
 hidden_size=2048<prepare_x_and_y>
test_rate = 0.05
maxlen = 20
train_date_count = len(set(train_df["Date"]))
X, Y = [],[]
scaler = StandardScaler()
train_df["Fatalities_std"] = scaler.fit_transform(train_df["Fatalities"].values.reshape(len(train_df["Fatalities"].values),1))
ss = StandardScaler()
train_df["ConfirmedCases_std"] = ss.fit_transform(train_df["ConfirmedCases"].values.reshape(len(train_df["ConfirmedCases"].values),1))
for state,country in train_df.groupby(["Province_State","Country_Region"] ).sum().index:
df = train_df[(train_df["Country_Region"] == country)&(train_df["Province_State"] == state)]
if df["Fatalities"].sum() != 0 or df["ConfirmedCases"].sum() != 0:
for i in range(len(df)- maxlen):
if(df[['ConfirmedCases']].iloc[i+maxlen].values != 0 or df[['Fatalities']].iloc[i+maxlen].values != 0):
X.append(df[['Fatalities_std','ConfirmedCases_std']].iloc[i:(i+maxlen)].values)
 Y.append(df[['Fatalities_std']].iloc[i+maxlen].values)
 X=np.array(X)
 Y=np.array(Y)
 X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=test_rate, shuffle = True ,random_state = 0 )
def run_training(fold, seed):
seed_everything(seed)
 train = process_data(folds)
 test_ = process_data(test)
 trn_idx = train[train['kfold'] != fold].index
val_idx = train[train['kfold'] == fold].index
train_df = train[train['kfold'] != fold].reset_index(drop=True)
 valid_df = train[train['kfold'] == fold].reset_index(drop=True)
 x_train, y_train = train_df[feature_cols].values, train_df[target_cols].values
x_valid, y_valid = valid_df[feature_cols].values, valid_df[target_cols].values
train_dataset = MoADataset(x_train, y_train)
 valid_dataset = MoADataset(x_valid, y_valid)
 trainloader = torch.utils.data.DataLoader(train_dataset, batch_size=BATCH_SIZE, shuffle=True)
 validloader = torch.utils.data.DataLoader(valid_dataset, batch_size=BATCH_SIZE, shuffle=False)
 model = Model(
 num_features=num_features,
num_targets=num_targets,
hidden_size=hidden_size, 
)
 model.to(DEVICE)
 optimizer = torch.optim.Adam(model.parameters() , lr=LEARNING_RATE, weight_decay=WEIGHT_DECAY)
 scheduler = optim.lr_scheduler.OneCycleLR(optimizer=optimizer, pct_start=0.1, div_factor=1e3,
max_lr=1e-2, epochs=EPOCHS, steps_per_epoch=len(trainloader))
loss_fn = nn.BCEWithLogitsLoss()
early_stopping_steps = EARLY_STOPPING_STEPS
early_step = 0
oof = np.zeros(( len(train), target.iloc[:, 1:].shape[1]))
best_loss = np.inf
print(f"FOLD: {fold}")
 for epoch in range(EPOCHS):
train_loss = train_fn(model, optimizer,scheduler, loss_fn, trainloader, DEVICE)
 valid_loss, valid_preds = valid_fn(model, loss_fn, validloader, DEVICE)
 print(f"EPOCH: {epoch}, train_loss: {train_loss}, valid_loss: {valid_loss}")
 if valid_loss < best_loss:
best_loss = valid_loss
oof[val_idx] = valid_preds
torch.save(model.state_dict() , f"FOLD{fold}_.pth")
 elif(EARLY_STOP == True):
early_step += 1
if(early_step >= early_stopping_steps):
break
x_test = test_[feature_cols].values
testdataset = TestDataset(x_test)
 testloader = torch.utils.data.DataLoader(testdataset, batch_size=BATCH_SIZE, shuffle=False)
 model = Model(
 num_features=num_features,
num_targets=num_targets,
hidden_size=hidden_size, 
)
 model.load_state_dict(torch.load(f"FOLD{fold}_.pth"))
model.to(DEVICE)
 predictions = np.zeros(( len(test_), target.iloc[:, 1:].shape[1]))
predictions = inference_fn(model, testloader, DEVICE)
 return oof, predictions<categorify>
epochs_num = 25
n_hidden = 300
n_in = 2
model = Sequential()
model.add(GRU(n_hidden,
batch_input_shape=(None, maxlen, n_in),
kernel_initializer='random_uniform',
return_sequences=False))
model.add(Dense(1, kernel_initializer='random_uniform'))
model.add(Activation("linear"))
opt = Adagrad(lr=0.01, epsilon=1e-08, decay=1e-4)
 model.compile(loss = huber_loss_mean, optimizer=opt )
def run_k_fold(NFOLDS, seed):
oof = np.zeros(( len(train), len(target_cols)))
 predictions = np.zeros(( len(test), len(target_cols)))
 for fold in range(NFOLDS):
oof_, pred_ = run_training(fold, seed)
 predictions += pred_ / NFOLDS
oof += oof_
return oof, predictions<feature_engineering>
early_stopping = EarlyStopping(monitor='loss', patience=5, verbose=1)
 hist = model.fit(X_train, Y_train, batch_size=8, epochs=epochs_num,
callbacks=[early_stopping],shuffle=False )
SEED = [1903, 1881]
oof = np.zeros(( len(train), len(target_cols)))
 predictions = np.zeros(( len(test), len(target_cols)))
 for seed in SEED:
print(f"SEED: {seed}")
 oof_, predictions_ = run_k_fold(NFOLDS, seed)
 oof += oof_ / len(SEED)
 predictions += predictions_ / len(SEED)
 train[target_cols] = oof
test[target_cols] = predictions<merge>
predicted_std = model.predict(X_test)
 result_std= pd.DataFrame(predicted_std)
 result_std.columns = ['predict']
result_std['actual'] = Y_test
valid_results = train_targets_scored.drop(columns=target_cols ).merge(train[['sig_id']+target_cols], on='sig_id', how='left' ).fillna(0)
 y_true = train_targets_scored[target_cols].values
y_pred = valid_results[target_cols].values
score = 0
for i in range(len(target_cols)) :
score_ = log_loss(y_true[:, i], y_pred[:, i])
 score += score_ / target.shape[1]
print("CV log_loss: ", score )<save_to_csv>
predicted = scaler.inverse_transform(predicted_std)
 Y_test = scaler.inverse_transform(Y_test )
sub = sample_submission.drop(columns=target_cols ).merge(test[['sig_id']+target_cols], on='sig_id', how='left' ).fillna(0)
 sub.to_csv('submission.csv', index=False )<install_modules>
X_test_ = scaler.inverse_transform(X_test)
 X_test_[9]
! pip install.. /input/pytorch16gpu/torch-1.6.0cu101-cp37-cp37m-linux_x86_64.whl<install_modules>
submission_df = submission_c
!pip install.. /input/iterative-stratification/iterative_stratification-0.1.6-py3-none-any.whl 
<feature_engineering>
temp =(datetime.datetime.strptime("2020-03-18", '%Y-%m-%d')- datetime.timedelta(days=maxlen)).strftime('%Y-%m-%d')
 test_df = train_df[train_df["Date"] > temp]
os.environ["CUDA_LAUNCH_BLOCKING"] = "1" 
<set_options>
check_df["Fatalities_std"] = scaler.transform(check_df["Fatalities"].values.reshape(len(check_df["Fatalities"].values),1))
check_df
def seed_everything(seed_value):
random.seed(seed_value)
 np.random.seed(seed_value)
 torch.manual_seed(seed_value)
 os.environ['PYTHONHASHSEED'] = str(seed_value)
 if torch.cuda.is_available() :
torch.cuda.manual_seed(seed_value)
 torch.cuda.manual_seed_all(seed_value)
 torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
seed_everything(42 )<load_from_csv>
fatalities_pred = []
for i in range(0,294*maxlen,maxlen):
temp_array = np.array(test_df[["Fatalities_std","ConfirmedCases_std"]][i:i+maxlen])
 for j in range(43):
if j<13:
temp_array = np.append(temp_array,np.append(np.array(check_df["Fatalities_std"])[int(i*13/maxlen)+j],np.array(check_df["ConfirmedCases_std"])[int(i*13/maxlen)+j] ).reshape(1,2),axis=0)
 elif np.array(test_df[["Fatalities","ConfirmedCases"]][i:i+maxlen] ).sum() == 0:
temp_array = np.append(temp_array,np.array(temp_array[-1] ).reshape(1,2),axis=0)
 else:
temp_array = np.append(temp_array,np.append(model.predict(temp_array[-maxlen:].reshape(1,maxlen,2)) ,submission_df["ConfirmedCases_std"][i/maxlen*43+j] ).reshape(1,2),axis=0)
 fatalities_pred.append(temp_array[-43:] )
train_features = pd.read_csv('.. /input/lish-moa/train_features.csv')
 train = pd.read_csv('.. /input/lish-moa/train_features.csv')
 train_targets_scored = pd.read_csv('.. /input/lish-moa/train_targets_scored.csv')
 train_targets_nonscored = pd.read_csv('.. /input/lish-moa/train_targets_nonscored.csv')
 test_features = pd.read_csv('.. /input/lish-moa/test_features.csv')
 submission = pd.read_csv('.. /input/lish-moa/sample_submission.csv' )<define_variables>
submission_df["Fatalities"] = np.abs(scaler.inverse_transform([i[0] for i in np.array(fatalities_pred ).reshape(294*43,2)]))
submission_df
GENES = [col for col in train_features.columns if col.startswith('g-')]
CELLS = [col for col in train_features.columns if col.startswith('c-')]<concatenate>
submission_df[["ConfirmedCases","Fatalities"]] = submission_df[["ConfirmedCases","Fatalities"]].round().astype(int)
 submission_df
n_comp = 29
data = pd.concat([pd.DataFrame(train_features[GENES]), pd.DataFrame(test_features[GENES])])
 data2 =(PCA(n_components=n_comp, random_state=42 ).fit_transform(data[GENES]))
train2 = data2[:train_features.shape[0]]; test2 = data2[-test_features.shape[0]:]
train2 = pd.DataFrame(train2, columns=[f'pca_G-{i}' for i in range(n_comp)])
 test2 = pd.DataFrame(test2, columns=[f'pca_G-{i}' for i in range(n_comp)])
 train_features = pd.concat(( train_features, train2), axis=1)
 test_features = pd.concat(( test_features, test2), axis=1)
 n_comp = 4
data = pd.concat([pd.DataFrame(train_features[CELLS]), pd.DataFrame(test_features[CELLS])])
 data2 =(PCA(n_components=n_comp, random_state=42 ).fit_transform(data[CELLS]))
train2 = data2[:train_features.shape[0]]; test2 = data2[-test_features.shape[0]:]
train2 = pd.DataFrame(train2, columns=[f'pca_C-{i}' for i in range(n_comp)])
 test2 = pd.DataFrame(test2, columns=[f'pca_C-{i}' for i in range(n_comp)])
 train_features = pd.concat(( train_features, train2), axis=1)
 test_features = pd.concat(( test_features, test2), axis=1 )<filter>
submission_df = submission_df.drop("ConfirmedCases_std",axis=1 )
remove_vehicle = True
if remove_vehicle:
train_features = train_features.loc[train['cp_type']=='trt_cp'].reset_index(drop=True)
 train_targets_scored = train_targets_scored.loc[train['cp_type']=='trt_cp'].reset_index(drop=True)
 train_targets_nonscored = train_targets_nonscored.loc[train['cp_type']=='trt_cp'].reset_index(drop=True)
 else:
train_features = train_features<data_type_conversions>
submission_df = submission_df.set_index('ForecastId' )
<categorify><EOS> 
submission_df.to_csv('submission.csv' )