I created a number of shared variables and placed them in an array like so:
self.params = [self.We, self.Wr, self.Wv, self.b]
When I tried to get their value in another part of the code, something like this:
self.h = [theano.shared(value=p.get_value()*0.) for p in self.params]
I get this error:
AttributeError: 'TensorVariable' object has no attribute 'get_value'
Any help really appreciated.
The problem was that eventhough I used the shared api, I also cast to a float32 with .astype(theano.config.floatX) , and this was causing the conversion from sharedVariable to just tensorVariable
Related
I want to find the caller callable from within the called object, without explcitely forwarding the caller to the called as an object.
My current code looks something like this:
class Boo:
#classmethod
def foo(cls, aa, b2=2):
_ret = aa + b2
autolog(fn=Boo.foo, values={"input": locals(), "output": _ret}, message="This is what it should look like")
autolog_nameless(values={"input": locals(), "output": _ret}, message="This would be convenient")
return _ret
and yields
DEBUG | Boo.foo with aa=3.14159, b2=2 yields 5.14159. Message: This is what it should look like
DEBUG | cls=<class '__main__.Boo'>, aa=3.14159, b2=2, _ret=5.14159 yields 5.14159. Message: This would be convenient
The method autolog gets the locals() and the caller method fn, and parses them using the signature of the caller. This works nice and provides the desired output, but requires passing the caller as an object - something I'd like to avoid as I'm refractoring to include this feature and have about 1000 places to modify.
What I'd like to achieve is: pass locals() only; get the name of the caller within autolog_nameless, using inspect.stack()[1][3] or rather inspect.currentframe().f_back.f_code.co_name (latter has much less overhead), and using this - an possibly the information in locals() - find the caller object to inspect it for its signature.
The method autolog_nameless gets cls, actually the class as part of locals() (or would get self if the caller was a simple method), but I can't really do anything with it.
I'd think all the information required is given, but I just can't find a solution. Any help is greatly appreciated.
As it turns out it's quite simple: listing the methods of the class object found in locals() and searching by name should do the trick.
Code, without error checking:
# getting all methods of the class
methods = inspect.getmembers(locals()['cls'], predicate=inspect.ismethod)
# finding the callers name; won't work within the list comprehension for scope issues
_name = inspect.currentframe().f_back.f_code.co_name
# methods is a list of tuples, each tuple holds the name and the method object
fn = [x for x in methods if x[0] == _name][0][1]
and fn is the caller object to check the signature.
Note, locals()['cls'] works here as in the example we have a classmethod, but this is just the object that the called method belongs to.
I defined a subclass of Atom in rdkit.Chem. I also defined an instance attribute in it but I could not get that instance from RWMol object in rdkit.
Below there is a sample code for my problem:
from rdkit import Chem
class MyAtom(Chem.Atom):
def __init__(self, symbol, **kwargs):
super().__init__(symbol, **kwargs)
self.my_attribute = 0
def get_my_attribute(self):
return self.my_attribute
if __name__ == '__main__':
rw_mol = Chem.RWMol()
# I created MyAtom class object then added to RWMol. But I couldn't get it again.
my_atom = MyAtom('C')
my_atom.my_attribute = 3
rw_mol.AddAtom(my_atom)
atom_in_mol = rw_mol.GetAtoms()[0]
# I can access my_atom new defined attributes.
print(my_atom.get_my_attribute())
# below two line gives error: AttributeError: 'Atom' object has no attribute 'get_my_attribute'
print(atom_in_mol.get_my_attribute())
print(atom_in_mol.my_attribute)
# type(atom1): <class '__main__.MyAtom'>
# type(atom_in_mol): <class 'rdkit.Chem.rdchem.Atom'>
# Why below atom types are different? Thanks to polymorphism, that two object types must be same.
Normally this code must run but it gives error due to last line because atom_in_mol object type is Chem.Atom. But should it be MyAtom? I also cannot access my_attribute directly.
rdkit Python library is a wrapper of C++. So is the problem this? Cannot I use inheritance for this library?
Note: I researched rdkit documentation and there is a SetProp method for saving values in atoms. It uses dictionary to save values. It runs fine but it is too slow for my project. I want to use instance attributes to save my extra values. Is there any solution for that inheritance problem, or faster different solution?
Python RDKit library is a C++ wrapper, so sometimes it does not follows the conventional Python object handling.
To go deeper, you will have to dig through the source code:
rw_mol.AddAtom(my_atom)
Above will execute AddAtom method in rdkit/Code/GraphMol/Wrap/Mol.cpp, which, in turn, calls addAtom method in rdkit/Code/GraphMol/RWMol.h, which then calls addAtom method in rdkit/Code/GraphMol/ROMol.cpp with default argument of updateLabel = true and takeOwnership = false.
The takeOwnership = false condition makes the argument atom to be duplicated,
// rdkit/Code/GraphMol/ROMol.cpp
if (!takeOwnership)
atom_p = atom_pin->copy();
else
atom_p = atom_pin;
Finally, if you look into what copy method do in rdkit/Code/GraphMol/Atom.cpp
Atom *Atom::copy() const {
auto *res = new Atom(*this);
return res;
}
So, it reinstantiate Atom class and returns it.
I have a class consisting of 14 methods. Here is the skeleton:
class Field
def __init__():
...
return
def ...():
country = Field()
country.re_fitness_population()
It's a large class, so here is the full pastebin.
Running this code results in:
----> 1 country.re_fitness_population()
AttributeError: 'Field' object has no attribute 're_fitness_population'
Running dir() on this class doesn't show the method as available, and I've tried fixing any spacing issues, but running python3 -tt also doesn't show anything. I've tried renaming the method, also doesn't help.
I clearly have written the function as one of the methods of the class. I feel like there is something big I'm missing.
I have a problem about exporting a savedmodel from an estimator of Tensorflow. My tensorflow program is using an estimator to do the CNN function, where the input is a 2D image. This is my code for the saving part.
def serving_input_rec_fn():
serving_features = {'images': tf.placeholder(shape=[None, self.num_input[0], self.num_input[1]], dtype=tf.float32)}
return tf.estimator.export.build_raw_serving_input_receiver_fn(features=serving_features)
self.model.export_savedmodel(export_dir, serving_input_rec_fn,
strip_default_attrs=True)
But when I ran export_savedmodel function, it produced the following error:
AttributeError: 'function' object has no attribute 'features'
When I checked the code, I actually provided the serving_features here. Could any one help me solve this problem?
you miss a bracket in the argument 'serving_input_rec_fn' passed to export_savedmodel, the right way should be like:
self.model.export_savedmodel(export_dir, **serving_input_rec_fn()**, strip_default_attrs=True)
Because the export_savedmodel api require a 'serving_input_receiver_fn' function, while the value of 'serving_input_rec_fn' is a function: 'serving_input_rec_fn'. You need to call 'serving_input_rec_fn()' which returns tf.estimator.export.build_raw_serving_input_receiver_fn(features=serving_features) which then returns a function: 'serving_input_receiver_fn'.
In method export_savedmodel(),
change
serving_input_rec_fn
to
serving_input_rec_fn()
In serving_input_rec_fn() change:
def serving_input_rec_fn():
...
return tf.estimator.export.build_raw_serving_input_receiver_fn(features=serving_features)
to:
def serving_input_rec_fn():
...
return tf.estimator.export.build_raw_serving_input_receiver_fn(serving_features)
As of documentation (here), build_raw_serving_input_receiver_fn function does not have a features argument
it should be like
def serving_input_rec_fn():
...
tf.estimator.export.build_raw_serving_input_receiver_fn(serving_features)()
I'm trying to generate a per-sourcefile macro that will hold the base file name of the source file. This is described for make here.
I tried to override the Object builder, but it didn't work...
I tried to do what is described here.
def my_object_builder(env, target, source, **kwargs):
"""A builder that calls the Object builder, with the addition of defining
a macro that holds the source file's basename
"""
if SCons.Util.is_List(source):
if len(source) > 1:
raise ValueError('cannot pass a list of sources to Object builder: %s',
[str(x) for x in source])
else:
source, = source
if 'CPPDEFINES' not in kwargs:
kwargs['CPPDEFINES'] = []
kwargs['CPPDEFINES'].append(('__MY_FILENAME',
os.path.basename(str(source))))
ret = env._Object(target=target,
source=source,
**kwargs)
return ret
Then, replacing the builders:
env['BUILDERS']['_Object'] = env['BUILDERS']['Object']
env['BUILDERS']['Object'] = my_object_builder
This didn't work. I got the following error:
AttributeError: 'function' object has no attribute 'src_suffixes'
I think it has to do with something with Environment's MethodWrapper, but I couldn't verify.
Maybe I'm going for this from the wrong angle. Maybe I should change the environment for each source file (seems like a lot of work...)
The main requirement is that the usage will be seamless. I don't want users to have to call a MyObjectBuilder class. Also, the StaticLibrary Builder should call the new Object builder.
Any help would be much appreciated.
Thanks!
BugoK.
Found it. It's a one liner...
env.Append(CCFLAGS=['-D__MY_FILENAME=\\"${SOURCE.file}\\"'])
Just adding a define which is rule based.
The quotes are just an addition to be able to printf it without strigifying the expression.