grnexus 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/README.md ADDED
@@ -0,0 +1,1105 @@
1
+ # GRNexus
2
+
3
+ [![Gem Version](https://badge.fury.io/rb/grnexus.svg)](https://badge.fury.io/rb/grnexus)
4
+ [![License](https://img.shields.io/badge/license-GPL--3.0-green.svg)](LICENSE)
5
+ [![Ruby](https://img.shields.io/badge/ruby-3.0+-red.svg)](https://www.ruby-lang.org)
6
+
7
+ **High-Performance Cross-Language Neural Network Framework for Ruby**
8
+
9
+ GRNexus is a revolutionary neural network library that combines Ruby's elegance with native C acceleration. Train models in Ruby and deploy them anywhere - even in Python. With 10-100x performance improvements over pure Ruby implementations, GRNexus brings enterprise-grade machine learning to the Ruby ecosystem.
10
+
11
+ ---
12
+
13
+ ## Table of Contents
14
+
15
+ - [Key Features](#key-features)
16
+ - [Installation](#installation)
17
+ - [Quick Start](#quick-start)
18
+ - [Deep Learning](#deep-learning)
19
+ - [Classical Machine Learning](#classical-machine-learning)
20
+ - [Text Processing & NLP](#text-processing--nlp)
21
+ - [Numeric Processing](#numeric-processing)
22
+ - [Advanced Features](#advanced-features)
23
+ - [API Reference](#api-reference)
24
+ - [Documentation](#documentation)
25
+ - [License](#license)
26
+
27
+ ---
28
+
29
+ ## Key Features
30
+
31
+ ### Performance & Architecture
32
+ - **Native C Acceleration**: 10-100x faster than pure Ruby implementations via FFI
33
+ - **Cross-Language Compatibility**: Train in Ruby, deploy in Python (and vice versa)
34
+ - **Zero Heavy Dependencies**: No TensorFlow or PyTorch required
35
+ - **Cross-Platform**: Windows, macOS, and Linux support
36
+
37
+ ### Deep Learning Capabilities
38
+ - **35+ Activation Functions**: GELU, Swish, Mish, Snake, and more
39
+ - **12+ Layer Types**: Dense, Conv2D, LSTM, GRU, BatchNorm, Dropout, Embedding
40
+ - **Smart Training**: EarlyStopping, ModelCheckpoint, ReduceLR, LearningRateScheduler
41
+ - **Model Inspection**: Analyze saved models without loading them
42
+
43
+ ### Classical Machine Learning
44
+ - **K-Nearest Neighbors (KNN)**: Fast classification with native C implementation
45
+ - **K-Means Clustering**: Efficient unsupervised learning
46
+ - **Linear Regression**: Optimized least squares regression
47
+ - **Logistic Regression**: Binary and multiclass classification
48
+ - **Naive Bayes**: Probabilistic classification
49
+
50
+ ### Natural Language Processing
51
+ - **Vocabulary Management**: Tokenization with frequency filtering
52
+ - **Text Vectorization**: TF-IDF and count vectorization
53
+ - **Word Embeddings**: Xavier-initialized embeddings for NLP
54
+ - **Document Similarity**: Cosine similarity and text analysis
55
+
56
+ ### Numeric Operations
57
+ - **Statistical Functions**: Mean, std, variance, correlation
58
+ - **Normalization**: Z-score, MinMax, L1, L2
59
+ - **Time Series**: Moving average, differences, integration
60
+ - **Array Operations**: 40+ operations for data manipulation
61
+
62
+ ---
63
+
64
+ ## Installation
65
+
66
+ Add this line to your application's Gemfile:
67
+
68
+ ```ruby
69
+ gem 'grnexus'
70
+ ```
71
+
72
+
73
+ And then execute:
74
+
75
+ ```bash
76
+ bundle install
77
+ ```
78
+
79
+ Or install it yourself as:
80
+
81
+ ```bash
82
+ gem install grnexus
83
+ ```
84
+
85
+ ---
86
+
87
+ ## Quick Start
88
+
89
+ ### XOR Problem - Neural Network Basics
90
+
91
+ ```ruby
92
+ require 'grnexus'
93
+
94
+ # XOR dataset
95
+ x_train = [[0, 0], [0, 1], [1, 0], [1, 1]]
96
+ y_train = [[0], [1], [1], [0]]
97
+
98
+ # Build neural network
99
+ model = GRNexus::NeuralNetwork.new(loss: 'mse', learning_rate: 0.5)
100
+ model.add(GRNEXUSLayer::DenseLayer.new(
101
+ units: 4,
102
+ input_dim: 2,
103
+ activation: GRNEXUSActivations::Tanh.new
104
+ ))
105
+ model.add(GRNEXUSLayer::DenseLayer.new(
106
+ units: 1,
107
+ input_dim: 4,
108
+ activation: GRNEXUSActivations::Sigmoid.new
109
+ ))
110
+
111
+ # Train the model
112
+ model.train(x_train, y_train, epochs: 1000, batch_size: 4)
113
+
114
+ # Make predictions
115
+ puts model.predict([[0, 0]]) # => ~0.0
116
+ puts model.predict([[1, 1]]) # => ~0.0
117
+ puts model.predict([[0, 1]]) # => ~1.0
118
+ puts model.predict([[1, 0]]) # => ~1.0
119
+
120
+ # Save model (compatible with Python!)
121
+ model.save('xor_model.nexus')
122
+ ```
123
+
124
+ ---
125
+
126
+ ## Deep Learning
127
+
128
+ ### Modern Deep Network with State-of-the-Art Activations
129
+
130
+ ```ruby
131
+ require 'grnexus'
132
+
133
+ # Create advanced deep network
134
+ model = GRNexus::NeuralNetwork.new(
135
+ loss: 'cross_entropy',
136
+ optimizer: 'adam',
137
+ learning_rate: 0.001,
138
+ name: 'deep_classifier'
139
+ )
140
+
141
+ # Layer 1: GELU activation (used in GPT, BERT)
142
+ model.add(GRNEXUSLayer::DenseLayer.new(
143
+ units: 128,
144
+ input_dim: 50,
145
+ activation: GRNEXUSActivations::GELU.new
146
+ ))
147
+ model.add(GRNEXUSLayer::BatchNormLayer.new)
148
+
149
+ # Layer 2: Swish activation (Google's discovery)
150
+ model.add(GRNEXUSLayer::DenseLayer.new(
151
+ units: 96,
152
+ input_dim: 128,
153
+ activation: GRNEXUSActivations::Swish.new
154
+ ))
155
+ model.add(GRNEXUSLayer::DropoutLayer.new(rate: 0.3))
156
+
157
+ # Layer 3: Mish activation (state-of-the-art)
158
+ model.add(GRNEXUSLayer::DenseLayer.new(
159
+ units: 64,
160
+ input_dim: 96,
161
+ activation: GRNEXUSActivations::Mish.new
162
+ ))
163
+ model.add(GRNEXUSLayer::BatchNormLayer.new)
164
+
165
+ # Output layer
166
+ model.add(GRNEXUSLayer::DenseLayer.new(
167
+ units: 10,
168
+ input_dim: 64,
169
+ activation: GRNEXUSNormalization::Softmax.new
170
+ ))
171
+
172
+ # View architecture
173
+ model.summary
174
+
175
+ # Train with intelligent callbacks
176
+ early_stop = GRNEXUSCallbacks::EarlyStopping.new(
177
+ patience: 10,
178
+ monitor: 'val_loss'
179
+ )
180
+
181
+ checkpoint = GRNEXUSCallbacks::ModelCheckpoint.new(
182
+ filepath: 'best_model.nexus',
183
+ monitor: 'val_accuracy',
184
+ save_best_only: true
185
+ )
186
+
187
+ reduce_lr = GRNEXUSCallbacks::ReduceLROnPlateau.new(
188
+ monitor: 'val_loss',
189
+ factor: 0.5,
190
+ patience: 5
191
+ )
192
+
193
+ history = model.train(
194
+ x_train, y_train,
195
+ epochs: 100,
196
+ batch_size: 32,
197
+ validation_data: [x_val, y_val],
198
+ callbacks: [early_stop, checkpoint, reduce_lr],
199
+ verbose: true
200
+ )
201
+
202
+ # Evaluate
203
+ results = model.evaluate(x_test, y_test)
204
+ puts "Test Accuracy: #{results[:accuracy]}%"
205
+ ```
206
+
207
+ ### Convolutional Neural Network for Image Classification
208
+
209
+ ```ruby
210
+ require 'grnexus'
211
+
212
+ # Build CNN for image classification
213
+ model = GRNexus::NeuralNetwork.new(
214
+ loss: 'cross_entropy',
215
+ optimizer: 'adam',
216
+ learning_rate: 0.001,
217
+ name: 'image_classifier'
218
+ )
219
+
220
+ # Convolutional layers
221
+ model.add(GRNEXUSLayer::Conv2DLayer.new(
222
+ filters: 32,
223
+ kernel_size: 3,
224
+ input_shape: [28, 28, 1],
225
+ activation: GRNEXUSActivations::ReLU.new,
226
+ padding: 'same'
227
+ ))
228
+ model.add(GRNEXUSLayer::MaxPoolingLayer.new(pool_size: 2, stride: 2))
229
+
230
+ model.add(GRNEXUSLayer::Conv2DLayer.new(
231
+ filters: 64,
232
+ kernel_size: 3,
233
+ activation: GRNEXUSActivations::ReLU.new,
234
+ padding: 'same'
235
+ ))
236
+ model.add(GRNEXUSLayer::MaxPoolingLayer.new(pool_size: 2, stride: 2))
237
+
238
+ # Dense layers
239
+ model.add(GRNEXUSLayer::FlattenLayer.new)
240
+ model.add(GRNEXUSLayer::DenseLayer.new(
241
+ units: 128,
242
+ activation: GRNEXUSActivations::ReLU.new
243
+ ))
244
+ model.add(GRNEXUSLayer::DropoutLayer.new(rate: 0.5))
245
+ model.add(GRNEXUSLayer::DenseLayer.new(
246
+ units: 10,
247
+ activation: GRNEXUSNormalization::Softmax.new
248
+ ))
249
+
250
+ # Train
251
+ model.train(images, labels, epochs: 50, batch_size: 64)
252
+ model.save('cnn_classifier.nexus')
253
+ ```
254
+
255
+ ### LSTM for Sequence Processing
256
+
257
+ ```ruby
258
+ require 'grnexus'
259
+
260
+ # Build LSTM network
261
+ model = GRNexus::NeuralNetwork.new(
262
+ loss: 'cross_entropy',
263
+ optimizer: 'adam',
264
+ learning_rate: 0.001
265
+ )
266
+
267
+ # LSTM layers
268
+ model.add(GRNEXUSLayer::LSTMLayer.new(
269
+ units: 128,
270
+ return_sequences: true
271
+ ))
272
+ model.add(GRNEXUSLayer::DropoutLayer.new(rate: 0.3))
273
+
274
+ model.add(GRNEXUSLayer::LSTMLayer.new(
275
+ units: 64,
276
+ return_sequences: false
277
+ ))
278
+
279
+ # Output
280
+ model.add(GRNEXUSLayer::DenseLayer.new(
281
+ units: 10,
282
+ activation: GRNEXUSNormalization::Softmax.new
283
+ ))
284
+
285
+ model.train(sequences, labels, epochs: 50, batch_size: 32)
286
+ ```
287
+
288
+ ---
289
+
290
+ ## Classical Machine Learning
291
+
292
+ ### K-Nearest Neighbors Classification
293
+
294
+ ```ruby
295
+ require 'grnexus'
296
+
297
+ # Prepare data
298
+ x_train = [
299
+ [1.0, 2.0], [1.5, 1.8], [5.0, 8.0],
300
+ [8.0, 8.0], [1.0, 0.6], [9.0, 11.0]
301
+ ]
302
+ y_train = [0, 0, 1, 1, 0, 1]
303
+
304
+ # Create and train KNN classifier
305
+ knn = GRNEXUSMachineLearning::KNeighborsClassifier.new(n_neighbors: 3)
306
+ knn.fit(x_train, y_train)
307
+
308
+ # Make predictions
309
+ x_test = [[2.0, 3.0], [7.0, 9.0]]
310
+ predictions = knn.predict(x_test)
311
+ puts "Predictions: #{predictions}" # => [0, 1]
312
+
313
+ # Save model
314
+ knn.save('knn_model.lnexus')
315
+
316
+ # Load model
317
+ loaded_knn = GRNEXUSMachineLearning::KNeighborsClassifier.load('knn_model.lnexus')
318
+ ```
319
+
320
+ ### K-Means Clustering
321
+
322
+ ```ruby
323
+ require 'grnexus'
324
+
325
+ # Prepare data
326
+ data = [
327
+ [1.0, 2.0], [1.5, 1.8], [5.0, 8.0],
328
+ [8.0, 8.0], [1.0, 0.6], [9.0, 11.0],
329
+ [8.0, 2.0], [10.0, 2.0], [9.0, 3.0]
330
+ ]
331
+
332
+ # Create and fit K-Means
333
+ kmeans = GRNEXUSMachineLearning::KMeans.new(n_clusters: 3, max_iter: 300)
334
+ kmeans.fit(data)
335
+
336
+ # Get cluster assignments
337
+ puts "Labels: #{kmeans.labels}"
338
+ puts "Centroids: #{kmeans.centroids}"
339
+
340
+ # Predict new data
341
+ new_data = [[2.0, 2.0], [8.0, 9.0]]
342
+ clusters = kmeans.predict(new_data)
343
+ puts "Cluster assignments: #{clusters}"
344
+
345
+ # Save model
346
+ kmeans.save('kmeans_model.lnexus')
347
+ ```
348
+
349
+ ### Linear Regression
350
+
351
+ ```ruby
352
+ require 'grnexus'
353
+
354
+ # Prepare data
355
+ x_train = [[1.0], [2.0], [3.0], [4.0], [5.0]]
356
+ y_train = [[2.0], [4.0], [6.0], [8.0], [10.0]]
357
+
358
+ # Create and train linear regression
359
+ lr = GRNEXUSMachineLearning::LinearRegression.new
360
+ lr.fit(x_train, y_train)
361
+
362
+ # Make predictions
363
+ x_test = [[6.0], [7.0], [8.0]]
364
+ predictions = lr.predict(x_test)
365
+ puts "Predictions: #{predictions}"
366
+
367
+ # View learned weights
368
+ puts "Weights: #{lr.weights}"
369
+
370
+ # Save model
371
+ lr.save('linear_regression.lnexus')
372
+ ```
373
+
374
+ ### Logistic Regression
375
+
376
+ ```ruby
377
+ require 'grnexus'
378
+
379
+ # Binary classification data
380
+ x_train = [
381
+ [1.0, 2.0], [2.0, 3.0], [3.0, 4.0],
382
+ [6.0, 7.0], [7.0, 8.0], [8.0, 9.0]
383
+ ]
384
+ y_train = [[0.0], [0.0], [0.0], [1.0], [1.0], [1.0]]
385
+
386
+ # Create and train logistic regression
387
+ log_reg = GRNEXUSMachineLearning::LogisticRegression.new(
388
+ learning_rate: 0.1,
389
+ max_iter: 1000
390
+ )
391
+ log_reg.fit(x_train, y_train)
392
+
393
+ # Make predictions
394
+ x_test = [[2.5, 3.5], [7.5, 8.5]]
395
+ predictions = log_reg.predict(x_test)
396
+ puts "Predictions: #{predictions}" # => [0.0, 1.0]
397
+
398
+ # Save model
399
+ log_reg.save('logistic_regression.lnexus')
400
+ ```
401
+
402
+ ### Naive Bayes Classifier
403
+
404
+ ```ruby
405
+ require 'grnexus'
406
+
407
+ # Prepare data
408
+ x_train = [
409
+ [1.0, 2.0], [1.5, 1.8], [5.0, 8.0],
410
+ [8.0, 8.0], [1.0, 0.6], [9.0, 11.0]
411
+ ]
412
+ y_train = [0, 0, 1, 1, 0, 1]
413
+
414
+ # Create and train Naive Bayes
415
+ nb = GRNEXUSMachineLearning::NaiveBayes.new(n_classes: 2)
416
+ nb.fit(x_train, y_train)
417
+
418
+ # Make predictions
419
+ x_test = [[2.0, 3.0], [7.0, 9.0]]
420
+ predictions = nb.predict(x_test)
421
+ puts "Predictions: #{predictions}"
422
+
423
+ # Save model
424
+ nb.save('naive_bayes.lnexus')
425
+ ```
426
+
427
+ ---
428
+
429
+ ## Text Processing & NLP
430
+
431
+ ### Sentiment Analysis with TF-IDF
432
+
433
+ ```ruby
434
+ require 'grnexus'
435
+
436
+ # Training data
437
+ texts = [
438
+ "I love this product it's excellent",
439
+ "terrible product very bad quality",
440
+ "amazing quality exceeded expectations",
441
+ "worst purchase ever disappointed",
442
+ "highly recommend great value",
443
+ "waste of money poor quality"
444
+ ]
445
+ labels = [[1, 0], [0, 1], [1, 0], [0, 1], [1, 0], [0, 1]]
446
+
447
+ # Create vocabulary and vectorize
448
+ vocab = GRNexusTextProcessing::Vocabulary.new(
449
+ texts,
450
+ max_vocab_size: 100,
451
+ min_frequency: 1
452
+ )
453
+
454
+ vectorizer = GRNexusTextProcessing::TextVectorizer.new(vocab)
455
+ x_train = texts.map { |text| vectorizer.vectorize(text) }
456
+
457
+ # Build sentiment analyzer
458
+ model = GRNexus::NeuralNetwork.new(
459
+ loss: 'cross_entropy',
460
+ learning_rate: 0.05,
461
+ name: 'sentiment_analyzer'
462
+ )
463
+
464
+ model.add(GRNEXUSLayer::DenseLayer.new(
465
+ units: 32,
466
+ input_dim: vocab.size,
467
+ activation: GRNEXUSActivations::ReLU.new
468
+ ))
469
+ model.add(GRNEXUSLayer::DropoutLayer.new(rate: 0.3))
470
+ model.add(GRNEXUSLayer::DenseLayer.new(
471
+ units: 16,
472
+ input_dim: 32,
473
+ activation: GRNEXUSActivations::Tanh.new
474
+ ))
475
+ model.add(GRNEXUSLayer::DenseLayer.new(
476
+ units: 2,
477
+ input_dim: 16,
478
+ activation: GRNEXUSNormalization::Softmax.new
479
+ ))
480
+
481
+ # Train
482
+ model.train(x_train, labels, epochs: 100, batch_size: 2, verbose: true)
483
+
484
+ # Test predictions
485
+ test_text = "excellent product very good"
486
+ test_vector = vectorizer.vectorize(test_text)
487
+ prediction = model.predict([test_vector])[0]
488
+ sentiment = prediction[0] > prediction[1] ? "POSITIVE" : "NEGATIVE"
489
+ confidence = prediction.max * 100
490
+
491
+ puts "Text: '#{test_text}'"
492
+ puts "Sentiment: #{sentiment} (#{confidence.round(2)}% confidence)"
493
+
494
+ # Save for cross-language use
495
+ model.save('sentiment_analyzer.nexus')
496
+ ```
497
+
498
+
499
+ ### Advanced Sentiment Analysis with Word Embeddings
500
+
501
+ ```ruby
502
+ require 'grnexus'
503
+
504
+ # Larger dataset
505
+ texts = [
506
+ "This movie is absolutely fantastic and amazing",
507
+ "Terrible film waste of time and money",
508
+ "Great acting superb storyline loved it",
509
+ "Boring predictable disappointing experience",
510
+ "Outstanding performance brilliant direction",
511
+ "Awful terrible waste of time"
512
+ ]
513
+ labels = [[1, 0], [0, 1], [1, 0], [0, 1], [1, 0], [0, 1]]
514
+
515
+ # Create vocabulary
516
+ vocab = GRNexusTextProcessing::Vocabulary.new(texts, max_vocab_size: 5000)
517
+
518
+ # Normalize texts to sequences of indices
519
+ max_length = 20
520
+ x_train = texts.map { |text| vocab.normalize_text(text, max_length: max_length) }
521
+
522
+ # Build model with embedding layer
523
+ model = GRNexus::NeuralNetwork.new(
524
+ loss: 'cross_entropy',
525
+ learning_rate: 0.001,
526
+ name: 'sentiment_embeddings'
527
+ )
528
+
529
+ # Embedding layer converts word indices to dense vectors
530
+ model.add(GRNEXUSLayer::EmbeddingLayer.new(
531
+ vocab_size: vocab.size,
532
+ embedding_dim: 128,
533
+ input_length: max_length
534
+ ))
535
+
536
+ # Flatten embeddings
537
+ model.add(GRNEXUSLayer::FlattenLayer.new)
538
+
539
+ # Dense layers
540
+ model.add(GRNEXUSLayer::DenseLayer.new(
541
+ units: 64,
542
+ input_dim: max_length * 128,
543
+ activation: GRNEXUSActivations::ReLU.new
544
+ ))
545
+ model.add(GRNEXUSLayer::DropoutLayer.new(rate: 0.5))
546
+ model.add(GRNEXUSLayer::DenseLayer.new(
547
+ units: 32,
548
+ input_dim: 64,
549
+ activation: GRNEXUSActivations::ReLU.new
550
+ ))
551
+ model.add(GRNEXUSLayer::DenseLayer.new(
552
+ units: 2,
553
+ input_dim: 32,
554
+ activation: GRNEXUSNormalization::Softmax.new
555
+ ))
556
+
557
+ # Train
558
+ model.train(x_train, labels, epochs: 50, batch_size: 16, verbose: true)
559
+
560
+ # Predict
561
+ test_text = "amazing movie highly recommended"
562
+ test_seq = vocab.normalize_text(test_text, max_length: max_length)
563
+ prediction = model.predict([test_seq])[0]
564
+ sentiment = prediction[0] > prediction[1] ? "POSITIVE" : "NEGATIVE"
565
+ confidence = prediction.max * 100
566
+
567
+ puts "Sentiment: #{sentiment} (#{confidence.round(2)}% confidence)"
568
+
569
+ model.save('sentiment_embeddings.nexus')
570
+ ```
571
+
572
+ ### Text Vectorization and TF-IDF
573
+
574
+ ```ruby
575
+ require 'grnexus'
576
+
577
+ # Document corpus
578
+ documents = [
579
+ "Ruby is a dynamic programming language",
580
+ "Python is popular for machine learning",
581
+ "Machine learning requires data processing",
582
+ "Ruby has elegant syntax and powerful features"
583
+ ]
584
+
585
+ # Create TF-IDF vectorizer
586
+ tfidf = GRNexusTextProcessing::TFIDFVectorizer.new(documents)
587
+
588
+ # Vectorize new document
589
+ new_doc = "Ruby programming is elegant"
590
+ vector = tfidf.vectorize(new_doc)
591
+ puts "TF-IDF Vector: #{vector}"
592
+
593
+ # Calculate document similarity
594
+ similarity = tfidf.similarity(documents[0], documents[3])
595
+ puts "Similarity: #{similarity}"
596
+ ```
597
+
598
+ ---
599
+
600
+ ## Numeric Processing
601
+
602
+ ### Statistical Analysis
603
+
604
+ ```ruby
605
+ require 'grnexus'
606
+
607
+ data = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
608
+
609
+ # Basic statistics
610
+ mean = GRNEXUSNumericProcessing.mean(data)
611
+ std = GRNEXUSNumericProcessing.std(data)
612
+ variance = GRNEXUSNumericProcessing.variance(data)
613
+ median = GRNEXUSNumericProcessing.median(data)
614
+
615
+ puts "Mean: #{mean}"
616
+ puts "Std Dev: #{std}"
617
+ puts "Variance: #{variance}"
618
+ puts "Median: #{median}"
619
+
620
+ # Correlation
621
+ x = [1.0, 2.0, 3.0, 4.0, 5.0]
622
+ y = [2.0, 4.0, 6.0, 8.0, 10.0]
623
+ correlation = GRNEXUSNumericProcessing.correlation(x, y)
624
+ puts "Correlation: #{correlation}"
625
+ ```
626
+
627
+ ### Data Normalization
628
+
629
+ ```ruby
630
+ require 'grnexus'
631
+
632
+ data = [1.0, 2.0, 3.0, 4.0, 5.0, 10.0, 15.0, 20.0]
633
+
634
+ # Z-Score normalization
635
+ zscore = GRNEXUSNumericProcessing::ZScoreNormalize.new
636
+ normalized = zscore.process(data)
637
+ puts "Z-Score Normalized: #{normalized}"
638
+
639
+ # Min-Max normalization
640
+ minmax = GRNEXUSNumericProcessing::MinMaxNormalize.new(min: 0, max: 1)
641
+ scaled = minmax.process(data)
642
+ puts "Min-Max Scaled: #{scaled}"
643
+
644
+ # L2 normalization
645
+ l2_norm = GRNEXUSNumericProcessing::L2Normalize.new
646
+ l2_normalized = l2_norm.process(data)
647
+ puts "L2 Normalized: #{l2_normalized}"
648
+ ```
649
+
650
+ ### Time Series Processing
651
+
652
+ ```ruby
653
+ require 'grnexus'
654
+
655
+ # Generate time series data
656
+ time_series = (0..199).map { |i| Math.sin(i * 0.05) * 10 + rand * 2 }
657
+
658
+ # Moving average smoothing
659
+ ma = GRNEXUSNumericProcessing::MovingAverage.new(window_size: 5)
660
+ smoothed = ma.process(time_series)
661
+
662
+ # Calculate differences
663
+ diff = GRNEXUSNumericProcessing.difference(time_series)
664
+
665
+ # Integration
666
+ integrated = GRNEXUSNumericProcessing.integrate(diff)
667
+
668
+ puts "Original length: #{time_series.length}"
669
+ puts "Smoothed length: #{smoothed.length}"
670
+ puts "Differences length: #{diff.length}"
671
+ ```
672
+
673
+ ### Time Series Forecasting
674
+
675
+ ```ruby
676
+ require 'grnexus'
677
+
678
+ # Generate and preprocess time series
679
+ time_series = (0..199).map { |i| Math.sin(i * 0.05) * 10 + rand * 2 }
680
+
681
+ # Smooth and normalize
682
+ ma = GRNEXUSNumericProcessing::MovingAverage.new(window_size: 5)
683
+ smoothed = ma.process(time_series)
684
+
685
+ zscore = GRNEXUSNumericProcessing::ZScoreNormalize.new
686
+ normalized = zscore.process(smoothed)
687
+
688
+ # Create sliding windows
689
+ window_size = 10
690
+ x_train = []
691
+ y_train = []
692
+
693
+ (0...(normalized.length - window_size - 1)).each do |i|
694
+ x_train << normalized[i, window_size]
695
+ y_train << [normalized[i + window_size]]
696
+ end
697
+
698
+ # Build forecasting model
699
+ model = GRNexus::NeuralNetwork.new(loss: 'mse', learning_rate: 0.01)
700
+ model.add(GRNEXUSLayer::DenseLayer.new(
701
+ units: 64,
702
+ input_dim: window_size,
703
+ activation: GRNEXUSActivations::Tanh.new
704
+ ))
705
+ model.add(GRNEXUSLayer::DenseLayer.new(
706
+ units: 32,
707
+ input_dim: 64,
708
+ activation: GRNEXUSActivations::ReLU.new
709
+ ))
710
+ model.add(GRNEXUSLayer::DenseLayer.new(units: 1, input_dim: 32))
711
+
712
+ # Train
713
+ model.train(x_train, y_train, epochs: 50, batch_size: 16, verbose: true)
714
+
715
+ # Forecast next value
716
+ future_window = normalized[-window_size..-1]
717
+ prediction = model.predict([future_window])[0]
718
+ puts "Next value prediction: #{prediction[0].round(4)}"
719
+
720
+ model.save('time_series_forecaster.nexus')
721
+ ```
722
+
723
+ ---
724
+
725
+ ## Advanced Features
726
+
727
+ ### Cross-Language Model Compatibility
728
+
729
+ Train in Ruby, deploy in Python (or vice versa):
730
+
731
+ ```ruby
732
+ # Train in Ruby
733
+ model = GRNexus::NeuralNetwork.new(
734
+ loss: 'cross_entropy',
735
+ learning_rate: 0.1,
736
+ name: 'shared_model'
737
+ )
738
+
739
+ model.add(GRNEXUSLayer::DenseLayer.new(
740
+ units: 128,
741
+ input_dim: 50,
742
+ activation: GRNEXUSActivations::GELU.new
743
+ ))
744
+ model.add(GRNEXUSLayer::BatchNormLayer.new)
745
+ model.add(GRNEXUSLayer::DenseLayer.new(
746
+ units: 10,
747
+ input_dim: 128,
748
+ activation: GRNEXUSNormalization::Softmax.new
749
+ ))
750
+
751
+ model.train(x_train, y_train, epochs: 50)
752
+ model.save('shared_model.nexus')
753
+ ```
754
+
755
+ Then in Python:
756
+
757
+ ```python
758
+ from grnexus import NeuralNetwork
759
+
760
+ # Load Ruby-trained model
761
+ model = NeuralNetwork.load('shared_model.nexus')
762
+ # => Loading model: GRNexus v2.0 (created in Ruby)
763
+
764
+ # Continue training or make predictions
765
+ predictions = model.predict(test_data)
766
+ ```
767
+
768
+ ### Model Inspection Without Loading
769
+
770
+ ```ruby
771
+ require 'grnexus'
772
+
773
+ # Inspect model metadata without loading it
774
+ GRNexus::NeuralNetwork.inspect_model('my_model.nexus')
775
+
776
+ # Output:
777
+ # ================================================================================
778
+ # MODEL INSPECTION: my_model.nexus
779
+ # ================================================================================
780
+ # Framework: GRNexus
781
+ # Version: 2.0
782
+ # Language: Ruby
783
+ # Name: sentiment_analyzer
784
+ # Created: 2024-01-15T10:30:00Z
785
+ # Loss Function: cross_entropy
786
+ # Optimizer: adam
787
+ # Learning Rate: 0.001
788
+ #
789
+ # Metadata:
790
+ # Total Parameters: 6,538
791
+ # Trainable Parameters: 6,538
792
+ # Layers Count: 5
793
+ #
794
+ # Architecture:
795
+ # Layer 1: DenseLayer
796
+ # Units: 128
797
+ # Activation: ReLU
798
+ # Trainable: true
799
+ # Layer 2: BatchNormLayer
800
+ # Trainable: true
801
+ # ...
802
+ ```
803
+
804
+ ### Model Architecture Summary
805
+
806
+ ```ruby
807
+ require 'grnexus'
808
+
809
+ model = GRNexus::NeuralNetwork.new(name: 'example_model')
810
+ model.add(GRNEXUSLayer::DenseLayer.new(
811
+ units: 128,
812
+ input_dim: 50,
813
+ activation: GRNEXUSActivations::ReLU.new
814
+ ))
815
+ model.add(GRNEXUSLayer::BatchNormLayer.new)
816
+ model.add(GRNEXUSLayer::DropoutLayer.new(rate: 0.3))
817
+ model.add(GRNEXUSLayer::DenseLayer.new(
818
+ units: 10,
819
+ input_dim: 128,
820
+ activation: GRNEXUSNormalization::Softmax.new
821
+ ))
822
+
823
+ # Display architecture
824
+ model.summary
825
+
826
+ # Output:
827
+ # ================================================================================
828
+ # Model: example_model
829
+ # ================================================================================
830
+ # Output Shape Param #
831
+ # --------------------------------------------------------------------------------
832
+ # DenseLayer (ReLU) (1) (None, 128) 6528
833
+ # BatchNormLayer (2) (None, 128) 2
834
+ # DropoutLayer (3) (None, 128) 0
835
+ # DenseLayer (Softmax) (4) (None, 10) 1290
836
+ # ================================================================================
837
+ # Total params: 7,820
838
+ # Trainable params: 7,820
839
+ # Non-trainable params: 0
840
+ # ================================================================================
841
+ ```
842
+
843
+ ### Training History Visualization
844
+
845
+ ```ruby
846
+ require 'grnexus'
847
+
848
+ # Train model
849
+ history = model.train(
850
+ x_train, y_train,
851
+ epochs: 50,
852
+ batch_size: 32,
853
+ validation_data: [x_val, y_val],
854
+ verbose: true
855
+ )
856
+
857
+ # Plot training history (text-based)
858
+ model.plot_history(metrics: ['loss', 'accuracy', 'val_loss', 'val_accuracy'])
859
+
860
+ # Access history data
861
+ puts "Final training loss: #{history[:loss].last}"
862
+ puts "Final validation accuracy: #{history[:val_accuracy].last}"
863
+ puts "Best validation loss: #{history[:val_loss].min}"
864
+ ```
865
+
866
+ ### Custom Learning Rate Schedules
867
+
868
+ ```ruby
869
+ require 'grnexus'
870
+
871
+ # Exponential decay
872
+ lr_scheduler = GRNEXUSCallbacks::LearningRateScheduler.new do |epoch|
873
+ initial_lr = 0.1
874
+ decay_rate = 0.95
875
+ initial_lr * (decay_rate ** epoch)
876
+ end
877
+
878
+ # Step decay
879
+ step_scheduler = GRNEXUSCallbacks::LearningRateScheduler.new do |epoch|
880
+ initial_lr = 0.1
881
+ drop_every = 10
882
+ initial_lr * (0.5 ** (epoch / drop_every))
883
+ end
884
+
885
+ # Use in training
886
+ model.train(
887
+ x_train, y_train,
888
+ epochs: 100,
889
+ callbacks: [lr_scheduler]
890
+ )
891
+ ```
892
+
893
+ ---
894
+
895
+ ## API Reference
896
+
897
+ ### Neural Network Layers
898
+
899
+ **DenseLayer** - Fully connected layer
900
+ ```ruby
901
+ GRNEXUSLayer::DenseLayer.new(
902
+ units: 128,
903
+ input_dim: 50,
904
+ activation: GRNEXUSActivations::ReLU.new
905
+ )
906
+ ```
907
+
908
+ **Conv2DLayer** - 2D Convolutional layer
909
+ ```ruby
910
+ GRNEXUSLayer::Conv2DLayer.new(
911
+ filters: 32,
912
+ kernel_size: 3,
913
+ input_shape: [28, 28, 1],
914
+ activation: GRNEXUSActivations::ReLU.new,
915
+ padding: 'same'
916
+ )
917
+ ```
918
+
919
+ **LSTMLayer** - Long Short-Term Memory
920
+ ```ruby
921
+ GRNEXUSLayer::LSTMLayer.new(
922
+ units: 128,
923
+ return_sequences: true
924
+ )
925
+ ```
926
+
927
+ **GRULayer** - Gated Recurrent Unit
928
+ ```ruby
929
+ GRNEXUSLayer::GRULayer.new(
930
+ units: 64,
931
+ return_sequences: false
932
+ )
933
+ ```
934
+
935
+ **EmbeddingLayer** - Word embeddings
936
+ ```ruby
937
+ GRNEXUSLayer::EmbeddingLayer.new(
938
+ vocab_size: 10000,
939
+ embedding_dim: 300,
940
+ input_length: 100
941
+ )
942
+ ```
943
+
944
+ **BatchNormLayer** - Batch normalization
945
+ ```ruby
946
+ GRNEXUSLayer::BatchNormLayer.new(
947
+ epsilon: 1e-5,
948
+ momentum: 0.1
949
+ )
950
+ ```
951
+
952
+ **DropoutLayer** - Regularization
953
+ ```ruby
954
+ GRNEXUSLayer::DropoutLayer.new(rate: 0.5)
955
+ ```
956
+
957
+ ### Activation Functions
958
+
959
+ **Modern Activations**
960
+ - `GRNEXUSActivations::GELU.new` - Gaussian Error Linear Unit (GPT, BERT)
961
+ - `GRNEXUSActivations::Swish.new` - Self-gated activation (Google)
962
+ - `GRNEXUSActivations::Mish.new` - State-of-the-art smooth activation
963
+ - `GRNEXUSActivations::Snake.new` - Periodic activation
964
+
965
+ **Classic Activations**
966
+ - `GRNEXUSActivations::ReLU.new` - Rectified Linear Unit
967
+ - `GRNEXUSActivations::LeakyReLU.new` - Leaky ReLU
968
+ - `GRNEXUSActivations::ELU.new` - Exponential Linear Unit
969
+ - `GRNEXUSActivations::SELU.new` - Scaled ELU
970
+ - `GRNEXUSActivations::Sigmoid.new` - Sigmoid
971
+ - `GRNEXUSActivations::Tanh.new` - Hyperbolic tangent
972
+
973
+ **Normalization**
974
+ - `GRNEXUSNormalization::Softmax.new` - Softmax
975
+ - `GRNEXUSNormalization::LogSoftmax.new` - Log Softmax
976
+ - `GRNEXUSNormalization::LayerNorm.new` - Layer normalization
977
+
978
+ ### Training Callbacks
979
+
980
+ **EarlyStopping** - Stop training when metric stops improving
981
+ ```ruby
982
+ GRNEXUSCallbacks::EarlyStopping.new(
983
+ monitor: 'val_loss',
984
+ patience: 10,
985
+ min_delta: 0.001,
986
+ mode: 'min'
987
+ )
988
+ ```
989
+
990
+ **ModelCheckpoint** - Save best model during training
991
+ ```ruby
992
+ GRNEXUSCallbacks::ModelCheckpoint.new(
993
+ filepath: 'best_model.nexus',
994
+ monitor: 'val_accuracy',
995
+ save_best_only: true,
996
+ mode: 'max'
997
+ )
998
+ ```
999
+
1000
+ **ReduceLROnPlateau** - Reduce learning rate when metric plateaus
1001
+ ```ruby
1002
+ GRNEXUSCallbacks::ReduceLROnPlateau.new(
1003
+ monitor: 'val_loss',
1004
+ factor: 0.5,
1005
+ patience: 5,
1006
+ min_lr: 0.00001
1007
+ )
1008
+ ```
1009
+
1010
+ **LearningRateScheduler** - Custom learning rate schedule
1011
+ ```ruby
1012
+ GRNEXUSCallbacks::LearningRateScheduler.new do |epoch|
1013
+ 0.1 * (0.95 ** epoch)
1014
+ end
1015
+ ```
1016
+
1017
+ ### Classical ML Algorithms
1018
+
1019
+ **K-Nearest Neighbors**
1020
+ ```ruby
1021
+ knn = GRNEXUSMachineLearning::KNeighborsClassifier.new(n_neighbors: 5)
1022
+ knn.fit(x_train, y_train)
1023
+ predictions = knn.predict(x_test)
1024
+ ```
1025
+
1026
+ **K-Means Clustering**
1027
+ ```ruby
1028
+ kmeans = GRNEXUSMachineLearning::KMeans.new(n_clusters: 3, max_iter: 300)
1029
+ kmeans.fit(data)
1030
+ clusters = kmeans.predict(new_data)
1031
+ ```
1032
+
1033
+ **Linear Regression**
1034
+ ```ruby
1035
+ lr = GRNEXUSMachineLearning::LinearRegression.new
1036
+ lr.fit(x_train, y_train)
1037
+ predictions = lr.predict(x_test)
1038
+ ```
1039
+
1040
+ **Logistic Regression**
1041
+ ```ruby
1042
+ log_reg = GRNEXUSMachineLearning::LogisticRegression.new(
1043
+ learning_rate: 0.1,
1044
+ max_iter: 1000
1045
+ )
1046
+ log_reg.fit(x_train, y_train)
1047
+ predictions = log_reg.predict(x_test)
1048
+ ```
1049
+
1050
+ **Naive Bayes**
1051
+ ```ruby
1052
+ nb = GRNEXUSMachineLearning::NaiveBayes.new(n_classes: 2)
1053
+ nb.fit(x_train, y_train)
1054
+ predictions = nb.predict(x_test)
1055
+ ```
1056
+
1057
+ ---
1058
+
1059
+ ## Documentation
1060
+
1061
+ ### Complete Documentation
1062
+ Full documentation and advanced examples: [GitHub Repository](https://github.com/grcodedigitalsolutions/GRNexus)
1063
+
1064
+ ### File Formats
1065
+ - **`.nexus`** - Neural network models (cross-language compatible)
1066
+ - **`.lnexus`** - Classical ML models (KNN, K-Means, Linear/Logistic Regression, Naive Bayes)
1067
+
1068
+ ### Platform Support
1069
+ - **Windows**: Pre-compiled DLL files included
1070
+ - **macOS**: Pre-compiled dylib files included
1071
+ - **Linux**: Pre-compiled SO files included
1072
+
1073
+ ### Requirements
1074
+ - Ruby >= 3.0.0
1075
+ - FFI gem (automatically installed)
1076
+ - JSON gem (automatically installed)
1077
+
1078
+ ---
1079
+
1080
+ ## Contributing
1081
+
1082
+ Bug reports and pull requests are welcome on GitHub at:
1083
+ https://github.com/grcodedigitalsolutions/GRNexus
1084
+
1085
+ ---
1086
+
1087
+ ## License
1088
+
1089
+ This gem is available as open source under the terms of the [GPL-3.0 License](LICENSE).
1090
+
1091
+ Copyright (C) 2024 GR Code Digital Solutions
1092
+
1093
+ ---
1094
+
1095
+ ## Author
1096
+
1097
+ **GR Code Digital Solutions**
1098
+
1099
+ Email: gr.code.studio@gmail.com
1100
+
1101
+ GitHub: [@grcodedigitalsolutions](https://github.com/grcodedigitalsolutions)
1102
+
1103
+ ---
1104
+
1105
+ **Made with passion for the Ruby community**