🔧 Utils API Reference
Welcome to the KerasFactory Utilities documentation! All utilities are designed to work exclusively with Keras 3 and provide powerful tools for data analysis, generation, visualization, and development support.
What You'll Find Here
Each utility includes detailed documentation with: - ✨ Complete parameter descriptions with types and defaults - 🎯 Usage examples showing real-world applications - ⚡ Best practices and performance considerations - 🎨 When to use guidance for each utility - 🔧 Implementation notes for developers
Comprehensive Toolkit
The KerasFactory utilities provide intelligent data analysis, synthetic data generation, and professional visualization capabilities.
Developer-Friendly
All utilities are designed for easy integration into your data science workflows and Jupyter notebooks.
🔍 Data Analysis
🧠 DataAnalyzer
Intelligent data analyzer that examines CSV files and recommends appropriate KerasFactory layers based on data characteristics.
kerasfactory.utils.data_analyzer.DataAnalyzer
1 | |
Analyzes tabular data and recommends appropriate KerasFactory layers.
This class provides methods to analyze CSV files, extract statistics, and recommend layers from KerasFactory based on data characteristics.
Attributes:
| Name | Type | Description |
|---|---|---|
registrations |
dict[str, list[tuple[str, str, str]]]
|
Dictionary mapping data characteristics to recommended layer classes. |
Initialize the data analyzer with layer registrations.
Source code in kerasfactory/utils/data_analyzer.py
25 26 27 28 29 30 31 | |
Functions
register_recommendation
1 2 3 4 5 6 | |
Register a new layer recommendation for a specific data characteristic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
characteristic |
str
|
The data characteristic identifier (e.g., 'continuous_features') |
required |
layer_name |
str
|
The name of the layer class |
required |
description |
str
|
Brief description of the layer |
required |
use_case |
str
|
When to use this layer |
required |
Source code in kerasfactory/utils/data_analyzer.py
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 | |
analyze_csv
1 | |
Analyze a single CSV file and return statistics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath |
str
|
Path to the CSV file |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary containing dataset statistics and characteristics |
Source code in kerasfactory/utils/data_analyzer.py
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 | |
analyze_directory
1 2 3 | |
Analyze all CSV files in a directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory_path |
str
|
Path to the directory containing CSV files |
required |
pattern |
str
|
Glob pattern to match files (default: "*.csv") |
'*.csv'
|
Returns:
| Type | Description |
|---|---|
dict[str, dict[str, Any]]
|
Dictionary mapping filenames to their analysis results |
Source code in kerasfactory/utils/data_analyzer.py
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 | |
recommend_layers
1 2 3 | |
Recommend layers based on data statistics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stats |
dict[str, Any]
|
Dictionary of dataset statistics from analyze_csv |
required |
Returns:
| Type | Description |
|---|---|
dict[str, list[tuple[str, str, str]]]
|
Dictionary mapping characteristics to recommended layers |
Source code in kerasfactory/utils/data_analyzer.py
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 | |
analyze_and_recommend
1 2 3 | |
Analyze data and provide layer recommendations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source |
str
|
Path to file or directory to analyze |
required |
pattern |
str
|
File pattern if source is a directory |
'*.csv'
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with analysis results and recommendations |
Source code in kerasfactory/utils/data_analyzer.py
782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 | |
💻 DataAnalyzerCLI
Command-line interface for the data analyzer, allowing easy analysis of datasets from the terminal.
kerasfactory.utils.data_analyzer_cli
Command-line interface for the Keras Model Registry Data Analyzer.
This script provides a convenient way to analyze CSV data and get layer recommendations from the command line.
Classes
Functions
parse_args
1 | |
Parse command line arguments.
Returns:
| Type | Description |
|---|---|
Namespace
|
Parsed arguments namespace |
Source code in kerasfactory/utils/data_analyzer_cli.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | |
setup_logging
1 | |
Configure logging based on verbosity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
verbose |
bool
|
Whether to enable verbose logging |
required |
Source code in kerasfactory/utils/data_analyzer_cli.py
58 59 60 61 62 63 64 65 66 67 | |
format_result
1 2 3 | |
Format the result based on user preferences.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result |
dict[str, Any]
|
The analysis result |
required |
recommendations_only |
bool
|
Whether to include only recommendations |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Formatted result dictionary |
Source code in kerasfactory/utils/data_analyzer_cli.py
70 71 72 73 74 75 76 77 78 79 80 81 82 | |
main
1 | |
Main entry point for the script.
Source code in kerasfactory/utils/data_analyzer_cli.py
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | |
📊 Data Generation
🎲 KerasFactoryDataGenerator
Utility class for generating synthetic datasets for KerasFactory model testing, demonstrations, and experimentation.
Features: - Tabular Data: Regression, classification, anomaly detection, multi-input data - Time Series: Basic, multivariate, seasonal, multi-scale, anomalous, long-horizon, energy demand - Dataset Creation: Easy conversion to TensorFlow datasets with batching and shuffling
kerasfactory.utils.data_generator.KerasFactoryDataGenerator
Utility class for generating synthetic datasets for KerasFactory model testing.
Functions
generate_regression_data
staticmethod
1 2 3 4 5 6 7 8 | |
Generate synthetic regression data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_samples |
int
|
Number of samples |
1000
|
n_features |
int
|
Number of features |
10
|
noise_level |
float
|
Level of noise to add |
0.1
|
random_state |
int
|
Random seed |
42
|
include_interactions |
bool
|
Whether to include feature interactions |
True
|
include_nonlinear |
bool
|
Whether to include nonlinear relationships |
True
|
Returns:
| Type | Description |
|---|---|
tuple
|
Tuple of (X_train, X_test, y_train, y_test) |
Source code in kerasfactory/utils/data_generator.py
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | |
generate_classification_data
staticmethod
1 2 3 4 5 6 7 8 9 10 11 | |
Generate synthetic classification data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_samples |
int
|
Number of samples |
1000
|
n_features |
int
|
Number of features |
10
|
n_classes |
int
|
Number of classes |
2
|
noise_level |
float
|
Level of noise to add |
0.1
|
include_interactions |
bool
|
Whether to include feature interactions |
True
|
include_nonlinear |
bool
|
Whether to include nonlinear relationships |
True
|
random_state |
int
|
Random seed |
42
|
sparse_features |
bool
|
Whether to create sparse features |
True
|
sparse_ratio |
float
|
Ratio of features that are relevant |
0.3
|
Returns:
| Type | Description |
|---|---|
tuple
|
Tuple of (X_train, X_test, y_train, y_test) |
Source code in kerasfactory/utils/data_generator.py
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 | |
generate_anomaly_detection_data
staticmethod
1 2 3 4 5 6 7 | |
Generate synthetic anomaly detection data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_normal |
int
|
Number of normal samples |
1000
|
n_anomalies |
int
|
Number of anomaly samples |
50
|
n_features |
int
|
Number of features |
50
|
random_state |
int
|
Random seed |
42
|
anomaly_type |
str
|
Type of anomalies ("outlier", "cluster", "drift") |
'outlier'
|
Returns:
| Type | Description |
|---|---|
tuple
|
Tuple of (X_train, X_test, y_train, y_test) |
Source code in kerasfactory/utils/data_generator.py
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 | |
generate_context_data
staticmethod
1 2 3 4 5 6 7 | |
Generate synthetic data with context information.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_samples |
int
|
Number of samples |
1500
|
n_features |
int
|
Number of main features |
15
|
n_context |
int
|
Number of context features |
8
|
random_state |
int
|
Random seed |
42
|
context_effect |
float
|
Strength of context effect |
0.3
|
Returns:
| Type | Description |
|---|---|
tuple
|
Tuple containing (X_train, X_test, context_train, context_test, y_train, y_test) |
Source code in kerasfactory/utils/data_generator.py
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 | |
generate_multi_input_data
staticmethod
1 2 3 4 5 6 | |
Generate multi-input data for preprocessing model testing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_samples |
int
|
Number of samples |
1000
|
feature_shapes |
dict[str, tuple[int, ...]]
|
Dictionary mapping feature names to shapes |
None
|
random_state |
int
|
Random seed |
42
|
task_type |
str
|
Type of task - "regression" or "classification" |
'regression'
|
Returns:
| Type | Description |
|---|---|
tuple
|
Tuple containing (X_train_dict, X_test_dict, y_train, y_test) |
Source code in kerasfactory/utils/data_generator.py
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 | |
create_preprocessing_model
staticmethod
1 2 3 4 5 | |
Create a preprocessing model for multi-input data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_shapes |
dict[str, tuple[int, ...]]
|
Dictionary mapping input names to shapes |
required |
output_dim |
int
|
Output dimension |
32
|
name |
str
|
Model name |
'preprocessing_model'
|
Returns:
| Type | Description |
|---|---|
Model
|
Keras preprocessing model |
Source code in kerasfactory/utils/data_generator.py
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 | |
create_dataset
staticmethod
1 2 3 4 5 6 | |
Create a TensorFlow dataset from data (requires TensorFlow).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X |
Union[ndarray, dict[str, ndarray]]
|
Input data (array or dict of arrays) |
required |
y |
ndarray
|
Target data |
required |
batch_size |
int
|
Batch size |
32
|
shuffle |
bool
|
Whether to shuffle data |
True
|
Returns:
| Type | Description |
|---|---|
Dataset
|
TensorFlow dataset (if TensorFlow is available) |
Raises:
| Type | Description |
|---|---|
ImportError
|
If TensorFlow is not installed |
Source code in kerasfactory/utils/data_generator.py
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 | |
generate_timeseries_data
staticmethod
1 2 3 4 5 6 7 8 9 10 11 12 | |
Generate synthetic multivariate time series data for forecasting.
This method generates realistic time series data with optional trend and seasonality patterns, suitable for testing time series models like TSMixer and TimeMixer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_samples |
int
|
Number of time series samples to generate. |
1000
|
seq_len |
int
|
Length of input sequence (lookback window). |
96
|
pred_len |
int
|
Length of prediction horizon (forecast window). |
12
|
n_features |
int
|
Number of time series features (channels). |
7
|
random_state |
int
|
Random seed for reproducibility. |
42
|
include_trend |
bool
|
Whether to include trend component. |
True
|
include_seasonality |
bool
|
Whether to include seasonal component. |
True
|
trend_direction |
str
|
Direction of trend ('up', 'down', 'random'). |
'up'
|
noise_level |
float
|
Standard deviation of Gaussian noise. |
0.1
|
scale |
float
|
Scaling factor for the generated data. |
1.0
|
Returns:
| Type | Description |
|---|---|
tuple
|
Tuple of (X, y) where: |
tuple
|
|
tuple
|
|
Example
X, y = KerasFactoryDataGenerator.generate_timeseries_data( ... n_samples=100, ... seq_len=96, ... pred_len=12, ... n_features=7 ... ) X.shape (100, 96, 7) y.shape (100, 12, 7)
Source code in kerasfactory/utils/data_generator.py
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 | |
generate_multivariate_timeseries
staticmethod
1 2 3 4 5 6 7 8 | |
Generate correlated multivariate time series data.
Creates time series where features have dependencies on each other, simulating real-world scenarios where different variables influence one another.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_samples |
int
|
Number of samples. |
1000
|
seq_len |
int
|
Input sequence length. |
96
|
pred_len |
int
|
Prediction horizon. |
12
|
n_features |
int
|
Number of features. |
7
|
correlation_strength |
float
|
Strength of inter-feature correlations (0-1). |
0.5
|
random_state |
int
|
Random seed. |
42
|
Returns:
| Type | Description |
|---|---|
tuple
|
Tuple of (X, y) where X has shape (n_samples, seq_len, n_features) |
tuple
|
and y has shape (n_samples, pred_len, n_features). |
Source code in kerasfactory/utils/data_generator.py
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 | |
generate_seasonal_timeseries
staticmethod
1 2 3 4 5 6 7 8 | |
Generate strongly seasonal time series data.
Ideal for testing decomposition-based models like TimeMixer that explicitly handle trend and seasonal components.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_samples |
int
|
Number of samples. |
1000
|
seq_len |
int
|
Input sequence length. |
96
|
pred_len |
int
|
Prediction horizon. |
12
|
n_features |
int
|
Number of features. |
7
|
seasonal_period |
int
|
Period of seasonality. |
12
|
random_state |
int
|
Random seed. |
42
|
Returns:
| Type | Description |
|---|---|
tuple
|
Tuple of (X, y). |
Source code in kerasfactory/utils/data_generator.py
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 | |
generate_anomalous_timeseries
staticmethod
1 2 3 4 5 6 7 8 9 | |
Generate time series with anomalies for anomaly detection testing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_samples |
int
|
Number of samples. |
1000
|
seq_len |
int
|
Input sequence length. |
96
|
pred_len |
int
|
Prediction horizon. |
12
|
n_features |
int
|
Number of features. |
7
|
anomaly_ratio |
float
|
Ratio of anomalous samples (0-1). |
0.1
|
anomaly_magnitude |
float
|
Magnitude of anomalies in std deviations. |
3.0
|
random_state |
int
|
Random seed. |
42
|
Returns:
| Type | Description |
|---|---|
tuple
|
Tuple of (X, y, anomaly_labels) where anomaly_labels indicates |
tuple
|
which samples contain anomalies. |
Source code in kerasfactory/utils/data_generator.py
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 | |
generate_multiscale_timeseries
staticmethod
1 2 3 4 5 6 7 8 | |
Generate multi-scale time series with components at different frequencies.
Useful for testing models that use multi-scale mixing like TimeMixer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_samples |
int
|
Number of samples. |
1000
|
seq_len |
int
|
Input sequence length. |
96
|
pred_len |
int
|
Prediction horizon. |
12
|
n_features |
int
|
Number of features. |
7
|
scales |
list[int] | None
|
List of frequency scales (default: [7, 14, 28, 56]). |
None
|
random_state |
int
|
Random seed. |
42
|
Returns:
| Type | Description |
|---|---|
tuple
|
Tuple of (X, y). |
Source code in kerasfactory/utils/data_generator.py
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 | |
generate_long_horizon_timeseries
staticmethod
1 2 3 4 5 6 7 | |
Generate long-horizon time series for testing long-term forecasting.
Useful for benchmarking models on challenging long-range forecasting tasks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_samples |
int
|
Number of samples. |
500
|
seq_len |
int
|
Input sequence length (typically 336 = 2 weeks of hourly data). |
336
|
pred_len |
int
|
Prediction horizon (typically 336 for long-horizon). |
336
|
n_features |
int
|
Number of features. |
7
|
random_state |
int
|
Random seed. |
42
|
Returns:
| Type | Description |
|---|---|
tuple
|
Tuple of (X, y). |
Source code in kerasfactory/utils/data_generator.py
819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 | |
generate_synthetic_energy_demand
staticmethod
1 2 3 4 5 6 7 | |
Generate synthetic energy demand time series.
Simulates realistic energy consumption patterns with daily and weekly seasonality, useful for testing on realistic forecasting scenarios.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_samples |
int
|
Number of samples. |
1000
|
seq_len |
int
|
Input sequence length (default: 168 = 1 week). |
168
|
pred_len |
int
|
Prediction horizon (default: 24 = 1 day). |
24
|
n_features |
int
|
Number of features (e.g., residential, commercial, industrial). |
3
|
random_state |
int
|
Random seed. |
42
|
Returns:
| Type | Description |
|---|---|
tuple
|
Tuple of (X, y). |
Source code in kerasfactory/utils/data_generator.py
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 | |
create_timeseries_dataset
staticmethod
1 2 3 4 5 6 | |
Create a TensorFlow dataset from time series data (requires TensorFlow).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X |
ndarray
|
Input sequences of shape (n_samples, seq_len, n_features). |
required |
y |
ndarray
|
Target sequences of shape (n_samples, pred_len, n_features). |
required |
batch_size |
int
|
Batch size. |
32
|
shuffle |
bool
|
Whether to shuffle data. |
True
|
Returns:
| Type | Description |
|---|---|
Dataset
|
TensorFlow dataset with (X, y) pairs. |
Raises:
| Type | Description |
|---|---|
ImportError
|
If TensorFlow is not installed |
Example
X, y = KerasFactoryDataGenerator.generate_timeseries_data() dataset = KerasFactoryDataGenerator.create_timeseries_dataset(X, y) for x_batch, y_batch in dataset.take(1): ... print(x_batch.shape, y_batch.shape)
Source code in kerasfactory/utils/data_generator.py
945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 | |
Time Series Methods
generate_timeseries_data()
Generates synthetic multivariate time series with optional trend and seasonality.
1 2 3 4 5 6 7 8 9 10 11 | |
generate_multivariate_timeseries()
Generates time series with inter-feature correlations for realistic multivariate data.
1 2 3 4 5 6 7 | |
generate_seasonal_timeseries()
Emphasized seasonal patterns, ideal for decomposition models like TimeMixer.
1 2 3 4 5 6 7 | |
generate_multiscale_timeseries()
Components at different frequencies for testing multi-scale mixing models.
1 2 3 4 5 6 7 | |
generate_anomalous_timeseries()
Time series with injected anomalies for testing anomaly detection models.
1 2 3 4 5 6 7 8 | |
generate_long_horizon_timeseries()
For benchmarking long-term forecasting (e.g., 2 weeks ahead).
1 2 3 4 5 6 | |
generate_synthetic_energy_demand()
Realistic energy consumption patterns with daily/weekly seasonality.
1 2 3 4 5 6 | |
create_timeseries_dataset()
Converts numpy arrays to TensorFlow datasets with batching and auto-tuning.
1 2 3 4 5 6 7 8 | |
🎨 Visualization
📈 KerasFactoryPlotter
Utility class for creating consistent and professional visualizations for KerasFactory models, metrics, and data analysis.
Features: - Time Series Visualization: Multiple visualization styles for forecasts - Training History: Training and validation metrics - Classification Metrics: ROC, precision-recall, confusion matrix - Anomaly Detection: Anomaly score distributions - Performance Metrics: Bar charts and comparison visualizations
kerasfactory.utils.plotting.KerasFactoryPlotter
Utility class for creating consistent visualizations across KerasFactory notebooks.
Functions
plot_training_history
staticmethod
1 2 3 4 5 6 | |
Create training history plots.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
history |
Any
|
Keras training history object or dict with history data |
required |
metrics |
list[str]
|
List of metrics to plot (default: ['loss', 'accuracy']) |
None
|
title |
str
|
Plot title |
'Training Progress'
|
height |
int
|
Plot height |
400
|
Returns:
| Type | Description |
|---|---|
Figure
|
Plotly figure |
Source code in kerasfactory/utils/plotting.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | |
plot_confusion_matrix
staticmethod
1 2 3 4 5 6 | |
Create confusion matrix heatmap.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true |
ndarray
|
True labels |
required |
y_pred |
ndarray
|
Predicted labels |
required |
title |
str
|
Plot title |
'Confusion Matrix'
|
height |
int
|
Plot height |
400
|
Returns:
| Type | Description |
|---|---|
Figure
|
Plotly figure |
Source code in kerasfactory/utils/plotting.py
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | |
plot_predictions_vs_actual
staticmethod
1 2 3 4 5 6 | |
Create predictions vs actual values scatter plot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true |
ndarray
|
True values |
required |
y_pred |
ndarray
|
Predicted values |
required |
title |
str
|
Plot title |
'Predictions vs Actual Values'
|
height |
int
|
Plot height |
500
|
Returns:
| Type | Description |
|---|---|
Figure
|
Plotly figure |
Source code in kerasfactory/utils/plotting.py
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 | |
plot_anomaly_scores
staticmethod
1 2 3 4 5 6 7 | |
Create anomaly score distribution plot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scores |
ndarray
|
Anomaly scores |
required |
labels |
ndarray
|
True labels (0=normal, 1=anomaly) |
required |
threshold |
float
|
Anomaly threshold |
None
|
title |
str
|
Plot title |
'Anomaly Score Distribution'
|
height |
int
|
Plot height |
400
|
Returns:
| Type | Description |
|---|---|
Figure
|
Plotly figure |
Source code in kerasfactory/utils/plotting.py
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 | |
plot_performance_metrics
staticmethod
1 2 3 4 5 | |
Create performance metrics bar chart.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metrics_dict |
dict[str, float]
|
Dictionary of metric names and values |
required |
title |
str
|
Plot title |
'Performance Metrics'
|
height |
int
|
Plot height |
400
|
Returns:
| Type | Description |
|---|---|
Figure
|
Plotly figure |
Source code in kerasfactory/utils/plotting.py
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 | |
plot_precision_recall_curve
staticmethod
1 2 3 4 5 6 | |
Create precision-recall curve.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true |
ndarray
|
True labels |
required |
y_scores |
ndarray
|
Prediction scores |
required |
title |
str
|
Plot title |
'Precision-Recall Curve'
|
height |
int
|
Plot height |
400
|
Returns:
| Type | Description |
|---|---|
Figure
|
Plotly figure |
Source code in kerasfactory/utils/plotting.py
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 | |
plot_roc_curve
staticmethod
1 2 3 4 5 6 | |
Create ROC (Receiver Operating Characteristic) curve.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true |
ndarray
|
True labels (binary: 0 or 1) |
required |
y_scores |
ndarray
|
Prediction scores or probabilities |
required |
title |
str
|
Plot title |
'ROC Curve'
|
height |
int
|
Plot height |
400
|
Returns:
| Type | Description |
|---|---|
Figure
|
Plotly figure |
Source code in kerasfactory/utils/plotting.py
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 | |
plot_context_dependency
staticmethod
1 2 3 4 5 6 | |
Create context dependency plot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context_values |
ndarray
|
Context values or bin labels |
required |
accuracies |
list[float]
|
Accuracies for each context bin |
required |
title |
str
|
Plot title |
'Model Performance by Context'
|
height |
int
|
Plot height |
400
|
Returns:
| Type | Description |
|---|---|
Figure
|
Plotly figure |
Source code in kerasfactory/utils/plotting.py
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 | |
create_comprehensive_plot
staticmethod
1 2 3 | |
Create comprehensive plots with multiple subplots.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
plot_type |
str
|
Type of comprehensive plot ('anomaly_detection', 'classification', 'regression') |
required |
**kwargs |
Additional arguments for the specific plot type |
{}
|
Returns:
| Type | Description |
|---|---|
Figure
|
Plotly figure |
Source code in kerasfactory/utils/plotting.py
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 | |
plot_timeseries
staticmethod
1 2 3 4 5 6 7 8 9 | |
Plot time series data with optional predictions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X |
ndarray
|
Input sequences of shape (n_samples, seq_len, n_features). |
required |
y_true |
ndarray
|
True target sequences of shape (n_samples, pred_len, n_features). |
None
|
y_pred |
ndarray
|
Predicted sequences of shape (n_samples, pred_len, n_features). |
None
|
n_samples_to_plot |
int
|
Number of samples to visualize. |
5
|
feature_idx |
int
|
Which feature to plot. |
0
|
title |
str
|
Plot title. |
'Time Series Forecast'
|
height |
int
|
Plot height. |
500
|
Returns:
| Type | Description |
|---|---|
Figure
|
Plotly figure. |
Source code in kerasfactory/utils/plotting.py
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 | |
plot_timeseries_comparison
staticmethod
1 2 3 4 5 6 7 | |
Plot single time series forecast comparison.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true |
ndarray
|
True sequences of shape (n_samples, pred_len, n_features) or (pred_len, n_features). |
required |
y_pred |
ndarray
|
Predicted sequences of shape (n_samples, pred_len, n_features) or (pred_len, n_features). |
required |
sample_idx |
int
|
Index of sample to plot (if 3D arrays). |
0
|
title |
str
|
Plot title. |
'Forecast Comparison'
|
height |
int
|
Plot height. |
400
|
Returns:
| Type | Description |
|---|---|
Figure
|
Plotly figure. |
Source code in kerasfactory/utils/plotting.py
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 | |
plot_decomposition
staticmethod
1 2 3 4 5 6 7 8 | |
Plot time series decomposition into components.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
original |
ndarray
|
Original time series. |
required |
trend |
ndarray
|
Trend component. |
None
|
seasonal |
ndarray
|
Seasonal component. |
None
|
residual |
ndarray
|
Residual component. |
None
|
title |
str
|
Plot title. |
'Time Series Decomposition'
|
height |
int
|
Plot height. |
600
|
Returns:
| Type | Description |
|---|---|
Figure
|
Plotly figure. |
Source code in kerasfactory/utils/plotting.py
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 | |
plot_forecasting_metrics
staticmethod
1 2 3 4 5 6 | |
Calculate and plot forecasting error metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true |
ndarray
|
True values. |
required |
y_pred |
ndarray
|
Predicted values. |
required |
title |
str
|
Plot title. |
'Forecasting Metrics'
|
height |
int
|
Plot height. |
400
|
Returns:
| Type | Description |
|---|---|
Figure
|
Plotly figure with metrics. |
Source code in kerasfactory/utils/plotting.py
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 | |
plot_forecast_horizon_analysis
staticmethod
1 2 3 4 5 6 | |
Analyze forecast error across different forecast horizons.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true |
ndarray
|
True sequences of shape (n_samples, pred_len) or (n_samples, pred_len, n_features). |
required |
y_pred |
ndarray
|
Predicted sequences of same shape. |
required |
title |
str
|
Plot title. |
'Forecast Error by Horizon'
|
height |
int
|
Plot height. |
400
|
Returns:
| Type | Description |
|---|---|
Figure
|
Plotly figure. |
Source code in kerasfactory/utils/plotting.py
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 | |
plot_multiple_features_forecast
staticmethod
1 2 3 4 5 6 7 8 9 | |
Plot forecasts for multiple features side-by-side.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X |
ndarray
|
Input sequences. |
required |
y_true |
ndarray
|
True target sequences. |
required |
y_pred |
ndarray
|
Predicted sequences. |
required |
sample_idx |
int
|
Which sample to plot. |
0
|
n_features_to_plot |
int
|
Number of features to plot (default: all). |
None
|
title |
str
|
Plot title. |
'Multi-Feature Forecast'
|
height |
int
|
Plot height. |
500
|
Returns:
| Type | Description |
|---|---|
Figure
|
Plotly figure. |
Source code in kerasfactory/utils/plotting.py
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 | |
Time Series Plotting Methods
plot_timeseries()
Plot time series with input, true target, and predictions for multiple samples.
1 2 3 4 5 6 7 8 9 10 11 | |
Use When: Visualizing multiple forecast examples side-by-side to understand model behavior.
plot_timeseries_comparison()
Compare single forecast with true values.
1 2 3 4 5 6 7 | |
Use When: Detailed analysis of a single sample forecast.
plot_decomposition()
Visualize time series decomposition into components (trend, seasonal, residual).
1 2 3 4 5 6 7 8 | |
Use When: Understanding component contributions in time series models.
plot_forecasting_metrics()
Calculate and display MAE, RMSE, and MAPE metrics.
1 2 3 4 5 6 | |
Use When: Quick performance overview of forecasting model.
plot_forecast_horizon_analysis()
Analyze forecast error across different forecast horizons (how far ahead).
1 2 3 4 5 6 | |
Use When: Understanding if model degrades for longer forecasts.
plot_multiple_features_forecast()
Plot forecasts for multiple features side-by-side.
1 2 3 4 5 6 7 8 9 | |
Use When: Comparing forecast quality across multiple time series channels.
Training & Metrics Methods
plot_training_history()
Visualize training and validation metrics over epochs.
1 2 3 4 5 6 | |
plot_confusion_matrix()
Heatmap of classification confusion matrix.
1 2 3 4 5 6 | |
plot_roc_curve()
ROC curve with AUC score.
1 2 3 4 5 6 | |
plot_precision_recall_curve()
Precision-recall curve visualization.
1 2 3 4 5 6 | |
plot_anomaly_scores()
Distribution of anomaly scores with threshold visualization.
1 2 3 4 5 6 7 | |
plot_performance_metrics()
Bar chart of performance metrics.
1 2 3 4 5 6 7 8 9 | |
🛠️ Decorators
✨ Decorators
Utility decorators for common functionality in KerasFactory components and enhanced development experience.
kerasfactory.utils.decorators
Functions
log_init
1 | |
Class decorator to log initialization arguments.
Source code in kerasfactory/utils/decorators.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | |
log_method
1 | |
Method decorator to log method calls with their arguments.
Source code in kerasfactory/utils/decorators.py
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | |
log_property
1 | |
Property decorator to log property access.
Source code in kerasfactory/utils/decorators.py
118 119 120 121 122 123 124 125 126 127 | |
add_serialization
1 | |
Decorator to add serialization methods to a Keras model class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls |
T
|
The class to decorate. |
required |
Returns:
| Type | Description |
|---|---|
T
|
The decorated class. |
Source code in kerasfactory/utils/decorators.py
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 | |
📚 Complete Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | |
🎯 Best Practices
- Always use
KerasFactoryDataGeneratorfor synthetic data in notebooks - Leverage
KerasFactoryPlotterfor consistent visualizations across projects - Create TensorFlow datasets with
create_timeseries_dataset()for efficient training - Use semantic data generation methods (e.g.,
generate_seasonal_timeseries()) that match your use case - Chain visualizations to tell a complete story about model performance
📦 Testing
All utilities are thoroughly tested. Run tests with:
1 | |
Test coverage includes:
- ✓ Time series generation with various configurations
- ✓ Data distribution validation
- ✓ Plotting function robustness with edge cases
- ✓ Different data shapes and dimensions
- ✓ Error handling and validation