### Get General Configuration Settings Source: https://context7.com/kalmannet/kalmannet_tsp/llms.txt Retrieves a parsed argparse.Namespace containing dataset, training, and network hyperparameters. This is the primary configuration entry point. ```python import Simulations.config as config args = config.general_settings() ``` -------------------------------- ### Dataset and Training Parameters Source: https://context7.com/kalmannet/kalmannet_tsp/llms.txt Prints dataset and training configuration parameters. Allows overriding parameters for specific experiments. ```python print(args.N_E) # 1000 (training sequences) print(args.N_CV) # 100 (validation sequences) print(args.N_T) # 200 (test sequences) print(args.T) # 100 (sequence length) print(args.T_test) # 100 print(args.randomLength) # False # --- Training --- print(args.n_steps) # 1000 print(args.n_batch) # 20 print(args.lr) # 0.001 print(args.wd) # 0.0001 print(args.use_cuda) # False print(args.CompositionLoss) # False print(args.alpha) # 0.3 (weight for composition loss) # --- Override for a specific experiment --- args.N_E = 2000 args.n_steps = 500 args.use_cuda = True args.n_batch = 64 args.lr = 5e-4 print("Modified lr:", args.lr) # 0.0005 ``` -------------------------------- ### Run Linear Case Simulations Source: https://github.com/kalmannet/kalmannet_tsp/blob/main/README.md Execute the Python scripts to simulate the linear KalmanNet models. These include the canonical model and the constant acceleration model. ```python python3 main_linear_canonical.py ``` ```python python3 main_linear_CA.py ``` -------------------------------- ### Configure Training Parameters for EKF Pipeline Source: https://context7.com/kalmannet/kalmannet_tsp/llms.txt Sets training hyperparameters, initializes the Adam optimizer and MSE loss, and optionally enables composition loss for the EKF pipeline. ```python import torch from KNet.KalmanNet_nn import KalmanNetNN from Simulations.Linear_sysmdl import SystemModel from Pipelines.Pipeline_EKF import Pipeline_EKF import Simulations.config as config from datetime import datetime args = config.general_settings() args.use_cuda = False args.n_steps = 1000 args.n_batch = 30 args.lr = 1e-3 args.wd = 1e-4 args.CompositionLoss = True # enable blended loss args.alpha = 0.5 # 0.5 * state_loss + 0.5 * obs_loss args.in_mult_KNet, args.out_mult_KNet = 5, 40 m, n = 2, 2 sys_model = SystemModel(torch.eye(m), 0.01*torch.eye(m), torch.eye(n), 0.1*torch.eye(n), T=100, T_test=100) knet = KalmanNetNN() knet.NNBuild(sys_model, args) strTime = datetime.now().strftime("%m.%d.%y_%H:%M:%S") pipeline = Pipeline_EKF(strTime, "KNet", "knet_comp_loss") pipeline.setssModel(sys_model) pipeline.setModel(knet) pipeline.setTrainingParams(args) print("Optimizer:", pipeline.optimizer) # Adam with lr=0.001, wd=1e-4 print("N_steps:", pipeline.N_steps) # 1000 print("Batch size:", pipeline.N_B) # 30 print("Composition loss alpha:", pipeline.alpha) # 0.5 ``` -------------------------------- ### Lorenz Attractor Dynamics Functions Source: https://context7.com/kalmannet/kalmannet_tsp/llms.txt Demonstrates the use of Lorenz Attractor state-transition functions, including exact dynamics, Jacobian calculation, inaccurate models, and observation mappings. Requires torch and specific parameters from Simulations.Lorenz_Atractor.parameters. ```python import torch from Simulations.Lorenz_Atractor.parameters import ( m, n, f, fInacc, fRotate, h, h_nonlinear, hRotate, getJacobian, toSpherical, delta_t ) batch_size = 8 x = torch.ones(batch_size, m, 1) * 0.5 # [B, 3, 1] # Exact dynamics x_next = f(x) # [B, 3, 1] print("f(x) shape:", x_next.shape) # torch.Size([8, 3, 1]) # With Jacobian (for EKF) x_next_j, F_jac = f(x, jacobian=True) print("Jacobian shape:", F_jac.shape) # torch.Size([8, 3, 3]) # Inaccurate model (lower Taylor order, used for mismatch experiments) x_inacc = fInacc(x) print("fInacc differs from f:", not torch.allclose(x_next, x_inacc)) # True # Rotated model x_rot = fRotate(x) print("fRotate(x) shape:", x_rot.shape) # torch.Size([8, 3, 1]) # Observation: identity (linear) y_lin = h(x) print("h(x) shape:", y_lin.shape) # torch.Size([8, 3, 1]) # Observation: Cartesian -> Spherical (non-linear) y_sph = h_nonlinear(x) print("h_nonlinear(x) shape:", y_sph.shape) # torch.Size([8, 3, 1]) # y_sph[:,0,:] = rho (radius), y_sph[:,1,:] = theta, y_sph[:,2,:] = phi # Get Jacobian of f at x for EKF Jac_f = getJacobian(x, f) print("Jacobian of f:", Jac_f.shape) # torch.Size([8, 3, 3]) ``` -------------------------------- ### Build KalmanNet Neural Network Architecture Source: https://context7.com/kalmannet/kalmannet_tsp/llms.txt Initializes the KalmanNet neural network, including GRU units for covariance tracking and fully connected layers for Kalman gain prediction. Configure input/hidden layer multipliers as needed. ```python import torch from KNet.KalmanNet_nn import KalmanNetNN from Simulations.Linear_sysmdl import SystemModel import Simulations.config as config args = config.general_settings() args.use_cuda = False args.n_batch = 20 args.in_mult_KNet = 5 # input feature multiplier args.out_mult_KNet = 40 # hidden layer size multiplier for FC2 m, n = 2, 2 F = torch.eye(m); F[0] = torch.ones(1, m) H = torch.eye(n) Q = 0.01 * torch.eye(m) R = 0.1 * torch.eye(n) sys_model = SystemModel(F, Q, H, R, T=100, T_test=100) # Build KalmanNet knet = KalmanNetNN() knet.NNBuild(sys_model, args) total_params = sum(p.numel() for p in knet.parameters() if p.requires_grad) print("Trainable parameters:", total_params) # e.g. 3660 # Inspect GRU dimensions print("GRU_Q input/hidden:", knet.d_input_Q, knet.d_hidden_Q) # 10, 4 print("GRU_S input/hidden:", knet.d_input_S, knet.d_hidden_S) # 12, 4 print("GRU_Sig input/hidden:", knet.d_input_Sigma, knet.d_hidden_Sigma) # 14, 4 ``` -------------------------------- ### Initialize and Generate Batch with ExtendedKalmanFilter Source: https://context7.com/kalmannet/kalmannet_tsp/llms.txt Initializes the ExtendedKalmanFilter for batched non-linear systems and generates a batch of synthetic observations. Ensure system model parameters and initial conditions are correctly set. ```python import torch from Simulations.Extended_sysmdl import SystemModel from Filters.EKF import ExtendedKalmanFilter import Simulations.config as config from Simulations.Lorenz_Atractor.parameters import m, n, m1x_0, m2x_0, f, h, Q_structure, R_structure args = config.general_settings() args.use_cuda = False Q = 0.001 * Q_structure R = 0.1 * R_structure sys_model = SystemModel(f, Q, h, R, T=100, T_test=100, m=m, n=n) sys_model.InitSequence(m1x_0, m2x_0) N_T, T_test = 50, 100 test_input = torch.randn(N_T, n, T_test) # synthetic observations ekf = ExtendedKalmanFilter(sys_model, args) ekf.Init_batched_sequence( m1x_0.view(1, m, 1).expand(N_T, -1, -1), m2x_0.view(1, m, m).expand(N_T, -1, -1) ) ekf.GenerateBatch(test_input) print("EKF estimates shape:", ekf.x.shape) # torch.Size([50, 3, 100]) print("EKF Kalman gains shape:", ekf.KG_array.shape) # torch.Size([50, 3, 3, 100]) ``` -------------------------------- ### Initialize KalmanNet Filter State for Batch Inference Source: https://context7.com/kalmannet/kalmannet_tsp/llms.txt Sets the initial posterior state estimate and temporal-difference buffers for KalmanNet before running inference. Must be called before each inference pass. Ensure batch size and sequence length are correctly specified. ```python import torch from KNet.KalmanNet_nn import KalmanNetNN from Simulations.Linear_sysmdl import SystemModel import Simulations.config as config args = config.general_settings() args.use_cuda = False args.n_batch = 4 args.in_mult_KNet, args.out_mult_KNet = 5, 40 m, n = 2, 2 F = torch.eye(m); F[0] = torch.ones(1, m) H = torch.eye(n) sys_model = SystemModel(F, 0.01*torch.eye(m), H, 0.1*torch.eye(n), T=50, T_test=50) knet = KalmanNetNN() knet.NNBuild(sys_model, args) # Prepare batch initial conditions [batch_size, m, 1] batch_size = 4 M1_0 = torch.zeros(batch_size, m, 1) # zero mean initial state knet.batch_size = batch_size knet.init_hidden_KNet() # reset GRU hidden states using prior covariances knet.InitSequence(M1_0, T=50) # set m1x_posterior and temporal difference buffers print("Posterior state shape:", knet.m1x_posterior.shape) # [4, 2, 1] print("Sequence length set to:", knet.T) # 50 ``` -------------------------------- ### Batched Linear Kalman Filter Implementation Source: https://context7.com/kalmannet/kalmannet_tsp/llms.txt Implements the classic linear Kalman filter in a fully batched manner for linear Gaussian systems. Returns state estimates and covariance matrices for the entire batch. ```python import torch from Simulations.Linear_sysmdl import SystemModel from Filters.Linear_KF import KalmanFilter import Simulations.config as config args = config.general_settings() args.use_cuda = False args.N_T = 200 args.T_test = 100 args.randomLength = False m, n = 2, 2 F = torch.eye(m); F[0] = torch.ones(1, m) H = torch.eye(n) Q = 0.01 * torch.eye(m) R = 0.1 * torch.eye(n) sys_model = SystemModel(F, Q, H, R, T=100, T_test=100) sys_model.InitSequence(torch.zeros(m, 1), torch.zeros(m, m)) # Assume test_input has shape [N_T, n, T_test] test_input = torch.randn(args.N_T, n, args.T_test) # synthetic observations kf = KalmanFilter(sys_model, args) kf.Init_batched_sequence( sys_model.m1x_0.view(1, m, 1).expand(args.N_T, -1, -1), sys_model.m2x_0.view(1, m, m).expand(args.N_T, -1, -1) ) kf.GenerateBatch(test_input) # Results state_estimates = kf.x # shape [N_T, m, T_test] covariances = kf.sigma # shape [N_T, m, m, T_test] print("KF estimates shape:", state_estimates.shape) # torch.Size([200, 2, 100]) ``` -------------------------------- ### Generate Batched Dataset with SystemModel Source: https://context7.com/kalmannet/kalmannet_tsp/llms.txt Generates a batch of independent state-observation sequences simultaneously using vectorized PyTorch operations. Supports random initial conditions and lengths with zero-padding and a length mask. ```python import torch from Simulations.Linear_sysmdl import SystemModel import Simulations.config as config args = config.general_settings() args.randomInit_train = True args.distribution = 'normal' # 'normal' or 'uniform' args.variance = 1.0 # variance for random init args.randomLength = True args.T_min, args.T_max = 50, 200 m, n = 2, 2 F = torch.eye(m); F[0] = torch.ones(1, m) H = torch.eye(n) Q = 0.01 * torch.eye(m) R = 0.1 * torch.eye(n) sys_model = SystemModel(F, Q, H, R, T=200, T_test=200) sys_model.InitSequence(torch.zeros(m, 1), 1.0 * torch.eye(m)) # Generate a batch of 50 sequences with random lengths sys_model.GenerateBatch(args, size=50, T=200, randomInit=True) print("Input shape:", sys_model.Input.shape) # [50, n, 200] (zero-padded) print("Target shape:", sys_model.Target.shape) # [50, m, 200] (zero-padded) print("Length mask shape:", sys_model.lengthMask.shape)# [50, 200] (bool) print("Actual lengths:", sys_model.lengthMask.sum(dim=1)[:5]) # e.g. tensor([137, 89, ...]) ``` -------------------------------- ### Define and Generate Data for Non-linear System Model (Lorenz Attractor) Source: https://context7.com/kalmannet/kalmannet_tsp/llms.txt Defines a non-linear state-space model using custom PyTorch functions for state transition and observation, then generates batched datasets. Noise levels and system parameters must be correctly specified. ```python import torch from Simulations.Extended_sysmdl import SystemModel from Simulations.utils import DataGen import Simulations.config as config from Simulations.Lorenz_Atractor.parameters import ( m, n, m1x_0, m2x_0, f, h, Q_structure, R_structure ) # --- Set noise levels (r2=0.1, SNR=-20dB) --- r2 = torch.tensor([0.1]) q2 = torch.tensor([0.001]) # 20 dB below r2 Q = q2[0] * Q_structure # [m, m] R = r2[0] * R_structure # [n, n] # --- Build non-linear system model (Lorenz DT) --- sys_model = SystemModel(f, Q, h, R, T=100, T_test=100, m=m, n=n) sys_model.InitSequence(m1x_0, m2x_0) # --- Generate and save datasets --- args = config.general_settings() args.N_E, args.N_CV, args.N_T = 1000, 100, 200 args.T, args.T_test = 100, 100 args.randomInit_train = args.randomInit_cv = args.randomInit_test = False args.randomLength = False DataGen(args, sys_model, fileName='Simulations/Lorenz_Atractor/data/lor_dataset.pt') # Load and inspect data = torch.load('Simulations/Lorenz_Atractor/data/lor_dataset.pt') train_input, train_target = data[0], data[1] # [1000, 3, 100] each print("Lorenz train input shape:", train_input.shape) # torch.Size([1000, 3, 100]) ``` -------------------------------- ### Generate and Save Datasets with DataGen Source: https://context7.com/kalmannet/kalmannet_tsp/llms.txt Generates training, cross-validation, and test datasets from a system model and saves them to a .pt file. Supports random initial conditions and sequence lengths. ```python import torch from Simulations.Linear_sysmdl import SystemModel from Simulations.utils import DataGen import Simulations.config as config args = config.general_settings() args.N_E, args.N_CV, args.N_T = 500, 50, 100 args.T, args.T_test = 100, 100 args.randomInit_train = True args.randomInit_cv = True args.randomInit_test = True args.distribution = 'normal' args.variance = 1.0 args.randomLength = False m, n = 2, 2 F = torch.eye(m); F[0] = torch.ones(1, m) sys_model = SystemModel(F, 0.01*torch.eye(m), torch.eye(n), 0.1*torch.eye(n), T=100, T_test=100) sys_model.InitSequence(torch.zeros(m, 1), torch.eye(m)) DataGen(args, sys_model, fileName='Simulations/Linear_canonical/data/rand_init.pt') # Reload and verify data = torch.load('Simulations/Linear_canonical/data/rand_init.pt') [train_in, train_tgt, cv_in, cv_tgt, test_in, test_tgt, train_init, cv_init, test_init] = data print("Train input:", train_in.shape) # [500, 2, 100] print("CV input:", cv_in.shape) # [50, 2, 100] print("Test input:", test_in.shape) # [100, 2, 100] print("Train init:", train_init.shape) # [500, 2, 1] — per-sequence initial states ``` -------------------------------- ### Run Non-linear Lorenz Attractor Simulations Source: https://github.com/kalmannet/kalmannet_tsp/blob/main/README.md Execute the Python scripts for non-linear simulations using the Lorenz Attractor. Options include discrete-time, decimation, and non-linear observation functions. ```python python3 main_lor_DT.py ``` ```python python3 main_lor_decimation.py ``` ```python python3 main_lor_DT_NLobs.py ``` -------------------------------- ### Pipeline_EKF for KalmanNet Training and Evaluation Source: https://context7.com/kalmannet/kalmannet_tsp/llms.txt Orchestrates the training and evaluation cycle for KalmanNet, including optimizer configuration, mini-batch training, model saving based on validation MSE, and final evaluation on the test set. This pipeline is suitable for end-to-end model development. ```python import torch from datetime import datetime from KNet.KalmanNet_nn import KalmanNetNN from Simulations.Linear_sysmdl import SystemModel from Pipelines.Pipeline_EKF import Pipeline_EKF import Simulations.config as config args = config.general_settings() args.use_cuda = False args.n_steps = 500 # training epochs args.n_batch = 20 args.lr = 1e-3 args.wd = 1e-4 args.CompositionLoss = False args.in_mult_KNet, args.out_mult_KNet = 5, 40 m, n = 2, 2 F = torch.eye(m); F[0] = torch.ones(1, m) H = torch.eye(n) sys_model = SystemModel(F, 0.01*torch.eye(m), H, 0.1*torch.eye(n), T=100, T_test=100) sys_model.InitSequence(torch.zeros(m,1), torch.zeros(m,m)) # Synthetic data (replace with DataGen output in practice) N_E, N_CV, N_T, T = 200, 50, 50, 100 train_input = torch.randn(N_E, n, T) train_target = torch.randn(N_E, m, T) cv_input = torch.randn(N_CV, n, T) cv_target = torch.randn(N_CV, m, T) test_input = torch.randn(N_T, n, T) test_target = torch.randn(N_T, m, T) knet = KalmanNetNN() knet.NNBuild(sys_model, args) strTime = datetime.now().strftime("%m.%d.%y_%H:%M:%S") pipeline = Pipeline_EKF(strTime, folderName="KNet", modelName="KNet_linear") pipeline.setssModel(sys_model) pipeline.setModel(knet) pipeline.setTrainingParams(args) # --- Train --- [MSE_cv_lin, MSE_cv_dB, MSE_tr_lin, MSE_tr_dB] = pipeline.NNTrain( sys_model, cv_input, cv_target, train_input, train_target, path_results='KNet/', MaskOnState=False, randomInit=False ) # Epoch 499: MSE Training: -8.21 [dB] MSE Validation: -7.85 [dB] # --- Test --- [MSE_test_arr, MSE_test_avg, MSE_test_dB, x_out, runtime] = pipeline.NNTest( sys_model, test_input, test_target, path_results='KNet/' ) # KNet_linear-MSE Test: -7.93 [dB] # KNet_linear-STD Test: 1.02 [dB] # Inference Time: 0.031 print("Test MSE [dB]:", MSE_test_dB) # scalar tensor print("x_out shape:", x_out.shape) # torch.Size([50, 2, 100]) ``` -------------------------------- ### Generate Single Trajectory with SystemModel Source: https://context7.com/kalmannet/kalmannet_tsp/llms.txt Generates a single state-observation trajectory of a specified length using stored system matrices and adding noise. Useful for visualization or single-instance testing. ```python import torch from Simulations.Linear_sysmdl import SystemModel m, n = 2, 2 F = torch.eye(m); F[0] = torch.ones(1, m) H = torch.eye(n) Q = 0.01 * torch.eye(m) R = 0.1 * torch.eye(n) sys_model = SystemModel(F, Q, H, R, T=50, T_test=50) sys_model.InitSequence(torch.zeros(m, 1), torch.zeros(m, m)) # Generate a single 50-step trajectory sys_model.GenerateSequence(Q_gen=Q, R_gen=R, T=50) states = sys_model.x # shape [m, T] = [2, 50] observations = sys_model.y # shape [n, T] = [2, 50] print("States shape:", states.shape) # torch.Size([2, 50]) print("Observations shape:", observations.shape) # torch.Size([2, 50]) print("First state:", states[:, 0]) # tensor([x1_0, x2_0]) ``` -------------------------------- ### Define and Generate Data for Linear System Model Source: https://context7.com/kalmannet/kalmannet_tsp/llms.txt Defines a 2D linear canonical state-space model and generates batched datasets for training and testing. Ensure noise levels and initial conditions are set appropriately. ```python import torch from Simulations.Linear_sysmdl import SystemModel from Simulations.utils import DataGen import Simulations.config as config # --- Define a 2D linear canonical model --- m, n = 2, 2 F = torch.eye(m) F[0] = torch.ones(1, m) # canonical form H = torch.eye(n) Q = 1e-2 * torch.eye(m) # small process noise R = 1e-1 * torch.eye(n) # larger observation noise sys_model = SystemModel(F, Q, H, R, T=100, T_test=100) sys_model.InitSequence( m1x_0=torch.zeros(m, 1), # initial state mean m2x_0=torch.zeros(m, m) # initial state covariance (deterministic start) ) # --- Generate datasets --- args = config.general_settings() args.N_E, args.N_CV, args.N_T = 1000, 100, 200 args.randomInit_train = args.randomInit_cv = args.randomInit_test = False args.randomLength = False DataGen(args, sys_model, fileName='Simulations/Linear_canonical/data/dataset.pt') # Load back [train_input, train_target, cv_input, cv_target, test_input, test_target, train_init, cv_init, test_init] = torch.load( 'Simulations/Linear_canonical/data/dataset.pt' ) # train_input shape: [N_E, n, T] — noisy observations # train_target shape: [N_E, m, T] — true hidden states print("Train input shape:", train_input.shape) # torch.Size([1000, 2, 100]) print("Train target shape:", train_target.shape) # torch.Size([1000, 2, 100]) ``` -------------------------------- ### Kalman Filter Evaluation with KFTest Source: https://context7.com/kalmannet/kalmannet_tsp/llms.txt Evaluates the linear Kalman filter on a test set, computing various performance metrics including MSE, batch-average MSE in dB, standard deviation, and confidence-interval spread. Returns state estimates and runtime. ```python import torch from Simulations.Linear_sysmdl import SystemModel from Filters.KalmanFilter_test import KFTest import Simulations.config as config args = config.general_settings() args.use_cuda = False args.N_T = 200 args.T_test = 100 args.randomLength = False m, n = 2, 2 F = torch.eye(m); F[0] = torch.ones(1, m) H = torch.eye(n) Q = 0.01 * torch.eye(m) R = 0.1 * torch.eye(n) sys_model = SystemModel(F, Q, H, R, T=100, T_test=100) sys_model.InitSequence(torch.zeros(m, 1), torch.zeros(m, m)) test_input = torch.randn(args.N_T, n, args.T_test) test_target = torch.randn(args.N_T, m, args.T_test) [MSE_KF_linear_arr, MSE_KF_linear_avg, MSE_KF_dB_avg, KF_out] = KFTest( args, sys_model, test_input, test_target, allStates=True, randomInit=False ) # Output: # Kalman Filter - MSE LOSS: -12.3456 [dB] # Kalman Filter - STD: 0.8765 [dB] ``` -------------------------------- ### Decimate Data and Split Trajectories Source: https://context7.com/kalmannet/kalmannet_tsp/llms.txt Utilities for subsampling sequences by a ratio (DecimateData) and splitting long trajectories into fixed-length windows (Short_Traj_Split). ```python import torch from Simulations.utils import DecimateData, Short_Traj_Split # --- DecimateData: subsample a [N, m, T_long] tensor --- T_long = 1000 data = torch.randn(5, 3, T_long) # 5 sequences, 3 dims, 1000 steps delta_t_gen = 1e-5 # generation sampling time delta_t_mod = 0.02 # model sampling time ratio = delta_t_mod / delta_t_gen # = 2000 decimated = DecimateData(data, t_gen=delta_t_gen, t_mod=delta_t_mod, offset=0) print("Decimated shape:", decimated.shape) # roughly [5, 3, T_long // ratio] # --- Short_Traj_Split: chop long trajectories into fixed-length windows --- T_sub = 20 long_target = torch.randn(10, 3, 500) # 10 long sequences of length 500 long_input = torch.randn(10, 3, 500) [target_split, input_split, init_split] = Short_Traj_Split(long_target, long_input, T=T_sub) # Each window is T_sub steps; first step reserved as init condition expected_windows = 10 * (500 // (T_sub + 1)) print("Split target shape:", target_split.shape) # [N_windows, 3, 20] print("Init conditions shape:", init_split.shape) # [N_windows, 3] ``` -------------------------------- ### KalmanNetNN Forward Pass for Single Time-Step Inference Source: https://context7.com/kalmannet/kalmannet_tsp/llms.txt Processes one observation through the KalmanNet forward pass to predict the prior state, estimate the Kalman gain, and compute the updated posterior state. This function is intended to be called once per time step within a loop. ```python import torch from KNet.KalmanNet_nn import KalmanNetNN from Simulations.Linear_sysmdl import SystemModel import Simulations.config as config args = config.general_settings() args.use_cuda = False args.n_batch = 4 args.in_mult_KNet, args.out_mult_KNet = 5, 40 m, n = 2, 2 F = torch.eye(m); F[0] = torch.ones(1, m) H = torch.eye(n) sys_model = SystemModel(F, 0.01*torch.eye(m), H, 0.1*torch.eye(n), T=50, T_test=50) knet = KalmanNetNN() knet.NNBuild(sys_model, args) batch_size, T = 4, 50 observations = torch.randn(batch_size, n, T) # [B, n, T] x_out = torch.zeros(batch_size, m, T) # output buffer knet.batch_size = batch_size knet.init_hidden_KNet() knet.InitSequence(torch.zeros(batch_size, m, 1), T) knet.eval() with torch.no_grad(): for t in range(T): y_t = torch.unsqueeze(observations[:, :, t], 2) # [B, n, 1] x_t = knet(y_t) # [B, m, 1] x_out[:, :, t] = torch.squeeze(x_t, 2) print("Output trajectories shape:", x_out.shape) # torch.Size([4, 2, 50]) print("Final state estimate:", x_out[:, :, -1]) # last time-step posterior ``` -------------------------------- ### KalmanNetNN Hidden State Reset Source: https://context7.com/kalmannet/kalmannet_tsp/llms.txt Resets the GRU hidden states (h_Q, h_Sigma, h_S) for the KalmanNet. This must be called at the beginning of each training step and test pass to ensure proper state initialization. ```python import torch from KNet.KalmanNet_nn import KalmanNetNN from Simulations.Linear_sysmdl import SystemModel import Simulations.config as config args = config.general_settings() args.use_cuda = False args.n_batch = 8 args.in_mult_KNet, args.out_mult_KNet = 5, 40 m, n = 2, 2 sys_model = SystemModel( torch.eye(m), 0.01*torch.eye(m), torch.eye(n), 0.1*torch.eye(n), T=100, T_test=100 ) knet = KalmanNetNN() knet.NNBuild(sys_model, args) knet.batch_size = 8 knet.init_hidden_KNet() print("h_S shape:", knet.h_S.shape) # [1, 8, n^2] = [1, 8, 4] print("h_Sigma shape:", knet.h_Sigma.shape) # [1, 8, m^2] = [1, 8, 4] print("h_Q shape:", knet.h_Q.shape) # [1, 8, m^2] = [1, 8, 4] # Hidden states are initialised from prior covariance values (not zeros) print("h_S[0,0,:]:", knet.h_S[0, 0, :]) # flattened prior_S repeated for batch ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.