Skip to content

Commit 2420ecb

Browse files
JohnYao93Nabushikajudicaelclair
authored
Fixing ml (#56)
* changed tensor value None, starting investigation into ML * Debugging torch.tensor changes, added several bug fixes with duplicate traces * Fixed double trace * removed trace bug * ml working for 8x8 maps * fixed ml for all size maps... * pushing new models * added parameter changes, the training batch script * implemented requested changes * adding trainer requirements for the batch trainer * changing batch trainer to use trainer_requirements, added comments for the VIN file (dont touch), and deleted redundant GUI import from runtrainer * removed relative pathing from directory model * added the atlas generation back, fixed uniform random fill generation labelling. * adding bootstrap full generate + train * updating the batch train * setting the generator to true * fixed the np breaking change, currently have a torch breaking change for CUDA issues but hopefully will work on device with just cpu * lengths cpu hot fix * adding the 3000 trained for onlineLSTM * patching the fixes from the updates to master * removing last bit of resources folder * removing debugging and the versioning on the requirements * Fixed indentation Signed-off-by: [ 大鳄 ] Asew <[email protected]> * Made code concise Signed-off-by: [ 大鳄 ] Asew <[email protected]> * Delete vin.py * deleting comments * hasattr fix * removing print * Polished file not found message * Dependencies / requirements cleanup Signed-off-by: [ 大鳄 ] Asew <[email protected]> * Imports cleanup Signed-off-by: [ 大鳄 ] Asew <[email protected]> * Formatted code Signed-off-by: [ 大鳄 ] Asew <[email protected]> * Removed useless import Signed-off-by: [ 大鳄 ] Asew <[email protected]> Co-authored-by: Abel Shields <[email protected]> Co-authored-by: [ 大鳄 ] Asew <[email protected]> Co-authored-by: [ 大鳄 ] Asew <[email protected]>
1 parent e211b57 commit 2420ecb

22 files changed

+211
-208
lines changed
173 KB
Binary file not shown.
145 KB
Binary file not shown.
168 KB
Binary file not shown.
Binary file not shown.

src/algorithms/basic_testing.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -201,19 +201,20 @@ def get_occupancy_percentage_size(size: Size, items_nr: int) -> float:
201201

202202
@staticmethod
203203
def get_euclidean_distance_traveled(trace: List[Trace], agent: Agent) -> float:
204-
trace.append(Trace(agent.position))
204+
if (not trace) or trace[-1].position != agent.position:
205+
trace.append(Trace(agent.position))
205206
dist = 0
206207
for i in range(1, len(trace)):
207208
dist += np.linalg.norm(np.array(trace[i - 1].position) - np.array(trace[i].position))
208209
return dist
209210

210211
@staticmethod
211212
def get_smoothness(trace: List[Trace], agent: Agent) -> float:
212-
trace.append(Trace(agent.position))
213+
if (not trace) or trace[-1].position != agent.position:
214+
trace.append(Trace(agent.position))
213215
angle = 0
214216
prev_angle = None
215217

216-
# print(trace)
217218
for i in range(1, len(trace)):
218219

219220
if(not trace[i - 1].position == trace[i].position):

src/algorithms/configuration/configuration.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -65,11 +65,14 @@ def __init__(self) -> None:
6565

6666
# Generator
6767
self.generator = False
68-
self.generator_labelling_atlases = []
69-
self.generator_nr_of_examples = 10
70-
self.generator_gen_type = "house"
71-
self.generator_labelling_features = []
72-
self.generator_labelling_labels = []
68+
self.generator_labelling_atlases = ['block_map_100']
69+
self.generator_nr_of_examples = 100
70+
self.generator_gen_type = "block_map"
71+
self.generator_labelling_features = ["distance_to_goal_normalized",
72+
"raycast_8_normalized",
73+
"direction_to_goal_normalized",
74+
"agent_goal_angle"]
75+
self.generator_labelling_labels = ["next_position_index"]
7376
self.generator_single_labelling_features = []
7477
self.generator_single_labelling_labels = []
7578
self.generator_aug_labelling_features = []
@@ -79,9 +82,9 @@ def __init__(self) -> None:
7982
self.generator_modify = None
8083
self.generator_show_gen_sample = False
8184
self.generator_house_expo = False
82-
self.generator_size = 28
85+
self.generator_size = 64
8386

84-
self.num_dim = 3
87+
self.num_dim = 2
8588

8689
# Trainer
8790
self.trainer = False

src/algorithms/configuration/entities/trace.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,6 @@ def __eq__(self, other: object) -> bool:
2929
if not isinstance(other, Trace):
3030
return False
3131
return super().__eq__(other)
32+
33+
def __hash__(self) -> int:
34+
return hash(self.position)

src/algorithms/configuration/maps/map.py

Lines changed: 7 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
import copy
21
from typing import List, Optional, Set, Dict, Callable, TypeVar, Union, Tuple
3-
2+
from itertools import product
3+
import copy
44
import math
5+
56
import numpy as np
6-
from itertools import product
77

88
from algorithms.configuration.entities.agent import Agent
99
from algorithms.configuration.entities.entity import Entity
@@ -116,10 +116,6 @@ def get_obstacle_bound(self, obstacle_start_point: Point, visited: Optional[Set[
116116
"""
117117
# modified initialisation of visited set for n dimensional nodes
118118
if visited is None:
119-
#visited = [False for _ in range(self.size.width)]
120-
121-
# for i in range(self.dim - 1):
122-
# visited = [visited for _ in range(self.size[i + 1])]
123119
visited: Set[Point] = set()
124120

125121
if self.is_agent_valid_pos(obstacle_start_point):
@@ -149,6 +145,7 @@ def get_move_index(self, direction: List[float]) -> int:
149145
:param direction: The direction
150146
:return: The index corresponding to :ref:`ALL_POINTS_MOVE_VECTOR`
151147
"""
148+
direction = direction.tolist() if hasattr(direction, "tolist") else direction
152149
rounded_point = self.get_move_along_dir(direction)
153150
return self.ALL_POINTS_MOVE_VECTOR.index(rounded_point)
154151

@@ -158,6 +155,7 @@ def get_move_along_dir(self, direction: List[float]) -> Point:
158155
:param direction: The true direction
159156
:return: The :ref:`ALL_POINTS_MOVE_VECTOR` point
160157
"""
158+
assert(any(direction))
161159
dir_length = math.sqrt(sum(i*i for i in direction))
162160
norm_direction = list(map(lambda i: i/dir_length, direction))
163161
rounded_direction = list(map(lambda i: round(i), norm_direction))
@@ -195,23 +193,11 @@ def move_agent(self, to: Point, no_trace: bool = False, follow: bool = False) ->
195193

196194
if not follow:
197195
return self.move(self.agent, to, no_trace)
198-
# else:
199-
# line: List[Point] = self.get_line_sequence(self.agent.position, to)
200-
# for next_pos in line:
201-
# if not self.move(self.agent, next_pos, no_trace):
202-
# return False
203-
# return True
204-
# for pt in EIGHT_POINTS_MOVE_VECTOR:
205-
# inx = int(next_pos.x + point.x)
206-
# iny = int(next_pos.y + point.y)
207196
else:
208-
line: List[Point] = self.get_line_sequence(self.agent.position, to)
209-
print(line)
210-
n = 0
197+
line: List[Point] = self.get_line_sequence(self.agent.position, to)[1:] # Get rid of first point, the current agent pos
211198
for next_pos in line:
212199
if not self.move(self.agent, next_pos, no_trace):
213-
if n != 0:
214-
return False
200+
return False
215201
return True
216202

217203
def get_line_sequence(self, frm: Point, to: Point) -> List[Point]:

src/algorithms/lstm/LSTM_CAE_tile_by_tile.py

Lines changed: 36 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
class CAEEncoder(nn.Module):
2626
def __init__(self, latent_dim: int):
2727
super().__init__()
28-
#The four convolutional layers, and four batch normalization layers in the CAE Encoder.
28+
# The four convolutional layers, and four batch normalization layers in the CAE Encoder.
2929
self.conv1 = nn.Conv2d(in_channels=1, out_channels=64, kernel_size=3, padding=1)
3030
self.bn1 = nn.BatchNorm2d(num_features=64)
3131
self.conv2 = nn.Conv2d(in_channels=64, out_channels=32, kernel_size=3, padding=1)
@@ -37,8 +37,8 @@ def __init__(self, latent_dim: int):
3737
self.latent_linear = nn.Linear(in_features=8 * 4 * 4, out_features=latent_dim)
3838
self.bn_latent = nn.BatchNorm1d(num_features=latent_dim)
3939

40-
#Define the forward motion of the CAE Encoder, basically applies the Leakey Relu + Max pool activation function -
41-
# to the Batch Normalized Convolutional Layer,
40+
# Define the forward motion of the CAE Encoder, basically applies the Leakey Relu + Max pool activation function -
41+
# to the Batch Normalized Convolutional Layer,
4242
def forward(self, input):
4343
out1 = F.leaky_relu(F.max_pool2d(self.bn1(self.conv1(input)), kernel_size=2, stride=2))
4444
out2 = F.leaky_relu(F.max_pool2d(self.bn2(self.conv2(out1)), kernel_size=2, stride=2))
@@ -53,7 +53,7 @@ def __init__(self, latent_dim: int, with_skip):
5353
super().__init__()
5454

5555
self.__with_skip = with_skip
56-
#Similar to above, but in opposite order
56+
# Similar to above, but in opposite order
5757
self.latent_linear = nn.Linear(in_features=latent_dim, out_features=8 * 4 * 4)
5858
self.bn_latent = nn.BatchNorm1d(num_features=8 * 4 * 4)
5959
self.deconv1 = nn.ConvTranspose2d(in_channels=8, out_channels=16, kernel_size=2, stride=2)
@@ -81,15 +81,15 @@ def forward(self, x):
8181
return out5
8282

8383

84-
#Actual MLModel CAE class
84+
# Actual MLModel CAE class
8585
class CAE(MLModel):
8686
MAP_COLORMAP_FULL = LinearSegmentedColormap.from_list("my_list", [(1, 1, 1), (0, 0, 0), (1, 0, 0), (0, 1, 0)])
8787
MAP_COLORMAP = "gray_r"
8888
MNIST_COLORMAP = "gray"
8989

9090
def __init__(self, services: Services, config: Dict[str, any]):
9191
super().__init__(services, config)
92-
#Run encoder then dedoder
92+
# Run encoder then dedoder
9393
self.encoder = CAEEncoder(self.config["latent_dim"])
9494
self.decoder = CAEDecoder(self.config["latent_dim"], self.config["with_skip_connections"])
9595

@@ -112,7 +112,7 @@ def pre_process_data(self) -> Tuple[Dataset, Dataset]:
112112
return features, labels
113113

114114
def batch_start(self, inputs: torch.Tensor, labels: torch.Tensor) -> Tuple[
115-
torch.Tensor, torch.Tensor, torch.Tensor]:
115+
torch.Tensor, torch.Tensor, torch.Tensor]:
116116

117117
inp = inputs[0].view((inputs[0].shape[0], -1)).to(self._services.torch.device)
118118
lbl = labels[0].view((labels[0].shape[0], -1)).to(self._services.torch.device)
@@ -237,12 +237,8 @@ def get_config() -> Dict[str, Any]:
237237
],
238238
"save_name": "caelstm_section_cae",
239239
"training_data": [
240-
#'training_house_100'
241-
#"training_" + str(config.) + "_" + str(ui.nbr_ex)
242-
# "training_uniform_random_fill_10", #IMPT
243-
#"training_uniform_random_fill_100",
244240
"training_house_1000",
245-
], # training_uniform_random_fill_10000_block_map_10000_house_10000, "training_uniform_random_fill_10000_block_map_10000", "training_house_10000", "training_uniform_random_fill_10000", "training_block_map_10000",
241+
],
246242
"use_mnist_instead": False,
247243
"mnist_size": None,
248244
"epochs": 100,
@@ -355,32 +351,32 @@ def forward_features(self, mp: Map) -> torch.Tensor:
355351
@staticmethod
356352
def get_config() -> Dict[str, Any]:
357353
return {
358-
"data_features": [
359-
"raycast_8_normalized",
360-
"distance_to_goal_normalized",
361-
"direction_to_goal_normalized",
362-
"agent_goal_angle",
363-
],
364-
"data_single_features": [
365-
"global_map",
366-
],
367-
"data_labels": [
368-
"next_position_index",
369-
],
370-
"custom_encoder": None, # "caelstm_section_cae_training_uniform_random_fill_10000_block_map_10000_house_10000_model",
371-
"save_name": "caelstm_section_lstm",
372-
"training_data": [
373-
"training_house_100"
374-
#"training_uniform_random_fill_10000",
375-
#"training_block_map_10000",
376-
#"training_house_10000",
377-
], # training_uniform_random_fill_10000_block_map_10000_house_10000, "training_uniform_random_fill_10000_block_map_10000", "training_house_10000", "training_uniform_random_fill_10000", "training_block_map_10000",
378-
"epochs": 21,
379-
"num_layers": 2,
380-
#"with_init_fn": False,
381-
#"input_size": 114,
382-
"lstm_input_size": 112,
383-
"lstm_output_size": 8,
384-
"loss": nn.CrossEntropyLoss(),
385-
"optimizer": lambda model: torch.optim.Adam(model.parameters(), lr=0.01),
354+
"data_features": [
355+
"raycast_8_normalized",
356+
"distance_to_goal_normalized",
357+
"direction_to_goal_normalized",
358+
"agent_goal_angle",
359+
],
360+
"data_single_features": [
361+
"global_map",
362+
],
363+
"data_labels": [
364+
"next_position_index",
365+
],
366+
"custom_encoder": None, # "caelstm_section_cae_training_uniform_random_fill_10000_block_map_10000_house_10000_model",
367+
"save_name": "caelstm_section_lstm",
368+
"training_data": [
369+
"training_house_100"
370+
# "training_uniform_random_fill_10000",
371+
# "training_block_map_10000",
372+
# "training_house_10000",
373+
], # training_uniform_random_fill_10000_block_map_10000_house_10000, "training_uniform_random_fill_10000_block_map_10000", "training_house_10000", "training_uniform_random_fill_10000", "training_block_map_10000",
374+
"epochs": 21,
375+
"num_layers": 2,
376+
# "with_init_fn": False,
377+
# "input_size": 114,
378+
"lstm_input_size": 112,
379+
"lstm_output_size": 8,
380+
"loss": nn.CrossEntropyLoss(),
381+
"optimizer": lambda model: torch.optim.Adam(model.parameters(), lr=0.01),
386382
}

0 commit comments

Comments
 (0)