Im using objects.create to create object o my model. Using the following logic. But payment_quantity (somehow) is setting to NoneType. And not setting to the value i passed into objects.create
class PrizesExchangeModeResourceBMR(resources.ModelResource):
#transaction.atomic
def create_exchange_mode(self, code, points, price):
cuotas = [1,3,6,12] # array de cuotas
prize = Prize.objects.filter(code = code) # busca el premio
if len(prize) != 0: # si existe el premio
PrizesExchangeMode.objects.create( #crea puntos al 100%, 0 cuotas
prize = prize[0],
payment_amount = 0,
points_value = points,
payment_quantity=0,
price_value = 0
)
puntos = round(points/2)
for cuota in cuotas: # crea con puntos al 50% y [1,3,6,12] cuotas
valor = round(price/cuota)
PrizesExchangeMode.objects.create(
prize = prize[0],
payment_amount = valor,
points_value = puntos,
payment_quantity = 0.0,
price_value = 0.0)
else:
print("Premio no encontrado") # no existe el premio
def get_instance(self,instance_loader, row):
self.get_queryset().get(prize__code=row.get('prize'))
def save_instance(self, instance, using_transactions, dry_run):
code = instance.prize.code #guarda el codigo
points = instance.points_value # guarda puntos
price = instance.payment_amount # guarda precio
self.create_exchange_mode(code, points, price) # se lo pasa a la funcion anterior
class Meta:
model = PrizesExchangeMode
fields = ("prize", "points_value", "payment_amount") # Campos que queremos importar
It's a guessing game and at the end of the code I want to ask if they would like to play the game again. If they do say yes then it start back from the top and if they say no the program ends. This is what i currently have not sure what i did wrong, ive had some help and this is what i have so far
import random
name = input('Entrez votre nom: ')
Kilo = input (name + ' Veux-tu jouer un jeu ')
def play(name):
randomNumber = random.randrange(0,100)
guessed = False
want_to_play = True
while want_to_play:
print("Un nombre aléatoire a été généré 1 a 100 ")
while guessed==False:
userInput = int(input("Entrez votre estimation: "))
if userInput==randomNumber:
guessed = True
print("Bien joué!")
elif userInput>100:
print("Notre fourchette est entre 0 et 100, essayez un peu plus bas")
elif userInput<0:
print("Notre fourchette est comprise entre 0 et 100, essayez un peu plus haut ")
elif userInput>randomNumber:
print("Essayez une fois de plus, un peu plus bas")
elif userInput < randomNumber:
print("Essayer une fois de plus, un peu plus haut")
You could encapsulate your game into a function. Then, use a loop around the function call:
name = input('Entrez votre nom: ')
def play(name):
randomNumber = random.randrange(0,100)
guesses = False
# etc...
want_to_play = True
while want_to_play:
play(name) # This start your game
want_to_play = input('Veux tu encore jouer? (O/N)')
if want_to_play.lower() == 'o':
want_to_play = True
elif want_to_play.lower() == 'n':
want_to_play = False # EDIT: oups, thanks Primusa
else:
print('invalid input!')
want_to_play = False
I'm making an oscilloscope with python and Arduino UNO. And I'm having two strange problems. First, I would like to emphasize that my code works, but I want to understand why these problems happen.
Firstly, if I try to title my figure, my code stops working. I've commented and ended with 3 question marks ??? the three lines concerned.
See code:
My second question is why the buttons are not colorful (they are all black) and not clickable. See image
import serial
import numpy as np
import matplotlib.pyplot as plt
from drawnow import *
voltsent = [] #le signal reçu en chaine de caractères
signalsentfloat = [] #le signal reçu converti en float
ser = serial.Serial("com9",115200)
#affichage interactive des données
plt.ion()
cnt = 0
def figuresignal(): #fonction qui affiche le siganl analogue
#fig = plt.figure() ???
plt.grid(True)
#plt.legend(loc='upper left')
plt.subplot(2,1,1)
#fig.suptitle('Visualisation de signaux générés par le GBF') ???
plt.ylabel('Signal')
plt.plot(voltsent, '.')
plt.subplot(2,1,2)
plt.ylabel('Fourrier Transform')
plt.plot(voltsentFT, '-')
while True: #while loop that loops forever
while(ser.inWaiting()==0) :#wait here until there is a data
pass
signalsent = ser.readline() #read line of text from serial port
signalsentfloat = float(signalsent) #convert it
voltsent.append(signalsentfloat) #append its values to array
voltsentFT = np.fft.fft(voltsent)
drawnow(figuresignal) #call drawnow to update our the graph
#plt.pause(.000001)
cnt = cnt+1
if(cnt>50):
voltsent.pop(0)
fig = plt.figure() creates a new figure. So you would end up with a lot of figures, eventually leading the application to crash. What you want instead is to have one single figure, so put fig = plt.figure() outside the loop.
Since this would still plot a lot of lines on top of each other, the better option is to update the lines.
import serial
import numpy as np
import matplotlib.pyplot as plt
voltsent = [] #le signal reçu en chaine de caractères
signalsentfloat = [] #le signal reçu converti en float
ser = serial.Serial("com9",115200)
#affichage interactive des données
plt.ion()
cnt = 0
fig = plt.figure()
fig.suptitle(u'Visualisation de signaux générés par le GBF')
ax = plt.subplot(2,1,1)
ax.grid(True)
ax.set_ylabel('Signal')
line1, = ax.plot([],".")
ax2 = plt.subplot(2,1,2)
ax2.grid(True)
ax2.set_ylabel('Fourrier Transform')
line2, = ax2.plot([],"-")
def figuresignal(): #fonction qui affiche le siganl analogue
line1.set_data(np.arange(len(voltsent)),voltsent )
line2.set_data(np.arange(len(voltsentFT)),voltsentFT )
while True: #while loop that loops forever
while(ser.inWaiting()==0) :#wait here until there is a data
pass
signalsent = ser.readline() #read line of text from serial port
signalsentfloat = float(signalsent) #convert it
voltsent.append(signalsentfloat) #append its values to array
voltsentFT = np.fft.fft(voltsent)
figuresignal()
plt.pause(.001)
cnt = cnt+1
if(cnt>50):
voltsent.pop(0)
I've found a solution to my problem in above question by following a tutorial on Toptechboy.com
To give a title to my graph I used the function : plt.title('Le titre ici')
I am currently working on a Neural network that maps stft audio files to MFCC features..
But keep for some reason keep getting a validation_loss around 200.
Which compared desired range is (-100,100).. so the output the NN outputs is not desirable..
I tried different implementation..
Simple NN 1-layer, 2-layer, 3-layer => wiht no difference.
CNN , 1-layer, 2-layer => same result
tried with random forrest => never finished, memory allocation error.
So...
What am I doing wrong?
I tried normalizing the input and output, but the same error came back when i unormalized the dataset.. so...
the shape of the input is (x,2050) and the shape of the output (x,13)...
Any idea on why I am getting so poor results?..
Normalization:
def numpy_minmax(X):
print X.min()
print X.max()
xmin = X.min()
return (2*(X - xmin) / (X.max() - xmin)-1)*0.9
def numpy_unorm(x):
xmax = 109.2991
xmin = -97.23664
return x*(xmax-xmin)+xmin
files_train_path = [dnn_train+f for f in listdir(dnn_train) if isfile(join(dnn_train, f))]
files_test_path = [dnn_test+f for f in listdir(dnn_test) if isfile(join(dnn_test, f))]
files_train_name = [f for f in listdir(dnn_train) if isfile(join(dnn_train, f))]
files_test_name = [f for f in listdir(dnn_test) if isfile(join(dnn_test, f))]
os.chdir(dnn_train)
#train_name = generate_list_of_names_data(files_train_path)
#print train_name
train_data, train_output_data, max = load_sound_files(files_train_path)
#sys.exit()
#train_data_real, train_data_img = split_real_img(train_data)
#print train_data
train_set_data_vstacked = np.vstack(train_data)
train_set_output_vstacked = np.vstack(train_output_data)
print train_set_data_vstacked.shape
train_set_data_vstacked_normalized = numpy_minmax(train_set_data_vstacked)
train_set_output_vstacked_normalized = numpy_minmax(train_set_output_vstacked)
Currently network structure options tried:
############################### Training setup ##################################
#Define 10 folds:
seed = 7
np.random.seed(seed)
kfold = KFold(n_splits=10, shuffle=False, random_state=None)
print "Splits"
cvscores_acc = []
cvscores_loss = []
hist = []
i = 0
#train_set_data_vstacked_normalized_reshaped = np.reshape(train_set_data_vstacked_normalized,train_set_data_vstacked_normalized.shape+(1,))
#train_set_output_vstacked_normalized_reshaped = np.reshape(train_set_output_vstacked_normalized,train_set_output_vstacked_normalized.shape+(1,))
for train, test in kfold.split(train_set_data_vstacked_normalized):
print "Model definition!"
model = Sequential()
#act = PReLU(init='normal', weights=None)
model.add(Dense(output_dim=2050,input_dim=2050, init="normal", activation='relu'))
#act1 = PReLU(init='normal', weights=None)
#act2 = PReLU(init='normal', weights=None)
model.add(Dense(output_dim=2050, input_dim=2050, init="he_normal",activation='tanh'))
model.add(Dense(output_dim=13, input_dim=2050, init="he_normal",activation='tanh'))
model.add(Lambda(lambda x: numpy_unorm(x)))
#model.add(ELU(100))
#model.add(Convolution1D(13, 3, border_mode='same', input_shape=(2050,1)))
print "Compiling"
#rms_opt = keras.optimizers.RMSprop(lr=0.01, rho=0.9, epsilon=1e-08, decay=0.0)
model.compile(loss='mean_squared_error', optimizer="RMSprop")
print "Compile done! "
print '\n'
print "Train start"
reduce_lr=ReduceLROnPlateau(monitor='val_loss', factor=0.01, patience=3, verbose=1, mode='auto', epsilon=0.0001, cooldown=0, min_lr=0.000000000000000001)
stop = EarlyStopping(monitor='val_loss', min_delta=0, patience=5, verbose=1, mode='auto')
log=csv_logger = CSVLogger('training_'+str(i)+'.csv')
hist_current = model.fit(train_set_data_vstacked_normalized[train],
train_set_output_vstacked[train],
shuffle=False,
validation_data=(train_set_data_vstacked_normalized[test],train_set_output_vstacked[test]),
validation_split=0.1,
nb_epoch=150,
verbose=1,
callbacks=[reduce_lr,log,stop])
hist.append(hist_current)
Convolutional:
#Each frame length = 118
#Each feature length = 13
############################### Training setup ##################################
#Define 10 folds:
seed = 7
np.random.seed(seed)
kfold = KFold(n_splits=10, shuffle=False, random_state=None)
print "Splits"
cvscores_acc = []
cvscores_loss = []
hist = []
i = 0
#train_set_data_vstacked_normalized_reshaped = np.reshape(train_set_data_vstacked_normalized,train_set_data_vstacked_normalized.shape+(1,))
#train_set_output_vstacked_normalized_reshaped = np.reshape(train_set_output_vstacked_normalized,train_set_output_vstacked_normalized.shape+(1,))
train_set_data_vstacked_reshaped = train_set_data_vstacked[:,newaxis,:]
train_set_output_vstacked_reshaped = train_set_output_vstacked[:,newaxis,:]
print train_set_data_vstacked_reshaped.shape
print train_set_output_vstacked_reshaped.shape
for train, test in kfold.split(train_set_data_vstacked_reshaped):
print "Model definition!"
model = Sequential()
#act = PReLU(init='normal', weights=None)
#model.add(Dense(output_dim=400,input_dim=400, init="normal", activation=K.tanh))
#act1 = PReLU(init='normal', weights=None)
#act2 = PReLU(init='normal', weights=None)
#model.add(Dense(output_dim=2050, input_dim=2050, init="he_normal",activation='tanh'))
#model.add(Dense(output_dim=13, input_dim=2050, init="he_normal",activation='relu'))
#model.add(Lambda(lambda x: numpy_unorm(x)))
#model.add(ELU(100))
model.add(Convolution1D(2050, 1, border_mode='same', input_dim=2050))
model.add(Convolution1D(13, 1, border_mode='same', input_dim=2050))
#model.add(Convolution1D(13, 1, border_mode='same', input_dim=2050))
#model.add(Dense(output_dim=13, input_dim=2050, init="he_normal",activation='relu'))
print "Compiling"
#rms_opt = keras.optimizers.RMSprop(lr=0.01, rho=0.9, epsilon=1e-08, decay=0.0)
model.compile(loss='mean_squared_error', optimizer="Adam")
print "Compile done! "
print '\n'
print "Train start"
reduce_lr=ReduceLROnPlateau(monitor='val_loss', factor=0.01, patience=3, verbose=1, mode='auto', epsilon=0.01, cooldown=0, min_lr=0.000000000000000001)
stop = EarlyStopping(monitor='val_loss', min_delta=0, patience=5, verbose=1, mode='auto')
log=csv_logger = CSVLogger('training_'+str(i)+'.csv')
hist_current = model.fit(train_set_data_vstacked_reshaped[train],
train_set_output_vstacked_reshaped[train],
shuffle=False,
validation_data=(train_set_data_vstacked_reshaped[test],train_set_output_vstacked_reshaped[test]),
validation_split=0.1,
nb_epoch=150,
verbose=1,
callbacks=[reduce_lr,log,stop])
hist.append(hist_current)
Hi guys I have a syntax error that I really don't understand... Anyone can help?
I get this message on the console:
File "./data_4.0.1.py", line 170
elif:
^
SyntaxError: invalid syntax
The error is raised on this elif:
#controllo ultimo timestamp
elif:
with open(nomen, 'rb') as f:
last_timestamp = f.readlines()[-1].split(",")[0]
Here is my code:
def funzione_aggiornamento_prezzi(titolo,timeframe,lookback):
#parametri per scaricare lo storico dei prezzi
if timeframe =='TBT':
lookback = 0
elif timeframe =='1M':
lookback = 7
elif timeframe =='5M':
lookback = 60
elif timeframe =='60M':
lookback = 180
elif timeframe =='1D':
lookback = 1800
params = {'item': titolo,
'frequency': timeframe,
'dataDa':x_giorni_fa(lookback)}
try:
r = requests.get(myurl, params=params)
except:
pprint("Si e' verificato un errore")
else:
pprint(r.status_code)
pprint(r.url)
new_list = crea_lista(r)
#codice per scrivere su di un csv da una lista
nomen = "%s.%s.csv" % (titolo,timeframe)
csvfile = open(nomen, 'a')
reportwriter = csv.writer(csvfile, quoting=csv.QUOTE_MINIMAL)
#codice per scrivere su di un csv
#controllo del numero di rows nel file
with open(nomen,"r") as f:
reader = csv.reader(f,delimiter = ",")
data = list(reader)
row_count = len(data)
if row_count == 0:
for i in new_list:
da_appendere = i
reportwriter.writerow(da_appendere)
csvfile.close()
#controllo ultimo timestamp
elif:
with open(nomen, 'rb') as f:
last_timestamp = f.readlines()[-1].split(",")[0]
#codice per appendere solo i nuovi dati
found_it = 0
for i in range((len(new_list))-1):
if new_list[i] == last_timestamp:
found_it = 1
if found_it == 1:
this_elem = new_list[i]
next_elem = new_list[(i+1)]
#print(this_elem)
#print(next_elem)
da_appendere1 = next_elem
reportwriter.writerow(da_appendere1)
csvfile.close()
for i in lista_indici:
for j in lista_timeframe:
funzione_aggiornamento_prezzi(i,j,lookback)
you end the if block in the previous line when put a instruction at the same level indentation that the if statement
if condition:
stuff
something # doing this close the if block
and a elif can only happen in a if block
and you do that in
if row_count == 0:
for i in new_list:
da_appendere = i
reportwriter.writerow(da_appendere)
csvfile.close() #<-- here you close the if block
#controllo ultimo timestamp
elif: #<-- you forgot the condition, and is outside of a 'if' block
with open(nomen, 'rb') as f:
last_timestamp = f.readlines()[-1].split(",")[0]
futhermore you forget to put a condition in the elif, if you don't need one use else instead
If you do not have another if statement, you should use else instead of elif.
See the documentation regarding control-flow.