ID3 work, WM objective approach

This commit is contained in:
Milosz Rolewski 2023-05-28 10:23:30 +02:00
parent 6df02452bc
commit 91c2c2074e
14 changed files with 99 additions and 55 deletions

34
main.py
View File

@ -4,11 +4,12 @@ import random
from settings import screen_height, screen_width, SIZE, SPECIES, block_size, tile, road_coords, directions
from src.map import drawRoads, seedForFirstTime, return_fields_list, WORLD_MATRIX
from src.Tractor import Tractor
from src.Plant import Plant
from src.bfs import Astar
from src.Plant import Plant
from src.Field import Field
import pickle
import os
from src.ID3 import make_decision
# pygame initialization
@ -34,13 +35,15 @@ tractor = Tractor('oil','manual', 'fuel', 'fertilizer1', 20)
tractor_group = pygame.sprite.Group()
tractor_group.add(tractor)
tractor.setCapacity(90)
tractor.setFuel(100)
#PLANTS
plant_group = pygame.sprite.Group()
plant_group = seedForFirstTime()
fields = return_fields_list()
#ID3 TREE
tree = pickle.load(open(os.path.join('src','tree.plk'),'rb'))
#
tractor_move = pygame.USEREVENT + 1
@ -54,8 +57,29 @@ print("Destination: ", destination)
mx=int((mx+18)/36)
my=int((my+18)/36)
print("Destination: ", mx,my)
tmp = WORLD_MATRIX[mx][my]
print(tmp)
#POBIERZ MATRIXA OBJEKT FILD, Z FIELD POBIERZ PLANT, Z PLANTA PARAMETRY, WYWOŁAJ DECYCJNOSC
#ID3 TREE
dtree = pickle.load(open(os.path.join('src','tree.plk'),'rb'))
# pobierz dane o polu field i czy ma na sobie roslinke, zadecyduj czy zebrac
this_field = WORLD_MATRIX[mx][my]
this_contain = Field.getContain(this_field)
if isinstance(this_contain, Plant):
this_plant = this_contain
params=Plant.getParameters(this_plant)
decision=make_decision(params[0],params[1],params[2],params[3],params[4],tractor.fuel,tractor.capacity,params[5],dtree)
print('wzorst',params[0],'wilgotnosc',params[1],'dni_od_nawiezienia',params[2],'pogoda',params[3],'zdrowa',params[4],'paliwo',tractor.fuel,'pojemnosc eq',tractor.capacity,'cena sprzedazy',params[5])
print(decision)
if decision == 1:
# Tractor.collect(self=tractor, plant_group=plant_group)
print('Gotowe do zbioru')
else:
print('nie zbieramy')
else:
print('Road, no plant growing')
moves = goal_astar.search(
[tractor.rect.x, tractor.rect.y, directions[tractor.rotation]], destination)

BIN
mytree.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

View File

@ -3,7 +3,7 @@ from src.Plant import Plant
class Field(Sprite):
def __init__(self, type, x, y, image, cost, hydration_level , soil,
fertilizer_degree, development_degree, plant_type, fertilizer_type, to_water, plantObj):
fertilizer_degree, development_degree, plant_type, fertilizer_type, to_water, contain):
super().__init__()
self.type = type
self.x = x
@ -19,11 +19,12 @@ class Field(Sprite):
self.plant_type = plant_type
self.fertilizer_type = fertilizer_type
self.to_water = to_water
self.plantObj = plantObj
self.contain = contain
def getPlantObj(self):
return self.plantObj
def getContain(self):
return self.contain
def setContain(self,newPlant):
self.contain=newPlant
def setPlantObj(self,newPlant):
self.plantObj=newPlant

View File

@ -2,7 +2,7 @@
"cells": [
{
"cell_type": "code",
"execution_count": 15,
"execution_count": 22,
"metadata": {},
"outputs": [],
"source": [
@ -18,21 +18,9 @@
},
{
"cell_type": "code",
"execution_count": 18,
"execution_count": 23,
"metadata": {},
"outputs": [
{
"ename": "TypeError",
"evalue": "globals must be a real dict; try eval(expr, {}, mapping)",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[18], line 14\u001b[0m\n\u001b[1;32m 11\u001b[0m data \u001b[39m=\u001b[39m tree\u001b[39m.\u001b[39mexport_graphviz(d_tree, out_file\u001b[39m=\u001b[39m\u001b[39mNone\u001b[39;00m, feature_names\u001b[39m=\u001b[39m[\u001b[39m'\u001b[39m\u001b[39mWzrost\u001b[39m\u001b[39m'\u001b[39m,\u001b[39m'\u001b[39m\u001b[39mwilgotnosc\u001b[39m\u001b[39m'\u001b[39m,\u001b[39m'\u001b[39m\u001b[39mdni_od_nawiezienia\u001b[39m\u001b[39m'\u001b[39m,\u001b[39m'\u001b[39m\u001b[39maktualna_pogoda\u001b[39m\u001b[39m'\u001b[39m,\u001b[39m'\u001b[39m\u001b[39mczy_roslina_robaczywa\u001b[39m\u001b[39m'\u001b[39m,\u001b[39m'\u001b[39m\u001b[39mpaliwo\u001b[39m\u001b[39m'\u001b[39m,\u001b[39m'\u001b[39m\u001b[39mpojemnosc_ekwipunku\u001b[39m\u001b[39m'\u001b[39m,\u001b[39m'\u001b[39m\u001b[39mcena_sprzedarzy\u001b[39m\u001b[39m'\u001b[39m])\n\u001b[1;32m 12\u001b[0m graph \u001b[39m=\u001b[39m pydotplus\u001b[39m.\u001b[39mgraph_from_dot_data(data)\n\u001b[0;32m---> 14\u001b[0m accuracy \u001b[39m=\u001b[39m \u001b[39meval\u001b[39;49m(d_tree,train,\u001b[39m'\u001b[39;49m\u001b[39mczy_zebrac\u001b[39;49m\u001b[39m'\u001b[39;49m)\n",
"\u001b[0;31mTypeError\u001b[0m: globals must be a real dict; try eval(expr, {}, mapping)"
]
}
],
"outputs": [],
"source": [
"# Read the CSV file\n",
"train = pd.read_csv(\"train_3.csv\", delimiter=\";\")\n",
@ -50,7 +38,7 @@
},
{
"cell_type": "code",
"execution_count": 17,
"execution_count": 24,
"metadata": {},
"outputs": [
{

View File

@ -7,25 +7,39 @@ import pydotplus
import matplotlib.image as pltimg
import matplotlib.pyplot as plt
# Read the CSV file
train = pd.read_csv("train_3.csv", delimiter=";")
def make_decision(Wzrost, wilgotnosc, dni_od_nawiezienia, aktualna_pogoda, czy_roslina_robaczywa, paliwo, pojemnosc_ekwipunku,cena_sprzedarzy, tree):
decision = tree.predict([[Wzrost,wilgotnosc, dni_od_nawiezienia, aktualna_pogoda, czy_roslina_robaczywa, paliwo, pojemnosc_ekwipunku,cena_sprzedarzy]])
return decision
x_train = train.drop('czy_zebrac',axis=1)
y_train = train['czy_zebrac']
def learnTree():
# Read the CSV file
train = pd.read_csv("src/train_3.csv", delimiter=";")
d_tree = DecisionTreeClassifier()
d_tree = d_tree.fit(x_train,y_train)
# print(f'Shape: {train.shape}')
# print(f'Head:\n{train.head()}')
pickle.dump(d_tree, open(os.path.join('.','tree.plk'),'wb'))
data = tree.export_graphviz(d_tree, out_file=None, feature_names=['Wzrost','wilgotnosc','dni_od_nawiezienia','aktualna_pogoda','czy_roslina_robaczywa','paliwo','pojemnosc_ekwipunku','cena_sprzedarzy'])
graph = pydotplus.graph_from_dot_data(data)
x_train = train.drop('czy_zebrac',axis=1)
y_train = train['czy_zebrac']
# Save the graph as a PNG image in the script's folder
graph.write_png(os.path.join('.', 'mytree.png'))
d_tree = DecisionTreeClassifier()
d_tree = d_tree.fit(x_train,y_train)
# Read the PNG image
# img = pltimg.imread(os.path.join('.', 'mytree.png'))
pickle.dump(d_tree, open(os.path.join('.','tree.plk'),'wb'))
data = tree.export_graphviz(d_tree, out_file=None, feature_names=['Wzrost','wilgotnosc','dni_od_nawiezienia','aktualna_pogoda','czy_roslina_robaczywa','paliwo','pojemnosc_ekwipunku','cena_sprzedarzy'])
graph = pydotplus.graph_from_dot_data(data)
# Display the image
# imgplot = plt.imshow(img)
# plt.show()
# Save the graph as a PNG image in the script's folder
graph.write_png(os.path.join('.', 'mytree.png'))
# Read the PNG image
# img = pltimg.imread(os.path.join('.', 'mytree.png'))
# Display the image
# imgplot = plt.imshow(img)
# plt.show()
return d_tree
# dtree = learnTree() #w, w, d, p,R,P,P,S
#przy robaczywej == 1 daje ok czyli jak 1 to git jest mozna zbierac, ale planowalem inaczej
# decision=make_decision(70,85,12,3,1,65,54,1000,dtree)
# print(decision)

View File

@ -61,5 +61,5 @@ class Plant(pygame.sprite.Sprite):
self.rect = self.image.get_rect()
self.rect.center = [pos_x,pos_y]
def getParameters(self):
return [self.species, self.wzrost, self.wilgotnosc, self.dni_od_nawiezienia,self.aktualna_pogoda,self.czy_robaczywa,self.cena_sprzedarzy]
def getParameters(self):
return [self.wzrost, self.wilgotnosc, self.dni_od_nawiezienia,self.aktualna_pogoda,self.czy_robaczywa,self.cena_sprzedarzy]

View File

@ -1,9 +1,13 @@
import pygame
from settings import block_size, tile
import pickle
from sklearn import tree
mx=0
my=0
class Tractor(pygame.sprite.Sprite):
def __init__(self, engine, transmission, fuel, fertilizer, capacity):
super().__init__()
@ -22,12 +26,19 @@ class Tractor(pygame.sprite.Sprite):
self.rotation = 90
self.collected = 0
self.capacity = capacity
self.engine = engine
self.transmission = transmission
self.fuel = fuel
self.fertilizer = fertilizer
self.capacity = capacity
self.fuel = fuel
def setFuel(self,fuelLevel):
self.fuel=fuelLevel
def setCapacity(self, newCapacity):
self.capacity = newCapacity
def movement_using_keys(self):
@ -75,7 +86,7 @@ class Tractor(pygame.sprite.Sprite):
self.image = self.left
def movement(self, direction):
print(int((self.rect.x-18)/36),';',int((self.rect.y-18)/36))
# print(int((self.rect.x-18)/36),';',int((self.rect.y-18)/36))
if direction == 'F':
self.move_forward()
elif direction == 'L':
@ -107,4 +118,8 @@ class Tractor(pygame.sprite.Sprite):
def find_nearest_plant(self, plant_group):
self.plant_group = plant_group
def getLocation(self):
return [self.rect.x, self.rect.y]

Binary file not shown.

Binary file not shown.

View File

@ -42,15 +42,17 @@ def drawRoads(screen):
for x in road_coords:
for block in range(int(fields_amount)+1):
screen.blit(road, (x*block_size, block * 36))
tmp_field=Field('road', x*block_size, block * 36, None, get_cost_by_type('road'), None, None, None, None, 'road', None, None,plantObj=None)
new_road = Road(x,block)
tmp_field=Field('road', x*block_size, block * 36, None, get_cost_by_type('road'), None, None, None, None, 'road', None, None,contain=new_road)
fields.add(tmp_field)
WORLD_MATRIX[x][block]=Road(x,block)
WORLD_MATRIX[x][block]=tmp_field
for y in road_coords:
for block in range(int(fields_amount)+1):
screen.blit(road, (block * block_size, y*block_size))
tmp_field=Field('road', block * block_size, y*block_size, None, get_cost_by_type('road'), None, None, None, None, 'road', None, None,plantObj=None)
new_road = Road(block,y)
tmp_field=Field('road', block * block_size, y*block_size, None, get_cost_by_type('road'), None, None, None, None, 'road', None, None,contain=new_road)
fields.add(tmp_field)
WORLD_MATRIX[block][y]=Road(block,y)
WORLD_MATRIX[block][y]=tmp_field
barn_img = pygame.image.load('assets/barn.png')
@ -74,7 +76,7 @@ def seedForFirstTime():
wzrost=random.randint(0, 100),
wilgotnosc=random.randint(0, 100),
dni_od_nawiezienia=random.randint(0, 31),
aktualna_pogoda='_',
aktualna_pogoda=random.randint(1,4),
czy_robaczywa=random.randint(0, 1),
cena_sprzedarzy=random.randint(500, 2000),
species=plant_name,
@ -82,7 +84,7 @@ def seedForFirstTime():
pos_y=y)
blocks_seeded_in_field = blocks_seeded_in_field + 1
plant_group.add(new_plant)
tmp_field_plant = Field('field', x-18, y-18, None, get_cost_by_type(plant_name), None, None, None, None, plant_name, None, None, plantObj=new_plant)
tmp_field_plant = Field('field', x-18, y-18, None, get_cost_by_type(plant_name), None, None, None, None, plant_name, None, None, contain=new_plant)
fields.add(tmp_field_plant)
mx = int((x-18)/36)

BIN
tree.plk Normal file

Binary file not shown.