Тёмный

Genetic Algorithm from Scratch in Python (tutorial with code) 

Kie Codes
Подписаться 18 тыс.
Просмотров 144 тыс.
50% 1

PART 1: • Genetic Algorithms Exp...
This video is part two of my series on genetic algorithms. In last week's video, we looked at how a genetic algorithm works and I have explained by example the theory behind it and its different applications and I highly recommend watching this video first.
In this week's tutorial, we will implement our first example of a genetic algorithm to solve the knapsack problem discussed last week in python. We won't use any libraries but write everything from scratch.
Happy Coding!
🙏 Support me: / kiecodes
🛰 Join our Discord, to interact with other Coders and me: / discord
🧠 Pick my brain: calendly.com/kiecodes/ai-cons...
Check out my newest video: • How to use the OpenAI ...
Follow me here:
kiecodes
kiecodes
The code can be found here: github.com/kiecodes/genetic-a...
Timestamps:
00:00 Intro
00:17 Genome
01:25 Fitness function
02:26 Data for the example
02:43 Selection function
04:00 Crossover function
04:50 Mutation function
05:55 Evolutionary main loop
09:17 Implementing the example from last week's tutorial
---
This video contains advertising content.
---
#python #machinelearning #geneticalgorithms

Наука

Опубликовано:

 

5 авг 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 254   
@msubookstoreitsupport2819
@msubookstoreitsupport2819 2 года назад
I have learned a *ton* from this video, but the biggest thing I've learned is about good practices with type hinting and software architecture. The way this is laid out is brilliant. If this is how everyone in the software industry codes, I am way behind, however I've never seen anyone else do it this way in formal courses or other videos. I first watched this months ago and I genuinely believe I have vastly improved as a programmer as a direct result. You should make more videos... about just anything. I guarantee people will learn a ton, regardless of what you're actually trying to teach
@KieCodes
@KieCodes 2 года назад
Wow! Thank you for these kind words. It is really motivating. 🙏🙏🙏
@GabrielSouza-sk6ne
@GabrielSouza-sk6ne 2 года назад
I could not understand everything of python sintaxe of this video, but DEFINITELY I'm more inspired to look into it!
@jackhoefnagel
@jackhoefnagel 4 года назад
Yoooo this video is SO well made! As well as the first part, just great explanations, visuals/animations, and a clear rundown of the code you're writing. SO GOOD!
@KieCodes
@KieCodes 4 года назад
Thank you for your kind words! I am looking forward to see what creative stuff you’ll use it for. 🙏
@LEARNWITHPANDA
@LEARNWITHPANDA 4 года назад
Totally agree with you!
@polu9133
@polu9133 3 года назад
Hey, cool video. In 5:16 you can also use "else 1 - genome[index]". This will also flip the bit (or just xor it with 1).
@o.rudyemonvuon64
@o.rudyemonvuon64 3 года назад
Editing skills on point !!! Referring to the previous videos totally makes sense and makes the video more interactive.
@KieCodes
@KieCodes 3 года назад
Thank you Rudy
@ronboprime
@ronboprime 26 дней назад
wow. glad I ran in to you. you're videos are great! fast, to the point, informative, and a wee bit funny. sub earned, for sho!
@Human_A113
@Human_A113 Год назад
Dude your content is really great and super high-quality and very easy to follow I 100% feel like you should definitely have more a following and I know that pretty soon you're gonna blow up, glad I'm here to see it
@tyleraldous9158
@tyleraldous9158 3 года назад
I'm so glad I found your channel. I can't believe you don't have more views- your production quality is fantastic and it is apparent you are putting a lot of time into each video. Keep up the great work!
@KieCodes
@KieCodes 3 года назад
Thank you so much for your kind words! :)
@davneelchand1727
@davneelchand1727 2 года назад
@@KieCodes it's true i was struggling with genetic algorithm and your video found the best solution for me
@seb6302
@seb6302 2 года назад
Disappointed to see you haven't made other videos on similar topics! I loved both this and the first video on GA. Would be super interested in topics such as Simulated Annealing, Tabu Search and Evolutionary Strategies !
@barbi97
@barbi97 3 года назад
Just started my GA classes and this video helped me a lot! It was short, concise and very clear. Thank you for the content ♥
@KieCodes
@KieCodes 3 года назад
You are more than welcome my friend. 🙏 Rock on! 🚀
@pedroribeiro6271
@pedroribeiro6271 3 года назад
Thanks for the video! I recently found about the genetic algorithm and this video helped me understand it better. An alternative to that parte of abs(genome[ idx ]-1) is ( genome[ idx ]+1)%2.
@lucacoraggio5179
@lucacoraggio5179 3 года назад
So well done! Clean, clear and teaches a lot (both for the GA and python code/style). Nailed it! Thank you for the content.
@KieCodes
@KieCodes 3 года назад
Thank you for your kind words, Luca! 🙏
@crypto1886
@crypto1886 3 года назад
too good my man, i have seen other youtubers use genetic algorithms, and after like a year i can finnally make my own TYSM
@KieCodes
@KieCodes 3 года назад
You are more than welcome my friend. 🙏 Rock on! 🚀
@AdrianSP55
@AdrianSP55 3 года назад
I am very grateful, both of your videos about genetic algorithms really helped me to approve my exam. Keep it up!
@KieCodes
@KieCodes 3 года назад
You are very welcome Adrian. Congrats on your exam!
@mihirshrestha6652
@mihirshrestha6652 3 года назад
Good video, but this goes way too fast. This is supposed to be a 20-30 minute video, but you sped it and talk way too fast. I have been programming in Python for about 3 years, and I learned more about the nitty gritty type hinting functions and Callables than I did about genetic algorithms. Not to nitpick, but since the topic is genetic algorithms, it'd be best if you didn't use all these nitty gritty details from Python. Nonetheless, good video. But just letting you know I had to watch this video twice in 0.75x speed to understand what you were doing.
@KieCodes
@KieCodes 3 года назад
Thanks for the feedback Mihir. Have you watched the first video about GAs as well? If not, please do. In that video I talk in detail about how GAs work. I hope that helps. But thanks again for the feedback.
@zac2577
@zac2577 Год назад
This was the best pace ive written python only about 2 years
@samariddinzarifov8917
@samariddinzarifov8917 5 месяцев назад
Yes, you are talking so fast for smb like me who is a new in GA and please, don't include background music, it just makes person confused and unfocused
@pelzmorph7265
@pelzmorph7265 4 года назад
Nice. This problem solving algorithm will come in handy for many problems to come :) Thanks for the vid!
@KieCodes
@KieCodes 4 года назад
It really is useful and quite underused in professional applications. But there are so many great creative applications and projects to find.
@weronikaprawda8938
@weronikaprawda8938 2 года назад
Thank you!! I had an assignment related to genetic algorithms and this is the best example I have seen for begginers:)
@KieCodes
@KieCodes 2 года назад
Thank you. 🙏
@elviszambrano8076
@elviszambrano8076 3 года назад
Fantastic introductory tutorial on this topic, thanks for posting this video. Any recommendations on books to start on genetic algorithms or genetic algorithm with Python? Thanks
@_zeppeh
@_zeppeh 2 года назад
Yeah nice high quality production! You got my respect!
@KieCodes
@KieCodes 2 года назад
Thank you. 🙏
@isbeb507
@isbeb507 3 года назад
hey this was really good! im gonna check out your other stuff.
@KieCodes
@KieCodes 3 года назад
Thank you. 🙏
@TheCzarsoham
@TheCzarsoham 3 года назад
You're a literal life saver! I'll be citing your videos on my uni project!
@KieCodes
@KieCodes 3 года назад
Thank you! 🙏
@rattrap777
@rattrap777 3 года назад
Is your uni project on AI and music??
@SG-ll5qt
@SG-ll5qt 3 года назад
how u going to cite video? and which country u r from if udm
@TheCzarsoham
@TheCzarsoham 3 года назад
@@rattrap777 My project was on optimizing PID controllers using genetic algorithms
@anonymousvevo8697
@anonymousvevo8697 Год назад
i really like the way you code in python !
@ammanuelbekeletilahun9526
@ammanuelbekeletilahun9526 4 года назад
It was really really helpful. I salute. I have no words.
@KieCodes
@KieCodes 4 года назад
Thank you very much for your kind words Ammanuel!
@IgorSantarek
@IgorSantarek Год назад
Very good presentation!
@debd.9220
@debd.9220 3 года назад
A new subscriber. 🤗 Thanks for your explanatory teachings.
@KieCodes
@KieCodes 3 года назад
Thank you for being here! 💪
@dejan919
@dejan919 2 года назад
Kie, i think some uf us would need a tutorial on Callables after this video :D
@souravdeb6126
@souravdeb6126 Год назад
Respect++ for maintaining good coding practices (aka architectural thoughts) which a very few tutors do!!
@KieCodes
@KieCodes Год назад
Thank you for noticing!
@cyberpunk_edgerunners
@cyberpunk_edgerunners Год назад
amazing work , love it
@mohamedfouadhanani
@mohamedfouadhanani 2 года назад
very good explanation, amazingly written code. Awesome video.
@KieCodes
@KieCodes 2 года назад
Thank you. 🙏
@v-for-victory
@v-for-victory 2 года назад
Great video. I really like your style of explaining.
@KieCodes
@KieCodes 2 года назад
Thank you. 🙏
@melika4601
@melika4601 3 года назад
hi sir. i have a project which is to find the min value of the given fx (fx should be single-variable and can be whatever the user wants) by using genetic algorithm. for example the user enters f(x)=x^2-1 as an input and program should give us the min value for this function by using GA algorithm. i don know how to implement it . do you know where i can find such program or how can i implement it?
@r11sr
@r11sr Год назад
thank you! Appreciated
@philosophiabme
@philosophiabme 2 года назад
Great video! This is really useful :)
@KieCodes
@KieCodes 2 года назад
Thank you. 🙏 I am glad it helped!
@howtosolveoptimizationprob8462
@howtosolveoptimizationprob8462 4 года назад
Very useful python code of genetic algorithm. Many thanks Kie!
@KieCodes
@KieCodes 4 года назад
You are more than welcome. I am glad you find it useful.
@howtosolveoptimizationprob8462
@howtosolveoptimizationprob8462 4 года назад
@@KieCodes are you a professional programmer?
@KieCodes
@KieCodes 4 года назад
Yes, I work as a software engineer.
@howtosolveoptimizationprob8462
@howtosolveoptimizationprob8462 4 года назад
@@KieCodes very cool. Thanks
@doyourealise
@doyourealise 2 года назад
subscribed :) keep on making more videos on genetic algorithms.
@KieCodes
@KieCodes 2 года назад
I will try! Glad you liked it! 🙌
@davidmateosgarriga8755
@davidmateosgarriga8755 3 года назад
Great video! Thanks!
@KieCodes
@KieCodes 3 года назад
You are more than welcome my friend. 🙏 Rock on! 🚀
@michaelfekadu6116
@michaelfekadu6116 3 года назад
thank you for doing type annotations in python! That's the best kind of python!
@KieCodes
@KieCodes 3 года назад
Thank you for writing this! I love the type hints too, but some viewers are a little confused by them.
@marco.nascimento
@marco.nascimento 3 года назад
Awesome video!!
@KieCodes
@KieCodes 3 года назад
Thank you!
@offsideplayer
@offsideplayer 3 года назад
More genetic algorithms video and preferably without type hinting as it is very very hard to follow for beginners in python. Very well explained. Subscribed and waiting for new content :)
@KieCodes
@KieCodes 3 года назад
Thanks Daniel. I will work on that. Regards to the type hinting: I have a video on that and why I use them especially in my videos. If you haven‘t already, please check it out. I hope everything is a little clearer then.
@offsideplayer
@offsideplayer 3 года назад
@@KieCodes Already been doing that while writing my initial comment haha. Good luck!
@KieCodes
@KieCodes 3 года назад
Thanks to you too!
@peterdonnelly1074
@peterdonnelly1074 2 года назад
Thanks. Very good.
@dlisetteb
@dlisetteb 3 года назад
5:50 definitely i will suscribe! btw i m newby at python, your code seems a radically different language (c++ likely as far as i know) XD
@KieCodes
@KieCodes 3 года назад
Thank you. 🙏
@theodoregiannilias5140
@theodoregiannilias5140 3 года назад
I would suggest to do longer videos and explain also the functions you're importing and using because most of the times we stop the video to fix function implementations. Good job though keep it up!!
@KieCodes
@KieCodes 3 года назад
Thanks for the tips! I will keep that in mind! 🙏
@offsideplayer
@offsideplayer 3 года назад
Hey again, sorry if my question sounds dumb: I want to create a track for a "race" of individuals which have as their purpose to get to the end of the track. Is sensory implementation a good idea (if the next random move is hitting the wall, we should randomly assign the next move again till it no longer hits the wall and moves in an available direction, till the end of the track, meaning it is being constrained and forced to follow the path by the walls). Would this algorithm still qualified as genetic? Is it up to me how I define an individual or does it have to be as primitive as possible?
@KieCodes
@KieCodes 3 года назад
Hey Daniel! I hope I understand your question correctly and am able to help. If not, please don't hesitate to ask another question. Frist of all: The structure and complexity of one individual in your population is totally up to you. Regarding your idea: Yes you can solve this using a genetic algorithm. For instance you could encode the configuration of your cars in a genome. Inside the genome there would be parameters like num sensors, sensor length, and some for the steering behaviour. A genetic algorithm could try to find the best combination for a car. The fitness of a car would be % of the track completed or time to completion. This wy you can generate different cars and let them race against each other. I know my answer is pretty high-level, but to give you more details I would need to know your setup better. Have a great day! Kie
@offsideplayer
@offsideplayer 3 года назад
@@KieCodes Hey! Thanks for the answer. I was looking into Q Learning and Reinforcement Learning to set checkpoints for the car which would mean a reward so the individual is more inclined to get to the next checkpoint etc. I actually just finished my first GA - a variation of the knapsack problem but with many more traits to the items (more values corresponding to different preferences the user sets). e.g. A user sets his happiness as being 8/10 important to him, and money to 10/10. Then he'd add one item and evaluate it in regard to the previously set needs. The user says the item "scooter" would contribute 0 to his happiness and 10 to his money, so the algorithm would set this item's fitness as high and with many more needs and items, it gets really interesting. Thanks for the answer and the videos, really pushed me to start :)
@zafersaglk1391
@zafersaglk1391 2 года назад
Perfect Video Man!!!
@KieCodes
@KieCodes 2 года назад
Thank you. 🙏
@ruksharalam173
@ruksharalam173 11 месяцев назад
Really useful vid! I'm just getting into genetic algo. Can you make tutorial vids on PyGAD, python library for genetic algo.?
@flyingsquirrel3271
@flyingsquirrel3271 3 года назад
Awesome video! Also: As a rustacean I really apprechiate the type hinting ;-)
@KieCodes
@KieCodes 3 года назад
Thank you. 🙏
@GK-ee7mw
@GK-ee7mw 2 года назад
The affiliate link for kit isn't working for me (running on Windows in Chrome)
@KieCodes
@KieCodes 2 года назад
Thank you for bringing this to my attention.
@tsaiwarrant1650
@tsaiwarrant1650 3 года назад
Hello, Kie Code. I tried to follow the video and type the code in my notepad++ and run it. But there is a problem of the population in run_evolution. Please help me. This is the error: Traceback (most recent call last): File "test.py", line 145, in generation_limit=100 File "test.py", line 112, in run_evolution population = populate_func() TypeError: generate_population() got an unexpected keyword argument 'generation_length' My code is: from random import choices, randint, randrange, random from typing import List, Optional, Callable, Tuple from collections import namedtuple import time from functools import partial Genome = List[int] Population = List[Genome] # To keep the seperation of functions, we use parameter to call functions FitnessFunc = Callable[[Genome], int] PopulateFunc = Callable[[], Population] SelectionFunc = Callable[[Population, FitnessFunc], Tuple[Genome, Genome]] CrossoverFunc = Callable[[Genome, Genome], Tuple[Genome, Genome]] MutationFunc = Callable[[Genome], Genome] Thing = namedtuple('Thing',['name', 'value', 'weight']) # tuple can not be changed. things = [ Thing('Laptop', 500, 2200), Thing('Headphones', 150, 160), Thing('CoffeeMug', 60, 350), Thing('Notepad', 40, 333), Thing('WaterBottle', 30, 192), ] more_things = [ Thing('Mints', 5, 25), Thing('Socks', 10, 38), Thing('Tissues', 15, 80), Thing('Phone', 500, 200), Thing('Baseball Cap', 100, 70), ] + things def generate_genome(length: int) -> Genome: return choices([0,1], k=length) def generate_population(size: int, genome_length: int) -> Population: return [generate_genome(genome_length) for _ in range(size)] def fitness(genome: Genome, things: [Thing], weight_limit: int) -> int: if len(genome)!=len(things): raise ValueError("genome and things must be of the same length.") weight = 0 # record the weight value = 0 # record the value # calculate the weight and value if it is selected. for i, thing in enumerate(things): if genome[i] == 1: weight += thing.weight value += thing.value if weight > weight_limit: return 0 return value # note: why not to simply call the fitness() because of software architecture and seperation concers. def selection_pair(population:Population, fitness_func:FitnessFunc) -> Population: return choices( population=population, weights=[fitness_func(genome) for genome in population], k=2 # this parameter draw states that we draw twice from our population to get a pair. ) def single_point_crossover(a:Genome, b:Genome) -> Tuple[Genome, Genome]: if len(a) != len(b): raise ValueError("Genomes a and b must be of same length.") length = len(a) if length < 2: return a, b p = randint(1, length-1) # select a random bit as flag. crossover the last bits between two of them. return a[0:p] + b[p:], b[0:p] + a[p:] def mutation(genome:Genome, num:int=1, probability:float=0.5) -> Genome: for _ in range(num): index = randrange(len(genome)) genome[index] = genome[index] if random() > probability else abs(genome[index]-1) return genome def run_evolution( populate_func: PopulateFunc, fitness_func: FitnessFunc, fitness_limit: int, selection_func: SelectionFunc = selection_pair, crossover_func: CrossoverFunc = single_point_crossover, mutation_func: MutationFunc = mutation, generation_limit: int = 100, )-> Tuple[Population, int]: population = populate_func() # This is the line with error for i in range(generation_limit): population = sorted(population, key=lambda genome: fitness_func(genome), reverse=True) if fitness_func(population[0]) >= fitness_limit: break next_generation = population[0:2] for j in range(int(len(population) / 2) - 1): parents = selection_func(population, fitness_func) offspring_a, offspring_b = crossover_func(parents[0], parents[1]) offspring_a = mutation_func(offspring_a) offspring_b = mutation_func(offspring_b) next_generation += [offspring_a, offspring_b] population = next_generation return population, i start = time.time() population, generations = run_evolution( populate_func=partial( generate_population, size=10, generation_length=len(things) ), fitness_func=partial( fitness, things=things,weight_limit=3000 ), fitness_limit=740, generation_limit=100 ) end = time.time() def genome_to_things(genome: Genmoe, things:[Thing]) -> [Thing]: result = [] for i, thing in enumerate(things): if genome[i] == 1: result += [thing.name] return result print(f"numberof generations: {generateions}") print(f"time: {end - start}s") print(f"best solution: {genome_to_things(population[0], things)}")
@KieCodes
@KieCodes 3 года назад
Hey. Thanks for you comment. You need to call generate_population with the named parameter *genome_length* and not *generation_length* . So the populate_func parameter must be set like this: populate_func=partial(generate_population, size=10, *genome_length* =len(things)) I hope that makes sense and helps. Have a great day! P.S. Sorry or the late response, but youtube classified this comment mistakenly as spam, because of all the code in it.
@wouterr6063
@wouterr6063 4 года назад
Hi kie codes, First of all, I really like your explanation of Genetic Algorithms. The things that you could improve however are the code sections. You could turn off autocorrection in you editor as it just clobbers the view of the code. Also, although the type hinting in your code does makes it more readable for seasoned python programmers, it only confuses beginners. Because the video is about Genetic Algorithms and not about type hinting, I think the cons outweigh the pros. Finally, I can follow the high level explanation of the algorithm (other video), but the code parts go to fast in my case. I hope this helps.
@KieCodes
@KieCodes 4 года назад
Hello Wouter, thank you so much for your feedback. First. Yes, I will disable the autocomplete next time. I hoped it makes the recording less error-prone and faster, but it just clutters the video. Regarding the type hints: I totally understand where you are coming from. In my opinion type hints are a really good feature for python and I am a promoter of using them. :D It also helps me to describe the data structures for an algorithm while actually coding something which gets lost in untyped languages a lot. That said: I think the pros outweigh the cons. :-) I guess the code is a little too fast, but I hope it is a good addition to the github repo and helps you nonetheless. Have a great day and again: Thank you for your feedback.
@olegsafronov9936
@olegsafronov9936 3 года назад
@@KieCodes Please don't. You did everything right. You make people follow this standard (type hinting) despite the topic we discuss. It's like basic programming etiquette. Also, python beginners trying to study GA?.. Seriously? :) I doubt they exist. If they don't know Python syntax and studying GA then it means they know some different language. So problem Wouterr mentioned is not quite actual.
@007Sylvester007
@007Sylvester007 3 года назад
@@olegsafronov9936 Well, here I am :) New in Python, implementing a GA for an uni project. I can't say that I am fluent in other languages but the video here and the previous one made me understand a lot about how the GA work even without previous in-depth knowledge. Also, Python's syntax is so easy to understand. Great video and thanks for the help @Kie Codes
@olegsafronov9936
@olegsafronov9936 3 года назад
@@007Sylvester007 Congrats with your venture :) But all fame is to author of this video which is @Kie Codes :)
@pinypon7386
@pinypon7386 2 года назад
excellent!
@KieCodes
@KieCodes 2 года назад
Thank you. 🙏
@mandana4286
@mandana4286 3 года назад
yre theeee beeesssst, this was so helpfulllllll
@KieCodes
@KieCodes 3 года назад
Thank you so much!
@wewonn5530
@wewonn5530 3 года назад
thank you for the video. may I ask do you used roulette wheel selection for the selection?
@KieCodes
@KieCodes 3 года назад
Yes exactly: Fitness proportionate selection, also known as roulette wheel selection! Well spotted!
@wewonn5530
@wewonn5530 3 года назад
@@KieCodes thank you!!!
@KieCodes
@KieCodes 3 года назад
You are more than welcome my friend. 🙏 Rock on! 🚀
@mohammedal-eryani3085
@mohammedal-eryani3085 2 года назад
Hello, Your video was great it helped me to understand GA, thank you and good job, Though I have a question, In your example, you demonstrate the possibilities of filling the bag with 3 Kilo, My question is if we have different bags with different sizes how can we fix this, I was trying to implement it to find the optimal solar panel stringing and the problem here that we could have multiple groups of panels with different power output need to be connected to different inverters that accept the same power so how can we decide what is the best inverter for each group some inverter could accept a different number of groups, can you provide an example of that please
@tomkersten9764
@tomkersten9764 3 года назад
These videos are awesome
@KieCodes
@KieCodes 3 года назад
Thanks Tom! 🙏
@emmanuelonuoha1880
@emmanuelonuoha1880 3 года назад
i wish you could share the exact code you ran in the video and not just the template. I dont have a lot of expereience programming and ive been stuck for two days adding comments and trying to duplicate the results in the video from the version on github. Is it still available Kie?
@KieCodes
@KieCodes 3 года назад
Hey Södra, as far as I know the code in the linked repository is the one from the video. Just split up into different files. What problems are you facing? If you use discord, consider joining my DIscord serve (link in description), because it is often times easier to chat there than to help through YT comments. Have a great day!
@EduardoRohdeEras
@EduardoRohdeEras 3 года назад
That might help me to do that in fortran. Thanks!
@KieCodes
@KieCodes 3 года назад
Amazing. Glad I could help. Thank you!
@clementmwai1055
@clementmwai1055 Год назад
Hello @Kie codes what if you you try to evenly distribute the weights evenly between n number of containers?
@KieCodes
@KieCodes Год назад
Hey. You would need to change your fitness function in a way that an uneven distribution has less fitness than a even one. For instance using means squared error to add a penalty.
@clementmwai1055
@clementmwai1055 Год назад
Thanks so much 🙏
@soufiane7792
@soufiane7792 3 года назад
Amazing video ! Also: When you explaind the abs trick can you tell me the name of the song that was playing.
@KieCodes
@KieCodes 3 года назад
Thank you! Sure. The song is called "Operatic 3" by "Vibe Mountain".
@dmrn2009
@dmrn2009 3 года назад
Where did you buy that cap?
@KieCodes
@KieCodes 3 года назад
Hey Dm, It's a German brand. You find it here: www.nebelkind.com/de/pixelherz-grau-snapback.html I hope that helps.
@dmrn2009
@dmrn2009 3 года назад
@@KieCodes Vielen Dank :)
@pablomartinez1504
@pablomartinez1504 Год назад
my solution incluides the notepad and exceeds the weight limit. I have tried to copy the code as closely as possible but don't see an error. Any ideas?
@KieCodes
@KieCodes Год назад
Hey Pablo. It is quite hard to help without seeing the code. If you could reach out me on Discord I am happy to help. Link to the server is on the channel and below the video. Cheers
@sahl8732
@sahl8732 3 года назад
What book about genetic algorithms do you recommend?
@KieCodes
@KieCodes 3 года назад
Hey Yung, I haven't read a book about it, so it is hard for me to recommend one. I hope my video helped you to give you an introduction none the less and I will also do more videos about different implementations of GAs in the near future, which hopefully will give you more insights. Have a great day!
@stevepires1876
@stevepires1876 5 месяцев назад
great job. think i can use this to finally solve training ai to play tetris :)
@KieCodes
@KieCodes 5 месяцев назад
Let me know how it goes. I still that on my list. 😅
@stevepires1876
@stevepires1876 5 месяцев назад
@@KieCodes will do. after 2 weeks of trying DQN and failing to learn effective strategies, i have hope for genetic algorithm
@stevepires1876
@stevepires1876 5 месяцев назад
@@KieCodes so I got my Tetris game clearing lines. Only can do max of 4 per game. Doesn't seem to be improving much. Going to keep adjusting things. Trying to train for Tetris has been kicking my butt. Lol.
@AbdulAzeem-hz3ex
@AbdulAzeem-hz3ex 3 года назад
Can you please guide me for this error, i followed the complete code but having an issue in this part (I am using google colab): def fitness(genome: Genome, things: [Thing], weight_limit: int) -> int: if len(genome) != len (things): raise ValueError("genome and things must be of the same length") weight = 0 value = 0 for i, thing in enumerate(things): if genome[i]== 1: (( weight += thing.weight value = thing.value + 1 )) In this part that i have put in bracket it gives me this error : TypeError: unsupported operand type(s) for +=: 'int' and 'str'
@KieCodes
@KieCodes 3 года назад
Somehow thing.weight seems to be a string and not an integer. But the mistake most likely happens somewhere else in your code.
@AbdulAzeem-hz3ex
@AbdulAzeem-hz3ex 3 года назад
@@KieCodes Well I went step by step with your tutorial. However, I will cross-check again.
@cy-ti8ln
@cy-ti8ln 3 года назад
What name is that tool you type to code ? Juputer notebook ?
@KieCodes
@KieCodes 3 года назад
Just regular pycharm.
@vj8355
@vj8355 3 года назад
Hi, when i run the code the error population, generations = run_evolution( TypeError: cannot unpack non-iterable NoneType object, may I know what I am doing wrong here
@KieCodes
@KieCodes 3 года назад
Please check that you are running this on Python 3.7 or above.
@vj8355
@vj8355 3 года назад
@@KieCodes I am using python 3.9
@KieCodes
@KieCodes 3 года назад
That should work. Could you please post the whole function call here and mark the line in which the error is occurring. When you have an unintentional None, please check the spelling of all the variables as well.
@vj8355
@vj8355 3 года назад
@@KieCodes Sometimes my code work and I get solutions, but the number of generations is always 0, fitness_func=partial( fitness, things=more_things, weight_limit=3000 ),
@vj8355
@vj8355 3 года назад
@@KieCodes i found the problem, thanks for replying, you're a legned
@m.tufailalichaudhary1218
@m.tufailalichaudhary1218 3 года назад
At 7:21 from where this populate_func() come from please help
@KieCodes
@KieCodes 3 года назад
It is handed over at 9:32.
@johnfeldhausen5576
@johnfeldhausen5576 2 года назад
What is the name of your IDE and predictive text interpreter?
@KieCodes
@KieCodes 2 года назад
I am using PyCharm.
@s.n.aaruran8411
@s.n.aaruran8411 Год назад
Bro can you make a video of coding part for the generation of automatic timetable
@chaosrider100
@chaosrider100 2 года назад
for the fitness function: why use a for loop, when you could just multiply two vectors ???
@KieCodes
@KieCodes 2 года назад
Its just to make it more accessible for beginners.
@themrevil6373
@themrevil6373 3 года назад
when I try to code an AI I just keep getting "UserWarning: WARN: Box bound precision lowered by casting to float32"
@gameandgamingyt
@gameandgamingyt 2 года назад
how can i go to the genetic algorithms in python?
@KieCodes
@KieCodes 2 года назад
Hello. What do you mean?
@farnazfarhand5957
@farnazfarhand5957 3 года назад
thanks for your amazing tutorial and coding. can we find the code anywhere?
@KieCodes
@KieCodes 3 года назад
Thank you. A link to the github repo is in the description below.
@archardor3392
@archardor3392 Год назад
My bro, you are a gem. Why did you stop uploading :(?
@KieCodes
@KieCodes 9 месяцев назад
I was very busy with client work the last year. I am back now.
@saemson94
@saemson94 3 года назад
Danke für das Video! Wirklich top Qualität was du da ablieferst! Könntest du mir bitte noch verraten wo man deinen nicen Programmierhelm kaufen kann? Kannst gerne auch einen affiliate link posten falls möglich. Hab das Gefühl dann schwirren mir plötzlich die Code-Lösungen unters Dach.
@KieCodes
@KieCodes 3 года назад
Hey Simon, danke dir für die netten Worte. Hier der Link zu dem Helm: www.amazon.de/gp/product/B07GVCLBK2 Die Cap hilft auf jedenfall bei der Ideenfindung. 😅 Hab nen tollen Tag und bleib Gesund. Cheers!
@daesk
@daesk 2 года назад
I just have a question, how could I develop a "generic" genetic algorithm? like, can I use this for implementation what purposes? thanks in advance!
@KieCodes
@KieCodes 2 года назад
I am not sure what you mean. But the implementation I did is pretty adaptable to any problem you might have.
@daesk
@daesk 2 года назад
@@KieCodes sorry english is not my first language but now I understood thank you
@abhinavgv5178
@abhinavgv5178 3 года назад
in your github repository i think theres a missing file. the file to define partial. because everything else is there but that one defining file.
@KieCodes
@KieCodes 3 года назад
Please check your python version to be 3.6 or higher.
@abhinavgv5178
@abhinavgv5178 3 года назад
@@KieCodes Its python 3.8.2
@KieCodes
@KieCodes 3 года назад
Then it should work. Its part of python‘s functools library. Check your imports.
@abhinavgv5178
@abhinavgv5178 3 года назад
@@KieCodes okay cool
@Nikhil-hi1qs
@Nikhil-hi1qs 2 года назад
Yo have made a nice video. But i hope u dont mind if I give a slight improvement suggestion. Your coding is really cumbersome to implement, plz make it simpler in the videos. In the source code you can implement the concepts and other best practices. For Ex: ' choices() got an unexpected keyword argument 'weights' ' - These kind of multiple errors were found when I tried to implement it in jupyter.
@aicancode5676
@aicancode5676 3 года назад
may i know what ide is this
@KieCodes
@KieCodes 3 года назад
Sure! I am using PyCharm.
@aicancode5676
@aicancode5676 3 года назад
Thanks!
@736939
@736939 Год назад
Genome = List[int] # that's already something new :))))
@arashhn8678
@arashhn8678 2 года назад
would someone be so kind as to explain the last part where we use "partial"?
@KieCodes
@KieCodes 2 года назад
Hey. What exactly are you struggling with? If you want, join the Discord server. I and a lot of other helpful developers are there to help yoiu understand partial and any question you have along the way. Cheers
@arashhn8678
@arashhn8678 2 года назад
@@KieCodes Oh okay, thank you so much! Just joined there.
@wasiqkhan300
@wasiqkhan300 2 года назад
Hi, It's the perfect video. Can you please make for job shop scheduling problem?
@KieCodes
@KieCodes 2 года назад
I have it on my list. Thank you!
@wasiqkhan300
@wasiqkhan300 2 года назад
@@KieCodes thanks for the reply. Can you please share the link I am not able to find a scheduling problem
@KieCodes
@KieCodes 2 года назад
I haven’t created it yet. I have it on my list of videos I want to create.
@wasiqkhan300
@wasiqkhan300 2 года назад
@@KieCodes Ok,thanks .
@maniaczek12300
@maniaczek12300 3 года назад
How do i know what fitness limit should i set?
@KieCodes
@KieCodes 3 года назад
That really depends on your problem.
@maniaczek12300
@maniaczek12300 3 года назад
@@KieCodes I mean, if i have to get best solution using this, and i dont know what is that best solution should i just skip that limit?
@KieCodes
@KieCodes 3 года назад
GAs are not for finding the best solution. They are used for finding a good enough solution. If you don’t need a fitness limit you can skip it and just run the algo for as long as you want.
@FreakingRockstar101
@FreakingRockstar101 3 года назад
Great explanation, but your code is not easy to follow because of inability to see it when it reaches right limit or your autofinish covers things. Also my main complaint is that your code here doesn't match the code in your repository so connections can be difficult to draw.
@KieCodes
@KieCodes 3 года назад
Thank you for your feedback. I will improve that in future videos! 🙏
@FreakingRockstar101
@FreakingRockstar101 3 года назад
@@KieCodes I have a feeling I'll be a long time viewer of your videos.
@KieCodes
@KieCodes 3 года назад
Thank you. 🙌 That‘s really motivating.
@qiguosun129
@qiguosun129 2 года назад
Hi, Kie codes, I like your high-quality video. Since this is my first time learning Genetic Algorithms, I feel a little hard to follow your ideas. Nevertheless, I think it is a fantastic tutorial on this topic, and thank you for posting this video.
@KieCodes
@KieCodes 2 года назад
Thank you. 🙏
@SintaxErorr
@SintaxErorr 3 года назад
this was my code when I made mine import random, time class Chromosome: fitness = None genomes = [] mutation_rate = None def __init__(self, length,mut_rate): self.genomes = [random.randint(0,1) for x in range(length)] self.mutation_rate = mut_rate def calculate_fitness(self,expected_weight, object_weights): total_weight = sum([object_weights[x][1] if self.genomes[x] == 1 else 0 for x in range(len(self.genomes))]) if total_weight > expected_weight: total_weight = 0 self.fitness = total_weight/expected_weight def cross_over(self,parents): split = random.randint(0,len(parents[0].genomes)-1) self.genomes = [parents[0].genomes[x] if x
@wilfredomartel7781
@wilfredomartel7781 9 месяцев назад
😊
@DennisPing
@DennisPing 3 года назад
What I found more interesting was your Python architecture and design. That is stuff you can't learn from google. You need to learn it from a professor. I wrote all my populate, selection, fitness, mutation functions as standalone functions, but you're saying that it's better to abstract-out the functions. Thus, if you wanted to use a different "thing" you would just change the "thing" class rather than your algorithm.
@KieCodes
@KieCodes 3 года назад
Thank you. Exactly. I try to separate the algorithm from its specific application in order to make the algorithm reusable. In my design, this is done via function composition, where I use functions to parameterize other functions. But there are many different ways to get this separation of concerns.
@nosuchthing8
@nosuchthing8 Год назад
Hey, great stuff. One thing. It's pronounced nap sack. The k is silent.
@caiziyuan1345
@caiziyuan1345 3 года назад
Could you please post all the code in your video? Thanks a lot!
@KieCodes
@KieCodes 3 года назад
Its all on github. Link in the description.
@arihantgupta4550
@arihantgupta4550 Год назад
can you pls provide the source code for this , this video was very helpful
@KieCodes
@KieCodes Год назад
Hey. Thats great. Thank you. There should be a link in the video description.
@mandana4286
@mandana4286 3 года назад
could you also make a video for GA on MATLAB plsssss…
@KieCodes
@KieCodes 3 года назад
I am sorry, I am not really using Matlab for anything.
@codesoon9668
@codesoon9668 2 года назад
I was examining your code and I prove it on my IDE and I don't know why [Thing] is not recognized in the list. from line 40 to along the code
@KieCodes
@KieCodes 2 года назад
Can you post the exact error message here?
@codesoon9668
@codesoon9668 2 года назад
@@KieCodes okay wait a minute
@codesoon9668
@codesoon9668 2 года назад
@@KieCodesLine 139,44 Line 139,56 as well. I mean these lines: def fitness(genome: Genome, things: [Thing], weight_limit: int) -> int: def genome_to_things(genome:Genome,things: [Thing]) -> [Thing]:
@KieCodes
@KieCodes 2 года назад
Please make sure you are using Python 3.8 or above. Cheers
@codesoon9668
@codesoon9668 2 года назад
@@KieCodes I'm using python 3.10.0
@sualehalam4259
@sualehalam4259 3 года назад
Idk why brother but I found your code pretty hard and complex :(
@KieCodes
@KieCodes 3 года назад
I am sorry to hear that, feel free to ask your questions here or in the discord. Cheers!
@mattnelson6798
@mattnelson6798 3 года назад
The code download source is not complete
@KieCodes
@KieCodes 2 года назад
Whats missing?
@mattnelson6798
@mattnelson6798 2 года назад
I was looking for all the code you wrote in the video. The one i found on GIT is not the same
@mattnelson6798
@mattnelson6798 2 года назад
@@KieCodes Thanks for replying though!
@KieCodes
@KieCodes 2 года назад
What are you missing in there?
@mattnelson6798
@mattnelson6798 2 года назад
@@KieCodes in short the code I found did not look like the code I coded along with in this video. I probably missed something along the way. In any case thank you for this video, it was so helpful. I just made my first Genetic Algorithm to solve a real world problem. Your videos are great and by the far the most in depth, well put together. Great channel
@AnoopSingh-gm7pg
@AnoopSingh-gm7pg 2 года назад
hello Kie, population,generations=run_evolution( populate_func=partial( generate_population,size=10,genome_length=len(things) ), fitness_func=partial( fitness,things=things,weight_limit=3000 ), fitness_limit=740, generation_limit=100 ) im facing TypeError: '
@KieCodes
@KieCodes 2 года назад
Hey Anoop. In order to help I would need to see the full code and errors. If you want, please join the Discord it is way easier to help there. Thanks.
@merrynoor6206
@merrynoor6206 3 года назад
i need this code
@KieCodes
@KieCodes 3 года назад
There should be a link to github in the description.
@merrynoor6206
@merrynoor6206 2 года назад
I want to learn genetic algorithm from scratch please make more videos for beginners sir
@guru_01
@guru_01 Год назад
Suggestions: don't add annoying music in the background, it disturbs the focus
@KieCodes
@KieCodes Год назад
True. I learned that now.
@JP-xm3qf
@JP-xm3qf 2 года назад
Are you Polish/Slavic? Lot’s of great mathematicians and scientists here
@ege1217
@ege1217 13 дней назад
7:45
@adimascahyaning9202
@adimascahyaning9202 2 года назад
Is it possible after 99 generations, we did not get a correct solution?
@KieCodes
@KieCodes 2 года назад
Depending on the problem you are trying to solve, that might be the case.
@adimascahyaning9202
@adimascahyaning9202 2 года назад
@@KieCodes Oh ya, I got it. Thank you!
@DevOpsDirective
@DevOpsDirective 4 года назад
abs(value - 1) ...VERSUS... int(not value) 🙃
@alexandre3989
@alexandre3989 4 года назад
1 - value
@KieCodes
@KieCodes 4 года назад
That’s what I saw later as well, but I figured there is no need to rerecord everything and I added this voiceover 😅 very good catch Alexandre.
@DevOpsDirective
@DevOpsDirective 4 года назад
@@alexandre3989 value ^ 1 🤷‍♂️ (Your proposed solution is the simplest though...)
Далее
Genetic Algorithms Explained By Example
11:52
Просмотров 319 тыс.
Я НЕ ОЖИДАЛ ЭТОГО!!! #Shorts #Глент
00:19
314 - How to code the genetic algorithm in python?
20:19
Binary Search Algorithm - Computerphile
18:34
Просмотров 158 тыс.
Please Master These 10 Python Functions…
22:17
Просмотров 112 тыс.
Genetic Algorithms - Jeremy Fisher
50:07
Просмотров 53 тыс.
Genetic Algorithm In Python Super Basic Example
17:42
Просмотров 123 тыс.
13. Learning: Genetic Algorithms
47:16
Просмотров 520 тыс.