### Install TrajDL Toolkit Source: https://context7.com/spatial-temporal-data-mining/trajdl/llms.txt Installs the TrajDL Python package. Ensure PyTorch is installed separately, as per the official PyTorch installation guide, to support either CPU or GPU versions. ```bash # Install PyTorch first (CPU or GPU version) # See: https://pytorch.org/get-started/locally/ pip install trajdl ``` -------------------------------- ### T2VEC Model: Trajectory Embedding Setup (Python) Source: https://context7.com/spatial-temporal-data-mining/trajdl/llms.txt Sets up the T2VEC model for learning trajectory representations using a seq2seq model. This involves loading trajectory data, defining a grid system, and building a tokenizer aware of spatial proximity. ```python import os import numpy as np import torch import lightning as L import polars as pl from trajdl.datasets import Trajectory, TrajectoryDataset from trajdl.datasets.open_source import PortoDataset from trajdl.grid import SimpleGridSystem from trajdl.trajdl_cpp.grid import RectangleBoundary from trajdl.tokenizers import T2VECTokenizer from trajdl.datasets.modules.t2vec import T2VECDataModuleV2 from trajdl.algorithms.t2vec import T2VEC from trajdl.common.enum import TokenEnum # Load Porto taxi data porto_df = PortoDataset().load(return_as="pl").filter(pl.col("MISSING_DATA") == False) trajs = [Trajectory(p.to_numpy(), entity_id=str(i)) for i, p in enumerate(porto_df["POLYLINE"].head(1000))] # Setup grid and tokenizer boundary = RectangleBoundary(-8.69, 41.14, -8.55, 41.19) grid = SimpleGridSystem(boundary.to_web_mercator(), step_x=100, step_y=100) tokenizer = T2VECTokenizer.build(grid, boundary, trajs, max_vocab_size=40000, min_freq=100) ``` -------------------------------- ### Custom Data Module Creation in TrajDL Source: https://context7.com/spatial-temporal-data-mining/trajdl/llms.txt This Python code defines a custom data module by extending `BaseLocSeqDataModule` from the TrajDL library. It includes a custom collate function (`my_collate_fn`) for processing batches of trajectory data and a `MyDataModule` class that integrates this function. The example shows how to instantiate and use this custom data module for training. ```python from dataclasses import dataclass from typing import Dict, List, Optional import torch from torch.nn.utils.rnn import pad_sequence from trajdl.datasets import LocSeqDataset from trajdl.datasets.modules.abstract import BaseLocSeqDataModule from trajdl.tokenizers import LocSeqTokenizer from trajdl.common.samples import TULERSample # Define custom collate function def my_collate_fn(batch: LocSeqDataset, user_map: Dict[str, int], tokenizer: LocSeqTokenizer) -> TULERSample: seqs, lengths, labels = [], [], [] for i in range(len(batch)): seq = tokenizer.tokenize_loc_seq(batch.seq[i], return_as="pt") seqs.append(seq) lengths.append(seq.shape[0]) labels.append(user_map[batch.entity_id[i].as_py()]) return TULERSample( src=pad_sequence(seqs, batch_first=True, padding_value=tokenizer.pad), seq_len=lengths, labels=torch.LongTensor(labels) ) # Create custom data module @dataclass class MyDataModule(BaseLocSeqDataModule): user_map: Optional[Dict[str, int]] = None def __post_init__(self): super().__post_init__() if not isinstance(self.user_map, dict): raise ValueError("`user_map` must be a Dict[str, int]") def collate_function(self, batch: LocSeqDataset) -> TULERSample: return my_collate_fn(batch, self.user_map, self.tokenizer) # Usage data_module = MyDataModule( tokenizer=tokenizer, train_table=train_ds, val_table=val_ds, train_batch_size=32, val_batch_size=64, user_map=user_map, num_cpus=-1 ) data_module.setup("fit") train_loader = data_module.train_dataloader() batch = next(iter(train_loader)) print(f"Batch src shape: {batch.src.shape}") print(f"Batch labels: {batch.labels}") ``` -------------------------------- ### Run CTLE Sample Script Source: https://github.com/spatial-temporal-data-mining/trajdl/blob/main/scripts/benchmark/hier/README.md Executes the CTLE sample script using Python. This script is likely part of the trajectory analysis tools within the HIER project. ```bash python scripts/samples/ctle.py ``` -------------------------------- ### Build KNN Matrices and Prepare Datasets for T2VEC Source: https://context7.com/spatial-temporal-data-mining/trajdl/llms.txt This code snippet demonstrates the process of building K-Nearest Neighbors (KNN) matrices for spatial-aware loss calculation. It involves tokenizing locations, computing distances and nearest neighbors, initializing matrices for indices and distances, and saving the results. It also includes preparing training, validation, and testing datasets from trajectories and initializing a T2VEC data module. ```python k = 10 SPECIAL_TOKENS = TokenEnum.values() loc_list = [loc for loc in tokenizer.vocab.keys() if loc not in SPECIAL_TOKENS] idx_list = [tokenizer.loc2idx(loc) for loc in loc_list] dists, nearest = tokenizer.k_nearest_hot_loc(loc_list, k=k) V = np.zeros((len(tokenizer), k), dtype=np.int64) D = np.zeros_like(V, dtype=np.float32) D[idx_list, :] = dists for token in SPECIAL_TOKENS: idx = tokenizer.loc2idx(token) V[idx] = idx for line_idx, locs in zip(idx_list, nearest): V[line_idx] = [tokenizer.loc2idx(l) for l in locs] output_dir = "./t2vec_output" os.makedirs(output_dir, exist_ok=True) np.save(f"{output_dir}/knn_indices.npy", V) np.save(f"{output_dir}/knn_distances.npy", D) tokenizer.save_pretrained(f"{output_dir}/tokenizer.pkl") # Prepare datasets train_trajs = [t for t in trajs[:800] if 20 <= len(t) <= 100] val_trajs = [t for t in trajs[800:900] if 20 <= len(t) <= 100] test_trajs = [t for t in trajs[900:] if 60 <= len(t) <= 200] train_ds = TrajectoryDataset.init_from_trajectories(train_trajs) val_ds = TrajectoryDataset.init_from_trajectories(val_trajs) test_ds = TrajectoryDataset.init_from_trajectories(test_trajs) # Create data module (with online sample augmentation) data_module = T2VECDataModuleV2( tokenizer=tokenizer, train_table=train_ds, val_table=val_ds, test_table=test_ds, train_batch_size=4, val_batch_size=4, num_train_batches=10, num_val_batches=10, k=2 ) # Build T2VEC model model = T2VEC( embedding_dim=256, hidden_size=256, tokenizer=tokenizer, knn_indices_path=f"{output_dir}/knn_indices.npy", knn_distances_path=f"{output_dir}/knn_distances.npy", num_layers=1, bidirectional_encoder=False ) # Train trainer = L.Trainer(max_epochs=5, logger=False, enable_checkpointing=False) trainer.fit(model, data_module) ``` -------------------------------- ### Create Grid System and Locate Points with TrajDL Source: https://context7.com/spatial-temporal-data-mining/trajdl/llms.txt Demonstrates creating a simple grid system with specified cell dimensions and locating individual points or arrays of coordinates within this grid. It also shows how to convert GPS coordinates to Web Mercator coordinates. ```python from trajdl.grid import SimpleGridSystem from trajdl.trajdl_cpp.grid import RectangleBoundary import numpy as np # Create grid system with 1x1 cells boundary = RectangleBoundary(-8.69, 41.14, -8.55, 41.19) # Example boundary grid = SimpleGridSystem(boundary=boundary.to_web_mercator(), step_x=1.0, step_y=1.0) print(f"Total grids: {len(grid)}") # Example output: 100 print(f"X grids: {grid.num_x_grids}") # Example output: 10 print(f"Y grids: {grid.num_y_grids}") # Example output: 10 # Locate points to grid cells print(grid.locate(x=0.5, y=0.5)) # Example output: 0 print(grid.locate(x=1.5, y=1.5)) # Example output: 11 print(grid.locate(x=9.9, y=9.9)) # Example output: 99 # Batch locate (unsafe - doesn't check boundaries) coords = np.array([[0.5, 0.5], [5.5, 5.5], [9.9, 9.9]]) print(grid.locate_unsafe_np(coords)) # GPS to Web Mercator coordinate conversion from trajdl import trajdl_cpp mercator = trajdl_cpp.grid.convert_gps_to_webmercator(-8.61, 41.15) print(f"X: {mercator.x}, Y: {mercator.y}") ``` -------------------------------- ### Fit HIER Model with Gowalla Data Source: https://github.com/spatial-temporal-data-mining/trajdl/blob/main/scripts/benchmark/hier/README.md Fits the HIER model using the HIERDataModule and a specified configuration file for the Gowalla dataset. This command initiates the training process for the spatial-temporal model. ```bash python scripts/main.py fit --model HIER --data HIERDataModule --config scripts/configs/hier/gowalla_config.yaml ``` -------------------------------- ### Fit CTLE Model (Python) Source: https://github.com/spatial-temporal-data-mining/trajdl/blob/main/scripts/benchmark/ctle/README.md Fits the CTLE model using specified data and configuration. This command trains the model based on the provided parameters. It requires the TrajDL library, a data module (e.g., CTLEDataModule), and a configuration file (e.g., gowalla_config.yaml). ```bash python scripts/main.py fit --model CTLE --data CTLEDataModule --config scripts/configs/ctle/gowalla_config.yaml ``` -------------------------------- ### Create and Use Location Sequence (LocSeq) Source: https://context7.com/spatial-temporal-data-mining/trajdl/llms.txt Demonstrates the creation and usage of the `LocSeq` class, which represents a sequence of location IDs for an entity's movement. It supports initialization with location sequences, entity IDs, and timestamps, and allows access to properties like origin and destination. ```python from trajdl.datasets import LocSeq # Create a simple location sequence locseq = LocSeq(["A", "B", "C", "D"]) print(locseq) # LocSeq(size=4, loc_seq='A', 'B', 'C', 'D') # Create with entity ID and timestamps locseq = LocSeq( seq=["loc_001", "loc_002", "loc_003"], entity_id="user_123", ts_seq=[1609459200, 1609459260, 1609459320] # Unix timestamps ) # Access properties print(len(locseq)) # 3 print(locseq.entity_id) # 'user_123' print(locseq.o) # 'loc_001' (origin) print(locseq.d) # 'loc_003' (destination) # Iterate over locations for loc in locseq: print(loc) ``` -------------------------------- ### Load Open Source Trajectory Datasets (Gowalla, Porto) - Python Source: https://context7.com/spatial-temporal-data-mining/trajdl/llms.txt Loads popular trajectory datasets (Gowalla, Porto) with automatic caching. Supports loading as Polars, Pandas DataFrames, or PyArrow Tables. Allows custom dataset URLs and loading from local files. ```python from trajdl.datasets.open_source import GowallaDataset, PortoDataset # Load Gowalla check-in dataset gowalla = GowallaDataset() print(gowalla) # Dataset info: name, size, URL, SHA-256 # Load as Polars DataFrame (default) df_gowalla = gowalla.load(return_as="pl") print(df_gowalla.head()) # Columns: user_id, check_in_time, lat, lng, loc_id # Load as Pandas DataFrame df_pandas = gowalla.load(return_as="pd") # Load as PyArrow Table table = gowalla.load(return_as="pa") # Load Porto taxi trajectory dataset porto = PortoDataset() df_porto = porto.load(return_as="pl") print(df_porto.head()) # Columns: TRIP_ID, CALL_TYPE, TAXI_ID, TIMESTAMP, POLYLINE, etc. # Custom dataset URL (for network restrictions) import os os.environ["GOWALLA_URL"] = "https://your-mirror/loc-gowalla_totalCheckins.txt.gz" # Or programmatically gowalla.set_url("https://your-mirror/loc-gowalla_totalCheckins.txt.gz") # Load from local file gowalla.load(original_dataset_path="/local/path/to/dataset.txt.gz") ``` -------------------------------- ### GridSystem - Geographic Grid Management - Python Source: https://context7.com/spatial-temporal-data-mining/trajdl/llms.txt Divides geographic regions into grids for converting coordinates to discrete location IDs. Supports creating rectangular boundaries and checking if points fall within these boundaries. ```python import numpy as np from trajdl.grid import SimpleGridSystem from trajdl.trajdl_cpp.grid import RectangleBoundary # Create a rectangular boundary boundary = RectangleBoundary(min_x=0, min_y=0, max_x=10, max_y=10) print(boundary) # Check if points are within boundary print(boundary.in_boundary(5, 5)) # True print(boundary.in_boundary(15, 5)) # False # Batch check with numpy array coords = np.array([[1, 1], [5, 5], [15, 15]]) print(boundary.in_boundary_np(coords)) # [True, True, False] ``` -------------------------------- ### Manage Location Sequences with LocSeqDataset Source: https://context7.com/spatial-temporal-data-mining/trajdl/llms.txt Details the `LocSeqDataset` class for managing multiple `LocSeq` objects using Apache Arrow for efficient, zero-copy operations. It covers initialization from `LocSeq` lists, conversion to Polars DataFrames, saving/loading to Parquet, and iteration. ```python from trajdl.datasets import LocSeq, LocSeqDataset # Create from list of LocSeq objects seq1 = LocSeq(["A", "B", "C"], entity_id="user_1") seq2 = LocSeq(["C", "D", "E"], entity_id="user_2") seq3 = LocSeq(["A", "D"], entity_id="user_3") ds = LocSeqDataset.init_from_loc_seqs([seq1, seq2, seq3]) print(ds) # LocSeqDataset(3) print(len(ds)) # 3 # Convert to Polars DataFrame for data manipulation df = ds.to_polars() print(df.head()) # Access underlying Arrow columns print(ds.seq) # Arrow column of sequences print(ds.entity_id) # Arrow column of entity IDs # Indexing returns a view (zero-copy) subset = ds[0] # Returns LocSeqDataset with first sequence # Save and load from Parquet ds.save("/path/to/dataset.parquet") loaded_ds = LocSeqDataset.init_from_parquet("/path/to/dataset.parquet") # Iterate as sequences for locseq in ds.iter_as_seqs(): print(locseq) ``` -------------------------------- ### Create and Use GPS Trajectory (Trajectory) Source: https://context7.com/spatial-temporal-data-mining/trajdl/llms.txt Illustrates the creation and manipulation of the `Trajectory` class, designed for raw GPS data. It accepts sequences of longitude-latitude coordinates, either as lists or NumPy arrays, and can be associated with an entity ID. ```python import numpy as np from trajdl.datasets import Trajectory # Create from list of coordinates [longitude, latitude] traj = Trajectory([ [-8.608833, 41.147586], [-8.608707, 41.147685], [-8.608473, 41.14773], [-8.608284, 41.148054], [-8.607708, 41.148999], [-8.60742, 41.149719] ]) print(traj) # Trajectory(entity_id=None, length=6) # Create from numpy array coords = np.array([ [-8.608833, 41.147586], [-8.608707, 41.147685], [-8.608473, 41.14773] ], dtype=np.float64) traj = Trajectory(seq=coords, entity_id="taxi_001") print(len(traj)) # 3 print(traj.entity_id) # 'taxi_001' print(traj[0]) # array([-8.608833, 41.147586]) ``` -------------------------------- ### LocSeqTokenizer - Convert Location Sequences to Indices - Python Source: https://context7.com/spatial-temporal-data-mining/trajdl/llms.txt Converts location sequences into integer indices for embedding layers. Manages vocabulary and special tokens ([BOS], [EOS], [PAD], [UNK], [MASK]). Supports saving and loading tokenizers. ```python from trajdl.datasets import LocSeq from trajdl.tokenizers import LocSeqTokenizer # Build tokenizer from location sequences locseqs = [ LocSeq(["A", "B", "C", "D"]), LocSeq(["A", "D", "E"]), LocSeq(["B", "C", "F"]) ] tokenizer = LocSeqTokenizer.build(loc_seqs=locseqs) # Vocabulary size (includes special tokens) print(len(tokenizer)) # 11 (6 locations + 5 special tokens) # Special tokens print(tokenizer.bos) # [BOS] index print(tokenizer.eos) # [EOS] index print(tokenizer.pad) # [PAD] index print(tokenizer.unk) # [UNK] index print(tokenizer.mask) # [MASK] index # Location to index print(tokenizer.loc2idx("A")) # Returns index print(tokenizer.loc2idx("Z")) # Returns UNK index for unknown # Tokenize sequences seq = LocSeq(["A", "B", "C"]) # Return as list indices = tokenizer.tokenize_loc_seq(seq) # [idx_A, idx_B, idx_C] # Return as numpy array with BOS/EOS indices = tokenizer.tokenize_loc_seq(seq, add_bos=True, add_eos=True, return_as="np") # Return as PyTorch tensor indices = tokenizer.tokenize_loc_seq(seq, return_as="pt") # Save and load tokenizer tokenizer.save_pretrained("/path/to/tokenizer.pkl") loaded = LocSeqTokenizer.load_pretrained("/path/to/tokenizer.pkl") ``` -------------------------------- ### Manage GPS Trajectories with TrajectoryDataset Source: https://context7.com/spatial-temporal-data-mining/trajdl/llms.txt Explains the `TrajectoryDataset` class, which manages multiple `Trajectory` objects with Apache Arrow's zero-copy capabilities. It includes methods for initialization from `Trajectory` lists, viewing the schema, conversion to Polars DataFrames, and saving/loading to Parquet. ```python import numpy as np from trajdl.datasets import Trajectory, TrajectoryDataset # Create from list of Trajectory objects traj1 = Trajectory(seq=np.random.uniform(size=(10, 2)), entity_id="trip_1") traj2 = Trajectory(seq=np.random.uniform(size=(15, 2)), entity_id="trip_2") traj3 = Trajectory(seq=np.random.uniform(size=(5, 2)), entity_id="trip_3") ds = TrajectoryDataset.init_from_trajectories([traj1, traj2, traj3]) print(ds) # TrajectoryDataset(3) # View schema (Arrow types) print(ds.schema()) # seq: large_list[2]> # entity_id: large_string # Convert to Polars DataFrame df = ds.to_polars() # Save and load ds.save("/path/to/trajectories.parquet") loaded_ds = TrajectoryDataset.init_from_parquet("/path/to/trajectories.parquet") ``` -------------------------------- ### T2VECTokenizer - Convert Trajectories to Tokens - Python Source: https://context7.com/spatial-temporal-data-mining/trajdl/llms.txt Converts GPS trajectories to token sequences using a grid system, suitable for trajectory embedding models. Defines geographic boundaries, creates grid systems, and tokenizes trajectories. ```python from trajdl.datasets import Trajectory from trajdl.grid import SimpleGridSystem from trajdl.trajdl_cpp.grid import RectangleBoundary from trajdl.tokenizers import T2VECTokenizer # Define geographic boundary (Porto, Portugal) wgs_boundary = RectangleBoundary( min_x=-8.690261, # min longitude min_y=41.140092, # min latitude max_x=-8.549155, # max longitude max_y=41.185969 # max latitude ) # Create grid system in Web Mercator coordinates (100m x 100m cells) grid = SimpleGridSystem( boundary=wgs_boundary.to_web_mercator(), step_x=100.0, step_y=100.0 ) print(f"Grid cells: {len(grid)}, X: {grid.num_x_grids}, Y: {grid.num_y_grids}") # Sample trajectories trajs = [ Trajectory([[-8.61, 41.15], [-8.605, 41.155], [-8.60, 41.16]]), Trajectory([[-8.62, 41.14], [-8.615, 41.145]]) ] # Build tokenizer tokenizer = T2VECTokenizer.build( grid=grid, boundary=wgs_boundary, trajectories=trajs, max_vocab_size=10000, min_freq=1, with_kd_tree=True # Enable KD-tree for nearest hot cell lookup ) # Tokenize trajectory traj = Trajectory([[-8.61, 41.15], [-8.605, 41.155], [-8.60, 41.16]]) tokens = tokenizer.tokenize_traj(traj) print(tokens) # List of grid cell indices # Get k-nearest hot locations (for spatial-aware loss) locs = list(tokenizer.vocab.keys())[:10] distances, nearest_locs = tokenizer.k_nearest_hot_loc(locs, k=5) ``` -------------------------------- ### TULER Model: User Identification from Trajectories (Python) Source: https://context7.com/spatial-temporal-data-mining/trajdl/llms.txt Implements the TULER model for identifying users from movement trajectories using RNN-based sequence classification. It involves data loading, preprocessing, tokenization, model building, training with PyTorch Lightning, and inference. ```python import torch import lightning as L import polars as pl import numpy as np from trajdl.datasets import LocSeq, LocSeqDataset from trajdl.datasets.open_source import GowallaDataset from trajdl.tokenizers import LocSeqTokenizer from trajdl.datasets.modules.tuler import TULERDataModule from trajdl.algorithms.tuler import TULER from trajdl.common.samples import TULERSample # Load and preprocess Gowalla dataset df = GowallaDataset().load(return_as="pl") df = ( df.filter(pl.col("user_id").cast(pl.Int64) < 100) .with_columns(pl.col("check_in_time").dt.strftime("%Y%m%d").alias("ds")) .group_by("user_id", "ds") .agg(pl.col("loc_id").sort_by(pl.col("check_in_time")).alias("loc_seq")) .filter(pl.col("loc_seq").list.len() >= 5) .select(pl.col("user_id").alias("id"), "loc_seq") ) # Create user mapping user_map = {uid: idx for idx, uid in enumerate(df["id"].unique())} # Split data df = df.with_columns(pl.lit(np.random.uniform(size=df.height)).alias("r")) train_df = df.filter(pl.col("r") <= 0.8).select("id", "loc_seq") val_df = df.filter(pl.col("r") > 0.8).select("id", "loc_seq") # Convert to LocSeq objects train_locseqs = [LocSeq(seq=seq, entity_id=uid) for uid, seq in train_df.iter_rows()] val_locseqs = [LocSeq(seq=seq, entity_id=uid) for uid, seq in val_df.iter_rows()] # Build tokenizer and datasets tokenizer = LocSeqTokenizer.build(loc_seqs=train_locseqs) train_ds = LocSeqDataset.init_from_loc_seqs(train_locseqs) val_ds = LocSeqDataset.init_from_loc_seqs(val_locseqs) # Create data module data_module = TULERDataModule( tokenizer=tokenizer, train_table=train_ds, val_table=val_ds, train_batch_size=32, val_batch_size=256, user_map=user_map, num_cpus=-1 ) # Build TULER model model = TULER( tokenizer=tokenizer, num_users=len(user_map), embedding_dim=32, hidden_dim=32, rnn_type="lstm", # or "gru" bidirectional=True, dropout=0.5, learning_rate=1e-3, topk=5 ) # Train with Lightning trainer = L.Trainer(max_epochs=10, logger=False, enable_checkpointing=False) trainer.fit(model, data_module) # Inference test_seq = val_locseqs[0] src = tokenizer.tokenize_loc_seq(test_seq, return_as="pt").unsqueeze(0) sample = TULERSample(src=src, seq_len=[src.shape[1]]) with torch.inference_mode(): logits = model.eval()(sample) pred_idx = torch.argmax(logits, dim=-1).item() user_map_inv = {v: k for k, v in user_map.items()} print(f"Predicted: {user_map_inv[pred_idx]}, Actual: {test_seq.entity_id}") ``` -------------------------------- ### Configure Trajdl C++ Module with Pybind11 (CMake) Source: https://github.com/spatial-temporal-data-mining/trajdl/blob/main/CMakeLists.txt This CMake script configures the Trajdl C++ module for Python integration using Pybind11. It specifies the minimum CMake version, project name, C++ standard, finds the Pybind11 package, and compiles the C++ source files into a Python module named 'trajdl_cpp'. ```cmake cmake_minimum_required(VERSION 3.15...3.26) project(${SKBUILD_PROJECT_NAME} LANGUAGES CXX) set(PYBIND11_FINDPYTHON ON) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) execute_process( COMMAND python3 -c "import pybind11; print(pybind11.get_cmake_dir())" OUTPUT_VARIABLE PYBIND11_CMAKE_DIR OUTPUT_STRIP_TRAILING_WHITESPACE ) list(APPEND CMAKE_PREFIX_PATH "${PYBIND11_CMAKE_DIR}") find_package(pybind11 CONFIG REQUIRED) file(GLOB_RECURSE SRC_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/trajdl_cpp/src/*.cpp") pybind11_add_module(trajdl_cpp MODULE ${SRC_FILES} src/trajdl_cpp/pybind11_module.cpp ) target_include_directories(trajdl_cpp PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/trajdl_cpp/include) install(TARGETS trajdl_cpp DESTINATION ${SKBUILD_PROJECT_NAME}) ``` -------------------------------- ### Inference and Similarity Computation with T2VEC Source: https://context7.com/spatial-temporal-data-mining/trajdl/llms.txt This code snippet demonstrates how to perform inference using a trained T2VEC model to obtain trajectory embeddings. It then utilizes scikit-learn's `euclidean_distances` to compute the similarity matrix between these embeddings. The output includes the shapes of the embedding tensor and the resulting similarity matrix. ```python # Inference - get trajectory embeddings data_module.setup("test") test_loader = data_module.test_dataloader() batch = next(iter(test_loader)) model.eval() with torch.inference_mode(): embeddings = model(batch) # (batch_size, hidden_size) print(f"Embedding shape: {embeddings.shape}") # Compute trajectory similarity from sklearn.metrics.pairwise import euclidean_distances emb_np = embeddings.cpu().numpy() similarity_matrix = euclidean_distances(emb_np, emb_np) print(f"Similarity matrix shape: {similarity_matrix.shape}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.