import numpy as np def nonlin(x,deriv=False): if(deriv==True): return (x)*(1-(x)) return 1/(1+np.exp(-x)) def fmax(x,deriv=False): if(deriv==True): return 0.33 return np.maximum(x,0)/3 class NN: def __init__(self, shapes, func=nonlin): self.func = func self.shapes = shapes self.syns = [ 2*np.random.random((shapes[i-1][1],shapes[i][0])) - 1 for i in range(1, len(shapes)) ] self.layers = [ np.zeros(shapes[i]) for i in range(1, len(shapes)) ] def learn(self, X, y, cycles): for j in range(cycles): res = self.calc(X) prev = y - res for i in range(len(self.layers)-1,-1,-1): l_delta = (prev*self.func(self.layers[i], True)).T if i == 0: self.syns[i] += XTdot(l_delta) else: prev = l_delta.dot(self.syns[i].T) self.syns[i] += self.layers[i-1].T.dot(l_delta) return self.layers[-1] def calc(self,X): for i in range(len(self.syns)): if i == 0: self.layers[i] = self.func(np.dot(X,self.syns[i])).T else: self.layers[i] = self.func(np.dot(self.layers[i-1],self.syns[i])).T return self.layers[-1] if __name__ == '__main__': X = np.array([ [0,0,1],[0,1,1],[1,0,1],[1,1,1] ]) y = np.array([[0,1,1,0]]) print('X =',X) print('y =',y) nn = NN((X.shape, (y.shape[1], X.shape[0]), y.shape)) nn.learn(X,y,1000) print('Result =',nn.calc(X).round(2))
X = [[0 0 1] [0 1 1] [1 0 1] [1 1 1]] y = [[0 1 1 0]] Result = [[ 0.02 0.99 0.98 0.02]]
def readImage(file, imageSize): img = QImage(file) if img.isNull(): return 0 img = img.convertToFormat(QImage.Format_Grayscale8) img = img.scaled(imageSize[0],imageSize[1],Qt.IgnoreAspectRatio) return img
srcBi = img.bits() srcBi.setsize(img.width() * img.height()) srcBy = bytes(srcBi) srcW, srcH = img.width(), img.height() srcArr = np.recarray((srcH, srcW), dtype=np.int8, buf=srcBy).view(dtype=np.byte,type=np.ndarray)
srcArr[x:x+dw, y:y+dw]
class ImgNN: def __init__(self, shape, resultShape = (16, 16), imageSize = (400,400)): self.resultShape = resultShape self.w = imageSize[0] // shape[0] self.h = imageSize[1] // shape[1] self.net = NN([shape, (1,shape[0]), (1,1)]) self.shape = shape self.imageSize = imageSize
def calc(self, srcArr): w = srcArr.shape[0] // self.shape[0] h = srcArr.shape[1] // self.shape[1] resArr = np.zeros(self.resultShape) for x in range(w): for y in range(h): a = srcArr[x:x+self.shape[0], y:y+self.shape[1]] if a.shape != (self.shape[0], self.shape[1]): continue if x >= self.resultShape[0] or y >= self.resultShape[1]: continue res = self.nn.calc(a) resArr[x,y] = res[0,0] return resArr
y = np.array([[1,0,1,0]]) firstShape = (40, 40) middleShape = (5, 5) imageSize = firstShape[0]*middleShape[0], firstShape[1]*middleShape[1] ... nn = ImgNN(firstShape, resultShape=middleShape, imageSize=imageSize) nn2 = NN([middleShape, (y.shape[1], middleShape[0]), y.shape]) ... i = readImage(f, imageSize) mid = nn.calc(i) res = nn2.calc(mid)
y = np.array([[1,0,1,0]])
import os fl = [e.path for e in os.scandir('flowers')] nofl = [e.path for e in os.scandir('noflowers')] all = fl+nofl
for epoch in range(100): print('Epoch =', epoch) nn = ImgNN(firstShape, resultShape=middleShape, imageSize=imageSize) nn2 = NN([middleShape, (y.shape[1], middleShape[0]), y.shape]) for f in fl: i = readImage(f, imageSize) # nn.learn(i, yy, 1) mid = nn.calc(i) nn2.learn(mid, y, 1000)
for f in all: i = readImage(f, imageSize) mid = nn.calc(i) res = nn2.calc(mid) delta = abs(y-res) v = round(np.std(delta),3)
if v > 0.2 and f in fl: fails += 1 failFiles.append(f) elif v<0.2 and f in nofl: fails +=1 failFiles.append(f) if minFails == None or fails < minFails: minFails = fails lastSyns = nn.net.syns lastSyns2 = nn2.syns print('fails =',fails, failFiles) print('min =',minFails) if minFails <= 1: print('found!') break for i in range(len(lastSyns)): np.savetxt('syns_save%s.txt'%i, lastSyns[i]) for i in range(len(lastSyns2)): np.savetxt('syns2_save%s.txt'%i, lastSyns2[i])
flowers\178.jpg res = [[ 0.98 0.5 0.98 0.5 ]] v = 0.241
flowers\179.jpg res = [[ 0.98 0.5 0.98 0.5 ]] v = 0.24
flowers\180.jpg res = [[ 0.98 0.5 0.98 0.5 ]] v = 0.241
flowers\182.jpg res = [[ 0.98 0.5 0.98 0.5 ]] v = 0.24
flowers\186-2.jpg res = [[ 0.98 0.5 0.98 0.5 ]] v = 0.241
flowers\186.jpg res = [[ 0.98 0.5 0.98 0.5 ]] v = 0.24
flowers\187.jpg res = [[ 0.98 0.5 0.98 0.5 ]] v = 0.24
flowers\190 (2).jpg res = [[ 0.98 0.5 0.98 0.5 ]] v = 0.24
flowers\190.jpg res = [[ 0.98 0.5 0.98 0.5 ]] v = 0.241
flowers\191.jpg res = [[ 0.98 0.5 0.98 0.5 ]] v = 0.24
flowers\195.jpg res = [[ 0.98 0.5 0.98 0.5 ]] v = 0.241
flowers\199.jpg res = [[ 0.98 0.5 0.98 0.5 ]] v = 0.24
flowers\2.jpg res = [[ 0.98 0.5 0.98 0.5 ]] v = 0.241
flowers\200.jpg res = [[ 0.98 0.5 0.98 0.5 ]] v = 0.241
noflowers\032.jpg res = [[ 0.98 0.5 0.98 0.5 ]] v = 0.241
noflowers\085.jpg res = [[ 0.98 0.5 0.98 0.5 ]] v = 0.24
noflowers\088.jpg res = [[ 0.98 0.5 0.98 0.5 ]] v = 0.241
noflowers\122.JPG res = [[ 0.98 0.5 0.98 0.5 ]] v = 0.241
noflowers\123.jpg res = [[ 0.98 0.5 0.98 0.5 ]] v = 0.241
noflowers\173.jpg res = [[ 0.98 0.5 0.98 0.5 ]] v = 0.24
noflowers\202.jpg res = [[ 0.98 0.5 0.98 0.5 ]] v = 0.241
noflowers\205.jpg res = [[ 0.98 0.5 0.98 0.5 ]] v = 0.241
noflowers\cutxml.jpg res = [[ 0.98 0.5 0.98 0.5 ]] v = 0.241
noflowers\Getaway.jpg res = [[ 0.98 0.5 0.98 0.5 ]] v = 0.24
noflowers\IMGP1800.JPG res = [[ 0.98 0.5 0.98 0.5 ]] v = 0.24
noflowers\trq-4.png res = [[ 0.97 0.51 0.97 0.51]] v = 0.239
fails = 14
import cv2 def readImageCV(file, imageSize): img = cv2.imread(file) small = cv2.resize(img, imageSize) hsv = cv2.cvtColor(small, cv2.COLOR_BGR2HSV) return hsv[:,:,0]/255
yy = np.zeros(middleShape) np.fill_diagonal(yy,1) ... for f in fl: i = readImage(f, imageSize) nn.learn(i, yy, 2) # - mid = nn.calc(i) nn2.learn(mid, y, 1000)
Epoch = 34
flowers\178.jpg res = [[ 0.86 0.47 0.88 0.47]] v = 0.171
flowers\179.jpg res = [[ 0.87 0.51 0.89 0.5 ]] v = 0.194
flowers\180.jpg res = [[ 0.79 0.69 0.79 0.67]] v = 0.233
flowers\182.jpg res = [[ 0.87 0.53 0.88 0.48]] v = 0.189
flowers\186-2.jpg res = [[ 0.89 0.41 0.89 0.39]] v = 0.144
flowers\186.jpg res = [[ 0.85 0.54 0.83 0.55]] v = 0.194
flowers\187.jpg res = [[ 0.86 0.54 0.86 0.54]] v = 0.199
flowers\190 (2).jpg res = [[ 0.96 0.25 0.97 0.15]] v = 0.089
flowers\190.jpg res = [[ 0.95 0.13 0.97 0.14]] v = 0.048
flowers\191.jpg res = [[ 0.81 0.57 0.82 0.57]] v = 0.195
flowers\195.jpg res = [[ 0.81 0.55 0.79 0.56]] v = 0.177
flowers\199.jpg res = [[ 0.89 0.45 0.89 0.45]] v = 0.171
flowers\2.jpg res = [[ 0.83 0.56 0.83 0.55]] v = 0.195
flowers\200.jpg res = [[ 0.91 0.42 0.89 0.43]] v = 0.163
noflowers\032.jpg res = [[ 0.7 0.79 0.69 0.8 ]] v = 0.246
noflowers\085.jpg res = [[ 0.86 0.53 0.86 0.53]] v = 0.192
noflowers\088.jpg res = [[ 0.86 0.56 0.87 0.53]] v = 0.207
noflowers\122.JPG res = [[ 0.81 0.63 0.81 0.62]] v = 0.218
noflowers\123.jpg res = [[ 0.83 0.59 0.84 0.55]] v = 0.204
noflowers\173.jpg res = [[ 0.83 0.6 0.83 0.58]] v = 0.209
noflowers\202.jpg res = [[ 0.78 0.7 0.8 0.65]] v = 0.234
noflowers\205.jpg res = [[ 0.84 0.77 0.79 0.75]] v = 0.287
noflowers\cutxml.jpg res = [[ 0.81 0.61 0.81 0.63]] v = 0.213
noflowers\Getaway.jpg res = [[ 0.85 0.56 0.85 0.55]] v = 0.202
noflowers\IMGP1800.JPG res = [[ 0.85 0.55 0.86 0.54]] v = 0.199
noflowers\trq-4.png res = [[ 0.7 0.72 0.7 0.71]] v = 0.208
fails = 3 ['flowers\\180.jpg', 'noflowers\\085.jpg', 'noflowers\\IMGP1800.JPG']
min = 3
import numpy as np from nnmat import * import os import sys from PyQt5.QtGui import * from PyQt5.QtCore import * import meshandler import random import cv2 class ImgNN: def __init__(self, shape, resultShape = (16, 16), imageSize = (400,400)): self.resultShape = resultShape self.w = imageSize[0] // shape[0] self.h = imageSize[1] // shape[1] self.net = NN([shape, (1,shape[0]), (1,1)]) self.shape = shape self.imageSize = imageSize def learn(self, srcArr, result, cycles): for c in range(cycles): for x in range(self.w): for y in range(self.h): a = srcArr[x:x+self.shape[0], y:y+self.shape[1]] if a.shape != (self.shape[0], self.shape[1]): print(a.shape) continue self.net.learn(a, result[x,y], 1) def calc(self, srcArr): resArr = np.zeros(self.resultShape) for x in range(self.w): for y in range(self.h): a = srcArr[x:x+self.shape[0], y:y+self.shape[1]] if a.shape != (self.shape[0], self.shape[1]): continue if x >= self.resultShape[0] or y >= self.resultShape[1]: continue res = self.net.calc(a) resArr[x,y] = res[0,0] return resArr def learnFile(self, file, result, cycles): return self.learn(readImage(file, self.imageSize), result, cycles) def calcFile(self, file): return self.calc(readImage(file, self.imageSize)) def readImageCV(file, imageSize): img = cv2.imread(file) small = cv2.resize(img, imageSize) hsv = cv2.cvtColor(small, cv2.COLOR_BGR2HSV) return hsv[:,:,0]/255 def readImageQ(file, imageSize): img = QImage(file) if img.isNull(): return 0 img = img.convertToFormat(QImage.Format_Grayscale8) img = img.scaled(imageSize[0],imageSize[1],Qt.IgnoreAspectRatio) srcBi = img.bits() srcBi.setsize(img.width() * img.height()) srcBy = bytes(srcBi) srcW, srcH = img.width(), img.height() srcArr = np.recarray((srcH, srcW), dtype=np.uint8, buf=srcBy).view(dtype=np.uint8,type=np.ndarray) return srcArr/255 if __name__ == '__main__': readImage = readImageCV y = np.array([[1,0,1,0]]) firstShape = (40, 40) middleShape = (10, 10) imageSize = firstShape[0]*middleShape[0], firstShape[1]*middleShape[1] StartLearn = True if not StartLearn: pictDir = '2014-05' nn = ImgNN(firstShape, resultShape=middleShape, imageSize=imageSize) nn.net.syns[0] = np.loadtxt('syns_save0.txt') nn.net.syns[1] = np.loadtxt('syns_save1.txt') nn2 = NN([middleShape, (y.shape[1], middleShape[0]), y.shape]) nn2.syns[0] = np.loadtxt('syns2_save0.txt') nn2.syns[1] = np.loadtxt('syns2_save1.txt') files = [e.path for e in os.scandir(pictDir)] for f in files: i = readImage(f, imageSize) res = nn2.calc(i) delta = y-res v = round(np.std(delta),3) if v < 0.2: print('Flower',f) else: print('No flower',f) else: fl = [e.path for e in os.scandir('flowers')] nofl = [e.path for e in os.scandir('noflowers')] all = fl+nofl yy = np.zeros(middleShape) np.fill_diagonal(yy,1) minFails = None for epoch in range(100): print('Epoch =', epoch) nn = ImgNN(firstShape, resultShape=middleShape, imageSize=imageSize) nn2 = NN([middleShape, (y.shape[1], middleShape[0]), y.shape]) for f in fl: i = readImage(f, imageSize) nn.learn(i, yy, 2) mid = nn.calc(i) nn2.learn(mid, y, 1000) fails = 0 failFiles = [] for f in all: i = readImage(f, imageSize) mid = nn.calc(i) res = nn2.calc(mid) delta = abs(y-res) v = round(np.std(delta),3) #v = round(delta.sum(),3) print(f, 'res = ', res.round(2),'v =',v) if v > 0.2 and f in fl: fails += 1 failFiles.append(f) elif v<0.2 and f in nofl: fails +=1 failFiles.append(f) if minFails == None or fails < minFails: minFails = fails lastSyns = nn.net.syns lastSyns2 = nn2.syns print('fails =',fails, failFiles) print('min =',minFails) if minFails <= 1: print('found!') break for i in range(len(lastSyns)): np.savetxt('syns_save%s.txt'%i, lastSyns[i]) for i in range(len(lastSyns2)): np.savetxt('syns2_save%s.txt'%i, lastSyns2[i])
Source: https://habr.com/ru/post/338548/
All Articles