<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 AnnGroups
This is just a test script to verify that the ANN code works as expected. It also serves as an example
for the usage.
It is NOT used for results reported in the article.
Step1:  Load some data
Step2:  Create an ANN model
With all correct parameters, ensemble settings and such.
Step3:  Train the ANNs
And print groupings on training data.
Step4:  Plot grouping
<ASSISTANT_TASK:>
Python Code:
# import stuffs
%matplotlib inline
import numpy as np
import pandas as pd
from pyplotthemes import get_savefig, classictheme as plt
plt.latex = True
Explanation: AnnGroups
This is just a test script to verify that the ANN code works as expected. It also serves as an example
for the usage.
It is NOT used for results reported in the article.
End of explanation
from datasets import get_pbc
d = get_pbc(prints=True, norm_in=True, norm_out=False)
durcol = d.columns[0]
eventcol = d.columns[1]
if np.any(d[durcol] < 0):
    raise ValueError("Negative times encountered")
# Sort the data before training - handled by ensemble
#d.sort(d.columns[0], inplace=True)
# Example: d.iloc[:, :2] for times, events
d
Explanation: Load some data
End of explanation
import ann
from classensemble import ClassEnsemble
mingroup = int(0.25 * d.shape[0])
def get_net(func=ann.geneticnetwork.FITNESS_SURV_KAPLAN_MIN):
    hidden_count = 10
    outcount = 2
    l = (d.shape[1] - 2) + hidden_count + outcount + 1
    net = ann.geneticnetwork((d.shape[1] - 2), hidden_count, outcount)
    net.fitness_function = func
    net.mingroup = mingroup
    # Be explicit here even though I changed the defaults
    net.connection_mutation_chance = 0.0
    net.activation_mutation_chance = 0
    # Some other values
    net.crossover_method = net.CROSSOVER_UNIFORM
    net.selection_method = net.SELECTION_TOURNAMENT
    net.population_size = 100
    net.generations = 1000
    net.weight_mutation_chance = 0.15
    net.dropout_hidden_probability = 0.5
    net.dropout_input_probability = 0.8
    ann.utils.connect_feedforward(net, [5, 5], hidden_act=net.TANH, out_act=net.SOFTMAX)
    #c = net.connections.reshape((l, l))
    #c[-outcount:, :((d.shape[1] - 2) + hidden_count)] = 1
    #net.connections = c.ravel()
    
    return net
net = get_net()
l = (d.shape[1] - 2) + net.hidden_count + 2 + 1
print(net.connections.reshape((l, l)))
hnets = []
lnets = []
netcount = 2
for i in range(netcount):
    if i % 2:
        n = get_net(ann.geneticnetwork.FITNESS_SURV_KAPLAN_MIN)
        hnets.append(n)
    else:
        n = get_net(ann.geneticnetwork.FITNESS_SURV_KAPLAN_MAX)
        lnets.append(n)
    
e = ClassEnsemble(hnets, lnets)
Explanation: Create an ANN model
With all correct parameters, ensemble settings and such.
End of explanation
e.fit(d, durcol, eventcol)
# grouplabels = e.predict_classes
grouplabels, mems = e.label_data(d)
for l, m in mems.items():
    print("Group", l, "has", len(m), "members")
Explanation: Train the ANNs
And print groupings on training data.
End of explanation
from lifelines.plotting import add_at_risk_counts
from lifelines.estimation import KaplanMeierFitter
from lifelines.estimation import median_survival_times
plt.figure()
fitters = []
for g in ['high', 'mid', 'low']:
    kmf = KaplanMeierFitter()
    fitters.append(kmf)
    members = grouplabels == g
        
    kmf.fit(d.loc[members, durcol],
            d.loc[members, eventcol],
            label='{}'.format(g))
    kmf.plot(ax=plt.gca())#, color=plt.colors[mi])
    print("End survival rate for", g, ":",kmf.survival_function_.iloc[-1, 0])
    if kmf.survival_function_.iloc[-1, 0] <= 0.5:
        print("Median survival for", g, ":",
              median_survival_times(kmf.survival_function_))
    
plt.legend(loc='best', framealpha=0.1)    
plt.ylim((0, 1))
add_at_risk_counts(*fitters)
Explanation: Plot grouping
End of explanation
<END_TASK>