Rozpoznawanie banknotów2

This commit is contained in:
Kinga 2020-05-18 14:17:23 +02:00
parent 2e97c014fe
commit 9c106e0980
4 changed files with 261 additions and 355 deletions

View File

@ -2,9 +2,9 @@
<project version="4">
<component name="ChangeListManager">
<list default="true" id="76f12f94-8135-4028-8378-41c67cca6cd2" name="Default Changelist" comment="Rozpoznawanie banknotów">
<change beforePath="$PROJECT_DIR$/.idea/Restaurant.iml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/Restaurant.iml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/misc.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/misc.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Kinga/data/examine/20/examine_013.png.jpg" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/Kinga/main4.py" beforeDir="false" afterPath="$PROJECT_DIR$/Kinga/main4.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/main.py" beforeDir="false" afterPath="$PROJECT_DIR$/main.py" afterDir="false" />
</list>
<option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
@ -15,22 +15,49 @@
</component>
<component name="FileEditorManager">
<leaf SIDE_TABS_SIZE_LIMIT_KEY="300">
<file pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/main.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="323">
<caret line="506" column="79" selection-start-line="506" selection-start-column="79" selection-end-line="506" selection-end-column="79" />
<folding>
<element signature="e#0#13#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
</file>
<file pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/Sara/image_classification.py">
<provider selected="true" editor-type-id="text-editor">
<state>
<caret line="4" column="16" lean-forward="true" selection-start-line="4" selection-start-column="16" selection-end-line="4" selection-end-column="16" />
<state relative-caret-position="154">
<caret line="7" selection-start-line="7" selection-end-line="7" />
<folding>
<element signature="e#0#94#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
</file>
<file pinned="false" current-in-tab="true">
<entry file="file://$PROJECT_DIR$/main.py">
<entry file="file://$PROJECT_DIR$/Kinga/main4.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="13508">
<caret line="668" column="15" lean-forward="true" selection-start-line="668" selection-start-column="15" selection-end-line="668" selection-end-column="15" />
<state relative-caret-position="504">
<caret line="76" column="14" lean-forward="true" selection-start-line="76" selection-start-column="14" selection-end-line="76" selection-end-column="14" />
<folding>
<element signature="e#0#13#0" expanded="true" />
<element signature="e#0#94#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
</file>
<file pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/Kinga/sth.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="625">
<caret line="90" column="62" selection-start-line="90" selection-start-column="62" selection-end-line="90" selection-end-column="62" />
<folding>
<element signature="e#0#94#0" expanded="true" />
</folding>
</state>
</provider>
@ -62,14 +89,15 @@
<option value="$PROJECT_DIR$/Kinga/main3.py" />
<option value="$PROJECT_DIR$/main4.py" />
<option value="$PROJECT_DIR$/venv/Lib/site-packages/torch/utils/data/_utils/collate.py" />
<option value="$PROJECT_DIR$/Sara/image_classification.py" />
<option value="$PROJECT_DIR$/Kinga/main5.py" />
<option value="$PROJECT_DIR$/main.py" />
<option value="$PROJECT_DIR$/sth.py" />
<option value="$PROJECT_DIR$/Kinga/main4.py" />
<option value="$PROJECT_DIR$/main6.py" />
<option value="$PROJECT_DIR$/Kinga/mian7.py" />
<option value="$PROJECT_DIR$/Kinga/main8.py" />
<option value="$PROJECT_DIR$/Sara/image_classification.py" />
<option value="$PROJECT_DIR$/Kinga/sth.py" />
<option value="$PROJECT_DIR$/Kinga/main4.py" />
<option value="$PROJECT_DIR$/main.py" />
</list>
</option>
</component>
@ -96,31 +124,6 @@
<item name="Restaurant" type="462c0819:PsiDirectoryNode" />
<item name="Kinga" type="462c0819:PsiDirectoryNode" />
</path>
<path>
<item name="Restaurant" type="b2602c69:ProjectViewProjectNode" />
<item name="Restaurant" type="462c0819:PsiDirectoryNode" />
<item name="Kinga" type="462c0819:PsiDirectoryNode" />
<item name="data" type="462c0819:PsiDirectoryNode" />
</path>
<path>
<item name="Restaurant" type="b2602c69:ProjectViewProjectNode" />
<item name="Restaurant" type="462c0819:PsiDirectoryNode" />
<item name="Kinga" type="462c0819:PsiDirectoryNode" />
<item name="data" type="462c0819:PsiDirectoryNode" />
<item name="examine" type="462c0819:PsiDirectoryNode" />
</path>
<path>
<item name="Restaurant" type="b2602c69:ProjectViewProjectNode" />
<item name="Restaurant" type="462c0819:PsiDirectoryNode" />
<item name="Kinga" type="462c0819:PsiDirectoryNode" />
<item name="data" type="462c0819:PsiDirectoryNode" />
<item name="train" type="462c0819:PsiDirectoryNode" />
</path>
<path>
<item name="Restaurant" type="b2602c69:ProjectViewProjectNode" />
<item name="Restaurant" type="462c0819:PsiDirectoryNode" />
<item name="Sara" type="462c0819:PsiDirectoryNode" />
</path>
</expand>
<select />
</subPane>
@ -149,7 +152,28 @@
</list>
</option>
</component>
<component name="RunManager" selected="Python.main">
<component name="RunManager" selected="Python.main4 (1)">
<configuration name="image_classification" type="PythonConfigurationType" factoryName="Python" temporary="true">
<module name="Restaurant" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/Sara" />
<option name="IS_MODULE_SDK" value="true" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/Sara/image_classification.py" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<option name="EMULATE_TERMINAL" value="false" />
<option name="MODULE_MODE" value="false" />
<option name="REDIRECT_INPUT" value="false" />
<option name="INPUT_FILE" value="" />
<method v="2" />
</configuration>
<configuration name="main" type="PythonConfigurationType" factoryName="Python" temporary="true">
<module name="Restaurant" />
<option name="INTERPRETER_OPTIONS" value="" />
@ -192,27 +216,6 @@
<option name="INPUT_FILE" value="" />
<method v="2" />
</configuration>
<configuration name="main6" type="PythonConfigurationType" factoryName="Python" temporary="true">
<module name="Restaurant" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="IS_MODULE_SDK" value="true" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/main6.py" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<option name="EMULATE_TERMINAL" value="false" />
<option name="MODULE_MODE" value="false" />
<option name="REDIRECT_INPUT" value="false" />
<option name="INPUT_FILE" value="" />
<method v="2" />
</configuration>
<configuration name="mian7" type="PythonConfigurationType" factoryName="Python" temporary="true">
<module name="Restaurant" />
<option name="INTERPRETER_OPTIONS" value="" />
@ -234,7 +237,7 @@
<option name="INPUT_FILE" value="" />
<method v="2" />
</configuration>
<configuration name="sth" type="PythonConfigurationType" factoryName="Python" temporary="true">
<configuration name="sth (1)" type="PythonConfigurationType" factoryName="Python" temporary="true">
<module name="Restaurant" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
@ -242,11 +245,11 @@
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/Kinga" />
<option name="IS_MODULE_SDK" value="true" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/sth.py" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/Kinga/sth.py" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<option name="EMULATE_TERMINAL" value="false" />
@ -257,11 +260,11 @@
</configuration>
<recent_temporary>
<list>
<item itemvalue="Python.main" />
<item itemvalue="Python.mian7" />
<item itemvalue="Python.main6" />
<item itemvalue="Python.main4 (1)" />
<item itemvalue="Python.sth" />
<item itemvalue="Python.sth (1)" />
<item itemvalue="Python.main" />
<item itemvalue="Python.image_classification" />
<item itemvalue="Python.mian7" />
</list>
</recent_temporary>
</component>
@ -283,7 +286,14 @@
<option name="project" value="LOCAL" />
<updated>1587817863041</updated>
</task>
<option name="localTasksCounter" value="2" />
<task id="LOCAL-00002" summary="Rozpoznawanie banknotów">
<created>1589726457118</created>
<option name="number" value="00002" />
<option name="presentableId" value="LOCAL-00002" />
<option name="project" value="LOCAL" />
<updated>1589726457118</updated>
</task>
<option name="localTasksCounter" value="3" />
<servers />
</component>
<component name="ToolWindowManager">
@ -294,13 +304,13 @@
<window_info id="Favorites" order="2" side_tool="true" />
<window_info anchor="bottom" id="Message" order="0" />
<window_info anchor="bottom" id="Find" order="1" />
<window_info anchor="bottom" id="Run" order="2" sideWeight="0.49925596" weight="0.26628897" />
<window_info anchor="bottom" id="Run" order="2" sideWeight="0.49925596" weight="0.32719547" />
<window_info anchor="bottom" id="Debug" order="3" weight="0.398017" />
<window_info anchor="bottom" id="Cvs" order="4" weight="0.25" />
<window_info anchor="bottom" id="Inspection" order="5" weight="0.4" />
<window_info anchor="bottom" id="TODO" order="6" />
<window_info anchor="bottom" id="Version Control" order="7" weight="0.21246459" />
<window_info active="true" anchor="bottom" id="Terminal" order="8" visible="true" weight="0.3243626" />
<window_info active="true" anchor="bottom" id="Terminal" order="8" visible="true" weight="0.5141643" />
<window_info anchor="bottom" id="Event Log" order="9" sideWeight="0.50074404" side_tool="true" weight="0.3289689" />
<window_info anchor="bottom" id="Python Console" order="10" />
<window_info anchor="right" id="Commander" internal_type="SLIDING" order="0" type="SLIDING" weight="0.4" />
@ -320,7 +330,8 @@
</component>
<component name="VcsManagerConfiguration">
<MESSAGE value="Dodanie kierunku agenta; rozstawienie stolow; dodanie kuchni; agent nie wchodzi na pola z obiektem stol i kuchnia" />
<option name="LAST_COMMIT_MESSAGE" value="Dodanie kierunku agenta; rozstawienie stolow; dodanie kuchni; agent nie wchodzi na pola z obiektem stol i kuchnia" />
<MESSAGE value="Rozpoznawanie banknotów" />
<option name="LAST_COMMIT_MESSAGE" value="Rozpoznawanie banknotów" />
</component>
<component name="editorHistoryManager">
<entry file="file://$USER_HOME$/Downloads/DSZI_2020_Projekt-master/dszi_2020_projekt/Restaurant/main.py" />
@ -414,101 +425,15 @@
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/sth.py">
<provider selected="true" editor-type-id="text-editor">
<state>
<caret selection-end-line="2" selection-end-column="10" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/main6.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="1210">
<caret line="58" selection-end-line="338" />
<folding>
<element signature="e#1744#1756#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/Kinga/__init__.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="242">
<caret line="11" column="18" lean-forward="true" selection-start-line="11" selection-start-column="18" selection-end-line="11" selection-end-column="18" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/Kinga/main5.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="1166">
<caret line="53" column="54" selection-start-line="53" selection-start-column="54" selection-end-line="53" selection-end-column="54" />
<folding>
<element signature="e#0#94#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/Kinga/mian7.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="748">
<caret line="88" column="32" selection-start-line="88" selection-start-column="32" selection-end-line="88" selection-end-column="32" />
<folding>
<element signature="e#1744#1756#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/Kinga/main8.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="2002">
<caret line="172" column="1" selection-start-line="172" selection-start-column="1" selection-end-line="172" selection-end-column="1" />
<folding>
<element signature="e#0#9#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/Kinga/main1.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="462">
<caret line="27" column="57" selection-start-line="27" selection-start-column="57" selection-end-line="27" selection-end-column="57" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/Kinga/main2.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="2156">
<caret line="103" selection-start-line="103" selection-end-line="103" selection-end-column="36" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/Kinga/main3.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="1459">
<caret line="92" column="28" selection-start-line="92" selection-start-column="28" selection-end-line="92" selection-end-column="28" />
<folding>
<element signature="e#0#9#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/Kinga/main4.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="-2017">
<caret line="22" column="33" selection-start-line="22" selection-start-column="33" selection-end-line="22" selection-end-column="69" />
<folding>
<element signature="e#0#12#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/Sara/image_classification.py">
<provider selected="true" editor-type-id="text-editor">
<state>
<caret line="4" column="16" lean-forward="true" selection-start-line="4" selection-start-column="16" selection-end-line="4" selection-end-column="16" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/sth.py" />
<entry file="file://$PROJECT_DIR$/main6.py" />
<entry file="file://$PROJECT_DIR$/Kinga/__init__.py" />
<entry file="file://$PROJECT_DIR$/Kinga/main5.py" />
<entry file="file://$PROJECT_DIR$/Kinga/mian7.py" />
<entry file="file://$PROJECT_DIR$/Kinga/main8.py" />
<entry file="file://$PROJECT_DIR$/Kinga/main1.py" />
<entry file="file://$PROJECT_DIR$/Kinga/main2.py" />
<entry file="file://$PROJECT_DIR$/Kinga/main3.py" />
<entry file="file://$PROJECT_DIR$/../README.md">
<provider selected="true" editor-type-id="split-provider[text-editor;markdown-preview-editor]">
<state split_layout="SPLIT">
@ -517,15 +442,45 @@
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/Sara/image_classification.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="154">
<caret line="7" selection-start-line="7" selection-end-line="7" />
<folding>
<element signature="e#0#94#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/main.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="13508">
<caret line="668" column="15" lean-forward="true" selection-start-line="668" selection-start-column="15" selection-end-line="668" selection-end-column="15" />
<state relative-caret-position="323">
<caret line="506" column="79" selection-start-line="506" selection-start-column="79" selection-end-line="506" selection-end-column="79" />
<folding>
<element signature="e#0#13#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/Kinga/sth.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="625">
<caret line="90" column="62" selection-start-line="90" selection-start-column="62" selection-end-line="90" selection-end-column="62" />
<folding>
<element signature="e#0#94#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/Kinga/main4.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="504">
<caret line="76" column="14" lean-forward="true" selection-start-line="76" selection-start-column="14" selection-end-line="76" selection-end-column="14" />
<folding>
<element signature="e#0#94#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
</component>
</project>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 269 KiB

View File

@ -1,186 +1,78 @@
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torchvision import transforms, datasets
import matplotlib.pyplot as plt
from PIL import Image
import os
import os.path
torch.manual_seed(42)
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K
img_width, img_height = 256, 256
train_dir = 'data2/train'
examine_dir = 'data2/validation'
train_data_dir = 'data/train'
examine_data_dir = 'data/examine'
nb_train_samples = 290
nb_examine_samples = 80
epochs = 1
batch_size = 16
transform_img = transforms.Compose(
[transforms.Resize(255),
#transforms.RandomHorizontalFlip(),
#transforms.ToTensor()().unsqueeze_(0),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
train_data = datasets.ImageFolder(train_dir, transform=transform_img)
examine_data = datasets.ImageFolder(examine_dir, transform=transform_img)
train_loader = DataLoader(dataset = train_data, batch_size = 255, shuffle=True, num_workers=0, collate_fn=None)
examine_loader = DataLoader(dataset = examine_data, batch_size = 255, shuffle=False, num_workers=0, collate_fn=None)
if torch.cuda.is_available():
device = torch.device('cuda')
if K.image_data_format() == 'channels_first':
input_shape = (3, img_width, img_height)
else:
device = torch.device('cpu')
input_shape = (img_width, img_height, 3)
epochs = 35
batch_size = 25
learning_rate = 0.001
model = Sequential()
model.add(Conv2D(32, (2, 2), input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
import torch.nn.functional as F
model.add(Conv2D(32, (2, 2)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Conv2d(in_channels=3, out_channels=10, kernel_size=3)
self.conv2 = nn.Conv2d(10, 20, kernel_size=3)
self.conv2_drop = nn.Dropout2d()
self.fc1 = nn.Linear(720, 1024)
self.fc2 = nn.Linear(1024, 2)
model.add(Conv2D(64, (2, 2)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
def forward(self, x):
x = F.relu(F.max_pool2d(self.conv1(x), 2))
x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
x = x.view(x.shape[0],-1)
x = F.relu(self.fc1(x))
x = F.dropout(x, training=self.training)
x = self.fc2(x)
return x
model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(7))
model.add(Activation('sigmoid'))
model = CNN()
print(model)
model.compile(loss='categorical_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
train_datagen = ImageDataGenerator(
rotation_range=45,
width_shift_range=0.3,
height_shift_range=0.3,
rescale=1. / 255,
shear_range=0.25,
zoom_range=0.1,
horizontal_flip=True)
examine_datagen = ImageDataGenerator(rescale=1. / 255)
model = CNN().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(),lr = learning_rate)
train_generator = train_datagen.flow_from_directory(
train_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='categorical')
examine_generator = examine_datagen.flow_from_directory(
examine_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='categorical')
train_losses = []
valid_losses = []
num_epochs = 25
model.fit_generator(
train_generator,
steps_per_epoch=nb_train_samples // batch_size,
epochs=epochs,
validation_data=examine_generator,
validation_steps=nb_examine_samples // batch_size)
for epoch in range(1, num_epochs + 1):
# keep-track-of-training-and-validation-loss
train_loss = 0.0
valid_loss = 0.0
# training-the-model
model.train()
for data, target in train_loader:
# move-tensors-to-GPU
data = data.to(device)
target = target.to(device)
# clear-the-gradients-of-all-optimized-variables
optimizer.zero_grad()
# forward-pass: compute-predicted-outputs-by-passing-inputs-to-the-model
output = model(data)
# calculate-the-batch-loss
loss = criterion(output, target)
# backward-pass: compute-gradient-of-the-loss-wrt-model-parameters
loss.backward()
# perform-a-ingle-optimization-step (parameter-update)
optimizer.step()
# update-training-loss
train_loss += loss.item() * data.size(0)
# validate-the-model
model.eval()
for data, target in examine_loader:
data = data.to(device)
target = target.to(device)
output = model(data)
loss = criterion(output, target)
# update-average-validation-loss
valid_loss += loss.item() * data.size(0)
# calculate-average-losses
train_loss = train_loss / len(train_loader)
valid_loss = valid_loss / len(examine_loader)
train_losses.append(train_loss)
valid_losses.append(valid_loss)
# print-training/validation-statistics
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch, train_loss, valid_loss))
# test-the-model
model.eval() # it-disables-dropout
with torch.no_grad():
correct = 0
total = 0
for images, labels in examine_loader:
images = images.to(device)
labels = labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Test Accuracy of the model: {} %'.format(100 * correct / total))
# Save
torch.save(model.state_dict(), 'model.ckpt')
'''''
def train(model, dataset, n_iter=100, batch_size=256):
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
criterion = nn.NLLLoss()
dl = DataLoader(dataset, batch_size=batch_size)
model.train()
for epoch in range(n_iter):
for images, targets in dl:
optimizer.zero_grad()
out = model(images.to(device))
loss = criterion(out, targets.to(device))
loss.backward()
optimizer.step()
if epoch % 10 == 0:
print('epoch: %3d loss: %.4f' % (epoch, loss))
def accuracy(model, dataset):
model.eval()
correct = sum([(model(images.to(device)).argmax(dim=1) == targets).sum()
for images, targets in DataLoader(dataset, batch_size=256)])
return correct.float()/len(dataset)
model = nn.Sequential(
nn.Linear(28*28, 10),
nn.LogSoftmax(dim=-1)
).to(device)
#print(train(model, train_data))
#print(accuracy(model, examine_data))
hidden_size = 300
model_2 = nn.Sequential(
nn.Linear(28*28, hidden_size),
nn.ReLU(),
nn.Linear(hidden_size, 10),
nn.LogSoftmax(dim=-1)
).to(device)
#print(train(model_2, train_data))
#print(accuracy(model_2, examine_data))
#torch.save(model, 'model.pth')
'''''
model.save_weights('model_paymenttttt.h5')
results = model.evaluate(train_generator)
print(results)
print((train_generator.class_indices))

View File

@ -479,6 +479,41 @@ def evaluate(b):
pass
def decide(client, image, dish):
img_width, img_height = 256, 256
client.pay(image)
test_image = load_img(image, target_size=(img_width, img_height))
test_image = img_to_array(test_image)
test_image = test_image.reshape((1,) + test_image.shape)
result = pln_model.predict(test_image)
print(result)
if result.tolist() == [[1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]:
messagebox.showinfo("Rachunek", "Dziękuję, należy się reszta: " + str(10 - dish.price) + " zł.")
return 0
elif result.tolist() == [[0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]]:
messagebox.showinfo("Rachunek", "Dziękuję, należy się reszta: " + str(100 - dish.price) + " zł.")
return 0
elif result.tolist() == [[0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0]]:
messagebox.showinfo("Rachunek", "Dziękuję, należy się reszta: " + str(20 - dish.price) + " zł.")
return 0
elif result.tolist() == [[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]]:
messagebox.showinfo("Rachunek", "Dziękuję, należy się reszta: " + str(200 - dish.price) + " zł.")
return 0
elif result.tolist() == [[0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0]]:
messagebox.showinfo("Rachunek", "Dziękuję, należy się reszta: " + str(50 - dish.price) + " zł.")
return 0
elif result.tolist() == [[0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0]]:
messagebox.showinfo("Rachunek", "Dziękuję, należy się reszta: " + str(500 - dish.price) + " zł.")
return 0
else:
messagebox.showinfo("Uwaga", "Niestety, nie przyjmujemy zapłaty kartą.")
return 1
def payment(c):
if c == 1:
@ -504,32 +539,23 @@ def payment(c):
bot.goByAStar((tables[1].pos[0] + 1, tables[1].pos[1]))
messagebox.showinfo("Rachunek", "Proszę o zapłatę " + str(dish_1.price) + " zł.")
client_1.pay('Kinga/data/examine/200/examine_056.png')
#classify image#
#if img == 1:
# messagebox.showinfo("Rachunek", "Dziękuję, należy się reszta: " + str(client_1.budget - dish_1.price) + " zł.")
#else: #karta
# messagebox.showinfo("Uwaga", "Niestety, nie przyjmujemy zapłaty kartą.")
client1_payment = ('Kinga/data/examine/200/examine_056.png')
decide(client_1, client1_payment, dish_1)
bot.goByAStar((tables[4].pos[0] + 1, tables[4].pos[1]))
messagebox.showinfo("Rachunek", "Proszę o zapłatę " + str(dish_2.price) + " zł.")
client_2.pay("Kinga/data/examine/100/examine_036.png")
#tak samo
#messagebox.showinfo("Rachunek", "Dziękuję, należy się reszta: " + str(client_2.budget - dish_2.price) + " zł.")
client2_payment = ("Kinga/data/examine/100/examine_036.png")
decide(client_2, client2_payment, dish_2)
bot.goByAStar((tables[5].pos[0] + 1, tables[5].pos[1]))
messagebox.showinfo("Rachunek", "Proszę o zapłatę " + str(dish_3.price) + " zł.")
client_3.pay("Kinga/data/examine/50/examine_029.png")
#messagebox.showinfo("Rachunek", "Dziękuję, należy się reszta: " + str(client_3.budget - dish_3.price) + " zł.")
client3_payment = ("Kinga/data/examine/50/examine_029.png")
decide(client_3, client3_payment, dish_3)
bot.goByAStar((tables[8].pos[0] + 1, tables[8].pos[1]))
messagebox.showinfo("Rachunek", "Proszę o zapłatę " + str(dish_4.price) + " zł.")
client_4.pay("Kinga/data/examine/cards/card_008.png")
#messagebox.showinfo("Rachunek", "Dziękuję, należy się reszta: " + str(client_4.budget - dish_4.price) + " zł.")
messagebox.showinfo("Uwaga", "Niestety, nie przyjmujemy zapłaty kartą.")
client4_payment = ("Kinga/data/examine/cards/card_008.png")
decide(client_4, client4_payment, dish_4)
messagebox.showinfo("Informacja końcowa", "Zakończono trasę.")
@ -619,10 +645,39 @@ def makeImgClassificator(model):
metrics=['accuracy'])
def recognizeCash(model):
img_width, img_height = 256, 256
if K.image_data_format() == 'channels_first':
input_shape = (3, img_width, img_height)
else:
input_shape = (img_width, img_height, 3)
model.add(Conv2D(32, (2, 2), input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(32, (2, 2)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (2, 2)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(7))
model.add(Activation('sigmoid'))
model.compile(loss='categorical_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
def main():
global width, rows, bot, light_beige, beige, white, black, sizeBetween, tables, kitchen, cantwalk, puddles, window, clock, \
img_classify
img_classify, pln_model
# skróty do kolorów
light_beige = (255, 240, 205)
beige = (255, 205, 178)
@ -633,6 +688,10 @@ def main():
makeImgClassificator(img_classify)
img_classify.load_weights('Sara/model_food_dirty.h5')
pln_model = Sequential()
recognizeCash(pln_model)
pln_model.load_weights('Kinga/model_payment.h5')
width = 600
rows = 15
sizeBetween = width // rows #wielkość pojedynczej kratki