If you run the program below, you will receive a stackoverflow error.
I don't know what to do, so please let me know if you know.
main.py
# Import Package
importos
from keras.layers import BatchNormalization, Dense, Dropout
from keras.models import Sequential
from keras.optimizers import SGD
import matplotlib.pyplot asplt
from tqdm import tqdm
import load_data
train_paths = [ ]
for root, dirs, files intqdm(os.walk("./font")):
train_paths+=list(map(lambdan:root+"/"+n, files))
val_count=int(len(train_paths)*0.2)
train_gen=load_data.Generator(
train_paths [val_count:],
batch_size=64)
val_gen = load_data.Generator(
train_paths [:val_count],
batch_size=64)
# Creating a Model
model=Sequential()
model.add(Dense(512, activation='sigmoid', input_shape=(32**2,)))#Input Layer
model.add(BatchNormalization())
model.add(Dense(256, activation='sigmoid'))#Hidden layer
model.add(Dropout(rate=0.5))#Dropout
model.add(Dense(94, activation='softmax'))# Output Layer
# compilation
model.compile(loss='categorical_crossentropy', optimizer=SGD(lr=0.1), metrics=['acc'])
# learning
history=model.fit_generator(
train_gen,
steps_per_epoch =train_gen.num_batches_per_epoch,
validation_data=val_gen,
validation_steps = val_gen.num_batches_per_epoch,
epochs = 100,
shuffle=True)
model.save ("model.h5")
# model=load_model("model.h5")
# Viewing Graphs
plt.plot(history.history['acc', label='acc')
plt.plot(history.history['val_acc', label='val_acc')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(loc='best')
plt.show()
load_data.py
import numpy as np
import import lib
from PIL import Image, ImageDraw, ImageFont
from keras.utils import sequence
Class Generator (sequence):
"""Custom generator"""
def_init__(self, data_paths, batch_size=1, width=32, height=32, font_size=32, num_of_class=94):
"""construction""
—param data_paths:List of image file
—param batch_size —Batch size
—param width —Image width
—param height —Image height
—param num_of_class —Num of classes
"""
self.data_paths=data_paths
self.length=len(data_paths)*94*int(180/5)
self.batch_size =batch_size
self.width = width
self.height=height
self.font_size=font_size
self.num_of_class = num_of_class
self.data_pos = [0,0,0]
self.font_data = ImageFont.truetype (self.data_paths [self.data_pos[0]], self.font_size)
self.num_batches_per_epoch=int(self.length-1)/batch_size)+1
def_load_data(self):
text=chr(self.data_pos[2]+33)
font_path=self.data_paths [self.data_pos[0]]
font_color="white"
rot=self.data_pos[1]*5
# get fontsize
tmp=Image.new('RGBA', (1,1),(0,0,0,0))#dummy for get text_size
tmp_d = ImageDraw.Draw(tmp)
text_size = tmp_d.textsize(text,self.font_data)
i=self.font_size
while text_size[0]>self.font_size-5 or text_size[1]>self.font_size-5:
i - = 1
font_data = ImageFont.truetype(font_path,i)
text_size = tmp_d.textsize(text, font_data)
# draw text
img=Image.new('RGBA', [self.font_size]*2,(0,0,0,0))#background:transparent
img_d=ImageDraw.Draw(img)
img_d.text(0,0), text, fill=font_color, font=self.font_data)
img = img.rotate(rot)
self.data_pos[2]+=1
if self.data_pos[2]>93:
self.data_pos[1]+=1
self.data_pos[2] = 0
if self.data_pos[1]>180/5:
importlib.reload(np)
importlib.reload (Image)
importlib.reload (ImageDraw)
importlib.reload (ImageFont)
importlib.reload (importlib)
self.data_pos[0]+=1
self.font_data = ImageFont.truetype (self.data_paths [self.data_pos[0]], self.font_size)
self.data_pos[1] = 0
img=np.array(img)
img=0.299*img[:,:,2]+0.587*img[:,:,1]+0.114*img[:,:,0]
return img,self.data_pos[2]
def__getitem__(self,idx)->np.array:
Get batch data
—param idx:Index of batch
—return imgs:number array of images
—return labels:number array of labels
"""
start_pos=self.batch_size*idx
end_pos = start_pos + self.batch_size
if end_pos>self.length:
end_pos = self.length
imgs=np.empty(end_pos-start_pos+1, self.height, self.width), dtype=np.float32)
labels=np.zeros(end_pos-start_pos+1,self.num_of_class), dtype=np.int16)
for i in range(self.batch_size):
img,label=self._load_data()
imgs[i,:] = img
labels[i][label] = 1
np.save("test.npy", labels)
# Data Set Image Preprocessing
imgs=imgs.reshape((imgs.shape[0], imgs.shape[1]**2))
return imgs, labels
def__len__(self):
"""Batch length"""
return self.num_batches_per_epoch
defon_epoch_end(self):
"""Task when end of epoch"""
pass
I look forward to your kind cooperation.
python python3 numpy keras pillow
I solved myself.The font was so big that I had to pinch it with try except.Sorry for the inconvenience.
© 2024 OneMinuteCode. All rights reserved.