Created
December 12, 2018 07:19
-
-
Save ytbilly3636/80beefc8244980698f06ecdf59607080 to your computer and use it in GitHub Desktop.
GAのようなもので連立方程式を解いてみる
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding:utf-8 -*- | |
import numpy as np | |
class GA(object): | |
def __init__(self, num, dim): | |
self.gen = np.random.randn(num, dim) | |
def run(self, x): | |
self.y = self.gen.dot(x.T) | |
return self.y | |
def learn(self, t): | |
w0, w1 = self.__winner(t) | |
self.__cross(w0, w1) | |
self.__mutation(0.1) | |
def __winner(self, t): | |
loss = (self.y - t) ** 2 | |
win0 = np.argmin(loss) | |
loss[win0] = np.max(loss) + 1 | |
win1 = np.argmin(loss) | |
return win0, win1 | |
def __cross(self, w0, w1): | |
mask = np.random.randint(2, size=self.gen.shape) | |
self.gen = self.gen[w0].reshape(1, -1) * mask + self.gen[w1].reshape(1, -1) * (1 - mask) | |
def __mutation(self, coef): | |
num = self.gen.shape[0] | |
dim = self.gen.shape[1] | |
random = np.random.randn(num, dim) | |
self.gen += coef * random | |
ga = GA(num=10, dim=4) | |
# 0.5a + -1.2b + 3.4c + -d | |
# (1, -1, 2, 3): 0.5 + 1.2 + 6.8 - 3 = 5.5 | |
# (2, -2, 1, 2): 1 + 2.4 + 3.4 - 2 = 4.8 | |
# (3, 2, 1, -1): 1.5 - 2.4 + 3.4 + 1 = 3.5 | |
# (4, 1, -1, 1): 2 - 1.2 - 3.4 - 1 = -3.6 | |
x = np.array([ | |
[1, -1, 2, 3], | |
[2, -2, 1, 2], | |
[3, 2, 1, -1], | |
[4, 1, -1, 1] | |
]) | |
t = np.array([5.5, 4.8, 3.5, -3.6]) | |
print(ga.gen) | |
for i in range(100000): | |
y = ga.run(x[i%4].reshape(1, -1)) | |
ga.learn(t[i%4].reshape(1, -1)) | |
y = ga.run(x[0].reshape(1, -1)) | |
print(y) | |
print(ga.gen) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment