Reshape Numpy Array: 'list' object is not callable - python

I have a method, get_input_representation that returns a numpy array
np.array = input_stack + input_buffer
return np.array
In another a different part of the program, I call the above method, save its return value and reshape it.
state_rep = self.extractor.get_input_representation(words, pos, state)
reshaped_state = np.array(state_rep).reshape(-1,6)
However, I get:
reshaped_state = np.array(state_rep).reshape(-1,6) TypeError: 'list'
object is not callable
I have also tried:
reshaped_state = np.array(self.extractor.get_input_representation(words, pos, state)).reshape(-1,6)
But I get the same list object is not callable. Where is the error in my code and how can I go about fixing it?

I think you should not be assigning default Numpy methods to a variable (even if it is inside a function) ie instead of np.array = input_stack + input_buffer and then return np.array you should have return input_stack + input_buffer in your function

Would you need brackets instead of parens?
np.array[state_rep].reshape(-1,6)
I think you are trying to index into the np array right?

Related

Numpy exp() not callable

If I use 2 np arrays as x,y input into the following expression...
out = np.exp(3(x-4)-0.0001*y)
...I get "TypeError: 'int' object is not callable
If I use the same as function and call this function with a curve fit I get a similiar error:
def func(X, a, b):
x,y = X
return np.exp(a(x-4)-b*y)
Here I get:'numpy.float64' object is not callable
What am I doing wrong? It's working with others type of functions that don't use exp.
out = np.exp(3(x-4)-0.0001*y)
The problem in this expression is that the np.exp() function takes one argument but you passed 2. I don't know this is the best solution but instead of this you can try:
operations = 3*(x-4) - (0.0001*y)
out = np.exp(operations)

Calculating the Downside Deviation of an Array of Returns

I'm trying to calculate the downside deviation of an array of returns using the code below:
def downside_deviation(arr):
downside_returns = 0
arr.loc[arr < 0, 'downside_returns'] = arr
down_stdev = downside_returns**2
arraysize = downside_returns.count()
down_stdev = downside_returns.sum()/arraysize
down_stdev = np.sqrt(down_stdev)*np.sqrt(12)
return down_stdev
But I keep encountering the and AttributeError as below:
AttributeError: 'float' object has no attribute 'loc'
I'm wondering if anyone could me on this error as nothing I have tried has worked so far.
Thanks a million for the help in advance!
It seems like the arr variable should a Pandas DataFrame, but you passed the float object for the arr variable. So, it raises the AttributeError: 'float' object has no attribute 'loc'.
Additionally, I see this arr.loc[arr < 0, 'downside_returns'] = arr might raise the next error if your arr is actually a Pandas DataFrame. To use it correctly, you may need to read more in its documentation (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html) - for example, df.loc[df['shield'] > 6, ['max_speed']].
You're passing a float into the function, but it expects it to be a type that has a .loc attribute.
Python is "duck typed". You can pass anything you want as the argument, but when it comes time to use the members, if they are not present you will get an error like this.

Print content and several attributes of a numpy array to a text file

I have an array. My task is to print out the array, along with its shape, size, item size, dimensions, and data type name. The output should be a text file - each attribute should be on a new line.
When I attempt to use the following code, I get the error:
File "<ipython-input-76-f4d4f45285be>", line 1, in <module>
print(a.shape)
AttributeError: 'NoneType' object has no attribute 'shape'
I have tried two options, open a text file and np.savetxt. Neither seems to work.
Here is the code:
import numpy as np
a = np.arange(15).reshape(3,5)
a = print(a)
shape = print(a.shape)
size = print(a.size)
itemsize = print(a.itemsize)
ndim = print(a.ndim)
dtype = print(type(a.dtype))
with open("demo_numpy.tx","w") as text:
text.write(a,shape,size,itemsize,ndim,dtype, file = text)
np.savetxt('demo_numpy.txt',[a,shape,size,itemsize,ndim,dtype])
What am I doing wrong, and how can I fix my output?
print just prints the value passed in to stdout and returns None. If you want to access a property just do it without print:
import numpy as np
a = np.arange(15).reshape(3,5)
shape = a.shape
size = a.size
itemsize = a.itemsize
ndim = a.ndim
dtype = a.dtype
And if you want to print don't assign the return value of print:
print(a)
print(a.shape)
print(a.size)
print(a.itemsize)
print(a.ndim)
print(a.dtype)
Note that you don't correctly write to files, in the first case you can only write one argument at a time, you need to either str.join them or do multiple text.writes. In the second case you should check the documentation of numpy.savetxt - it expects an array as second argument not a list of several attributes.
For example:
with open("demo_numpy.tx","w") as text:
text.write(str(a))
text.write(str(shape))
text.write(str(size))
text.write(str(itemsize))
text.write(str(ndim))
text.write(str(dtype))
# or:
# text.write('\n'.join(map(str, [a,shape,size,itemsize,ndim,dtype])))
np.savetxt('demo_numpy.txt', a)
I'd like to use something like this:
# import numpy as np
# my_array = np.arange(3)
metadata = [(method, getattr(my_array, method)) for method in dir(my_array) if (not callable(getattr(my_array, method))) and (not method.startswith('__'))]
names, values = zip(*metadata) # 2 lists
Then loop over names & values and write into a file.

getting nonetype after using numpy.fill

I want to use numpy array as the following:
room_1_class_value = numpy.empty(len(room_1_indices[0])).fill(1)
room_1_indices[0] is an array, and I can see the output of that array. But why I get "None" for "room_1_class_value"?
Thanks,
Because you're not assigning a numpy array to room_1_class_value. You're assigning to it the value of the fill(1) function call. This function doesn't return anything.
Try:
room_1_class_value = numpy.empty(len(room_1_indices[0]))
room_1_class_value.fill(1)

Why does my 'instance' turn into an 'ndarray' when I use Scipy optimize?

I have written a function using a quantum simulation class QuTIP that returns a float. Next, I called scipy.optimize.fmin_cg on the function. I keep getting the error:
AttributeError: 'numpy.ndarray' object has no attribute 'expm'
on the line:
U_sq = H_sq.expm
But H_sq is an instance of Qobj, not an ndarray. If I run the function outside of scipy.optimize.fmin_cg, it returns the type as 'instance'; when it runs inside of fmin_cg it returns the type as 'ndarray'.
Why does it do this? Is there a optimization function in python that will respect using instances like this?
Here is the code:
from qutip import *
from numpy import *
import scipy.optimize
def sq_fidelity(eps,N=7):
H_sq = squeez(N,eps);
print type(H_sq);
one_ph = basis(N,1);
U_sq = H_sq.expm();
squ = U_sq*one_ph;
fidelity = expect(fock_dm(N,1),squ);
return float(fidelity)
if __name__=='__main__':
print sq_fidelity(0.2);
eps = scipy.optimize.fmin_cg(sq_fidelity, x0=0.2, args=(7,));
The issue here is that fmin_cg is passing an ndarray (of length 1) to your objective function. You can extract the scalar value by just changing the first line of sq_fidelity to:
H_sq = squeez(N, float(eps))

Categories