diff --git a/graphs/depth_first_search_2.py b/graphs/depth_first_search_2.py index 8fe48b7f2b42..4b2ce36e31dc 100644 --- a/graphs/depth_first_search_2.py +++ b/graphs/depth_first_search_2.py @@ -108,6 +108,25 @@ def dfs_recursive(self, start_vertex: int, visited: list) -> None: print(" ", end="") self.dfs_recursive(i, visited) + def topological_sort(self): + visited = set() + stack = [] + + for vertex in self.vertex: + if vertex not in visited: + self.topological_sort_util(vertex, visited, stack) + + return stack[::-1] # Reverse the stack to get the correct order + + def topological_sort_util(self, v, visited, stack): + visited.add(v) + + for neighbor in self.vertex.get(v, []): + if neighbor not in visited: + self.topological_sort_util(neighbor, visited, stack) + + stack.append(v) # Push the vertex to stack + if __name__ == "__main__": import doctest @@ -123,5 +142,5 @@ def dfs_recursive(self, start_vertex: int, visited: list) -> None: g.add_edge(3, 3) g.print_graph() - print("DFS:") + print("Topological Sort:", g.topological_sort()) g.dfs() diff --git a/machine_learning/loss_functions.py b/machine_learning/loss_functions.py index 0bd9aa8b5401..1360950af914 100644 --- a/machine_learning/loss_functions.py +++ b/machine_learning/loss_functions.py @@ -658,8 +658,10 @@ def kullback_leibler_divergence(y_true: np.ndarray, y_pred: np.ndarray) -> float """ if len(y_true) != len(y_pred): raise ValueError("Input arrays must have the same length.") - - kl_loss = y_true * np.log(y_true / y_pred) + + # Mask y_true is 0 to avoid invalid log calculation + mask = y_true != 0 + kl_loss = y_true[mask] * np.log(y_true[mask] / y_pred[mask]) return np.sum(kl_loss)