MATLAB Size equivalent function in python - python

hI i have a code in matlab. Based on my understanding I have translated that code to python. Can someone let me know if it is the right way to translate.
for i = 1:length(Filters)
Filters{i} = gpuArray(2*(single(sign(Filters{i}))-0.5));
NumLearntWeightsEachLayer(i) = size(Filters{i},3)*size(Filters{i},4)*4;
end
NumLearntWeightsEachLayer(end) = size(Filters{end},3)*size(Filters{end},4);
NumLearntWeightsEachLayer
TotalLearntWeights = sum(NumLearntWeightsEachLayer)
Could someone let me know if this could be an equivalent code for the for loop here.
for i in range (1,Filters):
Filters(i) = (2* (Filters(i) - 0.5))
NumLearntWeightsEachLayer(i) = (Filters(i),3).shape * (Filters(i),4).shape *4
I also want to know what could be the right translation for the last part of the code
NumLearntWeightsEachLayer(end) = size(Filters{end},3)*size(Filters{end},4);

It's a good start.. some small fixes -
for i in range (0,len(Filters)):
for j in range(0, len(Filters[i]):
Filters[i][j] = 2*(round(Filters[i][j],1) - 0.5)
NumLearntWeightsEachLayer[i] = len(Filters[i][3])*len(Filters[i][4])*4
For the last line-
NumLearntWeightsEachLayer(end) = size(Filters{end},3)*size(Filters{end},4);
It can be written as -
NumLearntWeightsEachLayer[-1] = len(Filters[-1][3])*len(Filters[-1][4]);

Related

Problem to get old series data (Python for Finance)

I've converted this formula (ZLEMA Moving Average)
But I have many issues with "Data(Lag Days Ago)", it seems that it cant go back to find the result. Here's the function but unfortunately it doesn't produce the desired result.
def fzlema(source,period):
zxLag = period / 2 if (period / 2) == np.round(period / 2) else (period - 1) / 2
zxLag = int(zxLag)
zxEMAData = source + (source - source.iloc[zxLag]) # Probably error is in this line
zlema = zxEMAData.ewm(span=period, adjust=False).mean()
zlema = np.round(zlema,2)
return zlema
zlema = fzlema(dataframe['close'], 50)
To be clear, the script runs perfectly but what I got is unmatched as it's been calculated on Tradingview.
I tried used iloc[..] and tail(..) but neither return exact results.
I can use the libraries pandas and numpy.
Any point of view?
SOLVED:
Simply using source.shift(zxLag)

Two consecutive parentheses after name in Matlab

Please excuse me for this amateurish question,
I'm trying to convert some Matlab code to Python, I don't have any experience with Matlab but so far I have been able to deduce what the Matlab code does and the conversion so far has been successful.
But now I am stuck at these lines of code;
SERAstart = []
for n=1:length(bet)
alf = -bet(n) * 1e-2;
SERAstart = [SERAstart(alf - i * bet(n))(alf + i * bet(n))];
end
What I don't understand is this line;
SERAstart(alf - i * bet(n))(alf + i * bet(n))
Two consecutive parentheses after "SERAstart", are they nested array indexing? are they indexing and then function call to return of indexing? are they function call and then function call again to return value of first call?
Please help me understand what is going on here so that I can convert it to Python.
I realize that it might not be possible just from the piece of code I have posted to say definitively what it does, but otherwise if you can help guide me to how to figure it out (without the use of Matlab) then I would also be very grateful.
Thanks a lot for any help!.
EDIT:
This is my own attempt at a conversion, but I don't know if this makes sense;
# SERAstart = [];
SERAstart = [[]]
# for n=1:length(bet)
for n in range(len(bet)):
# alf = -bet(n) * 1e-2;
alf = -bet[n] * 1e-2
# SERAstart = [SERAstart(alf - i * bet(n))(alf + i * bet(n))];
SERAstart = [SERAstart[alf - 1j * bet[n]][alf + 1j * bet[n]]]
# end
EDIT2:
I just noticed this line in the documentation relating to SERAstart:
% SERAstart(N,1) : vector of starting poles [rad/sec]

How to Multiply array without numpy and math in pandas csv file

Halo, im sabil and newbie using python
First of all, i want to multiplle array with index:
[90,20] with [20,7]
My mentor ask me to not using anything library like (dot,add,etc) but using array
Here is my codefor transpose() :
def nilaiWeightTranspose():
nilaiWTranspose = jumlahBobot
x,y = jumlahBobot.shape
hasil = np.zeros((y,x))
for i in range(y):
for j in range(x):
hasil[i,j] = jumlahBobot.iloc[j,i]
hasilTranspose = pd.DataFrame(data = hasil[0:,0:])
return hasilTranspose
and output :
and here is my code for datanormalisasi():
def minmaxnormalization_latih(dropdata):
minperfeature = []
maxperfeature = []
datanormalisasilatih = datalatih
for i in range(len(dropdata.columns)):
minperfeature.append(min(dropdata[dropdata.columns[i]]))
maxperfeature.append(max(dropdata[dropdata.columns[i]]))
for i in range(len(datalatih.index)):
for j in range(len(datalatih.columns)):
datanormalisasilatih.loc[i, datalatih.columns[j]] = (datanormalisasilatih.loc[i, datalatih.columns[j]] - minperfeature[j]) / (maxperfeature[j] - minperfeature[j])
return datanormalisasilatih
and here is my code if i using library(dot) and succesful :
def nilaiHinit():
hitung_hInit = pd.DataFrame(datanormalisasilatih.values.dot(hasilTranspose.values), columns=jumlahBias.columns)
hitung_hInit_bias = hitung_hInit
the problem is idk how to multiple array without (dot) and i want to multiple array without (dot) or anything, can anyone know how to solve it?
thank you ^^

Can I write python code that modifies itself during execution?

I mean,
target_ZCR_mean = sample_dataframe_summary['ZCR'][1]
target_ZCR_std = sample_dataframe_summary['ZCR'][2]
lower_ZCR_lim = target_ZCR_mean - target_ZCR_std
upper_ZCR_lim = target_ZCR_mean + target_ZCR_std
target_RMS_mean = sample_dataframe_summary['RMS'][1]
target_RMS_std = sample_dataframe_summary['RMS'][2]
lower_RMS_lim = target_RMS_mean - target_RMS_std
upper_RMS_lim = target_RMS_mean + target_RMS_std
target_TEMPO_mean = sample_dataframe_summary['Tempo'][1]
target_TEMPO_std = sample_dataframe_summary['Tempo'][2]
lower_TEMPO_lim = target_TEMPO_mean - target_TEMPO_std
upper_TEMPO_lim = target_TEMPO_mean + target_TEMPO_std
target_BEAT_SPACING_mean = sample_dataframe_summary['Beat Spacing'][1]
target_BEAT_SPACING_std = sample_dataframe_summary['Beat Spacing'][2]
lower_BEAT_SPACING_lim = target_BEAT_SPACING_mean - target_BEAT_SPACING_std
upper_BEAT_SPACING_lim = target_BEAT_SPACING_mean + target_BEAT_SPACING_std
each block of four lines of code are very similar to each other except for a few characters.
Can I write a function, a class or some other piece of code, such that I can wrap just a template of four lines of code into it and let it modify itself during runtime to get the code do the work of the above code...?
By the way, I use python 3.6.
If you find yourself storing lots of variables like this, especially if they are related, there is almost certainly a better way of doing it. Modifying the source dynamically is never the solution. One way is to use a function to keep the repeated logic, and use a namedtuple to store the resultant data:
import collections
Data = collections.namedtuple('Data', 'mean, std, lower_lim, upper_lim')
def get_data(key, sample_dataframe_summary):
mean = sample_dataframe_summary[key][1]
std = sample_dataframe_summary[key][2]
lower_lim = mean - std
upper_lim = mean + std
return Data(mean, std, lower_lim, upper_lim)
zcr = get_data('ZCR', sample_dataframe_summary)
rms = get_data('RMS', sample_dataframe_summary)
tempo = get_data('Tempo', sample_dataframe_summary)
beat_spacing = get_data('Beat Spacing', sample_dataframe_summary)
then you can access the data with the . notation like zcr.mean and tempo.upper_lim

Blitz code produces different output

I want to use weave.blitz to improve the performance of the following numpy code:
def fastIteration(self):
g = self.grid
nx,ny = g.ux.shape
uxold = g.old_ux
ux = g.ux
ux[0:,1:-1] = uxold[0:,1:-1] + ReI* (uxold[0:,2:] - 2*uxold[0:,1:-1] + uxold[0:,0:-2])
g.setBC()
g.old_ux = ux.copy()
In this code g is the computational grid. Which consist of two different fields ux and uxold. The old is simply used for temporary storage of the variables. In the complete Code around 95% of the runtime is spend in the fastIteration method, therefore even a simple performance gain would reduce the amount of hours spend executing this code significantly.
The output of the numpy method looks as if:
As this code is my bottleneck I want to improve the speed by using weave blitz. This method looks like:
def blitzIteration(self):
### does not work correct so far
g = self.grid
nx,ny = g.ux.shape
uxold = g.old_ux
ux = g.ux
expr = "ux[0:,1:-1] = uxold[0:,1:-1] + ReI* (uxold[0:,2:] - 2*uxold[0:,1:-1] + uxold[0:,0:-2])"
weave.blitz(expr, check_size=0)
g.setBC()
g.old_ux = ux.copy()
However this does not produce the correct output:
It looks like a bug in weave.blitz (reproduced, filed and fixed. There's more information about the actual bug there).
I thought it was odd to write 0: instead of the shorter : to get a full slice so I replaced all those slices and voilĂ , it worked.
I don't really know where the bug lies, but the expr_code generated by weave.blitz is slightly different:
When using 0:
ipdb> expr_code
'ux_blitz_buggy(blitz::Range(0,_end),blitz::Range(1,Nux_blitz_buggy(1)-1-1))=uxold(blitz::Range(0,_end),blitz::Range(1,Nuxold(1)-1-1))+ReI*(uxold(blitz::Range(0,_end),blitz::Range(2,_end))-2*uxold(blitz::Range(0,_end),blitz::Range(1,Nuxold(1)-1-1))+uxold(blitz::Range(0,_end),blitz::Range(0,Nuxold(1)-2-1)));\n'
When using :
ipdb> expr_code
'ux_blitz_not_buggy(_all,blitz::Range(1,Nux_blitz_not_buggy(1)-1-1))=uxold(_all,blitz::Range(1,Nuxold(1)-1-1))+ReI*(uxold(_all,blitz::Range(2,_end))-2*uxold(_all,blitz::Range(1,Nuxold(1)-1-1))+uxold(_all,blitz::Range(0,Nuxold(1)-2-1)));\n'
So, blitz::Range(0,_end) becomes _all and they behave in a different way.
For convenience, here is a complete script that reproduces the problem and will only succeed while the problem exists.
import numpy as np
from scipy.weave import blitz
def test_blitz_bug(N=4):
ReI = 1.2
ux_blitz_buggy, ux_blitz_not_buggy, ux_np = np.zeros((N, N)), np.zeros((N, N)), np.zeros((N, N))
uxold = np.random.randn(N, N)
ux_np[0:,1:-1] = uxold[0:,1:-1] + ReI* (uxold[0:,2:] - 2*uxold[0:,1:-1] + uxold[0:,0:-2])
expr_buggy = 'ux_blitz_buggy[0:,1:-1] = uxold[0:,1:-1] + ReI* (uxold[0:,2:] - 2*uxold[0:,1:-1] + uxold[0:,0:-2])'
expr_not_buggy = 'ux_blitz_not_buggy[:,1:-1] = uxold[:,1:-1] + ReI* (uxold[:,2:] - 2*uxold[:,1:-1] + uxold[:,0:-2])'
blitz(expr_buggy)
blitz(expr_not_buggy)
assert not np.allclose(ux_blitz_buggy, ux_np)
assert np.allclose(ux_blitz_not_buggy, ux_np)
if __name__ == '__main__':
test_blitz_bug()

Categories

Resources