Skip to content
This repository has been archived by the owner on Apr 4, 2023. It is now read-only.

Commit

Permalink
save point 1
Browse files Browse the repository at this point in the history
  • Loading branch information
amithm3 committed May 1, 2022
1 parent ba743a7 commit 91afb4c
Show file tree
Hide file tree
Showing 13 changed files with 96 additions and 27 deletions.
File renamed without changes.
4 changes: 2 additions & 2 deletions gui/index.html → Demo/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@
<div id="toolbar">
<h1>Draw.</h1>
<label for="lineWidth">Line Width</label>
<input id="lineWidth" name='lineWidth' type="number" value="5">
<input id="lineWidth" name='lineWidth' type="number" value="10">
<button id="clear" onclick="ctx.clearRect(0, 0, canvas.width, canvas.height)">Clear</button>
<button id="predict" onclick="">Predict</button>
<button id="predict" onclick="console.log(convertCanvasToArray())">Predict</button>
</div>
<div class="drawing-board">
<canvas id="drawing-canvas"></canvas>
Expand Down
30 changes: 24 additions & 6 deletions gui/index.js → Demo/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,36 @@ const ctx = canvas.getContext('2d');
let isDown = false;
let beginPoint = null;
let points = [];
let lineWidth = 5;
let lineWidth = 10;

canvas.width = 500;
canvas.height = 500;
$html_body_pad = 2; // from style.css
function re (evt) {canvas.width = Math.min(500, window.innerWidth - toolbar.offsetWidth - 4 * $html_body_pad)}
re()
window.addEventListener("resize", re)
function resize(evt) {
canvas.width = Math.min(500, window.innerWidth - toolbar.offsetWidth - 4 * $html_body_pad)
}

resize()
window.addEventListener("resize", resize)

// function isTouchDevice() {
// return (('ontouchstart' in window) || (navigator.maxTouchPoints > 0));
// }

function convertCanvasToArray() {
let matrix = []
let imgData = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
let pos = null;
for (let j = 0; j < canvas.height; j++) {
let my = []
for (let i = 0; i < canvas.width; i++) {
pos = (j * canvas.width + i) * 4;
my[i] = imgData[pos + 3]
}
matrix[j] = my
}
return matrix
}

toolbar.addEventListener('change', e => {
if (e.target.id === 'stroke') {
Expand All @@ -38,6 +55,7 @@ document.addEventListener('touchmove', move, false);
document.addEventListener('touchend', up, false)

function down(evt) {
if (evt.x )
isDown = true;
const {x, y} = getPos(evt);
points.push({x, y});
Expand Down Expand Up @@ -85,8 +103,8 @@ function getPos(evt) {
}
let rect = canvas.getBoundingClientRect();
return {
x: Math.min(Math.max(evt.clientX - rect.left, lineWidth), canvas.width - lineWidth),
y: Math.min(Math.max(evt.clientY - rect.top, lineWidth), canvas.height - lineWidth)
x: Math.min(Math.max(evt.clientX - rect.left, lineWidth / 2), canvas.width - lineWidth / 2),
y: Math.min(Math.max(evt.clientY - rect.top, lineWidth / 2), canvas.height - lineWidth / 2)
}
}

Expand Down
3 changes: 3 additions & 0 deletions Demo/process.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
function findContours(matrix) {

}
File renamed without changes.
File renamed without changes.
File renamed without changes.
44 changes: 29 additions & 15 deletions __init__/NeuralNetworks/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,20 +107,20 @@ def __init__(self, shape: "BaseShape",
self.DEPS = self._defineDeps(*depArgs, **depKwargs)

def forPass(self, _input: "np.ndarray") -> "np.ndarray":
"""
f"""
method for forward pass of inputs
:param _input: self.output from the lower layer
:return: self.output
:return: {self.output}
"""
self.input = _input
self.output = self._fire()
return self.output

def backProp(self, _delta: "np.ndarray") -> "np.ndarray":
"""
f"""
method for back propagation of deltas
:param _delta: self.outputDelta from the higher layer
:return: self.outputDelta
:param _delta: value for {self.inputDelta} from {self.outputDelta} of the higher layer
:return: {self.outputDelta}
"""
self.inputDelta = _delta
self.outputDelta = self._wire()
Expand All @@ -132,27 +132,25 @@ def changeOptimizer(self, optimizer: "Optimizers.Base"):

@abstractmethod
def _initializeDepOptimizer(self):
"""create new optimizer instance for each dep in $DEPS by using self.optimizer.__new_copy__()"""
f"""create new optimizer instance for each dep in {self.DEPS} by using {self.optimizer.__new_copy__()}"""

@abstractmethod
def _defineDeps(self, *depArgs, **depKwargs) -> list['str']:
"""
f"""
define all dependant objects ($DEPS) for the layer
:return: list of $DEPS whose shape is displayed in __str__
:return: value for {self.DEPS}
"""

@abstractmethod
def _fire(self) -> "np.ndarray":
"""
method to use $DEPS & calculate output (input for next layer)
:return: value for self.output
f"""
:return: value for {self.output}, is input for the higher layer
"""

@abstractmethod
def _wire(self) -> "np.ndarray":
"""
method to adjust $DEPS & calculate delta for the lower layer
:return: value for self.outputDelta
f"""
:return: value for {self.outputDelta}, is delta for the lower layer
"""


Expand Down Expand Up @@ -187,20 +185,36 @@ def __init__(self, inputLayer: "BaseLayer", *layers: "BaseLayer", lossFunction:
self.LOSS_FUNCTION = lossFunction

def changeOptimizer(self, _optimizer: Union["Optimizers.Base", "Optimizers"], index: int = None):
f"""
changes optimizer at index if given else changes all the optimizers to {_optimizer} or
uses given collection {Optimizers}
"""
assert isinstance(_optimizer, (Optimizers, Optimizers.Base))
if index is None:
optimizers = _optimizer.get(len(self.LAYERS))
optimizers = _optimizer.get(len(self.LAYERS)) if isinstance(_optimizer, Optimizers) else \
(_optimizer,) * len(self.LAYERS)
for i, layer in enumerate(self.LAYERS):
layer.changeOptimizer(optimizers[i])
else:
layer: "BaseLayer" = self.LAYERS[index]
layer.changeOptimizer(_optimizer)

def forwardPass(self, _input) -> "np.ndarray":
f"""
calls(and sends hierarchical I/O) the forPass method of all the layers
:param _input: input for {self.INPUT_LAYER}
:return: output of {self.OUTPUT_LAYER}
"""
_output = self.INPUT_LAYER.forPass(_input)
for layer in self.HIDDEN_LAYERS: _output = layer.forPass(_output)
return self.OUTPUT_LAYER.forPass(_output)

def backPropagation(self, _delta) -> "np.ndarray":
f"""
calls(and sends hierarchical I/O) the backProp method of all the layers
:param _delta: delta for {self.OUTPUT_LAYER}
:return: delta of {self.INPUT_LAYER}
"""
_delta = self.OUTPUT_LAYER.backProp(_delta)
for reversedLayer in self.HIDDEN_LAYERS[::-1]: _delta = reversedLayer.backProp(_delta)
return self.INPUT_LAYER.backProp(_delta)
Expand Down
2 changes: 1 addition & 1 deletion __init__/Topologies/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
class Activators(Collections):
from .activationFunction import BaseActivationFunction as Base, \
Sigmoid, TanH, Relu, PRelu, Elu, SoftMax, SoftPlus
Base, Sigmoid, Tanh, Relu, Prelu, Elu, Softmax, Softplus = \
Base, Sigmoid, TanH, Relu, PRelu, Elu, SoftMax, SoftPlus = \
Base, Sigmoid, TanH, Relu, PRelu, Elu, SoftMax, SoftPlus

def __init__(self, *activationFunctions: "Activators.Base"):
Expand Down
5 changes: 3 additions & 2 deletions __init__/Topologies/dataBase.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,10 @@ def save(self, file: str = None, replace: bool = False) -> str:

@classmethod
def load(cls, file: str, *DataBase_args, **DataBase_kwargs) -> "DataBase":
"""
f"""
:param file: path like or name
:param DataBase_args: normalizeInp, normalizeTar, reshapeInp, reshapeTar, oneHotMaxInp, oneHotMaxTar, name
:param DataBase_args: to {DataBase.__init__}(normalizeInp, normalizeTar, reshapeInp, reshapeTar,
oneHotMaxInp, oneHotMaxTar, name)
"""
loadFile = super(DataBase, cls).load(file)
nnLoader = np.load(loadFile, mmap_mode='r')
Expand Down
2 changes: 1 addition & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
</head>
<body>
<div>
<a href="gui/" style="font-size: 300%">Draw</a>
<a href="Demo/" style="font-size: 300%">Draw</a>
</div>
<script src="./index.js"></script>
</body>
Expand Down
3 changes: 3 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,6 @@
# todo: DataBase shaping using self.SHAPE
# todo: auto hyperparameter tuning: Grid search, Population-based natural selection
# todo: auto train stop, inf train
from __init__ import *
from DataSets import dataSet
from Models import model
30 changes: 30 additions & 0 deletions toIPYNB.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import os
from p2j.p2j import p2j

__ignore__ = ["venv", "node_modules", "test.py", "test2.py", "test3.py", "testNumba.py"]
__bytes__ = []
__ignore__ += ["toIPYNB.py", ".git", ".idea", ".vs", "__pycache__"]
__path__ = os.path.dirname(__file__)


def makeIPNB(path):
for dirs in os.listdir(path):
if dirs in __ignore__: continue
if os.path.isfile(_path := path + '/' + dirs):
if os.path.splitext(_path)[1] == '.py':
tar = '__ipynb__' + _path.removeprefix(__path__).removesuffix('.py') + '.ipynb'
os.makedirs(os.path.dirname(tar), exist_ok=True)
with open(_path, 'r+') as file:
content = file.read()
file.seek(0, 0)
file.write("import import_ipynb\n" + content)
p2j(source_filename=_path, target_filename=tar, overwrite=True)
with open(_path, 'r+') as file:
content = file.read()
file.seek(0, 0)
file.write("import import_ipynb\n" + content)
else:
makeIPNB(_path)


makeIPNB(__path__)

0 comments on commit 91afb4c

Please sign in to comment.