Added neural network related things and other maths stuff

This commit is contained in:
2019-03-09 00:38:22 +01:00
parent 879abc9861
commit b670f9a195
15 changed files with 295 additions and 7 deletions
+37
View File
@@ -0,0 +1,37 @@
"""
#Vgg-16 architecture
from keras.models import Sequential
from keras.layers import Conv2D,MaxPooling2D,Flatten,Dense
my_VGG16=Sequential()
my_VGG16.add(Conv2D(64,(3,3),input_shape=(224,224,3),padding="same",activation="relu"))
my_VGG16.add(Conv2D(64,(3,3),padding="same"),activation="relu")
my_VGG16.add(MaxPooling2D(pool_size=(2,2),strides=(2,2)))
my_VGG16.add(Flatten())
my_VGG16.add(Dense(4096,activation="relu"))
my_VGG16.add(Dense(4096,activation="relu"))
my_VGG16.add(Dense(100,activation="softmax"))
from PIL import Image
img=Image.open("simba.png")
img.show()
"""
import keras
from keras.preprocessing.image import load_img, img_to_array
from keras.applications.vgg16 import VGG16, preprocess_input,decode_predictions
model=VGG16()
img=load_img("simba.png",target_size=(224,224))
img=img_to_array(img)
img=img.reshape((1,img.shape[0],img.shape[0],img.shape[2]))
img=preprocess_input(img)
y=model.predict(img)
print("top3:",decode_predictions(y,top=3)[0])
+46
View File
@@ -0,0 +1,46 @@
from PIL import Image,ImageFilter
import numpy as np
import matplotlib.pyplot as plt
#import sys
#print(sys.version)
Img=Image.open("simba.png")
img=np.array(Img)
Img.show()
imin,imax=200,255
img2=[[255*(img[y][x]-imin)/(imax-imin) for x in range(len(img[0]))] for y in range(len(img))]
noise=np.random.normal(0,7,img.shape)
Img3=Image.fromarray(img+noise).convert("L")
Img3.show()
Img3.filter(ImageFilter.BoxBlur(1)).show()
Img3.show()
#Img2=Image.fromarray(img2).convert("L")
#Img2.show()
#img2.show()
#img.show()
#w,h=img.size
#print(w,h)
#print(img.__dict__)
#print(rimg["im"])
#for key,value in rimg.__dict__.items():
#print(key,":",value)
#px_value=img.getpixel((20,100))
#print(px_value)
#mat=np.array(img)
#print(mat)
#print(mat.shape)
n,bins,patches=plt.hist(img.flatten(),bins=range(256))
plt.show()
Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

+14
View File
@@ -0,0 +1,14 @@
import math
def puissancede2(number):
a=1
while a*2<number:
a*=2
return a
print(puissancede2(513))
puissance=lambda x:2**int(math.log(x)/math.log(2))
print(puissance(513))
+48 -3
View File
@@ -3,6 +3,12 @@ import matplotlib.pyplot as plt
import csv
import numpy as np
import urllib
import matplotlib.dates as mdates
import sys
print(sys.version)
"""
x=[1,2,3]
@@ -88,14 +94,53 @@ x,y=np.loadtxt("text.txt",delimiter=",",unpack=True)
plt.plot(x,y,label="loaded from file")
"""
def bytespdate2num(fmt,encoding="utf-8"):
strconverter=mdates.strpdate2num(fmt)
def bytesconverter(b):
s=b.decode(encoding)
return strconverter(s)
return bytesconverter
def graph_data(stock):
#fig=plt.figure()
#ax1=plt.subplot2grid((1,1),(0,0))
stock_price_url = 'https://pythonprogramming.net/yahoo_finance_replacement'
plt.xlabel("x")
plt.ylabel("y")
source_code=urllib.request.urlopen(stock_price_url).read().decode()
#print(source_code)
stock_data=[]
split_source=source_code.split('\n')
for line in split_source:
split_line=line.split(",")
if len(split_line)==6:
if 'values' not in line and 'labels' not in line:
stock_data.append(line)
date,closep,highp,lowp,openp,volume=np.loadtxt(stock_data,
delimiter=",",
unpack=True,
#%Y=full year
#%y=partial year
#%m=number month
#%d=day
#%H=hours
#%M=minutes
#%S=seconds
#%m-%d-%Y
#converters={0: bytespdate2num('%Y%m%d')})
converters={0: lambda s : mdates.date2num(datetime.strptime(s.decode("utf-8"),'%Y%m%d'))})
plt.plot_date(date,closep,"-")
plt.xlabel("date")
plt.ylabel("price")
plt.title("Interesting graph\nCheck it out!")
plt.legend()
plt.show()
@@ -0,0 +1,19 @@
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
import random
style.use("fivethirtyeight")
fig=plt.figure()
ax1=fig.add_subplot(1,1,1)
x=[i for i in range(100)]
def animate(i):
y=[random.randint(0,10) for i in range(100)]
ax1.clear()
ax1.plot(x,y)
ani=animation.FuncAnimation(fig,animate,interval=1000)
plt.show()
+5 -3
View File
@@ -2,6 +2,8 @@ import numpy as np
picture=np.random.randn(28,28)
#import input_data
class NeuralNetwork:
def __init__(self,sizes=[784,784,28,10]):
"""Create a neural network using list of sizes."""
@@ -12,8 +14,8 @@ class NeuralNetwork:
def evaluate(self,test_data):
"""Return number of successful predictions using test_datas list."""
results=[(np.argmax(self.predict(x)),y]) for (x,y) in test_data]
return sum(int(x==y) for (x,y) in results])
results=[(np.argmax(self.predict(x)),y) for (x,y) in test_data]
return sum([int(x==y) for (x,y) in results])
def predict(self,input):
"""Return predictions for given input."""
@@ -59,7 +61,7 @@ class NeuralNetwork:
weighted.append(z)
x=sigmoid(z)
activations.append(x)
return dB,dW
Binary file not shown.
+3
View File
@@ -0,0 +1,3 @@
import pandas as pd
df=pd.read_csv("datasets/diamonds.csv",index_col=0)
df.head()
+45
View File
@@ -0,0 +1,45 @@
from pyglet.gl import *
class Triangle:
def __init__(self):
self.triangle=[-0.5,-0.5, 0.0, 1.0, 0.0, 0.0,
0.5,-0.5, 0.0, 0.0, 1.0, 0.0,
0.0, 0.5, 0.0, 0.0, 0.0, 1.0]
self.vertex_shader_source="""
#version 330
in layout(location=0) vec3 position;
in layout(location=1) vec3 color;
out vec3 newColor;
void main()
{
gl_Position=vec4(position,1.0f)
newColor=color;
}
"""
self.fragement_shader_source="""
#version 330
in vec3 newColor;
out vec4 outColor;
void main()
{
outColor=vec4(newColor,1.0f)
}
"""
shader=OpenGL.GL.shaders.compileProgram(OpenGL.GL.shaders.compileShader(self.vertex_shader_source,GL_VERTEX_SHADER),
OpenGL.GL.shaders.compileShader(self.fragement_shader_source,GL_FRAGMENT_SHADER))
glUseProgram(shader)
vbo=GLuint(0)
glGenBuffers(1,vbo)
glBindBuffer(GL_ARRAY_BUFFER,vbo)
glBufferData(GL_ARRAY_BUFFER,72,(GLfloat*len(self.triangles)(*self.triangles),GL_STATIC_DRAW))
#positions
glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,24,ctypes.c_void_p(0))
glEnableVertexAttribArray(0)
glVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE,24,ctypes.c_void_p(12))
glEnableVertexAttribArray(0)
+21
View File
@@ -0,0 +1,21 @@
from pyglet.gl import *
from Triangle import Triangle
class Window(pyglet.window.Window):
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.set_minimum_size(400,300)
glClearColor(0,0,1,1)
self.triangle=Triangle()
def on_draw(self):
self.clear()
glDrawArrays(GL_TRIANGLES,0,3)
def on_resize(self,width,height):
glViewport(0,0,width,height)
if __name__=="__main__":
window=Window(700,600,"My awesome window",resizable=True)
pyglet.app.run()
Binary file not shown.
+55
View File
@@ -0,0 +1,55 @@
from pyglet.gl import *
import pyglet
class Triangle:
def __init__(self):
self.vertices=pyglet.graphics.vertex_list(3,("v3f",[-0.5,-0.5,0.,0.5,-0.5,0.,0.,0.,0.5]),
("c3B",[100,200,220,200,110,100,100,250,100]))
class Quad:
def __init__(self):
self.vertices=pyglet.graphics.vertex_list_indexed(4,[0,1,2,3,0],
("v3f",[-0.5,-0.5,0.0, 0.5,-0.5,0.0, 0.5,0.5,0.0, -0.5,0.5,0.0]),
("c3f",[0,1,0, 1,1,0, 1,0,0, 1,0,1]))
class Quad2:
def __init__(self):
self.indices=[0,1,2,3,0]
self.vertex=[-0.5,-0.5,0.0, 0.5,-0.5,0.0, 0.5,0.5,0.0, -0.5,0.5,0.0]
self.color=[0,1,0, 1,1,0, 1,0,0, 1,0,1]
self.vertices=pyglet.graphics.vertex_list_indexed(4,self.indices,("v3f",self.vertex),("c3f",self.color))
class Quad3:
def __init__(self):
self.indices=[0,1,2,3,0]
self.vertex=[-0.5,-0.5,0.0, 0.5,-0.5,0.0, 0.5,0.5,0.0, -0.5,0.5,0.0]
self.color=[0,1,0, 1,1,0, 1,0,0, 1,0,1]
def render(self):
self.vertices=pyglet.graphics.draw_indexed(4,GL_TRIANGLES,self.indices,("v3f",self.vertex),("c3f",self.color))
class Window(pyglet.window.Window):
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.set_minimum_size(400,300)
color=(255,0,0)
glClearColor(255,0,0,1.0)
self.triangle=Triangle()
self.quad=Quad3()
def on_draw(self):
self.clear()
#self.triangle.vertices.draw(GL_TRIANGLES)
#self.quad.vertices.draw(GL_QUADS)
self.quad.render()
def on_resize(self,width,height):
glViewport(0,0,width,height)
if __name__=="__main__":
window=Window(1280,720,"First Pyglet Window",resizable=True)
pyglet.app.run()
-1
View File
@@ -237,7 +237,6 @@ if __name__=="__main__":
#print(sentence-"fucking ")
#sentence=MutableString(sentence)
#print(sentence)
#sentence.append(" enorme test")
#print(Str(sentence).title())
#print(list(a))
#print(a.remove("s"))
+2
View File
@@ -0,0 +1,2 @@
def __+__(a,b):
return a+b