this if statement drop me an unreachable error in python - python

I don't know why this if statement drop me this error, at the beginning I thought maybe my python version had a problem, son I uninstall it and then I install it again, this is my code.
def calc_bayes(prior_A, prob_B_dado_A, prob_B):
return (prior_A * prob_B_dado_A) / prob_B
if __name__ == '__main__':
prob_cancer = 1 / 100000
prob_sintoma_dado_cancer = 1
prob_sintoma_dado_no_cancer = 10 / 99999
prob_no_cancer = 1 - prob_cancer
prob_sintoma = (prob_sintoma_dado_cancer * prob_cancer) + (prob_sintoma_dado_no_cancer * prob_cancer)
prob_cancer_dado_sintoma = calc_bayes (prob_cancer, prob_sintoma_dado_cancer, prob_sintoma)
print(prob_cancer_dado_sintoma)

As in the comments, you cannot write _name_ = _main_ inside definitions. Instead, I think you want to do this
def calc_bayes(prior_A, prob_B_dado_A, prob_B):
return (prior_A * prob_B_dado_A) / prob_B
if __name__ == '__main__':
prob_cancer = 1 / 100000
prob_sintoma_dado_cancer = 1
prob_sintoma_dado_no_cancer = 10 / 99999
prob_no_cancer = 1 - prob_cancer
prob_sintoma = (prob_sintoma_dado_cancer * prob_cancer) + (prob_sintoma_dado_no_cancer * prob_cancer)
prob_cancer_dado_sintoma = calc_bayes (prob_cancer, prob_sintoma_dado_cancer, prob_sintoma)
print(prob_cancer_dado_sintoma)

Related

Python Return Statement Not Providing Expected Results

Just attempting to return values from a defined function. When calling the function first and attempting to print the return values I receive "[variable] not defined". However, if I run "print(qb_stat_filler())" it prints the results in a tuple. I need the individual variables returned to use in a separate function.
For Example
print(qb_stat_filler())
outputs: (0, 11, 24, 24.2024, 39.1143, 293.0, 1.9143000000000001, 0.2262, 97.84333355313255)
but when trying
qb_stat_filler()
print(cmp_avg)
print(att_avg)
outputs: NameError: name 'cmp_avg' is not defined
Process finished with exit code 1
I've tried establishing the variables outside of the function, then passing and returning them and that did not work either. Any thoughts?
def qb_stat_filler():
n_input = input('Player name: ')
t_input = input('Players team: ')
loc_input = input('H or #: ')
o_input = input('Opponent: ')
# convert index csv to dictionary of player values
q = pd.read_csv('Models\\QB Indexes\\QBname.csv')
q = q[['Player', 'Num']]
qb_dict = dict(q.values)
name = qb_dict.get('{}'.format(n_input))
t = pd.read_csv('Models\\QB Indexes\\Tmname.csv')
t = t[['Tm', 'Num']]
tm_dict = dict(t.values)
team = tm_dict.get('{}'.format(t_input))
loc = 0
if loc_input == '#':
loc = 0
elif loc_input == 'H':
loc = 1
z = pd.read_csv('Models\\QB Indexes\\Oppname.csv')
z = z[['Opp', 'Num']]
opp_dict = dict(z.values)
opp = opp_dict.get('{}'.format(o_input))
*there are several lines of code here that involve SQL
queries and data cleansing*
cmp_avg = (cmp_match + cmpL4) / 2
att_avg = (patt_match + pattL4) / 2
pyds_avg = (py_match + pydsL4) / 2
ptd_avg = (ptdL4 + ptd_match) / 2
int_avg = (intL4 + int_match) / 2
qbr_avg = (qbr_match + qbrL4) / 2
return name, team, opp, cmp_avg, att_avg, pyds_avg, ptd_avg,
int_avg, qbr_avg
qb_stat_filler()
You might consider:
def qb_stat_filler():
stats = {}
...
stats['name'] = name
z = z[['Opp', 'Num']]
opp_dict = dict(z.values)
stats['opp'] = opp_dict.get('{}'.format(o_input))
...
stats['cmp_avg'] = (cmp_match + cmpL4) / 2
stats['att_avg'] = (patt_match + pattL4) / 2
stats['pyds_avg'] = (py_match + pydsL4) / 2
stats['ptd_avg'] = (ptdL4 + ptd_match) / 2
stats['int_avg'] = (intL4 + int_match) / 2
stats['qbr_avg'] = (qbr_match + qbrL4) / 2
return stats
...
stats = qb_stat_filler()
print(stats['cmp_avg'])

Python decimal.InvalidOperation Error Using A Large Number

In python, I wrote a program to work out the value of pi using the Chudnovsky Algorithm. It works on numbers under 800. However, if I use a number above 800, it returns a decimal.InvalidOperation error. This is my code:
from math import factorial
from decimal import Decimal, getcontext
getcontext().prec = 1000
pi_input = input("How Many Digits Of Pi Are To Be Represented: ")
num = int(pi_input)
def cal(n):
t = Decimal(0)
pi = Decimal(0)
deno = Decimal(0)
for k in range(n):
t = ((-1) ** k) * (factorial(6 * k)) * (13591409 + 545140134 * k)
deno = factorial(3 * k) * (factorial(k) ** 3) * (640320 ** (3 * k))
pi += Decimal(t) / Decimal(deno)
pi = pi * Decimal(12) / Decimal(640320 ** Decimal(1.5))
pi = 1 / pi
return round(pi, n)
print(cal(num))
Could Anyone Please Help Me?
I wouldn't recommend your method. Try using the gmpy module like this:
import sys
import math
import os.path
from gmpy2 import mpz, sqrt
from time import time, sleep
print_pi = input("Should The Value Of Pi Be Printed: ").lower()
print_pi_bool = 0
if "y" in print_pi:
print_pi_bool = True
elif "n" in print_pi:
print_pi = False
else:
print("Incorrect Input. Please Try Again.")
sys.exit()
def sqrt(n, one):
"""
Return the square root of n as a fixed point number with the one
passed in. It uses a second order Newton-Raphson convgence. This
doubles the number of significant figures on each iteration.
"""
# Use floating point arithmetic to make an initial guess
floating_point_precision = 10**16
n_float = float((n * floating_point_precision) // one) / floating_point_precision
x = (int(floating_point_precision * math.sqrt(n_float)) * one) // floating_point_precision
n_one = n * one
count = 0
while 1:
count += 1
print(count)
x_old = x
x = (x + n_one // x) // 2
if x == x_old:
break
return x
def pi_chudnovsky_bs(digits):
"""
Compute int(pi * 10**digits)
This is done using Chudnovsky's series with binary splitting
"""
C = 640320
C3_OVER_24 = C**3 // 24
def bs(a, b):
"""
Computes the terms for binary splitting the Chudnovsky infinite series
a(a) = +/- (13591409 + 545140134*a)
p(a) = (6*a-5)*(2*a-1)*(6*a-1)
b(a) = 1
q(a) = a*a*a*C3_OVER_24
returns P(a,b), Q(a,b) and T(a,b)
"""
if b - a == 1:
# Directly compute P(a,a+1), Q(a,a+1) and T(a,a+1)
if a == 0:
Pab = Qab = mpz(1)
else:
Pab = mpz((6*a-5)*(2*a-1)*(6*a-1))
Qab = mpz(a*a*a*C3_OVER_24)
Tab = Pab * (13591409 + 545140134*a) # a(a) * p(a)
if a & 1:
Tab = -Tab
else:
# Recursively compute P(a,b), Q(a,b) and T(a,b)
# m is the midpoint of a and b
m = (a + b) // 2
# Recursively calculate P(a,m), Q(a,m) and T(a,m)
Pam, Qam, Tam = bs(a, m)
# Recursively calculate P(m,b), Q(m,b) and T(m,b)
Pmb, Qmb, Tmb = bs(m, b)
# Now combine
Pab = Pam * Pmb
Qab = Qam * Qmb
Tab = Qmb * Tam + Pam * Tmb
return Pab, Qab, Tab
# how many terms to compute
DIGITS_PER_TERM = math.log10(C3_OVER_24/6/2/6)
N = int(digits/DIGITS_PER_TERM + 1)
# Calclate P(0,N) and Q(0,N)
P, Q, T = bs(0, N)
one_squared = mpz(10)**(2*digits)
sqrtC = sqrt(10005*one_squared, one_squared)
return (Q*426880*sqrtC) // T
# The last 5 digits or pi for various numbers of digits
check_digits = {
100 : 70679,
1000 : 1989,
10000 : 75678,
100000 : 24646,
1000000 : 58151,
10000000 : 55897,
}
if __name__ == "__main__":
digits = 100
pi = pi_chudnovsky_bs(digits)
#raise SystemExit
for log10_digits in range(1,11):
digits = 10**log10_digits
start =time()
pi = pi_chudnovsky_bs(digits)
pi = str(pi)
pi = pi[:(len(str(pi)) // 2) + 1]
length = int(len(str(pi))) - 1
print("Chudnovsky Binary Splitting Using GMPY: Digits",f"{digits:,}","\n--------------",time()-start,"--------------")
print("Length Of " + f"{length:,}" + " Digits")
It's my first answer, so I hope it helps!

Chrome T-Rex-Game Reinforcement learning showing no improvement

I would like to create an AI for the Chrome-No-Internet-Dino-Game. Therefore I adapted this Github-Repository to fit my needs. I used the following formula to calculate the new Q:
Source: https://en.wikipedia.org/wiki/Q-learning
My problem now is that even after ~ 2.000.000 iterations my game score is not increasing.
You can find the game file here: https://pastebin.com/XrwQ0suJ
QLearning.py:
import pickle
import Game_headless
import Game
import numpy as np
from collections import defaultdict
rewardAlive = 1
rewardKill = -10000
alpha = 0.2 # Learningrate
gamma = 0.9 # Discount
Q = defaultdict(lambda: [0, 0, 0]) # 0 = Jump / 1 = Duck / 2 = Do Nothing
oldState = None
oldAction = None
gameCounter = 0
gameScores = []
def paramsToState(params):
cactus1X = round(params["cactus1X"] / 10) * 10
cactus2X = round(params["cactus2X"] / 10) * 10
cactus1Height = params["cactus1Height"]
cactus2Height = params["cactus2Height"]
pteraX = round(params["pteraX"] / 10) * 10
pteraY = params["pteraY"]
playerY = round(params["playerY"] / 10) * 10
gamespeed = params["gamespeed"]
return str(cactus1X) + "_" + str(cactus2X) + "_" + str(cactus1Height) + "_" + \
str(cactus2Height) + "_" + str(pteraX) + "_" + str(pteraY) + "_" + \
str(playerY) + "_" + str(gamespeed)
def shouldEmulateKeyPress(params): # 0 = Jump / 1 = Duck / 2 = Do Nothing
global oldState
global oldAction
state = paramsToState(params)
oldState = state
estReward = Q[state]
action = estReward.index(max(estReward))
if oldAction is None:
oldAction = action
return action
# Previous action was successful
# -> Update Q
prevReward = Q[oldState]
prevReward[oldAction] = (1 - alpha) * prevReward[oldAction] + \
alpha * (rewardAlive + gamma * max(estReward))
Q[oldState] = prevReward
oldAction = action
return action
def onGameOver(score):
# Previous action was NOT successful
# -> Update Q
global oldState
global oldAction
global gameCounter
global gameScores
gameScores.append(score)
if gameCounter % 10000 == 0:
print(f"{gameCounter} : {np.mean(gameScores[-100:])}")
prevReward = Q[oldState]
prevReward[oldAction] = (1 - alpha) * prevReward[oldAction] + \
alpha * rewardKill
Q[oldState] = prevReward
oldState = None
oldAction = None
if gameCounter % 10000 == 0:
with open("Q\\" + str(gameCounter) + ".pickle", "wb") as file:
pickle.dump(dict(Q), file)
gameCounter += 1
Game_headless.main(shouldEmulateKeyPress, onGameOver)
On every frame the gameplay() function from Game_headless.py calls shouldEmulateKeyPress(). Said function then returns 0 for Jump, 1 for duck and 2 for nothing.
I tried adjusting the constants, but that didn't show any effect.
If you any questions, please don't hesitate to ask me!
Thank you in advance!
Someone on Reddit did this, did you take a look at their code? https://www.reddit.com/r/MachineLearning/comments/8iujuu/p_tfrex_ai_learns_to_play_google_chromes_dinosaur/
I was able to fix the problem, but I don't really know what the mistake was. I added a return statement at the end the gameplay function, and somehow it works now.

UnboundLocalError: local variable 'Y_p' referenced before assignment

I have the following script:
guess = np.linspace(0,20/1000, num = 21)
def calc_U_LC_a(t)-> "U_LC_a":
alpha_c = calc_alpha_c(t)
S_p = calc_S_p(t)
M_p = calc_M_p(t)
p_b_LC = calc_p_b(t, min(fy,fu/1.15))
Y_p = calc_Y_p(t)
p_c_LC = calc_p_c(t)
if pl_net_LC >= 0:
U_P = (Y_p * pl_net_LC) / (alpha_c * p_b_LC)
else:
U_P = 1.02 * 2 * (- pl_net_LC / p_c_LC)
M_Sd_a = 500e3
S_Sd_a = 500e4
U_M = (1.02 * 2 / alpha_c) * (abs(M_Sd_a)/M_p)
U_S = (1.02 * 2 / alpha_c) * (S_Sd_a/S_p)
U_LC_a = ((U_M + U_S ** 2) ** 2) + U_P ** 2
return U_LC_a
def fun_LC_a(t):
return calc_U_LC_a(t) - 1
def calc_iter(fun,guess):
for i in range(0,len(guess)):
try:
tmin = optimize.newton(fun,guess[i]) #, disp = False)
except RuntimeError:
print('guess = ', guess[i],' failed to converge.')
else:
break
return tmin
tmin_X = calc_iter(fun_LC_a,guess)
All variables that are not defined here are constant values.
When I run this script, I get the error "UnboundLocalError: local variable 'Y_p' referenced before assignment"
and I am not sure why.

Print does not fit the data interval settings

I am using this answer here and I have this code which get the gauge strain signal (2 channels) and then I apply a calibration step, then I print the 2 channels and the current time. But it looks like the print does not match the frequency I use in my code.
from time import sleep
from Phidget22.Phidget import *
from Phidget22.Devices.VoltageRatioInput import *
import time
import datetime
TIME_OUT = 5000 #5s beofre it throws a timeout exception
DATA_INTERVAL = 50 #50ms sample frequency
A0 = -6.128983223994E-06
B0 = -0.000059639277340
A1 = -6.101017778744E-06
B1 = -0.000286467338645
def onVoltageRatioChange0(self, voltageRatio):
Masse = (voltageRatio - (B0) ) / (A0)
self.masse = Masse
def onVoltageRatioChange1(self, voltageRatio):
Masse = (voltageRatio - (B1) ) / (A1)
self.masse = Masse
def results():
voltageRatioInput0 = VoltageRatioInput()
voltageRatioInput0.masse = 0
voltageRatioInput0.setChannel(0)
voltageRatioInput0.setOnVoltageRatioChangeHandler(onVoltageRatioChange0)
voltageRatioInput0.openWaitForAttachment(TIME_OUT)
voltageRatioInput0.setBridgeGain(BridgeGain.BRIDGE_GAIN_128)
voltageRatioInput0.setDataInterval(DATA_INTERVAL)
voltageRatioInput1 = VoltageRatioInput()
voltageRatioInput1.masse = 0
voltageRatioInput1.setChannel(1)
voltageRatioInput1.setOnVoltageRatioChangeHandler(onVoltageRatioChange1)
voltageRatioInput1.openWaitForAttachment(TIME_OUT)
voltageRatioInput1.setBridgeGain(BridgeGain.BRIDGE_GAIN_128)
voltageRatioInput1.setDataInterval(DATA_INTERVAL)
print(str(datetime.datetime.now()) + " / " + str(voltageRatioInput0.masse) + " / " + str(voltageRatioInput1.masse))
voltageRatioInput0.close()
voltageRatioInput1.close()
if __name__ == '__main__':
try:
while True:
results()
except KeyboardInterrupt:
print("Goodbye")
pass
So normally using the voltageRatioInput0.setDataInterval(DATA_INTERVAL) it should print the value with a frequency of 20 hz. But it prints me this :
2019-11-22 10:24:59.460503 / -0.03847266852956798 / 0.2918630004986786
2019-11-22 10:25:00.099831 / -0.03695316689942101 / -0.02070779820379342
2019-11-22 10:25:00.772398 / -0.04029613574942367 / 0.28775155534154484
2019-11-22 10:25:01.420283 / -0.043487203384171676 / 0.25676361089420047
So clearly here I do not have 20 Hz...
A lot of time is probably spent in your result() function. I cannot reproduce here, but a simple
python -m cProfile -s tottime your_program.py
should help you to see where most of the time is spent each loop iteration.
I guess that instanciation of a VoltageRatioInput() and VoltageRatioInput.close() are a good way to start. Could you try taking them outside the loop as in:
from Phidget22.Phidget import *
from Phidget22.Devices.VoltageRatioInput import *
import datetime
TIME_OUT = 5000 #5s beofre it throws a timeout exception
DATA_INTERVAL = 50 #50ms sample frequency
A0 = -6.128983223994E-06
B0 = -0.000059639277340
A1 = -6.101017778744E-06
B1 = -0.000286467338645
def onVoltageRatioChange0(self, voltageRatio):
Masse = (voltageRatio - (B0) ) / (A0)
self.masse = Masse
def onVoltageRatioChange1(self, voltageRatio):
Masse = (voltageRatio - (B1) ) / (A1)
self.masse = Masse
def results(voltageRatioInput0, voltageRatioInput1):
voltageRatioInput0.masse = 0
voltageRatioInput0.setChannel(0)
voltageRatioInput0.setOnVoltageRatioChangeHandler(onVoltageRatioChange0)
voltageRatioInput0.openWaitForAttachment(TIME_OUT)
voltageRatioInput0.setBridgeGain(BridgeGain.BRIDGE_GAIN_128)
voltageRatioInput0.setDataInterval(DATA_INTERVAL)
voltageRatioInput1.masse = 0
voltageRatioInput1.setChannel(1)
voltageRatioInput1.setOnVoltageRatioChangeHandler(onVoltageRatioChange1)
voltageRatioInput1.openWaitForAttachment(TIME_OUT)
voltageRatioInput1.setBridgeGain(BridgeGain.BRIDGE_GAIN_128)
voltageRatioInput1.setDataInterval(DATA_INTERVAL)
print(str(datetime.datetime.now()) + " / " + str(voltageRatioInput0.masse) + " / " + str(voltageRatioInput1.masse))
if __name__ == '__main__':
try:
voltageRatioInput0 = VoltageRatioInput()
voltageRatioInput1 = VoltageRatioInput()
while True:
results(voltageRatioInput0, voltageRatioInput1)
voltageRatioInput0.close()
voltageRatioInput1.close()
except KeyboardInterrupt:
print("Goodbye")

Categories

Resources