this is a decode function for hexadecimal value,
I tried to figure out the encode function for it, but no luck.
function dtwin(flg: Integer): Integer;
var i:integer;
ner,yrd, yrv :Cardinal;
unr :Int64;
begin
ner := 1;
unr := flg;
yrd := $2E8CFFB0;
yrv := $0C8CFFF0;
for i := 1 to 32 do
begin
if (yrv and 1) <> 0 then
begin
ner := ((ner * unr) mod (yrd));
end;
unr := ((unr * unr) mod (yrd));
yrv := (yrv shr 1) and $7FFFFFFF;
end;
Result := ner;
end;
The short answer is: It can't be done.
Please read:
http://en.wikipedia.org/wiki/Modular_exponentiation
Let b = flg
Let e = $0C8CFFF0 = 210567152
Let m = $2E8CFFB0 = 780992432
Then this function is calculating ( b ^ e ) mod m
To reverse it, we need to find the multiplicative inverse of e mod m.
I tried using WolframAlpha.
http://www.wolframalpha.com/input/?i=multiplicative+inverse+of+210567152+mod+780992432
The result it gives is:
(210567152 is not invertible modulo 780992432)
The reason is that e and m are not co-prime. They are both divisible by two.
From this we can conclude that there is no way to reverse this function because there are colissions.
As an example:
dtwin(60) = dtwin(2326) = 62188800
What should the reverse function return when called with the parameter 62188800?
Should it return 60 or 2326?
Here are some more examples of collisions:
dtwin(658) = dtwin(1300) = 682595280
dtwin(60) = dtwin(2326) = 62188800
dtwin(1316) = dtwin(2600) = 76519712
dtwin(2312) = dtwin(3522) = 317601904
dtwin(1974) = dtwin(3900) = 52357088
dtwin(120) = dtwin(4652) = 144155936
dtwin(2632) = dtwin(5200) = 679101872
dtwin(3290) = dtwin(6500) = 322955216
dtwin(3989) = dtwin(6725) = 301338273
dtwin(180) = dtwin(6978) = 628048624
dtwin(4624) = dtwin(7044) = 435300992
dtwin(5080) = dtwin(7658) = 2152880
dtwin(3948) = dtwin(7800) = 682904608
dtwin(2685) = dtwin(8183) = 461799889
dtwin(2461) = dtwin(8951) = 170465
dtwin(4606) = dtwin(9100) = 138445536
dtwin(240) = dtwin(9304) = 231258592
dtwin(4741) = dtwin(9603) = 586985553
dtwin(6117) = dtwin(9923) = 277591073
To generate results that could be useful for encryption, you can generate numbers as follows.
I won't go into details here about how this works. You can Google public key cryptography if you need to know more.
Select P and Q that are prime.
Compute N = P * Q
Compute T = (P-1) * (Q-1) This is called the totient.
Select E that is coprime to N and T.
Select D that is the multiplicative inverse of E mod T.
Your modulus is N. The two exponents are E and D.
To encrypt A, calculate B = ( A ^ E ) mod N
To decrypt B, calculate A = ( B ^ D ) mod N
Note that in real-world encryption, these values typically have hundreds or thousands of digits.
Here are some results that are in the order of magnitude of your examples:
N = 590108483 =$232C5743
E = 547145911 =$209CC8B7
D = 507147559 =$1E3A7527
N = 763464677 =$2D818BE5
E = 545809367 =$208863D7
D = 622691303 =$251D83E7
N = 948703211 =$388C0FEB
E = 885205759 =$34C32AFF
D = 893844127 =$3546FA9F
N = 897918037 =$35852455
E = 894567871 =$355205BF
D = 539129719 =$20227777
N = 754905647 =$2CFEF22F
E = 540902531 =$203D8483
D = 534729131 =$1FDF51AB
Related
In pycocotools in cocoeval.py sctipt there is COCOeval class and in this class there is accumulate function for calculating Precision and Recall. Does anyone know what is this npig variable? Is this negative-positive or?
Because I saw this formula for recall: Recall = (True Positive)/(True Positive + False Negative)
Can I just use this precision and recall variable inside dictionary self.eval to get precision and recall of my model which I'm testing, and plot a precision-recall curve?
And the variable scores is this F1 score?
Because I'm not very well understand this T,R,K,A,M what is happening with this.
How can I print precision and recall in terminal?
def accumulate(self, p = None):
'''
Accumulate per image evaluation results and store the result in self.eval
:param p: input params for evaluation
:return: None
'''
print('Accumulating evaluation results...')
tic = time.time()
if not self.evalImgs:
print('Please run evaluate() first')
# allows input customized parameters
if p is None:
p = self.params
p.catIds = p.catIds if p.useCats == 1 else [-1]
T = len(p.iouThrs)
R = len(p.recThrs)
K = len(p.catIds) if p.useCats else 1
A = len(p.areaRng)
M = len(p.maxDets)
precision = -np.ones((T,R,K,A,M)) # -1 for the precision of absent categories
recall = -np.ones((T,K,A,M))
scores = -np.ones((T,R,K,A,M))
# create dictionary for future indexing
_pe = self._paramsEval
catIds = _pe.catIds if _pe.useCats else [-1]
setK = set(catIds)
setA = set(map(tuple, _pe.areaRng))
setM = set(_pe.maxDets)
setI = set(_pe.imgIds)
# get inds to evaluate
k_list = [n for n, k in enumerate(p.catIds) if k in setK]
m_list = [m for n, m in enumerate(p.maxDets) if m in setM]
a_list = [n for n, a in enumerate(map(lambda x: tuple(x), p.areaRng)) if a in setA]
i_list = [n for n, i in enumerate(p.imgIds) if i in setI]
I0 = len(_pe.imgIds)
A0 = len(_pe.areaRng)
# retrieve E at each category, area range, and max number of detections
for k, k0 in enumerate(k_list):
Nk = k0*A0*I0
for a, a0 in enumerate(a_list):
Na = a0*I0
for m, maxDet in enumerate(m_list):
E = [self.evalImgs[Nk + Na + i] for i in i_list]
E = [e for e in E if not e is None]
if len(E) == 0:
continue
dtScores = np.concatenate([e['dtScores'][0:maxDet] for e in E])
# different sorting method generates slightly different results.
# mergesort is used to be consistent as Matlab implementation.
inds = np.argsort(-dtScores, kind='mergesort')
dtScoresSorted = dtScores[inds]
dtm = np.concatenate([e['dtMatches'][:,0:maxDet] for e in E], axis=1)[:,inds]
dtIg = np.concatenate([e['dtIgnore'][:,0:maxDet] for e in E], axis=1)[:,inds]
gtIg = np.concatenate([e['gtIgnore'] for e in E])
npig = np.count_nonzero(gtIg==0 )
if npig == 0:
continue
tps = np.logical_and( dtm, np.logical_not(dtIg) )
fps = np.logical_and(np.logical_not(dtm), np.logical_not(dtIg) )
tp_sum = np.cumsum(tps, axis=1).astype(dtype=np.float)
fp_sum = np.cumsum(fps, axis=1).astype(dtype=np.float)
for t, (tp, fp) in enumerate(zip(tp_sum, fp_sum)):
tp = np.array(tp)
fp = np.array(fp)
nd = len(tp)
rc = tp / npig
pr = tp / (fp+tp+np.spacing(1))
q = np.zeros((R,))
ss = np.zeros((R,))
if nd:
recall[t,k,a,m] = rc[-1]
else:
recall[t,k,a,m] = 0
# numpy is slow without cython optimization for accessing elements
# use python array gets significant speed improvement
pr = pr.tolist(); q = q.tolist()
for i in range(nd-1, 0, -1):
if pr[i] > pr[i-1]:
pr[i-1] = pr[i]
inds = np.searchsorted(rc, p.recThrs, side='left')
try:
for ri, pi in enumerate(inds):
q[ri] = pr[pi]
ss[ri] = dtScoresSorted[pi]
except:
pass
precision[t,:,k,a,m] = np.array(q)
scores[t,:,k,a,m] = np.array(ss)
self.eval = {
'params': p,
'counts': [T, R, K, A, M],
'date': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
'precision': precision,
'recall': recall,
'scores': scores,
}
toc = time.time()
print('DONE (t={:0.2f}s).'.format( toc-tic))
I have an example of a code and not sure what way is the best to use.
For example I have
if (x = 1) and (y = 2) and (if abc = false then check if z = 3) then
begin
...
check only
if x = 1
if y = 2
if abc = false check z = 3. if abc = true then dont check z = 3
i am not sure if i am explaining the best but hopefuly people will understand.
I want to know if this is possible or the best way to do it. Keeping in mind that rather than in example where its x, y, z and abc. there can be more in my use.
I currently have structure as...which i dont think is practical, and think theres a better way but i am not sure
if (abc = false) then
begin
if (x = 1) and (y = 2) and (z = 3) then
begin
...
end
else
begin
if (x = 1) and (y = 2) then
begin
...
Thanks in advance
I think you're looking for or. Now you will check that x must be 1, y must be 2, and if abc is false, z must be 3.
If abc = true, z can still be three, but it won't be checked.
Note that I just wrote abc instead of abc = true. Since it's a Boolean (true/false) already, that's allowed.
Also note how the operations are grouped using parentheses. The total sub-expression abc or (z=3) must return true for the total expression to return true.
Furthermore the sequence of the terms is significant - they are evaluated left-to-right. If the term (abc or (z=3)) is replaced by the logically-equivalent term ((z=3) or abc) then z=3 will be evaluated.
if (x = 1) and (y = 2) and (abc or (z = 3)) then
// Your magic goes here
Test program body to prove sequence is important
function z : Integer;
begin
writeln('Z being evaluated');
result := x + y;
end;
begin
x := 1;y := 2;
abc := true;
if (x=1) and (y=2) and (abc or (z=3)) then
writeln ('evaluated true')
else
writeln ('evaluated false');
writeln('done');
readln;
end.
Neither of your code samples compile, because neither is using the proper syntax.
This should get you started:
if (x = 1) and (y = 2) then
begin
if (abc) then
// Handle abc = True
else
begin
if (z = 3) then
// Handle abc = false and z = 3
else
// Handle abc = false and z <> 3
end;
end;
I am writing codes to find a solution (E) to Kepler's equation:
E - e*sin(E) = M
and all angles are expressed in radians,
M = 3.52821,
e = 0.016714
and theses are the steps:
First guess, put E = Eo = M
Find the value of O = E - e*sin(E) - M
If |O| <= 0.000006, go to step 6
If |O| > 0.000006, proceed with step 4
Find delta_E = O/(1-e*sin(E))
Take new value E1 = E - delta_E, go to step 2
The present value of E is the solution, correct within 0.000006 of the true value
However, I don't know how to write codes (swift) of those steps, please help me.
Thanks to #NSNoob
I finally figure the solution out!!!
let M = 3.52821
var e = 0.016714
var E = M
var O = E - (e * sin(E)) - M
while (abs(O) > 0.000006) {
var Delta_E = O / (1-(e*cos(E)))
E = E - Delta_E
O = E - (e * sin(E)) - M
}
print(E)
First of all some corrections in your question which you apparently forgot to mention and I had to look for here.
E0 = M
E = E1 on next iteration if solution not found
Regarding technical terms, E here is called Eccentric Anomaly and M is called mean Anomaly. Where as eps is precision diameter. Also, E=e according to the shared article
Also in swift, we use camel case naming convention for variables and constants but here I have tried to use your names so that you could understand the code.
Now back to business, Following methods will do it for you using recursion:
func solveKeplersEquationForParamas(M:Double)->Void{
let E:Double = M
let eps:Double = 0.000006
let AbsoluteValueOfO:Double = getAbsoluteValueOfO(E, M: M,eps: eps)
print(NSString(format:"Answer is:%f", AbsoluteValueOfO))
}
func getAbsoluteValueOfO(E:Double,M:Double,eps:Double) -> Double {
var SinOFE: Double = Double(sin(E))
SinOFE = E*SinOFE
var E1 = E;
let O = E - SinOFE - M
var AbsoluteValueOfO = fabs(O)
if AbsoluteValueOfO > eps {
print("Solution not found. go to step 4");
let denom = 1-E*sin(E)
let absDenom = fabs(denom)
if absDenom>0{
let deltaE = O/denom
E1 = E-deltaE
AbsoluteValueOfO = getAbsoluteValueOfO(E1, M: M, eps: eps)
}
else{
print("Denom became 0, Can't divide by zero Denom is:%f",denom);
return AbsoluteValueOfO
}
}
else if AbsoluteValueOfO < eps || AbsoluteValueOfO == eps{
print("Solution found. Returning the value");
print(NSString(format:"Value of E is:%f", E1))
}
return AbsoluteValueOfO
}
Running this in playground like:
solveKeplersEquationForParamas(3.094763)
Playground output:
NOTE: This is the Swift solution to the steps you have mentioned. Responsibility for any error in steps lies on you.
I get what this wiki page says(http://en.wikipedia.org/wiki/Multinomial_logistic_regression), but I don't know how to get the update rules for stochastic gradient descent. Sorry to ask this here(this is really just about machine learning theories instead of actual implementation). Could someone provide a solution with explanation? Thanks in advance!
I happened to write code to implent softmax, I refer most to the page http://ufldl.stanford.edu/wiki/index.php/Softmax_Regression
this is the code I wrote in matlab ,hope it will help
function y = sigmoid_multi(weight,x,class_index)
%% weight feature_dim * class_num
%% x feature_dim * 1
%% class_index scalar
sum = eps;
class_num = size(weight,2);
for i = 1:class_num
sum = sum + exp(weight(:,i)'*x);
end
y = exp(weight(:,class_index)'*x)/sum;
end
function g = gradient(train_patterns,train_labels,weight)
m = size(train_patterns,2);
class_num = size(weight,2);
g = zeros(size(weight));
for j = 1:class_num
for i = 1:m
if(train_labels(i) == j)
g(:,j) = g(:,j) + (1 - log( sigmoid_multi(weight,train_patterns(:,i),j) + eps))*train_patterns(:,i);
end
end
end
g = -(g/m);
end
function J = object_function(train_patterns,train_labels,weight)
m = size(train_patterns,2);
J = 0;
for i = 1:m
J = J + log( sigmoid_multi(weight,train_patterns(:,i),train_labels(i)) + eps);
end
J = -(J/m);
end
function weight = multi_logistic_train(train_patterns,train_labels,alpha)
%% weight feature_dim * class_num
%% train_patterns featur_dim * sample_num
%% train_labels 1 * sample_num
%% alpha scalar
class_num = length(unique(train_labels));
m = size(train_patterns,2); %% sample_number;
n = size(train_patterns,1); % feature_dim;
weight = rand(n,class_num);
for i = 1:40
J = object_function(train_patterns,train_labels,weight);
fprintf('objec function value : %f\n',J);
weight = weight - alpha*gradient(train_patterns,train_labels,weight);
end
end
I'm writing a back propagation algorithm in matlab. But I can not get to write a good solution. I read a book Haykin and read some topics in Internet, how make it other people. I understand from door to door this algorithm in theory, but I have a much of error in practice. I have a NaN in my code.
You can see here.
I'm trying classification some points on plate. These are three ellipses, which are placed one inside the other.
I wrote this function. The second layer learn, but first layer dont learn.
function [E, W_1, W_2, B_1, B_2, X_3] = update(W_1, W_2, B_1, B_2, X_1, T, alpha)
V_1 = W_1 * X_1 + B_1;
X_2 = tansig(V_1);
V_2 = W_2 * X_2 + B_2;
X_3 = tansig(V_2);
E = 1 / 2 * sum((T - X_3) .^ 2);
dE = (T - X_3);
for j = 1 : size(X_2, 1)
delta_2_sum = 0;
for i = 1 : size(X_3, 1)
delta_2 = dE(i, 1) * dtansig(1, V_2(i, 1) );
W_2_tmp(i, j) = W_2(i, j) - alpha * delta_2 * X_2(j, 1);
B_2_tmp(i, 1) = B_2(i, 1) - alpha * delta_2;
end;
end;
for k = 1 : size(X_1, 1)
for j = 1 : size(X_2, 1)
delta_2_sum = 0;
for i = 1 : size(X_3, 1)
delta_2 = dE(i, 1) * dtansig(1, V_2(i, 1) );
delta_2_sum = delta_2_sum + W_2(i, j) * delta_2;
end;
delta_1 = delta_2_sum * dtansig(1, V_1(j, 1) );
W_1_tmp(j, k) = W_1(j, k) - alpha * delta_1 * X_1(k, 1);
B_1_tmp(j, 1) = B_1(j, 1) - alpha * delta_1;
end;
end;
if (min(W_1) < -10000 )
X = 1;
end;
B_1 = B_1_tmp;
B_2 = B_2_tmp;
W_1 = W_1_tmp
W_2 = W_2_tmp;
end
I wrote another variant code. And this code don't work. I calculated this code with 1-dimensional vector as input and as output. And I don't have truth result.
What can I do?
I use matlab nntool interface. But my backprop was written my hand.
How I can testing my code?
function [net] = backProp(net, epoch, alpha)
for u = 1 : epoch % Число эпох
for p = 1 : size(net.userdata{1, 1}, 2)
% Учим по всем элементам выборки
[~, ~, ~, De, Df, f] = frontProp(net, p, 1);
for l = size(net.LW, 1) : -1 : 1 % Обходим слои
if (size(net.LW, 1) == l )
delta{l} = De .* Df{l};
else
% size(delta{l + 1})
% size(net.LW{l + 1})
delta{l} = Df{l} .* (delta{l + 1}' * net.LW{l + 1} )';
end;
if (l == 1)
net.IW{l} + alpha * delta{l} * f{l}'
net.IW{l} = net.IW{l} + alpha * delta{l} * f{l}';
else
net.LW{l} + alpha * delta{l} * f{l}'
net.LW{l} = net.LW{l} + alpha * delta{l} * f{l}';
end;
end;
end;
end;
end