### Execute Experimental Pipeline in Python Source: https://context7.com/yuvenduan/probwm/llms.txt The run function automates the experimental workflow, including data loading, embedding extraction, parameter optimization via L-BFGS-B, and result visualization. It outputs performance metrics and diagnostic plots. ```python from bayesian import run import os os.makedirs('figures', exist_ok=True) init_params = {'sigma': 0.02, 'change_prior': 0.5} cnn_config = { 'cnn_archi': 'ResNet-50', 'cnn_pret': 'Classification_ImageNet', 'pca_dim': 16, 'cnn_layer': 'last', 'model_name': 'ResNet-50_last_16_Class' } optimized_params = run( exp_name='RedBlue', init_params=init_params, cnn_config=cnn_config, optimize=True ) print(f"Optimized params: {optimized_params}") ``` -------------------------------- ### Load Experimental Data with get_experiment Source: https://context7.com/yuvenduan/probwm/llms.txt The `get_experiment` function loads experimental datasets, returning a `ChangeDetection` instance. This instance provides trial data, behavioral responses, and methods for image generation. It supports various experiment types like 'RedBlue', 'BlackWhite', and 'ColoredSquares'. ```python from displays import get_experiment # Available experiments: # - 'RedBlue': 5x5 grid of red/blue circles (E1/1A_Data_RedBlue) # - 'BlackWhite': 5x5 grid of black/white patches (E1/1B_Data_BlackWhite) # - 'ColoredSquares': 4x5 grid of colored squares (E2/2A_Data, E2/2B_Data_Patterns) # - 'ColoredSquares_SetSize': Synthetic colored squares for set-size analysis exp = get_experiment('RedBlue') print(f"Number of trials: {len(exp)}") # Output: Number of trials: 48 # Access trial data trial = exp.get_trial(0) features = trial['features'] # Tuple of (sample_features, test_features) displays = trial['displays'] # Tuple of (sample_display, test_display) as Tensors changed = trial['changed'] # Boolean indicating if change occurred # Access behavioral data behavior = exp.behaviors[0] # Human response probability for this trial # Generate display image from features display_tensor = exp.feature_to_display(features[0]) # Shape: (3, H, W) # Generate all possible changed versions of a display changed_displays = exp.feature_to_changed_displays(features[1]) # Shape: (N, 3, H, W) ``` -------------------------------- ### Generate Visual Displays from Features (Python) Source: https://context7.com/yuvenduan/probwm/llms.txt Demonstrates the use of ChangeDetection classes to convert feature arrays into visual display tensors. It shows how to load pre-defined experiments or generate synthetic data, and extract trial information including features and displays. Dependencies include the 'displays' module and 'torch'. ```python from displays import RedBlueCircles, BlackWhitePatches, ColoredSquares import torch # RedBlueCircles: 5x5 grid of red/blue circles red_blue = RedBlueCircles(load_path='E1/1A_Data_RedBlue') trial = red_blue.get_trial(0) print(f"Feature shape: {trial['features'][0].shape}") # (5, 5) print(f"Display shape: {trial['displays'][0].shape}") # (3, 224, 224) # BlackWhitePatches: 5x5 grid of black/white patches bw_patches = BlackWhitePatches(load_path='E1/1B_Data_BlackWhite') trial = bw_patches.get_trial(0) print(f"Display shape: {trial['displays'][0].shape}") # (3, 150, 150) # ColoredSquares: 4x5 grid with 8 possible colors colored = ColoredSquares(load_paths=['E2/2A_Data', 'E2/2B_Data_Patterns']) trial = colored.get_trial(0) changed_displays = colored.feature_to_changed_displays(trial['features'][1]) print(f"Changed displays shape: {changed_displays.shape}") # (N, 3, 100, 100) # Synthetic ColoredSquares for set-size experiments synthetic = ColoredSquares(load_paths=None) # Generates random trials print(f"Synthetic trials: {len(synthetic)}") # 2400 trials (400 per set size) ``` -------------------------------- ### Visualize Behavioral Data in Python Source: https://context7.com/yuvenduan/probwm/llms.txt The plots module provides functions to compare model predictions against human behavioral data, typically used for scatter plots and performance correlation analysis. ```python import plots import numpy as np import os os.makedirs('figures/analysis', exist_ok=True) # Simulated data behaviors = np.random.uniform(0.3, 0.9, 48).tolist() predictions = [b + np.random.normal(0, 0.1) for b in behaviors] predictions = np.clip(predictions, 0, 1).tolist() ``` -------------------------------- ### Analyze Set Size Effects in Python Source: https://context7.com/yuvenduan/probwm/llms.txt The check_set_size_effect function evaluates model accuracy across different display set sizes (1-12 items). It generates performance curves and saves visual analysis of hit/false alarm rates. ```python from bayesian import check_set_size_effect import os os.makedirs('figures', exist_ok=True) params = {'sigma': 0.05, 'change_prior': 0.5} cnn_config = { 'cnn_archi': 'ResNet-18', 'cnn_pret': 'Classification_ImageNet', 'pca_dim': 16, 'cnn_layer': 'last', 'model_name': 'ResNet-18_last_16' } accuracies = check_set_size_effect(params, cnn_config) print(f"Accuracy by set size [1,2,3,4,8,12]: {[f'{a:.3f}' for a in accuracies]}") ``` -------------------------------- ### Plot Behavior vs. Prediction with Correlation Metrics (Python) Source: https://context7.com/yuvenduan/probwm/llms.txt Generates plots comparing behavioral data against model predictions, including d' metrics. This function takes behavior and prediction data as input and saves generated plots to a specified path. It returns a tuple containing behavior d' and prediction d'. ```python import plots d_prime = plots.compare_behavior_vs_prediction( behavior=behaviors, prediction=predictions, save_path='figures/analysis', plot_dprime=True ) # Generates: beh_vs_pred.png, beh_vs_pred_dprime.png # Returns: d_prime tuple (behavior_dprime, prediction_dprime) ``` -------------------------------- ### Plot Accuracy vs. Set Size (Python) Source: https://context7.com/yuvenduan/probwm/llms.txt Compares accuracy across different set sizes for multiple experimental conditions. This function takes a list of set sizes, a list of accuracy lists (one per condition), and optional labels and y-axis limits. It generates a plot saved to the specified path. ```python import plots set_sizes = [1, 2, 3, 4, 8, 12] accs_condition1 = [0.98, 0.95, 0.90, 0.85, 0.72, 0.62] accs_condition2 = [0.95, 0.88, 0.82, 0.75, 0.60, 0.52] plots.compare_acc_vs_set_size( set_sizes=set_sizes, accs=[accs_condition1, accs_condition2], y_label='Accuracy', ylim=[0.5, 1.0], save_path='figures/analysis', labels=['sigma=0.02', 'sigma=0.05'] ) # Generates: Accuracy_vs_set_size.png ``` -------------------------------- ### Create Gaussian Likelihood Distribution in Python Source: https://context7.com/yuvenduan/probwm/llms.txt The get_likelihood function generates a multivariate Gaussian distribution centered on an embedding vector. It is primarily used to model memory noise in Bayesian change detection tasks. ```python from bayesian import get_likelihood import numpy as np embedding = np.random.randn(16) embedding /= np.linalg.norm(embedding) # Normalize params = { 'sigma': 0.05, # Memory noise parameter 'change_prior': 0.5 # Prior probability of change } # Create likelihood distribution p(memory | embedding) likelihood = get_likelihood(embedding, params) # Sample from the distribution or compute PDF sample = likelihood.rvs(size=100) # Shape: (100, 16) pdf_value = likelihood.pdf(embedding) # Probability density at the embedding print(f"PDF at embedding: {pdf_value:.6f}") ``` -------------------------------- ### Create Feature Extraction Model with get_cnn Source: https://context7.com/yuvenduan/probwm/llms.txt The `get_cnn` function initializes a CNN model for visual embedding extraction. It supports various architectures (ResNet, AlexNet, ViT-B), pretrained weights, intermediate layer selection, and optional PCA for dimensionality reduction. The output embeddings are suitable for downstream tasks. ```python from cnn import get_cnn import torch # Configuration options: # cnn_archi: 'ResNet-18', 'ResNet-50', 'AlexNet', 'ViT-B', 'Identity' # cnn_pret: 'Classification_ImageNet', 'none' # cnn_layer: 'last', 'layer1', 'layer2', 'layer3', 'layer4' (ResNet only) # pca_dim: int or None (None disables PCA) cnn_config = { 'cnn_archi': 'ResNet-50', 'cnn_pret': 'Classification_ImageNet', 'cnn_layer': 'last', 'pca_dim': 16, 'exp_names': ['RedBlue', 'BlackWhite', 'ColoredSquares'] # For PCA fitting } cnn = get_cnn(**cnn_config) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') cnn.to(device) # Extract embedding from a display image display = torch.rand(3, 224, 224) # Input shape: (3, H, W) or (B, 3, H, W) embedding = cnn(display.unsqueeze(0).to(device)) # Output shape: (1, pca_dim) or (1, feature_dim) print(f"Embedding shape: {embedding.shape}") # Output: Embedding shape: (1, 16) ``` -------------------------------- ### Compute Change Detection Predictions in Python Source: https://context7.com/yuvenduan/probwm/llms.txt The get_predictions function calculates the posterior probability that no change occurred between trials. It utilizes Monte Carlo sampling to approximate the posterior based on provided embeddings and model parameters. ```python from bayesian import get_predictions import numpy as np # Prepare embeddings list: each element is [sample_emb, test_emb, changed_embs] dim = 16 embeddings = [] for _ in range(10): # 10 trials sample_emb = np.random.randn(dim) sample_emb /= np.linalg.norm(sample_emb) test_emb = np.random.randn(dim) test_emb /= np.linalg.norm(test_emb) changed_embs = np.random.randn(25, dim) # 25 possible changes changed_embs /= np.linalg.norm(changed_embs, axis=1, keepdims=True) embeddings.append([sample_emb, test_emb, changed_embs]) params = {'sigma': 0.05, 'change_prior': 0.5} predictions = get_predictions(params, embeddings, sampling_points=1000) print(f"Predictions (p(no change)): {predictions[:5]}") ``` -------------------------------- ### Plot Behavior vs. Embedding Distance (Python) Source: https://context7.com/yuvenduan/probwm/llms.txt Visualizes the relationship between behavioral data and embedding distances. This function requires behavior data (typically for changed trials) and a list of distances. It saves the resulting plot to a specified directory. ```python import plots import numpy as np distances = np.random.uniform(0.5, 2.0, 24).tolist() plots.compare_behavior_vs_distance( behavior=behaviors[1::2], # Changed trials only distance=distances, save_path='figures/analysis' ) # Generates: beh_vs_dist.png ``` -------------------------------- ### Normalize CNN Output with get_embedding Source: https://context7.com/yuvenduan/probwm/llms.txt The `get_embedding` function takes a CNN model and display images as input, processes them through the CNN, and returns L2-normalized embeddings. These normalized embeddings are crucial for calculating distances and likelihoods within the Bayesian framework. ```python from bayesian import get_embedding from cnn import get_cnn import torch import numpy as np device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') cnn = get_cnn(cnn_archi='ResNet-18', cnn_pret='Classification_ImageNet', pca_dim=16) cnn.to(device) # Single image input display = torch.rand(3, 224, 224) embedding = get_embedding(cnn, display) print(f"Single embedding shape: {embedding.shape}") # Shape: (16,) print(f"L2 norm: {np.linalg.norm(embedding):.4f}") # Output: ~1.0 (normalized) # Batch input batch_displays = torch.rand(5, 3, 224, 224) batch_embeddings = get_embedding(cnn, batch_displays) print(f"Batch embedding shape: {batch_embeddings.shape}") # Shape: (5, 16) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.