No video

Genetic Algorithm from Scratch in Python (tutorial with code)

  Рет қаралды 144,756

Kie Codes

Kie Codes

Күн бұрын

Пікірлер: 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
@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 6 ай бұрын
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
@ronboprime
@ronboprime Ай бұрын
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!
@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! 🚀
@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 3 жыл бұрын
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! 🚀
@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
@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!
@isbeb507
@isbeb507 3 жыл бұрын
hey this was really good! im gonna check out your other stuff.
@KieCodes
@KieCodes 3 жыл бұрын
Thank you. 🙏
@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 :)
@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
@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.
@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! 🙏
@_zeppeh
@_zeppeh 2 жыл бұрын
Yeah nice high quality production! You got my respect!
@KieCodes
@KieCodes 2 жыл бұрын
Thank you. 🙏
@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
@dejan919
@dejan919 2 жыл бұрын
Kie, i think some uf us would need a tutorial on Callables after this video :D
@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
@tobiasnickel3750
@tobiasnickel3750 2 жыл бұрын
thanks, this tutorial is awesome. I coded along, but in typeScript. I am very glad that I now have a better understanding of generic algorithms. I would kind of name the approach in this video "directed brute force"
@KieCodes
@KieCodes 2 жыл бұрын
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! 🙏
@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!
@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.
@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!
@anonymousvevo8697
@anonymousvevo8697 Жыл бұрын
i really like the way you code in python !
@souravdeb6126
@souravdeb6126 Жыл бұрын
Respect++ for maintaining good coding practices (aka architectural thoughts) which a very few tutors do!!
@KieCodes
@KieCodes Жыл бұрын
Thank you for noticing!
@mohamedfouadhanani
@mohamedfouadhanani 2 жыл бұрын
very good explanation, amazingly written code. Awesome video.
@KieCodes
@KieCodes 2 жыл бұрын
Thank you. 🙏
@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.
@IgorSantarek
@IgorSantarek Жыл бұрын
Very good presentation!
@v-for-victory
@v-for-victory 2 жыл бұрын
Great video. I really like your style of explaining.
@KieCodes
@KieCodes 2 жыл бұрын
Thank you. 🙏
@736939
@736939 Жыл бұрын
Genome = List[int] # that's already something new :))))
@debd.9220
@debd.9220 3 жыл бұрын
A new subscriber. 🤗 Thanks for your explanatory teachings.
@KieCodes
@KieCodes 3 жыл бұрын
Thank you for being here! 💪
@r11sr
@r11sr Жыл бұрын
thank you! Appreciated
@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. 🙏
@zafersaglk1391
@zafersaglk1391 2 жыл бұрын
Perfect Video Man!!!
@KieCodes
@KieCodes 2 жыл бұрын
Thank you. 🙏
@cyberpunk_edgerunners
@cyberpunk_edgerunners Жыл бұрын
amazing work , love it
@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.?
@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.
@philosophiabme
@philosophiabme 2 жыл бұрын
Great video! This is really useful :)
@KieCodes
@KieCodes 2 жыл бұрын
Thank you. 🙏 I am glad it helped!
@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.
@marco.nascimento
@marco.nascimento 3 жыл бұрын
Awesome video!!
@KieCodes
@KieCodes 3 жыл бұрын
Thank you!
@themrevil6373
@themrevil6373 3 жыл бұрын
when I try to code an AI I just keep getting "UserWarning: WARN: Box bound precision lowered by casting to float32"
@doyourealise
@doyourealise 2 жыл бұрын
subscribed :) keep on making more videos on genetic algorithms.
@KieCodes
@KieCodes 2 жыл бұрын
I will try! Glad you liked it! 🙌
@flyingsquirrel3271
@flyingsquirrel3271 3 жыл бұрын
Awesome video! Also: As a rustacean I really apprechiate the type hinting ;-)
@KieCodes
@KieCodes 3 жыл бұрын
Thank you. 🙏
@davidmateosgarriga8755
@davidmateosgarriga8755 3 жыл бұрын
Great video! Thanks!
@KieCodes
@KieCodes 3 жыл бұрын
You are more than welcome my friend. 🙏 Rock on! 🚀
@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
@pinypon7386
@pinypon7386 2 жыл бұрын
excellent!
@KieCodes
@KieCodes 2 жыл бұрын
Thank you. 🙏
@peterdonnelly1074
@peterdonnelly1074 2 жыл бұрын
Thanks. Very good.
@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".
@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.
@mandana4286
@mandana4286 3 жыл бұрын
yre theeee beeesssst, this was so helpfulllllll
@KieCodes
@KieCodes 3 жыл бұрын
Thank you so much!
@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.
@tomkersten9764
@tomkersten9764 3 жыл бұрын
These videos are awesome
@KieCodes
@KieCodes 3 жыл бұрын
Thanks Tom! 🙏
@EduardoRohdeEras
@EduardoRohdeEras 3 жыл бұрын
That might help me to do that in fortran. Thanks!
@KieCodes
@KieCodes 3 жыл бұрын
Amazing. Glad I could help. Thank you!
@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.
@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 .
@s.n.aaruran8411
@s.n.aaruran8411 Жыл бұрын
Bro can you make a video of coding part for the generation of automatic timetable
@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
@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!
@guru_01
@guru_01 Жыл бұрын
Suggestions: don't add annoying music in the background, it disturbs the focus
@KieCodes
@KieCodes Жыл бұрын
True. I learned that now.
@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.
@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!
@nosuchthing8
@nosuchthing8 Жыл бұрын
Hey, great stuff. One thing. It's pronounced nap sack. The k is silent.
@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! 🚀
@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.
@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
@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.
@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 :)
@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!
@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?
@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.
@wilfredomartel7781
@wilfredomartel7781 10 ай бұрын
😊
@SintaxErorr
@SintaxErorr 4 жыл бұрын
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
@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.
@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!
@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 :)
@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. 🙏
@JP-xm3qf
@JP-xm3qf 2 жыл бұрын
Are you Polish/Slavic? Lot’s of great mathematicians and scientists here
@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
@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
@johnfeldhausen5576
@johnfeldhausen5576 2 жыл бұрын
What is the name of your IDE and predictive text interpreter?
@KieCodes
@KieCodes 2 жыл бұрын
I am using PyCharm.
@ege1217
@ege1217 29 күн бұрын
7:45
@gameandgamingyt
@gameandgamingyt 2 жыл бұрын
how can i go to the genetic algorithms in python?
@KieCodes
@KieCodes 2 жыл бұрын
Hello. What do you mean?
@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 🙏
@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.
@aicancode5676
@aicancode5676 3 жыл бұрын
may i know what ide is this
@KieCodes
@KieCodes 3 жыл бұрын
Sure! I am using PyCharm.
@aicancode5676
@aicancode5676 3 жыл бұрын
Thanks!
@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
@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.
@backflipbro790
@backflipbro790 3 жыл бұрын
This is a well-made video, but way to complicated for a beginner course. He didn't explain the code very much and talked really fast.
@KieCodes
@KieCodes 3 жыл бұрын
Thank you. My videos are actually aimed at programmers with a couple of years experience. I hope you learned something nonetheless.
@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.
@cy-ti8ln
@cy-ti8ln 4 жыл бұрын
What name is that tool you type to code ? Juputer notebook ?
@KieCodes
@KieCodes 4 жыл бұрын
Just regular pycharm.
@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...)
@mattnelson6798
@mattnelson6798 3 жыл бұрын
The code download source is not complete
@KieCodes
@KieCodes 3 жыл бұрын
Whats missing?
@mattnelson6798
@mattnelson6798 3 жыл бұрын
I was looking for all the code you wrote in the video. The one i found on GIT is not the same
@mattnelson6798
@mattnelson6798 3 жыл бұрын
@@KieCodes Thanks for replying though!
@KieCodes
@KieCodes 3 жыл бұрын
What are you missing in there?
@mattnelson6798
@mattnelson6798 3 жыл бұрын
@@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.
@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.
@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.
Genetic Algorithms Explained By Example
11:52
Kie Codes
Рет қаралды 321 М.
Genetic Algorithms in Python - Evolution For Optimization
26:10
NeuralNine
Рет қаралды 13 М.
Алексей Щербаков разнес ВДВшников
00:47
Идеально повторил? Хотите вторую часть?
00:13
⚡️КАН АНДРЕЙ⚡️
Рет қаралды 18 МЛН
Box jumping challenge, who stepped on the trap? #FunnyFamily #PartyGames
00:31
Family Games Media
Рет қаралды 33 МЛН
UNO!
00:18
БРУНО
Рет қаралды 4,9 МЛН
Snake learns with NEUROEVOLUTION (implementing NEAT from scratch in C++)
28:08
Genetic Algorithm in Python generates Music (code included)
11:50
Essential AI prompts for developers
8:31
Visual Studio Code
Рет қаралды 54 М.
The Knapsack Problem & Genetic Algorithms - Computerphile
12:13
Computerphile
Рет қаралды 227 М.
314 - How to code the genetic algorithm in python?
20:19
DigitalSreeni
Рет қаралды 7 М.
The moment we stopped understanding AI [AlexNet]
17:38
Welch Labs
Рет қаралды 936 М.
Modern Python logging
21:32
mCoding
Рет қаралды 177 М.
Python Decorators in 15 Minutes
15:14
Kite
Рет қаралды 437 М.
Genetic Algorithm In Python Super Basic Example
17:42
The Builder
Рет қаралды 124 М.
Алексей Щербаков разнес ВДВшников
00:47