How to create a while loop that keeps going until 5 variables all equal 10 - while-loop

import random
damage_1 = random.randint(1, 10)
damage_2 = random.randint(1, 10)
damage_3 = random.randint(1, 10)
damage_4 = random.randint(1, 10)
damage_5 = random.randint(1, 10)
entries = 0
while damage_1 != 10 and damage_2 != 10 and damage_3 != 10 and damage_4 != 10 and damage_5 != 10:
entries = entries + 1
print(entries)
print(damage_1)
print(damage_2)
print(damage_3)
print(damage_4)
print(damage_5)
The while loop should keep adding to the entries var until all damage_X vars equal 10.

You should first initialize all the variables to 0 and then randomly generate them in the while loop.
import random
damage_1 = damage_2 = damage_3 = damage_4 = damage_5 = 0
entries = 0
while damage_1 != 10 and damage_2 != 10 and damage_3 != 10 and damage_4 != 10 and damage_5 != 10:
entries = entries + 1
print(entries)
damage_1 = random.randint(1, 10)
damage_2 = random.randint(1, 10)
damage_3 = random.randint(1, 10)
damage_4 = random.randint(1, 10)
damage_5 = random.randint(1, 10)
print(damage_1)
print(damage_2)
print(damage_3)
print(damage_4)
print(damage_5)
It should be like this. But you have not mentioned where you are stuck.

So to accomplish what you want, keep looping and add 1 to entries until all damage_X variables equal 10:
import random
damage_1 = damage_2 = damage_3 = damage_4 = damage_5 = 0
entries = 0
while damage_1 != 10 or damage_2 != 10 or damage_3 != 10 or damage_4 != 10 or damage_5 != 10:
entries += 1
print(entries)
if damage_1 != 10: damage_1 = random.randint(1, 10)
if damage_2 != 10: damage_2 = random.randint(1, 10)
if damage_3 != 10: damage_3 = random.randint(1, 10)
if damage_4 != 10: damage_4 = random.randint(1, 10)
if damage_5 != 10: damage_5 = random.randint(1, 10)
print(damage_1)
print(damage_2)
print(damage_3)
print(damage_4)
print(damage_5)
print("")
So you should check if damage_X equals 10 and only if it does not assign a new random integer to it. If you do not add that if check, your loop will run for a very long time since the chance that all 5 damage_X variables will equal 10 at the same time is extremely low. I did change the and to or in the while statement cause if you use and, the while loop will stop if one of the damage_X variables equals 10.

Related

Used MLESAC but got poor answer

MLESAC is better than RANSAC by calculating likelihood rather than counting numbers of inliers.
(Torr and Zisserman 2000)
So there is no reason to use RANSAC if we use MLESAC. But when I implied on the plane fitting problem, I got a worse result than RANSAC. It came out similar p_i when I substituted distance errors of each data in equation 19, leading wrong negative log likelihood.
%% MLESAC (REF.PCL)
% data
clc;clear; close all;
f = #(a_hat,b_hat,c_hat,x,y)a_hat.*x+b_hat.*y+c_hat; % z
a = 1;
b = 1;
c = 20;
width = 10;
range = (-width:0.01:width)'; % different from linespace
x = -width+(width-(-width))*rand(length(range),1); % r = a + (b-a).*rand(N,1)
y = -width+(width-(-width))*rand(length(range),1);
X = (-width:0.5:width)';
Y = (-width:0.5:width)';
[X,Y] = meshgrid(X,Y); % for drawing surf
Z = f(a/c,b/c,c/c,X,Y);
z_n = f(a/c,b/c,c/c,x,y); % z/c
% add noise
r = 0.3;
noise = r*randn(size(x));
z_n = z_n + noise;
% add outliers
out_rng = find(y>=8,200);
out_udel = 5;
z_n(out_rng) = z_n(out_rng) + out_udel;
plot3(x,y,z_n,'b.');hold on;
surf(X,Y,Z);hold on;grid on ;axis equal;
p_n = [x y z_n];
num_pt = size(p_n,1);
% compute sigma = median(dist (x - median (x)))
threshold = 0.3; %%%%%%%%% user-defined
medianx = median(p_n(:,1));
mediany = median(p_n(:,2));
medianz = median(p_n(:,3));
medianp = [medianx mediany medianz];
mediadist = median(sqrt(sum((p_n - medianp).*(p_n - medianp),2)));
sigma = mediadist * threshold;
% compute the bounding box diagonal
maxx = max(p_n(:,1));
maxy = max(p_n(:,2));
maxz = max(p_n(:,3));
minx = min(p_n(:,1));
miny = min(p_n(:,2));
minz = min(p_n(:,3));
bound = [maxx maxy maxz]-[minx miny minz];
v = sqrt(sum(bound.*bound,2));
%% iteration
iteration = 0;
num_inlier = 0;
max_iteration = 10000;
max_num_inlier = 0;
k = 1;
s = 5; % number of sample point
probability = 0.99;
d_best_penalty = 100000;
dist_scaling_factor = -1 / (2.0*sigma*sigma);
normalization_factor = 1 / (sqrt(2*pi)*sigma);
Gaussian = #(gamma,disterr,sig)gamma * normalization_factor * exp(disterr.^2*dist_scaling_factor);
Uniform = #(gamma,v)(1-gamma)/v;
while(iteration < k)
% get sample
rand_var = randi([1 length(x)],s,1);
% find coeff. & inlier
A_rand = [p_n(rand_var,1:2) ones(size(rand_var,1),1)];
y_est = p_n(rand_var,3);
Xopt = pinv(A_rand)*y_est;
disterr = abs(sum([p_n(:,1:2) ones(size(p_n,1),1)].*Xopt',2) - p_n(:,3))./sqrt(dot(Xopt',Xopt'));
inlier = find(disterr <= threshold);
outlier = find(disterr >= threshold);
num_inlier = size(inlier,1);
outlier_num = size(outlier,1);
% EM
gamma = 0.5;
iterations_EM = 3;
for i = 1:iterations_EM
% Likelihood of a datam given that it is an inlier
p_i = Gaussian(gamma,disterr,sigma);
% Likelihood of a datum given that it is an outlier
p_o = Uniform(gamma,v);
zi = p_i./(p_i + p_o);
gamma = sum(zi)/num_pt;
end
% Find the log likelihood of the mode -L
d_cur_pentnalty = -sum(log(p_i+p_o));
if(d_cur_pentnalty < d_best_penalty)
d_best_penalty = d_cur_pentnalty;
% record inlier
best_inlier = p_n(inlier,:);
max_num_inlier = num_inlier;
best_model = Xopt;
% Adapt k
w = max_num_inlier / num_pt;
p_no_outliers = 1 - w^s;
k = log(1-probability)/log(p_no_outliers);
end
% RANSAC
% if (num_inlier > max_num_inlier)
% max_num_inlier = num_inlier;
% best_model = Xopt;
%
% % Adapt k
% w = max_num_inlier / num_pt;
% p_no_outliers = 1 - w^s;
% k = log(1-probability)/log(p_no_outliers);
% end
iteration = iteration + 1;
if iteration > max_iteration
break;
end
end
a_est = best_model(1,:);
b_est = best_model(2,:);
c_est = best_model(3,:);
Z_opt = f(a_est,b_est,c_est,X,Y);
new_sur = mesh(X,Y,Z_opt,'edgecolor', 'r','FaceAlpha',0.5); % estimate
title('MLESAC',sprintf('original: a/c = %.2f, b/c = %.2f, c/c = %.2f\n new: a/c = %.2f, b/c = %.2f, c/c = %.2f',a/c,b/c,c/c,a_est,b_est,c_est));
The reference of my source code is from PCL(MLESAC), and I coded it in MATLAB.

Calculating gradients of cusom loss function with Gradient.Tape

I am trying custom traning of the network using Gradient.Tape method.
This traning is unsupervised.
The details of network and cost function is as following,
My Network is,
def CreateNetwork(inplayer, hidlayer, outlayer,seed):
model = keras.Sequential()
model.add(Dense(hidlayer, input_dim=inplayer, kernel_initializer=initializers.RandomNormal(mean=0.0,stddev=1/np.sqrt(inplayer),seed=seed), bias_initializer=initializers.RandomNormal(mean=0.0,stddev=1/np.sqrt(inplayer),seed=seed), activation='tanh'))
model.add(Dense(outlayer, kernel_initializer=initializers.RandomNormal(mean=0.0,stddev=1/np.sqrt(hidlayer),seed=seed), bias_initializer=initializers.Zeros(), activation='linear'))
return model
and my custom cost function is defined as,
def H_tilda(J,U,nsamples,nsites,configs,out_matrix):
EigenValue = 0.0
for k in range(nsamples):
config = configs[k,:]
out_n = out_matrix[k,:]
exp = 0.0
for i in range(nsamples):
n = configs[i,:]
out_nprime = out_matrix[i,:]
#------------------------------------------------------------------------------------------------
# Calculation of Hopping Term
#------------------------------------------------------------------------------------------------
hop = 0.0
for j in range(nsites):
if j == 0:
k = [nsites-1,j+1]
elif j == (nsites - 1):
k = [j-1,0]
else:
k = [j-1,j+1]
if n[k[0]] != 0:
annihiliate1 = np.sqrt(n[k[0]])
n1 = np.copy(n)
n1[k[0]] = n1[k[0]] - 1
n1[j] = n1[j] +1
if (config == n1).all():
delta1 = 1
else:
delta1 = 0
else:
annihiliate1 = 0
n1 = np.zeros(nsites)
delta1 = 0
if n[k[1]] != 0:
annihiliate2 = np.sqrt(n[k[1]])
n2 = np.copy(n)
n2[k[1]] = n2[k[1]] -1
n2[j] = n2[j] + 1
if (config == n2).all():
delta2 = 1
else:
delta2 = 0
else:
annihiliate2 = 0
n2 = np.zeros(nsites)
delta2 = 0
create = np.sqrt(n[j] + 1)
hop = hop + create*(annihiliate1*delta1 + annihiliate2*delta2)
#------------------------------------------------------------------------------------------------
#------------------------------------------------------------------------------------------------
# Calculation of Onsite Term
#------------------------------------------------------------------------------------------------
if (config == n).all():
ons = np.sum(np.dot(np.square(n),n - 1))
else:
ons = 0.0
#------------------------------------------------------------------------------------------------
phi_value = phi(out_nprime.numpy())
exp = exp + ((hop + ons) * phi_value)
Phi_value = phi(out_n.numpy())
EigenValue = EigenValue + exp/Phi_value
return np.real(EigenValue/nsamples)
I want to do custom traning using GradientTape method, for which I used following lines ,
optimizer = optimizers.SGD(learning_rate=1e-3)
with tf.GradientTape(watch_accessed_variables=False) as tape:
tape.watch(tf.convert_to_tensor(configs))
out_matrix = model(configs)
print(out_matrix)
eival = H_tilda(J,U,nsamples,nsites,configs,out_matrix)
print(eival)
gradients = tape.gradient(tf.convert_to_tensor(eival), model.trainable_weights)
print(gradients)
But the gradient I am getting is NONE,
output: [None, None, None, None]

Selenium Python: a better way to do this

A better cleaner way to achieve this is appreciated guys...
import random<br>
import time<br>
from selenium import webdriver<br>
from selenium.webdriver.common.keys import Keys<br>
randomNumber = random.randint(1, 3)<br>
randomNumber1 = random.randint(1, 3)<br>
randomNumber2 = random.randint(1, 3)<br>
randomNumber3 = random.randint(1, 3)<br>
randomNumber4 = random.randint(1, 3)<br>
randomNumber5 = random.randint(1, 3)<br>
randomNumber6 = random.randint(1, 3)<br>
randomNumber7 = random.randint(1, 3)<br>
randomNumber8 = random.randint(1, 3)<br>
randomNumber9 = random.randint(1, 3)<br>
randomNumber10 = random.randint(1, 3)<br>
driver.find_element_by_xpath("/html/body/div[1]/form/div[5]/div[6]/div[2]/div/div[3]/div[1]/div[3]/div[" + str(randomNumber) + "]/a/span").click()
driver.find_element_by_xpath("/html/body/div[1]/form/div[5]/div[6]/div[2]/div/div[3]/div[2]/div[3]/div[" + str(randomNumber2) + "]/a/span").click()
driver.find_element_by_xpath("/html/body/div[1]/form/div[5]/div[6]/div[2]/div/div[3]/div[3]/div[3]/div[" + str(randomNumber3) + "]/a/span").click()
driver.find_element_by_xpath("/html/body/div[1]/form/div[5]/div[6]/div[2]/div/div[3]/div[4]/div[3]/div[" + str(randomNumber4) + "]/a/span").click()
driver.find_element_by_xpath("/html/body/div[1]/form/div[5]/div[6]/div[2]/div/div[3]/div[5]/div[3]/div[" + str(randomNumber5) + "]/a/span").click()
driver.find_element_by_xpath("/html/body/div[1]/form/div[5]/div[6]/div[2]/div/div[7]/div[1]/div[3]/div[" + str(randomNumber6) + "]/a/span").click()
driver.find_element_by_xpath("/html/body/div[1]/form/div[5]/div[6]/div[2]/div/div[7]/div[2]/div[3]/div[" + str(randomNumber7) + "]/a/span").click()
driver.find_element_by_xpath("/html/body/div[1]/form/div[5]/div[6]/div[2]/div/div[7]/div[3]/div[3]/div[" + str(randomNumber8) + "]/a/span").click()
driver.find_element_by_xpath("/html/body/div[1]/form/div[5]/div[6]/div[2]/div/div[7]/div[4]/div[3]/div[" + str(randomNumber9) + "]/a/span").click()
driver.find_element_by_xpath("/html/body/div[1]/form/div[5]/div[6]/div[2]/div/div[7]/div[5]/div[3]/div[" + str(randomNumber10) + "]/a/span").click()
This should help you:
numbers = [random.randint(1,3) for x in range(11)] #Generates a list of 10 random numbers between 1 and 3
for number in numbers: #Loops through the list of random numbers generated
driver.find_element_by_xpath("/html/body/div[1]/form/div[5]/div[6]/div[2]/div/div[3]/div[1]/div[3]/div[" + str(number) + "]/a/span").click() #Clicks on the respective xpath of each number

Pandas/NumPy: concisely label first N values matching a mask

I have a sorted Series like this:
[2, 4, 5, 6, 8, 9]
I want to produce another Series or ndarray of the same length, where the first two odd numbers and the first two even numbers are labeled sequentially:
[0, 1, 2, _, _, 3]
The _ values I don't really care about. They can be zero.
Now I do it this way:
src = pd.Series([2, 4, 5, 6, 8, 9])
odd = src % 2 != 0
where = np.hstack((np.where(odd)[0][:2], np.where(~odd)[0][:2]))
where.sort() # maintain ordering - thanks to #hpaulj
res = np.zeros(len(src), int)
res[where] = np.arange(len(where))
Can you do it more concisely? The input will never be empty, but there might be no odds or no evens (in which case the result could have length 1, 2, or 3 instead of 4).
Great Problem! I'm still exploring and learning.
I've basically stuck with what you've done so far with modest tweaks for efficiency. I'll update if I think of anything else cool.
conclusions
So far, I've thrashed around alot and haven't improved much.
my answer
fast
odd = src.values % 2
even = 1 - odd
res = ((odd.cumsum() * odd) < 3) * ((even.cumsum() * even) < 3)
(res.cumsum() - 1) * res
alternative 1
pretty fast
a = src.values
odd = (a % 2).astype(bool)
rng = np.arange(len(a))
# same reason these are 2, we have 4 below
where = np.append(rng[~odd][:2], rng[odd][:2])
res = np.zeros(len(a), int)
# nature of the problem necessitates that this is 4
res[where] = np.arange(4)
alternative 2
not as quick, but creative
a = src.values
odd = a % 2
res = np.zeros(len(src), int)
b = np.arange(2)
c = b[:, None] == odd
res[(c.cumsum(1) * c <= 2).all(0)] = np.arange(4)
alternative 3
still slow
odd = src.values % 2
a = (odd[:, None] == [0, 1])
b = ((a.cumsum(0) * a) <= 2).all(1)
(b.cumsum() - 1) * b
timing
code
def pir3(src):
odd = src.values % 2
a = (odd[:, None] == [0, 1])
b = ((a.cumsum(0) * a) <= 2).all(1)
return (b.cumsum() - 1) * b
def pir0(src):
odd = src.values % 2
even = 1 - odd
res = ((odd.cumsum() * odd) < 3) * ((even.cumsum() * even) < 3)
return (res.cumsum() - 1) * res
def pir2(src):
a = src.values
odd = a % 2
res = np.zeros(len(src), int)
c = b[:, None] == odd
res[(c.cumsum(1) * c <= 2).all(0)] = np.arange(4)
return res
def pir1(src):
a = src.values
odd = (a % 2).astype(bool)
rng = np.arange(len(a))
where = np.append(rng[~odd][:2], rng[odd][:2])
res = np.zeros(len(a), int)
res[where] = np.arange(4)
return res
def john0(src):
odd = src % 2 == 0
where = np.hstack((np.where(odd)[0][:2], np.where(~odd)[0][:2]))
res = np.zeros(len(src), int)
res[where] = np.arange(len(where))
return res
def john1(src):
odd = src.values % 2 == 0
where = np.hstack((np.where(odd)[0][:2], np.where(~odd)[0][:2]))
res = np.zeros(len(src), int)
res[where] = np.arange(len(where))
return res
src = pd.Series([2, 4, 5, 6, 8, 9])
src = pd.Series([2, 4, 5, 6, 8, 9] * 10000)

multiprocessing.Process does not initiate the parallel run of functions by start()

I don't understand how to get multiprocessing.Process started. I used the following example code:
import random, time
import multiprocessing
def frz(no, tm):
a = 'start ' + str(no)
print(a)
time.sleep(tm)
a = str(no) + '=====> '+ str(tm) +'\n'
print(a)
if __name__ == '__main__':
freeze1 = random.randint(1, 5)
freeze2 = random.randint(1, 5)
freeze3 = random.randint(1, 5)
freeze4 = random.randint(1, 5)
freeze5 = random.randint(1, 5)
trd1 = multiprocessing.Process(target=frz, args=(1, freeze1))
trd2 = multiprocessing.Process(target=frz, args=(2, freeze2))
trd3 = multiprocessing.Process(target=frz, args=(3, freeze3))
trd4 = multiprocessing.Process(target=frz, args=(4, freeze4))
trd5 = multiprocessing.Process(target=frz, args=(5, freeze5))
#threading
trd1.start()
trd2.start()
trd3.start()
trd4.start()
trd5.start()
When multiprocessing.Process is being replaced by threading.Thread the function works fine, but with multiprocessing nothing seems to happen.
When I ran your code, this is what I saw:
start 5
start 4
start 3
start 2
start 1
2=====> 1
5=====> 3
3=====> 3
4=====> 4
1=====> 5
Is this what you were expecting?