Kaggle competition: Rock, Paper, Scissors
<SOS> metric: rps Kaggle data source: rock,-paper,-scissors<prepare_x_and_y>
%%writefile predict_only_when_confirmation.py
USE_BACK = 10
CHECK_WINS_RATE_THRES = 0.9
CHECK_PAST_PERIOD = 100
PRED_USE_STEP_THRES = 200
PRED_USE_SCORE_THRES = 0.9
my_actions = []
op_actions = []
pr_actions = []
cont_wins = 0
solutions = []
def predict(my_actions, op_actions):
size = len(my_actions)
 d = dict()
for u in range(USE_BACK):
d[f"OP_{u}"] = op_actions[u: size -(USE_BACK - u)]
d[f"MY_{u}"] = my_actions[u: size -(USE_BACK - u)]
X_train = pd.DataFrame(d)
 y_train = op_actions[USE_BACK: size]
y_train = pd.DataFrame(y_train, columns=["y"])
 n = dict()
for u in range(USE_BACK):
n[f"OP_{u}"] = [op_actions[size -(USE_BACK - u)]]
n[f"MY_{u}"] = [my_actions[size -(USE_BACK - u)]]
X_test = pd.DataFrame(n)
 classifier = lgb.LGBMClassifier(
 random_state=0,
n_estimators=20, 
)
 classifier.fit(X_train, y_train)
 return classifier.predict_proba(X_test ).tolist() [0], int(classifier.predict(X_test)[0])
 def randomize() :
return int(random.randint(0, 2))
def predict_only_when_confirmation(observation, configuration):
global my_actions
global op_actions
global pr_actions
global cont_wins
if observation.step != 0:
op_actions.append(observation.lastOpponentAction)
 if observation.step > USE_BACK:
pred_proba, pred = predict(my_actions, op_actions)
 pr_actions.append(pred)
 if observation.step > PRED_USE_STEP_THRES:
CONF_A = max(pred_proba)> PRED_USE_SCORE_THRES
CONF_B = sum([op==l for op, l in zip(op_actions[-CHECK_PAST_PERIOD:], pr_actions[-CHECK_PAST_PERIOD-1:-1])])/CHECK_PAST_PERIOD > CHECK_WINS_RATE_THRES
if CONF_A or CONF_B:
my_action = pred
my_action =(my_action + 1)% 3
else:
my_action = randomize()
else:
my_action = randomize()
else:
my_action = randomize()
my_actions.append(my_action)
 return my_action
for myplace in ['Iran']:
fig, axs = plt.subplots(1, 2, figsize=(15, 3))
dat = tt.query('Place == @myplace and Days_Since_Ten_Cases >= 0')[['Days_Since_Ten_Cases','ConfirmedCases']].dropna()
dat = dat.iloc[-10:]
X = dat['Days_Since_Ten_Cases']
y = dat['ConfirmedCases']
y = y.cummax()
dat_all = tt.query('Place == @myplace and Days_Since_Ten_Cases >= 0')[['Days_Since_Ten_Cases','ConfirmedCases']]
X_pred = dat_all['Days_Since_Ten_Cases']
en = ElasticNet()
en.fit(X.values.reshape(-1, 1), y.values)
 preds = en.predict(X_pred.values.reshape(-1, 1))
tt.loc[(tt['Place'] == myplace)&(tt['Days_Since_Ten_Cases'] >= 0), 'ConfirmedCases_Pred1'] = preds
pop_myplace = tt.query('Place == @myplace')['Population_final'].values[0]
tt.loc[(tt['Place'] == myplace)&(tt['ConfirmedCases_Pred1'] >(0.1 * pop_myplace)) , 'ConfirmedCases_Pred1'] =(0.1 * pop_myplace)
 ax = tt.query('Place == @myplace' ).set_index('Date')[['ConfirmedCases','ConfirmedCases_Pred1']].plot(figsize=(15, 5), title=myplace, ax=axs[0])
 dat = tt.query('Place == @myplace and Days_Since_Ten_Cases >= 0')[['Days_Since_Ten_Cases','Fatalities']].dropna()
dat = dat.iloc[-10:]
if len(dat)< 5:
tt.loc[(tt['Place'] == myplace), 'Fatalities_Pred1'] = tt.loc[(tt['Place'] == myplace)]['ConfirmedCases_Pred1'] * 0.001
elif tt.query('Place == @myplace')['Fatalities'].max() < 5:
tt.loc[(tt['Place'] == myplace), 'Fatalities_Pred1'] = tt.loc[(tt['Place'] == myplace)]['ConfirmedCases_Pred1'] * 0.001
else:
X = dat['Days_Since_Ten_Cases']
y = dat['Fatalities']
y = y.cummax()
dat_all = tt.query('Place == @myplace and Days_Since_Ten_Cases >= 0')[['Days_Since_Ten_Cases','Fatalities']]
X_pred = dat_all['Days_Since_Ten_Cases']
en = ElasticNet()
en.fit(X.values.reshape(-1, 1), y.values)
 preds = en.predict(X_pred.values.reshape(-1, 1))
tt.loc[(tt['Place'] == myplace)&(tt['Days_Since_Ten_Cases'] >= 0), 'Fatalities_Pred1'] = preds
pop_myplace = tt.query('Place == @myplace')['Population_final'].values[0]
tt.loc[(tt['Place'] == myplace)&(tt['Fatalities_Pred1'] >(0.0005 * pop_myplace)) , 'Fatalities_Pred1'] =(0.0005 * pop_myplace)
 ax = tt.query('Place == @myplace' ).set_index('Date')[['Fatalities','Fatalities_Pred1']].plot(figsize=(15, 5), title=myplace, ax=axs[1])
 plt.show()<feature_engineering>
!pip install -q -U kaggle_environments
tt['ConfirmedCases_Pred1'] = tt[['ConfirmedCases','ConfirmedCases_Pred1']].max(axis=1)
 tt['Fatalities_Pred1'] = tt[['Fatalities','Fatalities_Pred1']].max(axis=1)
 tt['ConfirmedCases_Pred1'] = tt['ConfirmedCases_Pred1'].fillna(0)
 tt['Fatalities_Pred1'] = tt['Fatalities_Pred1'].fillna(0)
 tt.loc[~tt['ConfirmedCases'].isna() , 'ConfirmedCases_Pred1'] = tt.loc[~tt['ConfirmedCases'].isna() ]['ConfirmedCases']
tt.loc[~tt['Fatalities'].isna() , 'Fatalities_Pred1'] = tt.loc[~tt['Fatalities'].isna() ]['Fatalities']
tt['ConfirmedCases_Pred1'] = tt.groupby('Place')['ConfirmedCases_Pred1'].transform('cummax')
 tt['Fatalities_Pred1'] = tt.groupby('Place')['Fatalities_Pred1'].transform('cummax' )<load_from_csv>
def simulate_score(player1, player2, steps):
return evaluate(
 "rps",
[player1, player2],
configuration={"episodeSteps": steps}
)
<save_to_csv><EOS> 
opponent_dict = dict()
opponent_dict["black"] = os.listdir(".. /input/rps-dojo/black_belt")
 opponent_dict["blue"] = os.listdir(".. /input/rps-dojo/blue_belt")
 opponent_dict["white"] = os.listdir(".. /input/rps-dojo/white_belt")
 results = []
for types, opponents in tqdm(opponent_dict.items()):
path = f".. /input/rps-dojo/{types}_belt"
for opponent in tqdm(opponents):
result = simulate_score("predict_only_when_confirmation.py", os.path.join(path, opponent), 1000)
 result = [opponent, result[0], types]
results.append(result)
 results_df = pd.DataFrame(results, columns=["opponent", "score", "belt"] )