Skip to content

Instantly share code, notes, and snippets.

@RileyLazarou
Last active November 17, 2019 01:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RileyLazarou/e900726c7fb19028be7b2bc9b2a35a10 to your computer and use it in GitHub Desktop.
Save RileyLazarou/e900726c7fb19028be7b2bc9b2a35a10 to your computer and use it in GitHub Desktop.
# Load the data
df = pd.read_csv('iris.csv')
# Enumerate the classes
unique_classes = sorted(list(set(df['variety'])))
class_number = {y : x for x,y in enumerate(unique_classes)}
df['variety'] = [class_number[x] for x in df['variety']]
# Convert to numpy array and standardize the features
data_X = df[['sepal.length', 'sepal.width', 'petal.length', 'petal.width']].values
data_Y = df[['variety']].values
data_X = data_X - np.min(data_X, axis=0)
data_X = data_X / np.max(data_X, axis=0)
# The function to create the initial population
organism_creator = lambda : Organism([4, 16, 16, 16, 3], output='softmax')
# The fitness function will be the classification accuracy
fitness_function = lambda y_true, y_estimate : (
np.mean(y_true.flatten() == np.argmax(y_estimate, axis=1)))
def simulate_and_evaluate(organism, indices):
"""
Predict the probabilities of each class and return the fitness
Indices is the list of indices to use in evaluation
"""
predictions = organism.predict(data_X[indices])
return fitness_function(data_Y[indices], predictions)
# Separate training and test data using random indices
indices = np.arange(len(df))
np.random.shuffle(indices)
indices_train, indices_test = indices[:100], indices[100:]
# Create the scoring function and build the ecosystem
scoring_function = lambda organism : simulate_and_evaluate(organism, indices=indices_train)
ecosystem = Ecosystem(organism_creator, scoring_function,
population_size=100, holdout=0.1, mating=True)
# Run 20 generations
generations = 20
for i in range(generations):
ecosystem.generation()
this_generation_best = ecosystem.get_best_organism(include_reward=True)
# [Visualization code omitted...]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment