NOT: BU PROJE VE ÇALIŞMA 18 YAŞINDA YAZILIM GELİŞTİRİCİYE AİTTİR (BEN - ZAYN(takma ad))

NOT: BU KOD DENEYSELDİR TAM KAPSAMLI TESTLER YAPILMAMIŞTIR VE AYRICA ÖNCEKİ VERSİYONLARDAN ÇOK DAHA FAZLA İYİLEŞTİRME VE YENİLİK İÇERİR. AÇIKLAMA EN SON VERSİYON V5 GÖRE AYARLANMIŞTIR. V6 KAPALI KAYNAKTIR EN İYİ VERSİYONU HEDEFLER VE KARMAŞIK PROBLEMLERİ ÇÖZER.

Bu proje (EvoNet Optimizer v5), PyTorch kütüphanesini kullanarak yapay sinir ağlarının (YSA) hem mimarisini (yapısını) hem de ağırlıklarını (parametrelerini) optimize etmek için geliştirilmiş bir neuroevolution (sinirsel evrim) çatısıdır. Evrimsel algoritmaların global arama yeteneklerini, uyarlanabilir parametre kontrolü ve paralel hesaplama ile birleştirerek belirli bir görev için optimize edilmiş YSA modelleri bulmayı hedefler. Bu sürüm (v5), önceki versiyonlar üzerine inşa edilmiş olup adaptif mutasyon gücü, karmaşıklık cezası, isteğe bağlı Weights & Biases entegrasyonu ve genel performans iyileştirmeleri içerir.

Temel Konsept: Neuroevolution

Geleneksel derin öğrenmede genellikle sabit bir sinir ağı mimarisi belirlenir ve ardından gradyan inişi gibi yöntemlerle sadece ağırlıklar optimize edilir. Neuroevolution ise daha ileri giderek evrimsel algoritmalardan ilham alır:

Popülasyon: Farklı mimari ve/veya ağırlıklara sahip bir grup YSA modeli (bireyler) oluşturulur. Uygunluk (Fitness) Değerlendirme: Her modelin belirli bir görevdeki performansı ölçülür (örneğin, bir veri setindeki hata oranı). Bu performans skoru, modelin "uygunluğunu" belirler. Seçilim: Daha yüksek uygunluk skoruna sahip modellerin bir sonraki nesle aktarılma veya üremede kullanılma olasılığı daha yüksektir (örneğin, turnuva seçilimi). Üreme (Crossover/Çaprazlama): İki veya daha fazla ebeveyn modelin özellikleri (mimari parçaları veya ağırlıkları) birleştirilerek yeni çocuk modeller oluşturulur. Mutasyon: Çocuk modellerin mimarilerinde veya ağırlıklarında küçük, rastgele değişiklikler yapılır. Bu, popülasyona çeşitlilik katar ve yeni potansiyel çözümlerin keşfedilmesini sağlar. Tekrarlama: Bu süreç (değerlendirme, seçilim, üreme, mutasyon) birçok nesil boyunca tekrarlanır ve popülasyonun görevdeki performansı zamanla iyileşir. EvoNet v5'in Öne Çıkan Özellikleri

PyTorch Tabanlı: Modern ve esnek bir derin öğrenme kütüphanesi üzerine inşa edilmiştir. Modeller standart PyTorch nn.Module sınıflarıdır. Adaptif Mutasyon Gücü: Evrimin ilerlemesine bağlı olarak mutasyonun ne kadar büyük değişiklikler yapacağını otomatik olarak ayarlar. Eğer gelişim yavaşlarsa (tıkanma/stagnation), daha büyük mutasyonlar yaparak yerel optimumlardan kaçmaya çalışır; gelişim iyi gidiyorsa, daha küçük, hassas ayarlamalar yapar. (--adapt_mutation, --stagnation_limit, --mut_strength_decay, --mut_strength_increase vb. parametreler) Paralel Uygunluk Hesaplama: concurrent.futures kullanarak birden fazla CPU çekirdeğinde modellerin uygunluk skorlarını aynı anda hesaplayarak evrim sürecini önemli ölçüde hızlandırır (--num_workers). Karmaşıklık Cezası: Uygunluk fonksiyonuna modelin parametre sayısına dayalı bir ceza ekleyerek, benzer performansı gösteren daha basit (daha az parametreli) modelleri tercih etme eğilimi yaratır (--complexity_penalty). Bu, aşırı öğrenmeyi (overfitting) azaltmaya yardımcı olabilir. Weights & Biases Entegrasyonu (İsteğe Bağlı): Deney takibi için popüler bir araç olan Weights & Biases (W&B) ile entegre olabilir. Uygunluk skorları, mutasyon gücü, nesil süreleri gibi metrikleri canlı olarak takip etmek, hiperparametreleri kaydetmek ve sonuçları görselleştirmek için kullanılabilir (--use_wandb, --wandb_project, --wandb_entity). Checkpointing ve Devam Etme: Evrim sürecinin durumunu belirli aralıklarla kaydederek (--checkpoint_interval), program durdurulursa veya hata verirse en baştan başlamak yerine kalınan yerden devam etme imkanı sunar (--resume_from). Esnek Model Tanımı: NeuralNetwork sınıfı, farklı sayıda gizli katman, nöron sayısı ve aktivasyon fonksiyonu ile dinamik olarak YSA'lar oluşturabilir. Son Eğitim ve Değerlendirme: Evrim süreci tamamlandıktan sonra bulunan en iyi modeli alır, standart bir eğitim süreciyle (örn. Adam optimizer ile belirli sayıda epoch) daha da ince ayar yapar ve ayrı bir test seti üzerinde performansını değerlendirir. Kod Akışı

Argüman Ayrıştırma (parse_arguments_v5): Komut satırı argümanlarını (popülasyon boyutu, nesil sayısı, mutasyon oranları, W&B ayarları vb.) alır. Kurulum (setup_logging, setup_device): Loglama mekanizmasını ve kullanılacak cihazı (CPU/GPU) ayarlar. Checkpoint Yükleme (Varsa): Eğer --resume_from ile bir dizin belirtilmişse, en son kaydedilen checkpoint'i bulur (find_latest_checkpoint_pytorch) ve yükler (load_checkpoint_pytorch), evrime kalınan nesilden devam edilir. W&B Başlatma (İstenmişse): --use_wandb aktifse ve wandb kütüphanesi kuruluysa, W&B oturumunu başlatır (veya devam ettirir). Veri Üretimi (generate_data): Eğitim ve test için girdi (X) ve hedef çıktı (y) verilerini oluşturur. Bu fonksiyon, farklı bir görev için kodu uyarlamak isterseniz değiştirmeniz gereken ana yerdir. Şu anki haliyle basit bir sıralama görevi için veri üretir. Popülasyon Başlatma (Gerekirse): Checkpoint'ten yüklenmediyse, rastgele mimarilere sahip başlangıç popülasyonunu oluşturur (create_individual_pytorch). Evrim Döngüsü (evolve_population_pytorch_v5): Belirlenen nesil sayısı kadar ana döngüyü çalıştırır: Uygunluk Hesaplama: Popülasyondaki her modelin uygunluğunu hesaplar (seri veya --num_workers > 0 ise paralel olarak _calculate_fitness_worker ile). Karmaşıklık cezası burada uygulanır. İstatistikler ve Takip: En iyi ve ortalama uygunluk skorlarını kaydeder, W&B'ye loglar (aktifse). Adaptif Mutasyon Ayarı: Gerekirse mutasyon gücünü günceller. Yeni Popülasyon Oluşturma: Elitizm: En iyi birkaç modeli doğrudan yeni nesle aktarır (--elitism_count). Seçilim: Turnuva seçilimi (tournament_selection) ile ebeveynleri seçer. Çaprazlama (crossover_individuals_pytorch): Belirli bir olasılıkla (--crossover_rate) ebeveynleri çaprazlayarak yeni çocuklar üretir (sadece mimarileri aynıysa). Mutasyon (mutate_individual_pytorch): Çaprazlama uygulanmazsa veya belirli bir olasılıkla (--mutation_rate), çocukların ağırlıklarını mevcut adaptif mutasyon gücüyle değiştirir. Checkpoint Kaydetme (Periyodik): Belirli aralıklarla mevcut durumu kaydeder (save_checkpoint_pytorch). Sonuçların İşlenmesi: Evrim boyunca elde edilen en iyi modeli belirler. Uygunluk geçmişini grafiğe döker (plot_fitness_history) ve kaydeder. Son Eğitim (train_final_model_pytorch): Evrimle bulunan en iyi modelin bir kopyasını alır ve eğitim verisi üzerinde gradyan tabanlı optimizasyon (Adam) ile eğitir (ince ayar). Erken durdurma (early stopping) ve öğrenme oranı zamanlaması (learning rate scheduling) kullanılır. Son Değerlendirme (evaluate_model_pytorch): İnce ayarı yapılmış son modeli test verisi üzerinde değerlendirir (örneğin, MSE - Ortalama Karesel Hata hesaplar). Sonuçları Kaydetme: Tüm konfigürasyon, evrim özeti, eğitim özeti, değerlendirme metrikleri ve son modelin yolunu bir JSON dosyasına kaydeder. W&B Bitirme (Aktifse): W&B oturumunu sonlandırır. Nasıl Kullanılır

Gerekli kütüphaneleri yükleyin: torch, numpy, matplotlib, scipy ve isteğe bağlı olarak wandb. Kodu bir Python betiği olarak kaydedin (örneğin, evonet_v5.py). Komut satırından çalıştırın: Bash

python evonet_v5.py [ARGÜMANLAR] Önemli argümanlar şunlardır: --pop_size: Popülasyon büyüklüğü. --generations: Çalıştırılacak nesil sayısı. --mutation_strength: Başlangıç mutasyon gücü. --num_workers: Paralel hesaplama için kullanılacak işçi (CPU çekirdeği) sayısı (0 = seri). --use_wandb: W&B takibini açar/kapatır. --output_base_dir: Çıktıların (loglar, checkpoint'ler, sonuçlar) kaydedileceği ana dizin. --resume_from : Belirtilen dizindeki son checkpoint'ten devam eder. Tüm argümanları görmek için: python evonet_v5.py --help Özelleştirme

Bu çatıyı kendi problemlerinize uyarlamak için yapmanız gereken en temel değişiklik generate_data fonksiyonunu kendi görevinize uygun girdi (X) ve çıktı (y) verilerini üretecek şekilde değiştirmektir. Ayrıca, görevinizin doğasına göre NeuralNetwork sınıfının oluşturduğu mimarilerin sınırlarını (örneğin, katman sayısı, aktivasyon fonksiyonları) veya evrimsel parametreleri (--crossover_rate, --mutation_rate vb.) ayarlamanız gerekebilir.

Potansiyel Kullanım Alanları

Belirli bir görev için en iyi sinir ağı mimarisini otomatik olarak bulma. Hiperparametre optimizasyonu (dolaylı olarak). Takviyeli öğrenme (Reinforcement Learning) politikalarını optimize etme (uygunluk fonksiyonu RL ödülü olacak şekilde uyarlanırsa). Gradyanların hesaplanmasının zor veya imkansız olduğu optimizasyon problemleri. Sınırlılıklar ve Dikkat Edilmesi Gerekenler

Hesaplama Maliyeti: Neuroevolution, özellikle büyük popülasyonlar ve uzun nesiller için hesaplama açısından pahalı olabilir. Paralel hesaplama bunu hafifletse de hala önemli bir faktördür. Hiperparametre Ayarı: Evrimsel algoritmanın kendi parametrelerinin (popülasyon boyutu, seçilim yöntemi, mutasyon/çaprazlama oranları, adaptif parametreler) ayarlanması gerekebilir ve bu da zaman alıcı olabilir. Yakınsama Garantisi Yok: Diğer sezgisel arama yöntemleri gibi, global optimum çözümü bulma garantisi yoktur, ancak genellikle çok iyi çözümler bulabilir.

NOTE: THIS PROJECT AND WORK BELONGS TO A 19-YEAR-OLD SOFTWARE DEVELOPER (ME - ZAYN(nick)) NOTE: THIS CODE IS EXPERIMENTAL, HAS NOT BEEN FULLY TESTED, AND ALSO CONTAINS MANY MORE IMPROVEMENTS AND INNOVATIONS THAN PREVIOUS VERSIONS. THE DESCRIPTION IS BASED ON THE LATEST VERSION V5. V6 IS CLOSED SOURCE, IT AIMS FOR THE BEST VERSION AND SOLVES COMPLEX PROBLEMS.

EvoNet Optimizer v5 - Adaptive & Parallel Neuroevolution with PyTorch

This project (EvoNet Optimizer v5) is a neuroevolution framework developed using PyTorch to optimize both the architecture (structure) and weights (parameters) of artificial neural networks (ANNs). It aims to find optimized ANN models for a specific task by combining the global search capabilities of evolutionary algorithms with adaptive parameter control and parallel computation. This version (v5) builds upon previous iterations, incorporating adaptive mutation strength, complexity penalty, optional Weights & Biases integration, and general performance improvements.

Core Concept: Neuroevolution

In traditional deep learning, a fixed neural network architecture is typically defined, and then only the weights are optimized using methods like gradient descent. Neuroevolution goes further, drawing inspiration from evolutionary algorithms:

Population: A group of ANN models (individuals) with different architectures and/or weights is created. Fitness Evaluation: Each model's performance on a specific task is measured (e.g., error rate on a dataset). This performance score determines the model's "fitness." Selection: Models with higher fitness scores are more likely to be passed on to the next generation or used in reproduction (e.g., via tournament selection). Reproduction (Crossover): Features (architectural components or weights) from two or more parent models are combined to create new offspring models. Mutation: Small, random changes are introduced into the architectures or weights of the offspring models. This adds diversity to the population and allows for the exploration of new potential solutions. Iteration: This process (evaluation, selection, reproduction, mutation) is repeated over many generations, and the population's performance on the task improves over time. Key Features of EvoNet v5

PyTorch-Based: Built on a modern and flexible deep learning library. Models are standard PyTorch nn.Module classes. Adaptive Mutation Strength: Automatically adjusts the magnitude of changes introduced by mutation based on the progress of evolution. If improvement stagnates, it increases mutation strength to potentially escape local optima; if progress is good, it uses smaller, finer adjustments. (Parameters: --adapt_mutation, --stagnation_limit, --mut_strength_decay, --mut_strength_increase, etc.) Parallel Fitness Evaluation: Significantly speeds up the evolution process by calculating the fitness scores of models concurrently on multiple CPU cores using concurrent.futures (--num_workers). Complexity Penalty: Introduces a penalty to the fitness function based on the model's parameter count, encouraging a preference for simpler (fewer parameters) models that exhibit similar performance (--complexity_penalty). This can help mitigate overfitting. Weights & Biases Integration (Optional): Can integrate with Weights & Biases (W&B), a popular tool for experiment tracking. It can be used to log metrics like fitness scores, mutation strength, generation times, record hyperparameters, and visualize results in real-time (--use_wandb, --wandb_project, --wandb_entity). Checkpointing and Resuming: Allows saving the state of the evolution process at regular intervals (--checkpoint_interval) and resuming from the last saved state if the program is interrupted or encounters an error (--resume_from), preventing loss of work. Flexible Model Definition: The NeuralNetwork class can dynamically create ANNs with varying numbers of hidden layers, neurons, and activation functions. Final Training and Evaluation: After the evolution process completes, it takes the best-evolved model, fine-tunes it further using a standard training process (e.g., Adam optimizer for a set number of epochs), and evaluates its performance on a separate test set. Code Workflow

Argument Parsing (parse_arguments_v5): Retrieves command-line arguments (population size, number of generations, mutation rates, W&B settings, etc.). Setup (setup_logging, setup_device): Configures the logging mechanism and sets up the device (CPU/GPU) to be used. Load Checkpoint (If applicable): If a directory is specified via --resume_from, it finds (find_latest_checkpoint_pytorch) and loads (load_checkpoint_pytorch) the latest checkpoint, resuming evolution from the saved generation. Initialize W&B (If requested): If --use_wandb is active and the wandb library is installed, it initializes (or resumes) the W&B run. Generate Data (generate_data): Creates the input (X) and target output (y) data for training and testing. This function is the primary place to modify if you want to adapt the code for a different task. Currently, it generates data for a simple sorting task. Initialize Population (If needed): If not loaded from a checkpoint, creates the initial population of random architectures (create_individual_pytorch). Evolutionary Loop (evolve_population_pytorch_v5): Runs the main loop for the specified number of generations: Fitness Calculation: Computes the fitness of each model in the population (serially or in parallel via _calculate_fitness_worker if --num_workers > 0). The complexity penalty is applied here. Statistics and Tracking: Records the best and average fitness scores, logs to W&B (if active). Adaptive Mutation Adjustment: Updates the mutation strength if necessary. Create New Population: Elitism: Directly copies the best few individuals to the next generation (--elitism_count). Selection: Selects parents using tournament selection (tournament_selection). Crossover (crossover_individuals_pytorch): Creates new offspring by combining parents with a certain probability (--crossover_rate) (only if architectures are compatible). Mutation (mutate_individual_pytorch): If crossover isn't applied or with a certain probability (--mutation_rate), modifies the weights of offspring using the current adaptive mutation strength. Save Checkpoint (Periodically): Saves the current state at specified intervals (save_checkpoint_pytorch). Process Results: Identifies the best model found during evolution. Plots (plot_fitness_history) and saves the fitness history. Final Training (train_final_model_pytorch): Takes a copy of the best-evolved model and fine-tunes it using gradient-based optimization (Adam) on the training data. Uses early stopping and learning rate scheduling. Final Evaluation (evaluate_model_pytorch): Evaluates the fine-tuned final model on the test dataset (e.g., calculates Mean Squared Error - MSE). Save Results: Saves the complete configuration, evolution summary, training summary, evaluation metrics, and the path to the final trained model in a JSON file. Finish W&B (If active): Finalizes the W&B run. How to Use

Install necessary libraries: torch, numpy, matplotlib, scipy, and optionally wandb. Save the code as a Python script (e.g., evonet_v5.py). Run from the command line: Bash

python evonet_v5.py [ARGUMENTS] Key arguments include: --pop_size: Population size. --generations: Number of generations to run. --mutation_strength: Initial mutation strength. --num_workers: Number of worker processes (CPU cores) for parallel evaluation (0 = serial). --use_wandb: Enables/disables W&B tracking. --output_base_dir: Base directory to save outputs (logs, checkpoints, results). --resume_from : Resumes from the latest checkpoint in the specified directory. For all arguments: python evonet_v5.py --help Customization

The most fundamental way to adapt this framework to your own problems is by modifying the generate_data function to produce input (X) and output (y) data appropriate for your task. You might also need to adjust the constraints on the architectures generated by NeuralNetwork (e.g., layer counts, activation functions) or tune the evolutionary parameters (--crossover_rate, --mutation_rate, etc.) based on the nature of your task.

Potential Use Cases

Automated discovery of optimal neural network architectures for a given task. Hyperparameter optimization (indirectly). Optimizing policies in Reinforcement Learning (if the fitness function is adapted to use the RL reward). Optimization problems where gradients are difficult or impossible to compute. Limitations and Considerations

Computational Cost: Neuroevolution can be computationally expensive, especially with large populations and many generations. Parallel computation alleviates this but it remains a significant factor. Hyperparameter Tuning: The evolutionary algorithm's own parameters (population size, selection method, mutation/crossover rates, adaptive parameters) may need tuning, which can also be time-consuming. No Guarantee of Convergence: Like other heuristic search methods, it does not guarantee finding the global optimum solution, although it can often find very good solutions.

Downloads last month
24
Inference Providers NEW
This model isn't deployed by any Inference Provider. 🙋 Ask for provider support