r/learnpython • • 25d ago
Help with training
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 • • 25d ago
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 • u/Sufficient-Noise8991 • 25d ago
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 • u/_nazwa_ • 24d ago
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 • u/DR_vanta • 25d ago
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_tempthis 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 • u/Senior-Ad-6588 • 26d ago
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 • u/doflamingo980 • 26d ago
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:
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 • u/Senior-Ad-6588 • 26d ago
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 • u/assorted-meat-stew • 26d ago
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: concatX_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 • u/Sure-Spread-1423 • 26d ago
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 • u/user_bars • 25d ago
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 • u/Valuable-Ant3465 • 25d ago
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 • u/Aggressive-Band-1276 • 26d ago
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 • u/Bipin_Gaire69 • 25d ago
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 • u/Intelligent-Rip-8181 • 26d ago
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 • u/Substantial-Hold9159 • 26d ago
**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 • u/assorted-meat-stew • 26d ago
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 • u/Lance_2564_ • 26d ago
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 • u/lichen_13 • 25d ago
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 • u/DrawerEmergency4981 • 26d ago
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 arrayr/learnpython • u/No-Opinion-1239 • 27d ago
I learned the basics of Python using the book Automate the Boring Stuff with Python, but I've realized that the other chapters don't interest me that much, except for the one about web scraping.
So now I'm looking for something else to learn. I've thought about learning how to make games or create GUIs, but I'd need some guidance.
r/learnpython • u/assorted-meat-stew • 26d ago
I tried to make a DCGAN based on this tutorial. 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?
r/learnpython • u/Tricky_Voice2829 • 27d ago
i am making script that it will launch localsend appimage through shell but and it will end after i pressed q but when script only user input first time asked starting of the script when reached to the else block app image is opening but not asking for user input again after launching
Here's the code,
import subprocess
import time
while True:
user_input = input("press q to quite and enter :-").rstrip()
if user_input == "q":
break
else:
time.sleep(3)
subprocess.run("/home/merlinhermes/Desktop/LocalSend-1.18.2-linux-x86-64.AppImage",shell=True)r/learnpython • u/ProgramBrave718 • 27d ago
Hello, I need some project ideas to practice.
I have learnt basic python, beginner libraries like random and math.
I learnt requests library two months ago and i have worked with many apis like aqi, joke, quote, weather, horoscope....
Even I try searching for apis I get the one which I have used .
Can anyone help me?
r/learnpython • u/BorderSad5441 • 26d ago
El contexto es que estoy desarrollando una página para cotizaciones para un proyecto, el punto es que quiero al momento de hacer una cotización la tabla de productos de actualice y se quite una unidad en existencia, ósea si tengo 20 cargadores y en una cotización vendo 5 en el apartado de productos se vea reflejado que solo hay 15.
Ya lo había intentado haciendo que se actualizara la tabla directamente desde la ruta de cotización pero por alguna razón rompí todo y ya no me daba acceso a la pagina.
¿Alguien sabe como le puedo hacer?