asign1 [Link]
Set Operations
In [1]: b1=[1,0.15,0.3,0.5,0]
b2=[1,0.6,0.2,0.1,0]
In [2]: union=[]
for i in range(len(b1)):
[Link](max(b1[i],b2[i]))
In [3]: print(union)
[1, 0.6, 0.3, 0.5, 0]
In [4]: intersct=[]
for i in range(len(b1)):
[Link](min(b1[i],b2[i]))
print(intersct)
[1, 0.15, 0.2, 0.1, 0]
In [5]: comp1=[]
for i in range(len(b1)):
[Link](1-b1[i])
print(comp1)
[0, 0.85, 0.7, 0.5, 1]
In [6]: comp2=[]
for i in range(len(b2)):
[Link](1-b2[i])
print(comp2)
[0, 0.4, 0.8, 0.9, 1]
In [7]: diff12=[]
for i in range(len(b1)):
[Link](min(b1[i],comp2[i]))
print(diff12)
[0, 0.15, 0.3, 0.5, 0]
In [8]: diff21=[]
for i in range(len(b1)):
[Link](min(b2[i],comp1[i]))
print(diff21)
[0, 0.6, 0.2, 0.1, 0]
1 of 3 26-09-2020, 18:01
asign1 [Link]
In [9]: cartesianprod=[]
for i in range(len(b1)):
z=[]
[Link](z)
for i in range(len(b1)):
for j in range(len(b1)):
cartesianprod[i].append(min(b1[i],b2[j]))
print(cartesianprod)
[[1, 0.6, 0.2, 0.1, 0], [0.15, 0.15, 0.15, 0.1, 0], [0.3, 0.3, 0.2,
0.1, 0], [0.5, 0.5, 0.2, 0.1, 0], [0, 0, 0, 0, 0]]
In [10]: from matplotlib import pyplot as plt
In [11]: x=[1,2,3,4,5]
[Link](x,b1,label="set 1")
[Link](x,b2,label="set 2")
[Link]()
Out[11]: <[Link] at 0x7fe7849b4668>
2 of 3 26-09-2020, 18:01
asign1 [Link]
In [12]: [Link](x,union)
Out[12]: [<[Link].Line2D at 0x7fe7848e66a0>]
In [13]: [Link](x,intersct)
Out[13]: [<[Link].Line2D at 0x7fe78485b5c0>]
In [14]: r1=[[0.6,0.3],[0.2,0.9]]
r2=[[1,0.5,0.3],[0.8,0.4,0.7]]
t=[]
for i in range(len(r1)):
z=[]
[Link](z)
for i in range(len(r1)):
for j in range(len(r2)):
t[i].append(min(r1[i],r2[j]))
print(t)
[[[0.6, 0.3], [0.6, 0.3]], [[0.2, 0.9], [0.2, 0.9]]]
In [ ]:
3 of 3 26-09-2020, 18:01
Single Layer Perceptron
import numpy as np
def unit_step(v):
""" Heavyside Step function. v must be a scalar """
if v >= 0:
return 1
else:
return 0
def perceptron(x, w, b):
v = [Link](w, x) + b
y = unit_step(v)
return y
def NOT_percep(x):
return perceptron(x, w=-1, b=0.5)
print("NOT(0) = {}".format(NOT_percep(0)))
print("NOT(1) = {}".format(NOT_percep(1)))
def AND_percep(x):
w = [Link]([1, 1])
b = -1.5
return perceptron(x, w, b)
example1_and = [Link]([1, 1])
example2_and = [Link]([1, 0])
example3_and = [Link]([0, 1])
example4_and = [Link]([0, 0])
print("AND(1, 1) = "+str(AND_percep(example1_and)))
print("AND(1, 0) = "+str(AND_percep(example2_and)))
print("AND(0, 1) = "+str(AND_percep(example3_and)))
print("AND(0, 0) = "+str(AND_percep(example4_and)))
def OR_percep(x):
w = [Link]([1, 1])
b = -0.5
return perceptron(x, w, b)
example1_or = [Link]([1, 1])
example2_or = [Link]([1, 0])
example3_or = [Link]([0, 1])
example4_or = [Link]([0, 0])
print("OR({}, {}) = {}".format(1, 1, OR_percep(example1_or)))
print("OR({}, {}) = {}".format(1, 0, OR_percep(example2_or)))
print("OR({}, {}) = {}".format(0, 1, OR_percep(example3_or)))
print("OR({}, {}) = {}".format(0, 0, OR_percep(example4_or)))
****************OUTPUT****************
NOT(0) = 1
NOT(1) = 0
AND(1, 1) = 1
AND(1, 0) = 0
AND(0, 1) = 0
AND(0, 0) = 0
OR(1, 1) = 1
OR(1, 0) = 1
OR(0, 1) = 1
OR(0, 0) = 0
PSO on Rosenbrock function
from [Link].global_best import GlobalBestPSO
# instatiate the optimizer
x_max = 10 * [Link](2)
x_min = -1 * x_max
bounds = (x_min, x_max)
options = {'c1': 0.5, 'c2': 0.3, 'w': 0.9}
optimizer = GlobalBestPSO(n_particles=10, dimensions=2, options=options, bounds=bounds)
# now run the optimization, pass a=1 and b=100 as a tuple assigned to args
cost, pos = [Link](rosenbrock_with_args, 1000, a=1, b=100, c=0)
# for c1=c2 = 2
options = {'c1': 2, 'c2': 2, 'w': 0.9}
optimizer = GlobalBestPSO(n_particles=10, dimensions=2, options=options, bounds=bounds)
cost, pos = [Link](rosenbrock_with_args, 1000, a=1, b=100, c=0)
GA on Rosenbrock function
from __future__ import division
import random
'''
Abbreviations:
gen: generation, a set of peer solutions
sol: solution, coordinates with SOL_DIM dimensions
Rosenbrock function: f(x, y) = (a - x) ^ 2 + b * (y - x ^ 2) ^ 2
Example parameters: a = 1 and b = 100
Goal: find the closest solution to the min of f(x, y)
'''
GEN_SIZE = 100
GEN_COUNT = 100
BOUNDS = ((-100, 100), (-100, 100))
def random_generation():
generation = []
for _ in xrange(GEN_SIZE):
random_point = ([Link](BOUNDS[0][0], BOUNDS[0][1]), [Link](BOUNDS[1][0],
BOUNDS[1][1]))
[Link](random_point)
return generation
def rosenbrock(solution):
return abs((1 - solution[0]) ** 2 + 100 * (solution[1] - solution[0] ** 2) ** 2)
def inverse(value):
if value == 0:
return 1
else:
return 1 / value
def fitness(solution):
return inverse(rosenbrock(solution))
def probability(fitness_score, total):
assert total != 0
return fitness_score / total
def weighted_choice(items):
weight_total = sum((item[1] for item in items))
n = [Link](0, weight_total)
for item, weight in items:
if n < weight:
return item
n = n - weight
return item
def crossover(solution1, solution2):
# pos = int([Link]() * 2) # this is a good line, but
pos = 1 # let's simplify
return solution1[:pos] + solution2[pos:], solution2[:pos] + solution1[pos:]
def mutate(solution):
tmp_sol = [solution[0], solution[1]]
mutation_threshold = 0.2
for i in range(len(solution)):
if [Link]() > mutation_threshold:
tmp_sol[i] = [Link](BOUNDS[i][0], BOUNDS[i][1])
mutated_sol = (tmp_sol[0], tmp_sol[1])
return mutated_sol
if __name__ == "__main__":
cur_gen_count = 0
gens = []
# Step 1. Create an initial generation
gen = random_generation()
[Link](gen)
cur_gen_count += 1
# Step 2. Calculate fitness
fitness_scores = []
for sol in gen:
fitness_score = fitness(sol)
fitness_scores.append(fitness_score)
total_value = 0
for score in fitness_scores:
total_value += score
probas = []
for score in fitness_scores:
proba = probability(score, total_value)
[Link](proba)
weighted_gen = []
for i, sol in enumerate(gen):
weighted_gen.append(((sol[0], sol[1]), probas[i]))
print "INITIAL GENERATION"
print "\tGENERATION #%s" % cur_gen_count
for i, sol in enumerate(weighted_gen):
print "\t\tSolution #%s: %s, probability: %s%%" % \
(i + 1, sol[0], int(sol[1] * 100))
# Step 3. Create next generations
print "NEXT GENERATIONS"
for _ in xrange(GEN_SIZE - cur_gen_count):
gen = []
cur_gen_count += 1
print "\tGENERATION #%s" % cur_gen_count
for pair_i in xrange(int(GEN_SIZE / 2)):
# Step 3.a Select parents
print "\t\tPair #%s" % (pair_i + 1)
parent1 = weighted_choice(weighted_gen)
parent2 = weighted_choice(weighted_gen)
print "\t\t\tParent 1: %s, Parent 2: %s" % (parent1, parent2)
# Step 3.b Create children
child1, child2 = crossover(parent1, parent2)
print "\t\t\tChild 1: %s, Child 2: %s" % (child1, child2)
# Step 3.c Mutate children
print '\t\t\tChild Mutation:'
child1 = mutate(child1)
child2 = mutate(child2)
print "\t\t\tChild 1: %s, Child 2: %s" % (child1, child2)
[Link](child1)
[Link](child2)
[Link](gen)
print "LAST GENERATION"
print "\tGENERATION #%s" % cur_gen_count
weighted_gen = []
fitness_scores = []
for sol in gen:
fitness_score = fitness(sol)
fitness_scores.append(fitness_score)
total_value = 0
for score in fitness_scores:
total_value += score
probas = []
for score in fitness_scores:
proba = probability(score, total_value)
[Link](proba)
weighted_gen = []
for i, sol in enumerate(gen):
weighted_gen.append(((sol[0], sol[1]), probas[i]))
for i, sol in enumerate(weighted_gen):
print "\t\tSolution #%s: %s, probability: %s%%" % \
(i + 1, sol[0], int(sol[1] * 100))
print("\nSUMMARY")
for gen_i, gen in enumerate(gens):
print "\tGENERATION #%s" % (gen_i + 1)
for sol in enumerate(gen):
print "\t\t", sol[1],
print
fittest_sol = gen[0]
fitness_max = fitness(gen[0])
for sol in gen:
sol_fitness = fitness(sol)
if sol_fitness >= fitness_max:
fittest_sol = sol
fitness_max = sol_fitness
print "\nFittest solution: ", fittest_sol
exit(0)