code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def step(self):
""" integrate state using simple rectangle rule """
thrust = float(self.action[0])
rudder = float(self.action[1])
h, hdot, v = self.sensors
rnd = random.normal(0, 1.0, size=3)
thrust = min(max(thrust, -1), +2)
rudder = min(max(rudder, -90), +90)
... | integrate state using simple rectangle rule | step | python | pybrain/pybrain | pybrain/rl/environments/shipsteer/shipsteer.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/shipsteer/shipsteer.py | BSD-3-Clause |
def reset(self):
""" re-initializes the environment, setting the ship to rest at a random orientation.
"""
# [h, hdot, v]
self.sensors = [random.uniform(-30., 30.), 0.0, 0.0]
if self.render:
if self.server.clients > 0:
... | re-initializes the environment, setting the ship to rest at a random orientation.
| reset | python | pybrain/pybrain | pybrain/rl/environments/shipsteer/shipsteer.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/shipsteer/shipsteer.py | BSD-3-Clause |
def performAction(self, action):
""" stores the desired action for the next time step.
"""
self.action = action
self.step()
if self.render:
if self.updateDone:
self.updateRenderer()
if self.server.clients > 0:
sleep(... | stores the desired action for the next time step.
| performAction | python | pybrain/pybrain | pybrain/rl/environments/shipsteer/shipsteer.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/shipsteer/shipsteer.py | BSD-3-Clause |
def drawScene(self):
''' This methode describes the complete scene.'''
# clear the buffer
if self.zDis < 10: self.zDis += 0.25
if self.lastz > 100: self.lastz -= self.zDis
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
# Point of view
... | This methode describes the complete scene. | drawScene | python | pybrain/pybrain | pybrain/rl/environments/shipsteer/viewer.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/shipsteer/viewer.py | BSD-3-Clause |
def __init__(self, size, suicideenabled=True):
""" the size of the board is generally between 3 and 19. """
self.size = size
self.suicideenabled = suicideenabled
self.reset() | the size of the board is generally between 3 and 19. | __init__ | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/capturegame.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/capturegame.py | BSD-3-Clause |
def _iterPos(self):
""" an iterator over all the positions of the board. """
for i in range(self.size):
for j in range(self.size):
yield (i, j) | an iterator over all the positions of the board. | _iterPos | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/capturegame.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/capturegame.py | BSD-3-Clause |
def getBoardArray(self):
""" an array with two boolean values per position, indicating
'white stone present' and 'black stone present' respectively. """
a = zeros(self.outdim)
for i, p in enumerate(self._iterPos()):
if self.b[p] == self.WHITE:
a[2 * i] = 1
... | an array with two boolean values per position, indicating
'white stone present' and 'black stone present' respectively. | getBoardArray | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/capturegame.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/capturegame.py | BSD-3-Clause |
def doMove(self, c, pos):
""" the action is a (color, position) tuple, for the next stone to move.
returns True if the move was legal. """
self.movesDone += 1
if pos == 'resign':
self.winner = -c
return True
elif not self.isLegal(c, pos):
retur... | the action is a (color, position) tuple, for the next stone to move.
returns True if the move was legal. | doMove | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/capturegame.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/capturegame.py | BSD-3-Clause |
def _setStone(self, c, pos):
""" set stone, and update liberties and groups. """
self.b[pos] = c
merge = False
self.groups[pos] = self.size * pos[0] + pos[1]
freen = [n for n in self._neighbors(pos) if self.b[n] == self.EMPTY]
self.liberties[self.groups[pos]] = set(freen)... | set stone, and update liberties and groups. | _setStone | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/capturegame.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/capturegame.py | BSD-3-Clause |
def _suicide(self, c, pos):
""" would putting a stone here be suicide for c? """
# any free neighbors?
for n in self._neighbors(pos):
if self.b[n] == self.EMPTY:
return False
# any friendly neighbor with extra liberties?
for n in self._neighbors(pos):... | would putting a stone here be suicide for c? | _suicide | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/capturegame.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/capturegame.py | BSD-3-Clause |
def _capture(self, c, pos):
""" would putting a stone here lead to a capture? """
for n in self._neighbors(pos):
if self.b[n] == -c:
if len(self.liberties[self.groups[n]]) == 1:
return True
return False | would putting a stone here lead to a capture? | _capture | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/capturegame.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/capturegame.py | BSD-3-Clause |
def getLiberties(self, pos):
""" how many liberties does the stone at pos have? """
if self.b[pos] == self.EMPTY:
return None
return len(self.liberties[self.groups[pos]]) | how many liberties does the stone at pos have? | getLiberties | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/capturegame.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/capturegame.py | BSD-3-Clause |
def getGroupSize(self, pos):
""" what size is the worm that this stone is part of? """
if self.b[pos] == self.EMPTY:
return None
g = self.groups[pos]
return len([x for x in list(self.groups.values()) if x == g]) | what size is the worm that this stone is part of? | getGroupSize | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/capturegame.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/capturegame.py | BSD-3-Clause |
def randomBoard(self, nbmoves):
""" produce a random, undecided and legal capture-game board, after at most nbmoves.
:return: the number of moves actually done. """
c = self.BLACK
self.reset()
for i in range(nbmoves):
l = set(self.getAcceptable(c))
l.diffe... | produce a random, undecided and legal capture-game board, after at most nbmoves.
:return: the number of moves actually done. | randomBoard | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/capturegame.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/capturegame.py | BSD-3-Clause |
def playToTheEnd(self, p1, p2):
""" alternate playing moves between players until the game is over. """
assert p1.color == -p2.color
i = 0
p1.game = self
p2.game = self
players = [p1, p2]
while not self.gameOver():
p = players[i]
self.perfo... | alternate playing moves between players until the game is over. | playToTheEnd | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/capturegame.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/capturegame.py | BSD-3-Clause |
def __init__(self, size):
""" the size of the board is a tuple, where each dimension must be minimum 5. """
self.size = size
assert size[0] >= 5
assert size[1] >= 5
self.reset() | the size of the board is a tuple, where each dimension must be minimum 5. | __init__ | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/gomoku.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/gomoku.py | BSD-3-Clause |
def _iterPos(self):
""" an iterator over all the positions of the board. """
for i in range(self.size[0]):
for j in range(self.size[1]):
yield (i, j) | an iterator over all the positions of the board. | _iterPos | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/gomoku.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/gomoku.py | BSD-3-Clause |
def _fiveRow(self, color, pos):
""" Is this placement the 5th in a row? """
# TODO: more efficient...
for dir in [(0, 1), (1, 0), (1, 1), (1, -1)]:
found = 1
for d in [-1, 1]:
for i in range(1, 5):
next = (pos[0] + dir[0] * i * d, pos[1... | Is this placement the 5th in a row? | _fiveRow | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/gomoku.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/gomoku.py | BSD-3-Clause |
def getBoardArray(self):
""" an array with thow boolean values per position, indicating
'white stone present' and 'black stone present' respectively. """
a = zeros(self.outdim)
for i, p in enumerate(self._iterPos()):
if self.b[p] == self.WHITE:
a[2 * i] = 1
... | an array with thow boolean values per position, indicating
'white stone present' and 'black stone present' respectively. | getBoardArray | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/gomoku.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/gomoku.py | BSD-3-Clause |
def doMove(self, c, pos):
""" the action is a (color, position) tuple, for the next stone to move.
returns True if the move was legal. """
self.movesDone += 1
if not self.isLegal(c, pos):
return False
elif self._fiveRow(c, pos):
self.winner = c
... | the action is a (color, position) tuple, for the next stone to move.
returns True if the move was legal. | doMove | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/gomoku.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/gomoku.py | BSD-3-Clause |
def playToTheEnd(self, p1, p2):
""" alternate playing moves between players until the game is over. """
assert p1.color == -p2.color
i = 0
p1.game = self
p2.game = self
players = [p1, p2]
while not self.gameOver():
p = players[i]
self.perfo... | alternate playing moves between players until the game is over. | playToTheEnd | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/gomoku.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/gomoku.py | BSD-3-Clause |
def getKilling(self, c):
""" return all legal positions for a color that immediately kill the opponent. """
res = GomokuGame.getKilling(self, c)
for p in self.getLegals(c):
k = self._killsWhich(c, p)
if self.pairsTaken[c] + len(k) / 2 >= 5:
res.append(p)
... | return all legal positions for a color that immediately kill the opponent. | getKilling | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/pente.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/pente.py | BSD-3-Clause |
def _killsWhich(self, c, pos):
""" placing a stone of color c at pos would kill which enemy stones? """
res = []
for dir in [(0, 1), (1, 0), (1, 1), (1, -1)]:
for d in [-1, 1]:
killcands = []
for i in [1, 2, 3]:
next = (pos[0] + dir... | placing a stone of color c at pos would kill which enemy stones? | _killsWhich | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/pente.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/pente.py | BSD-3-Clause |
def doMove(self, c, pos):
""" the action is a (color, position) tuple, for the next stone to move.
returns True if the move was legal. """
self.movesDone += 1
if not self.isLegal(c, pos):
return False
elif self._fiveRow(c, pos):
self.winner = c
... | the action is a (color, position) tuple, for the next stone to move.
returns True if the move was legal. | doMove | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/pente.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/pente.py | BSD-3-Clause |
def _setStone(self, c, pos, tokill=None):
""" set stone, and potentially kill stones. """
if tokill == None:
tokill = self._killsWhich(c, pos)
GomokuGame._setStone(self, c, pos)
for p in tokill:
self.b[p] = self.EMPTY
self.pairsTaken[c] += len(tokill) // 2 | set stone, and potentially kill stones. | _setStone | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/pente.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/pente.py | BSD-3-Clause |
def getAction(self):
""" get suggested action, return them if they are legal, otherwise choose randomly. """
ba = self.game.getBoardArray()
# network is given inputs with self/other as input, not black/white
if self.color != CaptureGame.BLACK:
# invert values
tmp ... | get suggested action, return them if they are legal, otherwise choose randomly. | getAction | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/capturegameplayers/moduledecision.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/capturegameplayers/moduledecision.py | BSD-3-Clause |
def _legalizeIt(self, a):
""" draw index from an array of values, filtering out illegal moves. """
if not min(a) >= 0:
print(a)
print((min(a)))
print((self.module.params))
print((self.module.inputbuffer))
print((self.module.outputbuffer))
... | draw index from an array of values, filtering out illegal moves. | _legalizeIt | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/capturegameplayers/moduledecision.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/capturegameplayers/moduledecision.py | BSD-3-Clause |
def getAction(self):
""" get suggested action, return them if they are legal, otherwise choose randomly. """
ba = self.game.getBoardArray()
# network is given inputs with self/other as input, not black/white
if self.color != GomokuGame.BLACK:
# invert values
tmp =... | get suggested action, return them if they are legal, otherwise choose randomly. | getAction | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/gomokuplayers/moduledecision.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/gomokuplayers/moduledecision.py | BSD-3-Clause |
def _legalizeIt(self, a):
""" draw index from an array of values, filtering out illegal moves. """
if not min(a) >= 0:
print(a)
print((min(a)))
print((self.module.params))
print((self.module.inputbuffer))
print((self.module.outputbuffer))
... | draw index from an array of values, filtering out illegal moves. | _legalizeIt | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/gomokuplayers/moduledecision.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/gomokuplayers/moduledecision.py | BSD-3-Clause |
def getReward(self):
""" Final positive reward for winner, negative for loser. """
if self.isFinished():
win = (self.env.winner != self.opponent.color)
moves = self.env.movesDone
res = self.winnerReward - self.numMovesCoeff * (moves -self.minmoves)/(self.maxmoves-self... | Final positive reward for winner, negative for loser. | getReward | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/tasks/capturetask.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/tasks/capturetask.py | BSD-3-Clause |
def f(self, x):
""" If a module is given, wrap it into a ModuleDecidingAgent before evaluating it.
Also, if applicable, average the result over multiple games. """
if isinstance(x, Module):
agent = ModuleDecidingPlayer(x, self.env, greedySelection = True)
elif isinstance(x, C... | If a module is given, wrap it into a ModuleDecidingAgent before evaluating it.
Also, if applicable, average the result over multiple games. | f | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/tasks/capturetask.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/tasks/capturetask.py | BSD-3-Clause |
def getReward(self):
""" Final positive reward for winner, negative for loser. """
if self.isFinished():
if self.env.winner == self.env.DRAW:
return 0
win = (self.env.winner != self.opponent.color)
moves = self.env.movesDone
res = self.winn... | Final positive reward for winner, negative for loser. | getReward | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/tasks/gomokutask.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/tasks/gomokutask.py | BSD-3-Clause |
def f(self, x):
""" If a module is given, wrap it into a ModuleDecidingAgent before evaluating it.
Also, if applicable, average the result over multiple games. """
if isinstance(x, Module):
agent = ModuleDecidingPlayer(x, self.env, greedySelection = True)
elif isinstance(x, G... | If a module is given, wrap it into a ModuleDecidingAgent before evaluating it.
Also, if applicable, average the result over multiple games. | f | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/tasks/gomokutask.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/tasks/gomokutask.py | BSD-3-Clause |
def goUp(self, h):
""" ready to go up one handicap? """
if self.results[h][1] >= self.minEvals:
return self.winProp(h) > 0.6
return False | ready to go up one handicap? | goUp | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/tasks/handicaptask.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/tasks/handicaptask.py | BSD-3-Clause |
def goDown(self, h):
""" have to go down one handicap? """
if self.results[h][1] >= self.minEvals:
return self.winProp(h) < -0.6
return False | have to go down one handicap? | goDown | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/tasks/handicaptask.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/tasks/handicaptask.py | BSD-3-Clause |
def _oneGame(self, preset = None):
""" a single black stone can be set as the first move. """
self.env.reset()
if preset != None:
self.env._setStone(GomokuGame.BLACK, preset)
self.env.movesDone += 1
self.env.playToTheEnd(self.opponent, self.player)
els... | a single black stone can be set as the first move. | _oneGame | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/tasks/relativegomokutask.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/tasks/relativegomokutask.py | BSD-3-Clause |
def _fixedStartingPos(self):
""" a list of starting positions, not along the border, and respecting symmetry. """
res = []
if self.size < 3:
return res
for x in range(1, (self.size + 1) // 2):
for y in range(x, (self.size + 1) // 2):
res.append((x,... | a list of starting positions, not along the border, and respecting symmetry. | _fixedStartingPos | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/tasks/relativetask.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/tasks/relativetask.py | BSD-3-Clause |
def _oneGame(self, preset=None):
""" a single black stone can be set as the first move. """
self.env.reset()
if preset != None:
self.env._setStone(CaptureGame.BLACK, preset)
self.env.movesDone += 1
self.env.playToTheEnd(self.opponent, self.player)
else... | a single black stone can be set as the first move. | _oneGame | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/tasks/relativetask.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/tasks/relativetask.py | BSD-3-Clause |
def doInteractionsAndLearn(self, number = 1):
""" Execute a number of steps while learning continuously.
no reset is performed, such that consecutive calls to
this function can be made.
"""
for _ in range(number):
self._oneInteraction()
self.agent.... | Execute a number of steps while learning continuously.
no reset is performed, such that consecutive calls to
this function can be made.
| doInteractionsAndLearn | python | pybrain/pybrain | pybrain/rl/experiments/continuous.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/experiments/continuous.py | BSD-3-Clause |
def _oneInteraction(self):
""" Do an interaction between the Task and the Agent. """
if self.doOptimization:
raise Exception('When using a black-box learning algorithm, only full episodes can be done.')
else:
return Experiment._oneInteraction(self) | Do an interaction between the Task and the Agent. | _oneInteraction | python | pybrain/pybrain | pybrain/rl/experiments/episodic.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/experiments/episodic.py | BSD-3-Clause |
def doEpisodes(self, number = 1):
""" Do one episode, and return the rewards of each step as a list. """
if self.doOptimization:
self.optimizer.maxEvaluations += number
self.optimizer.learn()
else:
all_rewards = []
for dummy in range(number):
... | Do one episode, and return the rewards of each step as a list. | doEpisodes | python | pybrain/pybrain | pybrain/rl/experiments/episodic.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/experiments/episodic.py | BSD-3-Clause |
def doInteractions(self, number = 1):
""" The default implementation directly maps the methods of the agent and the task.
Returns the number of interactions done.
"""
for _ in range(number):
self._oneInteraction()
return self.stepid | The default implementation directly maps the methods of the agent and the task.
Returns the number of interactions done.
| doInteractions | python | pybrain/pybrain | pybrain/rl/experiments/experiment.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/experiments/experiment.py | BSD-3-Clause |
def _oneInteraction(self):
""" Give the observation to the agent, takes its resulting action and returns
it to the task. Then gives the reward to the agent again and returns it.
"""
self.stepid += 1
self.agent.integrateObservation(self.task.getObservation())
self.task... | Give the observation to the agent, takes its resulting action and returns
it to the task. Then gives the reward to the agent again and returns it.
| _oneInteraction | python | pybrain/pybrain | pybrain/rl/experiments/experiment.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/experiments/experiment.py | BSD-3-Clause |
def _produceAllPairs(self):
""" produce a list of all pairs of agents (assuming ab <> ba)"""
res = []
for a in self.agents:
for b in self.agents:
if a != b:
res.append((a, b))
return res | produce a list of all pairs of agents (assuming ab <> ba) | _produceAllPairs | python | pybrain/pybrain | pybrain/rl/experiments/tournament.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/experiments/tournament.py | BSD-3-Clause |
def _oneGame(self, p1, p2):
""" play one game between two agents p1 and p2."""
self.numGames += 1
self.env.reset()
players = (p1, p2)
p1.color = self.startcolor
p2.color = -p1.color
p1.newEpisode()
p2.newEpisode()
i = 0
while not self.env.g... | play one game between two agents p1 and p2. | _oneGame | python | pybrain/pybrain | pybrain/rl/experiments/tournament.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/experiments/tournament.py | BSD-3-Clause |
def organize(self, repeat=1):
""" have all agents play all others in all orders, and repeat. """
for dummy in range(repeat):
self.rounds += 1
for p1, p2 in self._produceAllPairs():
self._oneGame(p1, p2)
return self.results | have all agents play all others in all orders, and repeat. | organize | python | pybrain/pybrain | pybrain/rl/experiments/tournament.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/experiments/tournament.py | BSD-3-Clause |
def eloScore(self, startingscore=1500, k=32):
""" compute the elo score of all the agents, given the games played in the tournament.
Also checking for potentially initial scores among the agents ('elo' variable). """
# initialize
elos = {}
for a in self.agents:
if 'el... | compute the elo score of all the agents, given the games played in the tournament.
Also checking for potentially initial scores among the agents ('elo' variable). | eloScore | python | pybrain/pybrain | pybrain/rl/experiments/tournament.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/experiments/tournament.py | BSD-3-Clause |
def _setSigma(self, sigma):
""" Wrapper method to set the sigmas (the parameters of the module) to a
certain value.
"""
assert len(sigma) == self.dim
self._params *= 0
self._params += sigma | Wrapper method to set the sigmas (the parameters of the module) to a
certain value.
| _setSigma | python | pybrain/pybrain | pybrain/rl/explorers/continuous/normal.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/explorers/continuous/normal.py | BSD-3-Clause |
def _setSigma(self, sigma):
""" Wrapper method to set the sigmas (the parameters of the module) to a
certain value.
"""
assert len(sigma) == self.actiondim
self._params *= 0
self._params += sigma | Wrapper method to set the sigmas (the parameters of the module) to a
certain value.
| _setSigma | python | pybrain/pybrain | pybrain/rl/explorers/continuous/sde.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/explorers/continuous/sde.py | BSD-3-Clause |
def activate(self, state, action):
""" The super class commonly ignores the state and simply passes the
action through the module. implement _forwardImplementation()
in subclasses.
"""
self.state = state
return Module.activate(self, action) | The super class commonly ignores the state and simply passes the
action through the module. implement _forwardImplementation()
in subclasses.
| activate | python | pybrain/pybrain | pybrain/rl/explorers/continuous/sde.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/explorers/continuous/sde.py | BSD-3-Clause |
def activate(self, state, action):
""" The super class ignores the state and simply passes the
action through the module. implement _forwardImplementation()
in subclasses.
"""
self._state = state
return DiscreteExplorer.activate(self, state, action) | The super class ignores the state and simply passes the
action through the module. implement _forwardImplementation()
in subclasses.
| activate | python | pybrain/pybrain | pybrain/rl/explorers/discrete/boltzmann.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/explorers/discrete/boltzmann.py | BSD-3-Clause |
def _forwardImplementation(self, inbuf, outbuf):
""" Draws a random number between 0 and 1. If the number is less
than epsilon, a random action is chosen. If it is equal or
larger than epsilon, the greedy action is returned.
"""
assert self.module
values = self.m... | Draws a random number between 0 and 1. If the number is less
than epsilon, a random action is chosen. If it is equal or
larger than epsilon, the greedy action is returned.
| _forwardImplementation | python | pybrain/pybrain | pybrain/rl/explorers/discrete/boltzmann.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/explorers/discrete/boltzmann.py | BSD-3-Clause |
def _setModule(self, module):
""" Tells the explorer the module (which has to be ActionValueTable). """
# removed: cause for circular import
# assert isinstance(module, ActionValueInterface)
self._module = module | Tells the explorer the module (which has to be ActionValueTable). | _setModule | python | pybrain/pybrain | pybrain/rl/explorers/discrete/discrete.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/explorers/discrete/discrete.py | BSD-3-Clause |
def __init__(self, epsilon = 0.2, decay = 0.9998):
""" TODO: the epsilon and decay parameters are currently
not implemented.
"""
DiscreteExplorer.__init__(self)
self.state = None | TODO: the epsilon and decay parameters are currently
not implemented.
| __init__ | python | pybrain/pybrain | pybrain/rl/explorers/discrete/discretesde.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/explorers/discrete/discretesde.py | BSD-3-Clause |
def activate(self, state, action):
""" Save the current state for state-dependent exploration. """
self.state = state
return DiscreteExplorer.activate(self, state, action) | Save the current state for state-dependent exploration. | activate | python | pybrain/pybrain | pybrain/rl/explorers/discrete/discretesde.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/explorers/discrete/discretesde.py | BSD-3-Clause |
def _forwardImplementation(self, inbuf, outbuf):
""" Activate the copied module instead of the original and
feed it with the current state.
"""
if random.random() < 0.001:
outbuf[:] = array([random.randint(self.module.numActions)])
else:
outbuf[:] = se... | Activate the copied module instead of the original and
feed it with the current state.
| _forwardImplementation | python | pybrain/pybrain | pybrain/rl/explorers/discrete/discretesde.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/explorers/discrete/discretesde.py | BSD-3-Clause |
def newEpisode(self):
""" Inform the explorer about the start of a new episode. """
self.explorerModule = deepcopy(self.module)
if isinstance(self.explorerModule, ActionValueNetwork):
self.explorerModule.network.mutationStd = 0.01
self.explorerModule.network.mutate()
... | Inform the explorer about the start of a new episode. | newEpisode | python | pybrain/pybrain | pybrain/rl/explorers/discrete/discretesde.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/explorers/discrete/discretesde.py | BSD-3-Clause |
def _forwardImplementation(self, inbuf, outbuf):
""" Draws a random number between 0 and 1. If the number is less
than epsilon, a random action is chosen. If it is equal or
larger than epsilon, the greedy action is returned.
"""
assert self.module
if random.rando... | Draws a random number between 0 and 1. If the number is less
than epsilon, a random action is chosen. If it is equal or
larger than epsilon, the greedy action is returned.
| _forwardImplementation | python | pybrain/pybrain | pybrain/rl/explorers/discrete/egreedy.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/explorers/discrete/egreedy.py | BSD-3-Clause |
def _setModule(self, module):
""" initialize gradient descender with module parameters and
the loglh dataset with the outdim of the module. """
self._module = module
# initialize explorer
self._explorer = NormalExplorer(module.outdim)
# build network
self._i... | initialize gradient descender with module parameters and
the loglh dataset with the outdim of the module. | _setModule | python | pybrain/pybrain | pybrain/rl/learners/directsearch/policygradient.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/directsearch/policygradient.py | BSD-3-Clause |
def _setExplorer(self, explorer):
""" assign non-standard explorer to the policy gradient learner.
requires the module to be set beforehand.
"""
assert self._module
self._explorer = explorer
# build network
self._initializeNetwork() | assign non-standard explorer to the policy gradient learner.
requires the module to be set beforehand.
| _setExplorer | python | pybrain/pybrain | pybrain/rl/learners/directsearch/policygradient.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/directsearch/policygradient.py | BSD-3-Clause |
def _initializeNetwork(self):
""" build the combined network consisting of the module and
the explorer and initializing the log likelihoods dataset.
"""
self.network = FeedForwardNetwork()
self.network.addInputModule(self._module)
self.network.addOutputModule(self._ex... | build the combined network consisting of the module and
the explorer and initializing the log likelihoods dataset.
| _initializeNetwork | python | pybrain/pybrain | pybrain/rl/learners/directsearch/policygradient.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/directsearch/policygradient.py | BSD-3-Clause |
def learn(self):
""" calls the gradient calculation function and executes a step in direction
of the gradient, scaled with a small learning rate alpha. """
assert self.dataset != None
assert self.module != None
# calculate the gradient with the specific function from subclas... | calls the gradient calculation function and executes a step in direction
of the gradient, scaled with a small learning rate alpha. | learn | python | pybrain/pybrain | pybrain/rl/learners/directsearch/policygradient.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/directsearch/policygradient.py | BSD-3-Clause |
def greedyEpisode(self):
""" run one episode with greedy decisions, return the list of rewards recieved."""
rewards = []
self.task.reset()
self.net.reset()
while not self.task.isFinished():
obs = self.task.getObservation()
act = self.net.activate(obs)
... | run one episode with greedy decisions, return the list of rewards recieved. | greedyEpisode | python | pybrain/pybrain | pybrain/rl/learners/directsearch/rwr.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/directsearch/rwr.py | BSD-3-Clause |
def trueFeatureStats(T, R, fMap, discountFactor, stateProp=1, MAT_LIMIT=1e8):
""" Gather the statistics needed for LSTD,
assuming infinite data (true probabilities).
Option: if stateProp is < 1, then only a proportion of all
states will be seen as starting state for transitions """
dim = len(fMap)... | Gather the statistics needed for LSTD,
assuming infinite data (true probabilities).
Option: if stateProp is < 1, then only a proportion of all
states will be seen as starting state for transitions | trueFeatureStats | python | pybrain/pybrain | pybrain/rl/learners/modelbased/leastsquares.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/modelbased/leastsquares.py | BSD-3-Clause |
def LSTD_Qvalues(Ts, policy, R, fMap, discountFactor):
""" LSTDQ is like LSTD, but with features replicated
once for each possible action.
Returns Q-values in a 2D array. """
numA = len(Ts)
dim = len(Ts[0])
numF = len(fMap)
fMapRep = zeros((numF * numA, dim * numA))
for a in range(... | LSTDQ is like LSTD, but with features replicated
once for each possible action.
Returns Q-values in a 2D array. | LSTD_Qvalues | python | pybrain/pybrain | pybrain/rl/learners/modelbased/leastsquares.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/modelbased/leastsquares.py | BSD-3-Clause |
def LSPI_policy(fMap, Ts, R, discountFactor, initpolicy=None, maxIters=20):
""" LSPI is like policy iteration, but Q-values are estimated based
on the feature map.
Returns the best policy found. """
if initpolicy is None:
policy, _ = randomPolicy(Ts)
else:
policy = initpolicy
... | LSPI is like policy iteration, but Q-values are estimated based
on the feature map.
Returns the best policy found. | LSPI_policy | python | pybrain/pybrain | pybrain/rl/learners/modelbased/leastsquares.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/modelbased/leastsquares.py | BSD-3-Clause |
def LSTD_PI_policy(fMap, Ts, R, discountFactor, initpolicy=None, maxIters=20):
""" Alternative version of LSPI using value functions
instead of state-action values as intermediate.
"""
def veval(T):
return LSTD_values(T, R, fMap, discountFactor)
return policyIteration(Ts, R, discountFactor, ... | Alternative version of LSPI using value functions
instead of state-action values as intermediate.
| LSTD_PI_policy | python | pybrain/pybrain | pybrain/rl/learners/modelbased/leastsquares.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/modelbased/leastsquares.py | BSD-3-Clause |
def trueValues(T, R, discountFactor):
""" Compute the true discounted value function for each state,
given a policy (encoded as collapsed transition matrix). """
assert discountFactor < 1
distr = T.copy()
res = dot(T, R)
for i in range(1, int(10 / (1. - discountFactor))):
distr = dot(dis... | Compute the true discounted value function for each state,
given a policy (encoded as collapsed transition matrix). | trueValues | python | pybrain/pybrain | pybrain/rl/learners/modelbased/policyiteration.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/modelbased/policyiteration.py | BSD-3-Clause |
def trueQValues(Ts, R, discountFactor, policy):
""" The true Q-values, given a model and a policy. """
T = collapsedTransitions(Ts, policy)
V = trueValues(T, R, discountFactor)
Vnext = V*discountFactor+R
numA = len(Ts)
dim = len(R)
Qs = zeros((dim, numA))
for si in range(dim):
fo... | The true Q-values, given a model and a policy. | trueQValues | python | pybrain/pybrain | pybrain/rl/learners/modelbased/policyiteration.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/modelbased/policyiteration.py | BSD-3-Clause |
def collapsedTransitions(Ts, policy):
""" Collapses a list of transition matrices (one per action) and a list
of action probability vectors into a single transition matrix."""
res = zeros_like(Ts[0])
dim = len(Ts[0])
for ai, ap in enumerate(policy.T):
res += Ts[ai] * repmat(ap, dim, 1).... | Collapses a list of transition matrices (one per action) and a list
of action probability vectors into a single transition matrix. | collapsedTransitions | python | pybrain/pybrain | pybrain/rl/learners/modelbased/policyiteration.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/modelbased/policyiteration.py | BSD-3-Clause |
def greedyPolicy(Ts, R, discountFactor, V):
""" Find the greedy policy, (soft tie-breaking)
given a value function and full transition model. """
dim = len(V)
numA = len(Ts)
Vnext = V*discountFactor+R
policy = zeros((dim, numA))
for si in range(dim):
actions = all_argmax([dot(T[si, :... | Find the greedy policy, (soft tie-breaking)
given a value function and full transition model. | greedyPolicy | python | pybrain/pybrain | pybrain/rl/learners/modelbased/policyiteration.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/modelbased/policyiteration.py | BSD-3-Clause |
def greedyQPolicy(Qs):
""" Find the greedy deterministic policy,
given the Q-values. """
dim = len(Qs)
numA = len(Qs[0])
policy = zeros((dim, numA))
for si in range(dim):
actions = all_argmax(Qs[si])
for a in actions:
policy[si, a] = 1. / len(actions)
return ... | Find the greedy deterministic policy,
given the Q-values. | greedyQPolicy | python | pybrain/pybrain | pybrain/rl/learners/modelbased/policyiteration.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/modelbased/policyiteration.py | BSD-3-Clause |
def randomDeterministic(Ts):
""" Pick a random deterministic action for each state. """
numA = len(Ts)
dim = len(Ts[0])
choices = (rand(dim) * numA).astype(int)
policy = zeros((dim, numA))
for si, a in choices:
policy[si, a] = 1
return policy, collapsedTransitions(Ts, policy) | Pick a random deterministic action for each state. | randomDeterministic | python | pybrain/pybrain | pybrain/rl/learners/modelbased/policyiteration.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/modelbased/policyiteration.py | BSD-3-Clause |
def policyIteration(Ts, R, discountFactor, VEvaluator=None, initpolicy=None, maxIters=20):
""" Given transition matrices (one per action),
produce the optimal policy, using the policy iteration algorithm.
A custom function that maps policies to value functions can be provided. """
if initpolicy is ... | Given transition matrices (one per action),
produce the optimal policy, using the policy iteration algorithm.
A custom function that maps policies to value functions can be provided. | policyIteration | python | pybrain/pybrain | pybrain/rl/learners/modelbased/policyiteration.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/modelbased/policyiteration.py | BSD-3-Clause |
def getMaxAction(self, state):
""" Return the action with the maximal value for the given state. """
values = self.params.reshape(self.numRows, self.numColumns)[int(state), :].flatten()
action = where(values == max(values))[0]
action = choice(action)
return action | Return the action with the maximal value for the given state. | getMaxAction | python | pybrain/pybrain | pybrain/rl/learners/valuebased/interface.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/valuebased/interface.py | BSD-3-Clause |
def _updateWeights(self, state, action, reward, next_state):
""" state and next_state are vectors, action is an integer. """
td_error = reward + self.rewardDiscount * max(dot(self._theta, next_state)) - dot(self._theta[action], state)
#print(action, reward, td_error,self._theta[action], state, ... | state and next_state are vectors, action is an integer. | _updateWeights | python | pybrain/pybrain | pybrain/rl/learners/valuebased/linearfa.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/valuebased/linearfa.py | BSD-3-Clause |
def _updateWeights(self, state, action, reward, next_state):
""" state and next_state are vectors, action is an integer. """
self._updateEtraces(state, action)
td_error = reward + self.rewardDiscount * max(dot(self._theta, next_state)) - dot(self._theta[action], state)
self._theta += sel... | state and next_state are vectors, action is an integer. | _updateWeights | python | pybrain/pybrain | pybrain/rl/learners/valuebased/linearfa.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/valuebased/linearfa.py | BSD-3-Clause |
def _updateWeights(self, state, action, reward, next_state, next_action):
""" state and next_state are vectors, action is an integer. """
td_error = reward + self.rewardDiscount * dot(self._theta[next_action], next_state) - dot(self._theta[action], state)
self._updateEtraces(state, action)
... | state and next_state are vectors, action is an integer. | _updateWeights | python | pybrain/pybrain | pybrain/rl/learners/valuebased/linearfa.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/valuebased/linearfa.py | BSD-3-Clause |
def _updateWeights(self, state, action, reward, next_state, learned_policy=None):
""" Policy is a function that returns a probability vector for all actions,
given the current state(-features). """
if learned_policy is None:
learned_policy = self._greedyPolicy
self.... | Policy is a function that returns a probability vector for all actions,
given the current state(-features). | _updateWeights | python | pybrain/pybrain | pybrain/rl/learners/valuebased/linearfa.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/valuebased/linearfa.py | BSD-3-Clause |
def learn(self):
""" Learn on the current dataset, either for many timesteps and
even episodes (batchMode = True) or for a single timestep
(batchMode = False). Batch mode is possible, because Q-Learning
is an off-policy method.
In batchMode, the algorithm goes th... | Learn on the current dataset, either for many timesteps and
even episodes (batchMode = True) or for a single timestep
(batchMode = False). Batch mode is possible, because Q-Learning
is an off-policy method.
In batchMode, the algorithm goes through all the samples in the... | learn | python | pybrain/pybrain | pybrain/rl/learners/valuebased/q.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/valuebased/q.py | BSD-3-Clause |
def _setModule(self, module):
""" Set module and tell explorer about the module. """
if self.explorer:
self.explorer.module = module
self._module = module | Set module and tell explorer about the module. | _setModule | python | pybrain/pybrain | pybrain/rl/learners/valuebased/valuebased.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/valuebased/valuebased.py | BSD-3-Clause |
def _setExplorer(self, explorer):
""" Set explorer and tell it the module, if already available. """
self._explorer = explorer
if self.module:
self._explorer.module = self.module | Set explorer and tell it the module, if already available. | _setExplorer | python | pybrain/pybrain | pybrain/rl/learners/valuebased/valuebased.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/valuebased/valuebased.py | BSD-3-Clause |
def __init__(self, constructor, dimensions, name = None, baserename = False):
""":arg constructor: a constructor method that returns a module
:arg dimensions: tuple of dimensions. """
self.dims = dimensions
if name != None:
self.name = name
# a dict where the tuple of... | :arg constructor: a constructor method that returns a module
:arg dimensions: tuple of dimensions. | __init__ | python | pybrain/pybrain | pybrain/structure/modulemesh.py | https://github.com/pybrain/pybrain/blob/master/pybrain/structure/modulemesh.py | BSD-3-Clause |
def constructWithLayers(layerclass, layersize, dimensions, name = None):
""" create the mesh using constructors that build layers of a specified size and class. """
c = lambda: layerclass(layersize)
return ModuleMesh(c, dimensions, name) | create the mesh using constructors that build layers of a specified size and class. | constructWithLayers | python | pybrain/pybrain | pybrain/structure/modulemesh.py | https://github.com/pybrain/pybrain/blob/master/pybrain/structure/modulemesh.py | BSD-3-Clause |
def viewOnFlatLayer(layer, dimensions, name = None):
""" Produces a ModuleMesh that is a mesh-view on a flat module. """
assert max(dimensions) > 1, "At least one dimension needs to be larger than one."
def slicer():
nbunits = reduce(lambda x, y: x*y, dimensions, 1)
insiz... | Produces a ModuleMesh that is a mesh-view on a flat module. | viewOnFlatLayer | python | pybrain/pybrain | pybrain/structure/modulemesh.py | https://github.com/pybrain/pybrain/blob/master/pybrain/structure/modulemesh.py | BSD-3-Clause |
def __init__(self, base, inSliceFrom = 0, inSliceTo = None, outSliceFrom = 0, outSliceTo = None):
""" :key base: the base module that is sliced """
if isinstance(base, ModuleSlice):
# tolerantly handle the case of a slice of another slice
self.base = base.base
self.in... | :key base: the base module that is sliced | __init__ | python | pybrain/pybrain | pybrain/structure/moduleslice.py | https://github.com/pybrain/pybrain/blob/master/pybrain/structure/moduleslice.py | BSD-3-Clause |
def __init__(self, paramdim = 0, **args):
""" initialize all parameters with random values, normally distributed around 0
:key stdParams: standard deviation of the values (default: 1).
"""
self.setArgs(**args)
self.paramdim = paramdim
if paramdim > 0:
sel... | initialize all parameters with random values, normally distributed around 0
:key stdParams: standard deviation of the values (default: 1).
| __init__ | python | pybrain/pybrain | pybrain/structure/parametercontainer.py | https://github.com/pybrain/pybrain/blob/master/pybrain/structure/parametercontainer.py | BSD-3-Clause |
def _setDerivatives(self, d, owner = None):
""" :key d: an array of numbers of self.paramdim """
assert self.owner == owner
assert size(d) == self.paramdim
self._derivs = d | :key d: an array of numbers of self.paramdim | _setDerivatives | python | pybrain/pybrain | pybrain/structure/parametercontainer.py | https://github.com/pybrain/pybrain/blob/master/pybrain/structure/parametercontainer.py | BSD-3-Clause |
def resetDerivatives(self):
""" :note: this method only sets the values to zero, it does not initialize the array. """
assert self.hasDerivatives
self._derivs *= 0 | :note: this method only sets the values to zero, it does not initialize the array. | resetDerivatives | python | pybrain/pybrain | pybrain/structure/parametercontainer.py | https://github.com/pybrain/pybrain/blob/master/pybrain/structure/parametercontainer.py | BSD-3-Clause |
def __init__(self, inmod, outmod, name = None,
inSliceFrom = 0, inSliceTo = None, outSliceFrom = 0, outSliceTo = None):
""" Every connection requires an input and an output module. Optionally, it is possible to define slices on the buffers.
:arg inmod: input module
:arg... | Every connection requires an input and an output module. Optionally, it is possible to define slices on the buffers.
:arg inmod: input module
:arg outmod: output module
:key inSliceFrom: starting index on the buffer of inmod (default = 0)
:key inSliceTo: ending index on... | __init__ | python | pybrain/pybrain | pybrain/structure/connections/connection.py | https://github.com/pybrain/pybrain/blob/master/pybrain/structure/connections/connection.py | BSD-3-Clause |
def forward(self, inmodOffset=0, outmodOffset=0):
"""Propagate the information from the incoming module's output buffer,
adding it to the outgoing node's input buffer, and possibly transforming
it on the way.
For this transformation use inmodOffset as an offset for the inmod and
... | Propagate the information from the incoming module's output buffer,
adding it to the outgoing node's input buffer, and possibly transforming
it on the way.
For this transformation use inmodOffset as an offset for the inmod and
outmodOffset as an offset for the outmodules offset. | forward | python | pybrain/pybrain | pybrain/structure/connections/connection.py | https://github.com/pybrain/pybrain/blob/master/pybrain/structure/connections/connection.py | BSD-3-Clause |
def backward(self, inmodOffset=0, outmodOffset=0):
"""Propagate the error found at the outgoing module, adding it to the
incoming module's output-error buffer and doing the inverse
transformation of forward propagation.
For this transformation use inmodOffset as an offset for the inmod ... | Propagate the error found at the outgoing module, adding it to the
incoming module's output-error buffer and doing the inverse
transformation of forward propagation.
For this transformation use inmodOffset as an offset for the inmod and
outmodOffset as an offset for the outmodules offse... | backward | python | pybrain/pybrain | pybrain/structure/connections/connection.py | https://github.com/pybrain/pybrain/blob/master/pybrain/structure/connections/connection.py | BSD-3-Clause |
def __repr__(self):
"""A simple representation (this should probably be expanded by
subclasses). """
params = {
'class': self.__class__.__name__,
'name': self.name,
'inmod': self.inmod.name,
'outmod': self.outmod.name
}
return "<%(c... | A simple representation (this should probably be expanded by
subclasses). | __repr__ | python | pybrain/pybrain | pybrain/structure/connections/connection.py | https://github.com/pybrain/pybrain/blob/master/pybrain/structure/connections/connection.py | BSD-3-Clause |
def newSimilarInstance(self):
""" Generates a new Evolvable of the same kind."""
res = self.copy()
res.randomize()
return res | Generates a new Evolvable of the same kind. | newSimilarInstance | python | pybrain/pybrain | pybrain/structure/evolvables/evolvable.py | https://github.com/pybrain/pybrain/blob/master/pybrain/structure/evolvables/evolvable.py | BSD-3-Clause |
def params(self):
""" returns an array with (usually) only the unmasked parameters """
if self.returnZeros:
return self.pcontainer.params
else:
x = zeros(self.paramdim)
paramcount = 0
for i in range(len(self.maskableParams)):
if sel... | returns an array with (usually) only the unmasked parameters | params | python | pybrain/pybrain | pybrain/structure/evolvables/maskedparameters.py | https://github.com/pybrain/pybrain/blob/master/pybrain/structure/evolvables/maskedparameters.py | BSD-3-Clause |
def randomize(self, **args):
""" an initial, random mask (with random params)
with as many parameters enabled as allowed"""
self.mask = zeros(self.pcontainer.paramdim, dtype=bool)
onbits = []
for i in range(self.pcontainer.paramdim):
if random() > self.maskOnProbabili... | an initial, random mask (with random params)
with as many parameters enabled as allowed | randomize | python | pybrain/pybrain | pybrain/structure/evolvables/maskedparameters.py | https://github.com/pybrain/pybrain/blob/master/pybrain/structure/evolvables/maskedparameters.py | BSD-3-Clause |
def topologyMutate(self):
""" flips some bits on the mask
(but do not exceed the maximum of enabled parameters). """
for i in range(self.pcontainer.paramdim):
if random() < self.maskFlipProbability:
self.mask[i] = not self.mask[i]
tooMany = sum(self.mask) - se... | flips some bits on the mask
(but do not exceed the maximum of enabled parameters). | topologyMutate | python | pybrain/pybrain | pybrain/structure/evolvables/maskedparameters.py | https://github.com/pybrain/pybrain/blob/master/pybrain/structure/evolvables/maskedparameters.py | BSD-3-Clause |
def mutate(self):
""" add some gaussian noise to all parameters."""
# CHECKME: could this be partly outsourced to the pcontainer directly?
for i in range(self.pcontainer.paramdim):
self.maskableParams[i] += gauss(0, self.mutationStdev)
self._applyMask() | add some gaussian noise to all parameters. | mutate | python | pybrain/pybrain | pybrain/structure/evolvables/maskedparameters.py | https://github.com/pybrain/pybrain/blob/master/pybrain/structure/evolvables/maskedparameters.py | BSD-3-Clause |
def newSimilarInstance(self):
""" generate a new Evolvable with the same topology """
res = self.copy()
res.randomize()
return res | generate a new Evolvable with the same topology | newSimilarInstance | python | pybrain/pybrain | pybrain/structure/evolvables/topology.py | https://github.com/pybrain/pybrain/blob/master/pybrain/structure/evolvables/topology.py | BSD-3-Clause |
def __init__(self, outdim, hiddim=15):
""" Create an EvolinoNetwork with for sequences of dimension outdim and
hiddim dimension of the RNN Layer."""
indim = 0
Module.__init__(self, indim, outdim)
self._network = RecurrentNetwork()
self._in_layer = LinearLayer(indim + out... | Create an EvolinoNetwork with for sequences of dimension outdim and
hiddim dimension of the RNN Layer. | __init__ | python | pybrain/pybrain | pybrain/structure/modules/evolinonetwork.py | https://github.com/pybrain/pybrain/blob/master/pybrain/structure/modules/evolinonetwork.py | BSD-3-Clause |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves Python code examples from Django repository that contain 'django' in the code, which helps identify Django-specific code snippets but provides limited analytical insights beyond basic filtering.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.