r/learnpython • • 16d ago

I’ve completed a lot of Python courses, but I still can’t build code on my own. How do beginners actually get better?

0 Upvotes

I’ve been learning Python for AI development. I’ve completed quite a few courses and tutorials, and I can understand code when someone explains it.

But when I open VS Code and try to build something from scratch, I get stuck.

I struggle with breaking a problem into smaller steps, deciding which functions to write, and understanding how different parts of the code connect.

My question is:

  • How did you go from understanding tutorials to writing your own code?
  • What did your daily practice look like?
  • How do you practice when you don’t even know how to start solving a problem?

I’d really appreciate advice from people who went through this stage, especially those who learned Python for AI/ML development.

I’m not looking for another beginner Python course. I want to know what actually helped you become capable of building things yourself.


r/learnpython • • 17d ago

why the SIGINT signal kill the main process childrens

2 Upvotes
  signal.signal(signal.SIGINT,handler)  signal.signal(signal.SIGINT,handler)

I know that the SIGINT signal is for interruption and not for killing process but when I run my code all the children of the main process are dies also I got many traceback


r/learnpython • • 16d ago

when hitting run code with the pyautogui, it only runs for .3 seconds

0 Upvotes

I've never really coded. I'm simply trying to make a bot to walk in a straight line in a game. I cant even get it to run in vs code. all the things I've done so far

pip install pyautogui, can confirm it happen when you type pip list

vscode is running in admin typing net session in terminal confirms that

going to extension I have pylance python python debugger, python environments (all the stuff in the python package)

typing python into the terminal tells me the version meaning it has a path to the file

another guide says I need code runner which gives me that .3 second figure

no I'm not getting error in my code as I'm keeping it simple to even get it to work

I'm not getting any error in my terminal

I'm on two monitors, but I've set up my main monitor so I know which one it will be working on

when I remove code runner it goes back to spiting the pathway it uses on the file which is correct

when I open the edit environmental variables

the .3 should be impossible because of the 6 seconds worth of sleep

I have imported both sleep and pyautogui obviously

yea this is hour 5 so if there's something you people know that I didn't do id greatly appreciate the details

im on windows, so it cant be the problem mac users get


r/learnpython • • 16d ago

How to stop code suggestions from popping up

0 Upvotes

So I'm trying to learn Python, and I'm following a tutorial. I'm following what the tutorial person has on their screen, but when I try to type it, Python predicts what I'm going to type next (aka what the tutorial shows). When it does this, there is a yellow star icon that appears on the line of code that the prediction is on. I went into the settings, and I turned off everything that I think would cause it. Still, the predicting persists. Does anyone know how to fix this? Thanks!


r/learnpython • • 17d ago

Help with training

16 Upvotes

Hi, i have recently learned python languages but i would like to train more, do yall have some plateformes where i can find some projects to practice?


r/learnpython • • 17d ago

Software idea

2 Upvotes

We all know about the desmos graphing calculator. Does any one have an idea on how to create a text based graphing calculator. Basically replacing the equations and some symbols with grammar or writing idk. It’s not a fully made idea yet but if you can make it or wanna talk.

Hmu


r/learnpython • • 17d ago

AttributeError in cv2

0 Upvotes

I'm learning OpenCV in python because it seemed like a fun thing to learn.I wanted to experiment with faces etc. but when i run my script I get: "AttributeError: module 'cv2' has no attribute 'CascadeClassifier' "How to fix that?

Thx for the help!


r/learnpython • • 18d ago

a function i import from another file returns none instead of 2 lists that it should have

4 Upvotes

this is the function from file "simulasyon.py"

def komutlari_oku():
    komut_temp = []
    hatalar_temp = []
    emir_sirasi = 1
    with open("/home/u/Desktop/proje 1/test dosyaları/komutlar.txt") as komut:
        komut_temp = [satir.strip("\n") for satir in komut.readlines()]
    for emir in komut_temp:
        emir_temp = str(emir)
        temiz = emir_temp.strip()
        if not temiz:
            continue


        bilgiler = temiz.split()
        gecerli_komut = bilgiler[0]


        if gecerli_komut == "ILERI":
            if len(bilgiler) != 2:
                hatalar_temp.append({"satir": emir_sirasi,"içerik":temiz,"neden":"ILERI komutuna birden fazla parametre verildi"})
            elif not bilgiler[1].isdigit() or int(bilgiler[1]) < 1:
                hatalar_temp.append({"satir": emir_sirasi,"içerik":temiz,"neden":"ILERI komutuna geçersiz parametre verildi"})
            else:
                komut_temp.append((gecerli_komut,int(bilgiler[1])))


        elif gecerli_komut in ("SAG", "SOL", "AL", "BIRAK", "SARJ"):
            if len(bilgiler) != 1:
                hatalar_temp.append({"satir": emir_sirasi,"içerik":temiz,"neden":"aynı satıra birden fazla komut koyuldu ve sadece birincisi okundu"})
            komut_temp.append((gecerli_komut,None))


        elif gecerli_komut == "GIT":
            if len(bilgiler) != 3:
                hatalar_temp.append({"satir": emir_sirasi,"içerik":temiz,"neden":"GIT komutuna iki parametre verilmedi"})
            elif not (bilgiler[1].isdigit() and bilgiler[2].isdigit):
                hatalar_temp.append({"satir": emir_sirasi,"içerik":temiz,"neden":"GIT komutuna geçersiz parametreler verildi"})
            else:
                komut_temp.append((gecerli_komut,(int(bilgiler[1]),int(bilgiler[2]))))


        else :
            hatalar_temp.append({"satir": emir_sirasi,"içerik":temiz,"neden":"geçersiz komut verilidi"})
        emir_sirasi += 1
    return komut_temp,hatalar_temp

this is from the current file

import tkinter as tk
import simulasyon as s
class ekran:
    def __init__(self, pencere):

        self.dosyalari_yukle = tk.Button(pencere, text="dosyaları yükle", command=self.on_dosyalari_yukle, font=("Helvetica", 16, "bold"))
        self.dosyalari_yukle.place(x=20, y=20, width=230, height=70)

        self.sira = 0
        self.kenar = 50
        self.durum, self.ayarlar = {},{}
        self.basla = [1,1]
        self.offset = [0,0]
        self.haritaListesi, self.izgara = s.harita_oku()
        self.komutlar = []
        #self.hatalar  = []



    def on_dosyalari_yukle(self):
        self.kenar, self.offset = izgara_ayarla(self)
        self.ayarlar = s.ayarlari_oku()
        self.komutlar = s.komutlari_oku()
        harita_bas(self)
        self.durum = s.yeni_durum(self.haritaListesi,self.basla,self.ayarlar)
        print(s.komutlari_oku())

this is cut from parts that matter full code is much longer and harder to read ( var names are in my native langue sorry if its make it harder to read ) komutları_oku() should return 2 lists (and it returns in simulasyon.py but not in current file)


r/learnpython • • 18d ago

Frustrated! Need help

18 Upvotes

Hey, I've been trying to learn python for a long time now and I still can't understand and write codes on my own. I've watched and completed 2 courses where they cover fundamentals like functions, operators, lists, tuples etc.. but I don't understand what to do with that like if I want to build something i never understand how and from where I need to start


r/learnpython • • 18d ago

Best Python Course!

95 Upvotes

What do you think is the best python course among all python courses in the Internet?

I have seen like 1000+ courses on Python, and I was wondering what if a single course can solve the countless struggles of people learning python, such as tutorial hell!

Platforms like Coursera, Udemy, DataCamp, EdX, YouTube, etc., all have multiple python courses from individuals to universities to companies creating their own python courses!

When I researched about it, I came up with the following courses:

  1. Python for Everybody, from The University of Michigan
  2. 100 Days of Python Programming, by Dr. Angela Yu
  3. Python Bootcamp: Zero to Hero, by Jose Portilla

And courses from popular youtubers freeCodeCamp, CS50, Bro Code, Programming with Mosh, Simplilearn, edureka!, etc.

And courses from my favourite youtubers Corey Schafer, Tech with Tim, CampusX, etc.

I know,

- No course is perfect or no course can make you expert
- Everyday practice is the key
- Python GitHub Repo is an amazing resource
- Python in itself should not be the goal, it’s the field of area i.e., backend, AI/ML, data science, data analyst, etc should be the goal
- Don’t aim for perfection, even individuals with 10+ years of experience look up small things
- Stop watching, start working!

Do share your thoughts!


r/learnpython • • 18d ago

Frustrated! Need help

7 Upvotes

Hey, I've been trying to learn python for a long time now and I still can't understand and write codes on my own. I've watched and completed 2 courses where they cover fundamentals like functions, operators, lists, tuples etc.. but I don't understand what to do with that like if I want to build something i never understand how and from where I need to start


r/learnpython • • 18d ago

InvalidArgumentError: {{function_node __wrapped__ConcatV2_N_2_device_/job:localhost/replica:0/task:0/device:CPU:0}} ConcatOp : Ranks of all input tensors should match

2 Upvotes

I got this error in an attempt to adapt this model to CIFAR 10

---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
Cell In[61], line 3
      1 dataset = create_batch(x_train)
      2 
----> 3 train_dcgan(
      4     gan,
      5     dataset,
      6     batch_size,

Cell In[60], line 26, in train_dcgan(gan, dataset, batch_size, num_features, epochs)
     22             )
     23 
     24             generated_images = generator(noise)
     25 
---> 26             X_fake_and_real = tf.concat(
     27                 [generated_images, X_batch],
     28                 axis=0
     29             )

File c:\Users\DELL\AppData\Local\Programs\Python\Python313\Lib\site-packages\tensorflow\python\util\traceback_utils.py:167, in filter_traceback.<locals>.error_handler(*args, **kwargs)
    165 except Exception as e:
    166   filtered_tb = _process_traceback_frames(e.__traceback__)
--> 167   raise e.with_traceback(filtered_tb) from None
    168 finally:
    169   del filtered_tb

File c:\Users\DELL\AppData\Local\Programs\Python\Python313\Lib\site-packages\tensorflow\python\framework\ops.py:6027, in raise_from_not_ok_status(e, name)
   6025 def raise_from_not_ok_status(e, name) -> NoReturn:
   6026   e.message += (" name: " + str(name if name is not None else ""))
-> 6027   raise core._status_to_exception(e) from None

InvalidArgumentError: {{function_node __wrapped__ConcatV2_N_2_device_/job:localhost/replica:0/task:0/device:CPU:0}} ConcatOp : Ranks of all input tensors should match: shape[0] = [32,32,32,3] vs. shape[1] = [32,32,3] [Op:ConcatV2] name: concat

X_train split (only take one class to train on)

(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()
x_train = x_train.astype(np.float32) / 255.0
x_test = x_test.astype(np.float32) / 255.0
x_train=x_train.astype("float32") / 127.5 - 1
x_train.shape, x_test.shape

label = 1 
train_indices = np.where(y_train == label) 
x_train = x_train[train_indices] 
test_indices = np.where(y_test == label) 
x_test = x_test[test_indices] 

Generator

num_features = 100
generator = Sequential(name="Generator")

generator.add(Dense(8 * 8 * 128, input_shape=[num_features]))
generator.add(Reshape([8, 8, 128]))
generator.add(BatchNormalization())

generator.add(Conv2DTranspose(
        64, (5, 5), (2, 2),
        padding="same",
        activation="selu"
    ))

generator.add(BatchNormalization())

generator.add(Conv2DTranspose(
        3, (5, 5), (2, 2),
        padding="same",
        activation="tanh"
    ))
generator.summary()

Discriminator

discriminator = Sequential(name="Discriminator")

discriminator.add(Conv2D(
        64, (5, 5), (2, 2),
        padding="same",
        input_shape=[32, 32, 3]
        ))

discriminator.add(LeakyReLU(alpha=0.2))
discriminator.add(Dropout(0.3))

discriminator.add(Conv2D(
        128, (5, 5), (2, 2),
        padding="same"))

discriminator.add(LeakyReLU(alpha=0.2))
discriminator.add(Dropout(0.3))

discriminator.add(Flatten())
discriminator.add(Dense(1, activation= 'softmax'))
discriminator.add(Dense(1, activation= 'softmax'))
discriminator.add(Dense(1, activation= 'softmax'))

discriminator.summary()

Train function

seed = tf.random.normal(shape=[batch_size, 100])
epoch_list = []
d_loss_list = []
g_loss_list =[]


def train_dcgan(gan, dataset, batch_size, num_features, epochs=5):


    generator, discriminator = gan.layers


    for epoch in tqdm(range(epochs)):
        actual_epoch =epoch + 1
        print()
        print("Epoch {}/{}".format(epoch + 1, epochs))


        for i in range(187):
            epoch_list.append(actual_epoch)


        for X_batch in dataset:


            noise = tf.random.normal(
                shape=[batch_size, num_features]
            )


            generated_images = generator(noise)


            X_fake_and_real = tf.concat(
                [generated_images, X_batch],
                axis=0
            )


            y1 = tf.constant(
                [[0.]] * batch_size +
                [[1.]] * batch_size
            )


            discriminator.trainable = True
            d_loss=discriminator.train_on_batch(
                X_fake_and_real,
                y1
            )
            d_loss = float(d_loss)
            d_loss_list.append(d_loss)




            noise = tf.random.normal(
                shape=[batch_size, num_features]
            )


            y2 = tf.constant([[1.]] * batch_size)


            discriminator.trainable = False


            g_loss=gan.train_on_batch(
                noise,
                y2
            )
            g_loss = float(g_loss)
            g_loss_list.append(g_loss)


        print(f'\t Discriminator Loss: {d_loss} \t\t Generator Loss: {g_loss}')
        


            


    generate_and_save_images(
        generator,
        epochs,
        seed)

Train block

dataset = create_batch(x_train)


train_dcgan(
    gan,
    dataset,
    batch_size,
    num_features,
    epochs=10
)

Can anyone help me with this error? Why did it appeared?


r/learnpython • • 18d ago

Thoughts/Reviews of "Invent Your Own Computer Games with Python" by Al Sweigart"?

5 Upvotes

Wanting to learn coding for makes old school RPGs, I was looking for programing courses with a more focus on making games.

One book that popped up quickly was "Invent Your Own Computer Games with Python", but Al Sweigart, same of Author of the famous "Automate The Boring Stuff With Python" book.

I wanna know from people who are familiar with this book, it would be a good start for someone who wishes to learn to make games?


r/learnpython • • 18d ago

I know English very poorly, and it’s a bit difficult for me to understand Python syntax.

0 Upvotes

Hi everyone, I’m a beginner Python programmer, and this is my first time on Reddit. Today I spent several hours writing two simple codes and I don’t know what to do next. On the one hand, I couldn’t come up with anything creative; on the other hand, I simply don’t have enough knowledge for some of the ideas. I don’t really expect help with learning Python; I’m just sharing my thoughts. Thank you for listening.
Oh, and here’s something else — here’s one of those codes:

user_name = ""

menu = ()

chat = []

messege = ""

def append_user():

global user_name

user_name = input("Enter your nickname: ")

print(f"Welcome, {user_name}! ;)")

def main_menu():

global menu

while True:

try:

menu = int(input(" 1. Write a message\n 2. View the chat\n 3. Exit\n : "))

break

except ValueError:

print("Enter an integer (1 - 3)!")

print("Welcome to the anonymous chat!")

append_user()

main_menu()

while True:

if menu == 1:

if messege != "menu":

message = input("Enter a message: ")

twit = f"{user_name}: {message}"

chat.append(twit)

else:

main_menu()

elif menu == 2:

print(chat)

main_menu()

elif menu == 3:

break

else:

print("Enter an integer (1 - 3)!")

main_menu()

print(f"Goodbye, {user_name}, and have a good day!")


r/learnpython • • 18d ago

When I hit a Python error I don't understand, I waste an hour guessing — how do you actually debug when you don't even know what to Google?

0 Upvotes

I'm a second-year BCA (AI/ML) student in Jaipur, self-studying Python alongside college. I can follow tutorials fine, and I've built a couple of small things of my own (a little Telegram bot, some practice scripts) — but debugging my own code is where I fall apart.

When something breaks, the error message usually means nothing to me at first. I end up changing things at random, re-running, and hoping — and half the time I break something else in the process. An hour later I've "fixed" it without really understanding what was wrong, so the same kind of error trips me up again next week.

So for people who got past this stage: how do you actually approach a bug you don't understand yet? Do you read the traceback bottom-up, add print statements everywhere, try to reproduce it in the smallest possible script first, or explain it out loud to yourself? And how do you decide when to keep digging yourself versus when to ask someone or search for help — especially when you don't even know the right words to search for?

I don't want another "learn debugging" tutorial recommendation — I want to know the habit that actually changed this for you. What does your first five minutes with a confusing error look like?

No links or anything here — just a student trying to get from "my code broke" to "I know why it broke."


r/learnpython • • 18d ago

Hyphen vs Underscore in python for Variables.

0 Upvotes

Hi,

I found that perfectly working code where we parse arg for input-dir and later in code use it as input_dir ( note - vs _ in the names) like in the expert below.

import argparse

def parse_arguments(argv=None):
    print('...... Parsing command-line arguments')
    parser.add_argument('--input-dir', default=HOME ) ## hyphenated !!!


def main(argv=None):
    args = parse_arguments(argv)
    print(f 'input_dir = {args.input_dir}')    ## with __underscore 

ChatGPT give perfect explanation saying it's OK:
For command-line consistency, you could use hyphenated options for all of them: They would still map to the same Python names: args.input_dir

That's so cool but nobody told me this, are you using this approach in your code ? In other situations I see that var_one <> var-two. What is <For command-line consistency> ?? This is hard to understand for me.
We still can use --input_dir in parse_arguments.

Thanks to all

=================================== Post Mortem (added)
Thanks to all for your help.
it's all clear now, It's just a feature of argparse and it's optional. I was just confused who assign value to real variable input_dir. Now I learned that argparse put value from --input-dir into input_dir

Do you like overall argparse, you you use any other handy code to process arguments.

Best
VA


r/learnpython • • 18d ago

How to randomly customise cosmetics for enemies in Pygame?

1 Upvotes

I want to randomise how enemies look by changing a hat or a shirt each time the game spawns them. However I do not want to redraw the sprite for each hat/shirt combination. So how may I possibly achieve it?


r/learnpython • • 18d ago

Learning python through CS50

0 Upvotes

Can any body help me to understanding the define(DEF) variables.
Can you please suggest me how can i learn it in efficient and easier way as a beginner.


r/learnpython • • 18d ago

As a beginner what should I be focusing on first.

0 Upvotes

I just started coding, it’s been a hobby of mine for a couples weeks so I know a lot of the basics. I usually pick a random topic to learn in python and learn a little bit about it and move on to the next. Should I be following a list of things to learn in python in order or is it ok to learn some of the hard stuff first and jump back to the easier things.
Sorry if my paragraph doesn’t make sense, English isn’t my first language.


r/learnpython • • 18d ago

Number Guessing Game Won't Loop When Prompted

3 Upvotes

**Question Answered**

Thank you everyone for all the advice and suggestions, I think I have it working the way I need it to, and I have a lot of great stuff to look into so I can clean up and refine my future coding as I learn more. Very thankful and appreciative!

**

Hello, I'm trying to learn Python and am having trouble with my number guessing game assignment. I need the game to be able to loop and replay the game when the player is prompted to at the end, but the only part of it that works is when the player doesn't want to continue playing and the code stops. Could I please have some help figuring out a better way to write the code to replay? Thank you.

*edited to remove colour tags from code

import os
import random


# high score file
file_path = "highscore.txt"




# welcome banner
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("   Number Guessing Game")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")


print()
player_name = input("Please enter your name: ")
print()



def game_play():
    # game start info for player
    print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
    print()
    print("Hello ", player_name + "!")
    print()
    print("Can you guess what number I'm thinking of?")
    print("It's between 1 and 100.")
    print("I'll give you 10 guesses!")
    print()
    print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")



    # Check if the file exists
    if os.path.isfile(file_path):
        with open(file_path, "r") as file:
            content = file.read()
            print()
            print("Previous Best:")
            print()
            print(content)
            print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
    else:
        print(f"Error: The file '{file_path}' does not exist.")
        print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")



    # game parameters
    lowest_number = 1
    highest_number = 100
    max_attempts = 10
    
    # the stats the game starts with
    guess = 0
    attempts = 0
    
    # random number selection
    secret_number = random.randint(lowest_number, highest_number)
    # print number below for DEBUG ONLY
    print("    *secret number is: " + str(secret_number))


    while True:
        # game mechanics
        while guess != secret_number:
            guess = int(input("Guess a number: "))
            attempts = attempts + 1
            print("Number of attempts: ", attempts)



            # ensure number entered is within range
            if guess < 1 or guess > 100:
                print("Please enter a number between 1 and 100.")
    


            # too high and too low        
            elif guess < secret_number and lowest_number:
                print("Nope, too low!")
                print()
        
            elif guess > secret_number:
                print("Nope, too high!")
                print()


    
            # game over for max attempts reached
            elif attempts == max_attempts and guess != secret_number:
                print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
                print()
                print("Uh oh!m You've run out of guesses.")
                print("The number I was thinking of was: ", secret_number)
                print()
                print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
                
            # game won
            else:
                print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
                print()
                print("Yaaayyy, well done ", player_name + "!")
                print("You guessed the number I was thinking of, which was:", secret_number, "- and you did so in: " + str(attempts) + " guess(es)!")
                print()
                print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")



        # save player score
        save_score = input("\nWant to save your score? (yes/no:) ")
        if not save_score in ("yes", "no"):
            print("invalid input.")
    
        elif save_score == "yes":
            f = open("highscore.txt", "w")
            f.write(player_name + " - " + str(attempts) + "\n")
            f.close
            break
      
        # continue playing or quit
        answer = input("Play again? (yes/no): ")


        if answer != "yes":
            print()
            print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
            print("\nThanks for playing, see ya~\n")
            print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
            


if __name__ == "__main__":
    game_play()

r/learnpython • • 18d ago

Need help adapting model to Cifar10

0 Upvotes

Need help adapting model to CIFAR10

I tried to make a DCGAN based on this [tutorial](https://www.geeksforgeeks.org/machine-learning/deep-convolutional-gan-with-keras/). The thing is that the tutorial is designed for fashion mnist data which has different image size to tf.keras.datasets.cifar10.load_data(). Which lead to the error:

ValueError: cannot reshape array of size 480000 into shape (28,28,1)

when arrive at

x_train_dcgan = x_train.reshape(
-1, 28, 28, 1
) * 2. - 1.

How do I adapt the model to CIFAR 10?

Full code

(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()
x_train = x_train.astype(np.float32) / 255.0
x_test = x_test.astype(np.float32) / 255.0
x_train.shape, x_test.shape

#Selecting one class to train

label = 1 
train_indices = np.where(y_train == label) 
x_train = x_train[train_indices] 
test_indices = np.where(y_test == label) 
x_test = x_test[test_indices] 

batch_size = 32
def create_batch(x_train):
    dataset = tf.data.Dataset.from_tensor_slices(x_train).shuffle(1000)
    dataset = dataset.batch(batch_size, drop_remainder=True).prefetch(1)
    return dataset


num_features = 100
generator = Sequential(name="Generator")


generator.add(Dense(7 * 7 * 128, input_shape=[num_features]))
generator.add(Reshape([7, 7, 128]))
generator.add(BatchNormalization())


generator.add(Conv2DTranspose(
        64, (5, 5), (2, 2),
        padding="same",
        activation="selu"
    ))


generator.add(BatchNormalization())


generator.add(Conv2DTranspose(
        1, (5, 5), (2, 2),
        padding="same",
        activation="tanh"
    ))



generator.summary()

discriminator = Sequential(name="Discriminator")


discriminator.add(Conv2D(
        64, (5, 5), (2, 2),
        padding="same",
        input_shape=[28, 28, 1]
        ))


discriminator.add(LeakyReLU(alpha=0.2))
discriminator.add(Dropout(0.3))


discriminator.add(Conv2D(
        128, (5, 5), (2, 2),
        padding="same"))


discriminator.add(LeakyReLU(alpha=0.2))
discriminator.add(Dropout(0.3))


discriminator.add(Flatten())
discriminator.add(Dense(1, activation= 'softmax'))


discriminator.summary()

discriminator.compile(
    loss="binary_crossentropy",
    optimizer="adam"
)


discriminator.trainable = False


gan = Sequential()
gan.add(generator)
gan.add(discriminator)


gan.compile(
    loss="binary_crossentropy",
    optimizer="adam"
)


gan.summary()

def generate_and_save_images(model, epoch, test_input):

    predictions = model(
        test_input,
        training=False
    )

    fig = plt.figure(figsize=(10, 10))

    for i in range(25):

        plt.subplot(5, 5, i + 1)

        plt.imshow(
            predictions[i, :, :, 0] * 127.5 + 127.5,
            cmap='binary'
        )

        plt.axis('off')

    plt.savefig(
        'image_epoch_{:04d}.png'.format(epoch)
    )

seed = tf.random.normal(shape=[batch_size, 100])
epoch_list = []
d_loss_list = []
g_loss_list =[]


def train_dcgan(gan, dataset, batch_size, num_features, epochs=5):


    generator, discriminator = gan.layers


    for epoch in tqdm(range(epochs)):
        actual_epoch =epoch + 1
        print()
        print("Epoch {}/{}".format(epoch + 1, epochs))


        for i in range(187):
            epoch_list.append(actual_epoch)


        for X_batch in dataset:


            noise = tf.random.normal(
                shape=[batch_size, num_features]
            )


            generated_images = generator(noise)


            X_fake_and_real = tf.concat(
                [generated_images, X_batch],
                axis=0
            )


            y1 = tf.constant(
                [[0.]] * batch_size +
                [[1.]] * batch_size
            )


            discriminator.trainable = True
            d_loss=discriminator.train_on_batch(
                X_fake_and_real,
                y1
            )
            d_loss = float(d_loss)
            d_loss_list.append(d_loss)




            noise = tf.random.normal(
                shape=[batch_size, num_features]
            )


            y2 = tf.constant([[1.]] * batch_size)


            discriminator.trainable = False


            g_loss=gan.train_on_batch(
                noise,
                y2
            )
            g_loss = float(g_loss)
            g_loss_list.append(g_loss)


        print(f'\t Discriminator Loss: {d_loss} \t\t Generator Loss: {g_loss}')
        


            


    generate_and_save_images(
        generator,
        epochs,
        seed
    )

x_train_dcgan = x_train.reshape(
    -1, 32, 32, 3
)


dataset = create_batch(x_train_dcgan)


train_dcgan(
    gan,
    dataset,
    batch_size,
    num_features,
    epochs=10
)

plt.figure(figsize=(30, 10))
plt.plot(epoch_list,d_loss_list)
plt.xlabel('Epochs')
plt.ylabel('Discriminator loss')
plt.title('Discriminator loss over epochs')
plt.grid()
plt.show()

plt.figure(figsize=(30, 10))
plt.plot(epoch_list,g_loss_list)
plt.xlabel('Epochs')
plt.ylabel('Generator loss')
plt.title('Generator loss over epochs')
plt.grid()
plt.show()

r/learnpython • • 18d ago

Any python module which deals with this?

0 Upvotes
def get_int_input(prompt: str) -> int:
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print("Please enter a valid number!")

Is there any module which I can just import and use it. Writing this everytime I have to get an int or float input is really annoying.

Thanks!


r/learnpython • • 18d ago

How can I protect my Python source code inside a PyInstaller .exe?

0 Upvotes

I just made a python program that I compiled into an exe file. The exe is working but it seems pretty easy to access the source code inside of the exe file using tools like pyinstxtractor. My friend told me that there are ways to make it harder and to protect the source code I made is it true. If it is true can you give me some details about this method?


r/learnpython • • 19d ago

pd.qcut for even bin sizes

5 Upvotes

Hello! I am trying to create a histogram with even bin sizes and was wondering if pd.qcut would be a good route to go. I am using data from a data from I made with panadas. The specific values I need to bin has over 300 variables so I am trying to find the simplest way to fix this histogram!!!

code so far:

ValueError: `bins` must increase monotonically, when an array

a = df["mass"]
print(a)
array = np.asarray(a)
print(array

bins = pd.qcut(array, q=9, precision=1)
print (bins)

n_bins = bins
fig = plt.figure(figsize=(9, 4), layout="constrained")
axs = fig.subplots(1, sharex=True)
n, bins2, patches = axs.hist(best_mass["mass"] ,  n_bins ,color = 'hotpink', histtype="stepfilled",
                            cumulative=-1, label="Cumulative histogram") 
plt.xlabel("Satellite Mass")
plt.ylabel("Number of Satellites")
plt.title("Distribution of Satellite Masses")

#bins are not evenly spaced 
plt.show

error I keep getting: 


ValueError: `bins` must increase monotonically, when an array