h2o set_params() takes exactly 1 argument (2 given), even though only 1 given? - h2o

Getting error
TypeError: set_params() takes exactly 1 argument (2 given)
even though I only appear to be providing a single argument...
HYPARAMS = {
unicode(HYPER_PARAM): best_random_forest.params[unicode(HYPER_PARAM)][u'actual']
for HYPER_PARAM in list_of_hyperparams_names
}
assert isinstance(HYPARAMS, dict)
print 'Setting optimal params for full-train model...'
pp.pprint(HYPARAMS)
model = model.set_params(HYPARAMS)
#output
{ u'col_sample_rate_per_tree': 1.0,
u'max_depth': 3,
u'min_rows': 1024.0,
u'min_split_improvement': 0.001,
u'mtries': 5,
u'nbins': 3,
u'nbins_cats': 8,
u'ntrees': 8,
u'sample_rate': 0.25}
model = model.set_params(OPTIM_HYPARAMS)
TypeError: set_params() takes exactly 1 argument (2 given)
Looking at the source code,
def set_params(self, **parms):
"""Used by sklearn for updating parameters during grid search.
Parameters
----------
parms : dict
A dictionary of parameters that will be set on this model.
Returns
-------
Returns self, the current estimator object with the parameters all set as desired.
"""
self._parms.update(parms)
return self
there does not appear to be much going on that I see could go wrong. Anyone know what I'm missing here or what is happening to cause this error?

TLDR: Need to unpack the keys/values as **kwargs keywords in order to get the expected behavior of updating the _parms dict. So do
model = model.set_params(**HYPARAMS) #see https://stackoverflow.com/a/22384521/8236733
Example:
# here's a basic standin for the set_params method
>>> def kfunc(**parms):
... print parms
...
# what I was doing
>>> kfunc({1:2})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: kfunc() takes exactly 0 arguments (1 given)
# and also tried
>>> kfunc(parms={1:2})
{'parms': {1: 2}}
>>> kfunc({u'1':2, u'2':3})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: kfunc() takes exactly 0 arguments (1 given)
# what should have been done
>>> kfunc(**{'1':2})
{'1': 2}
>>> kfunc(**{u'1':2, u'2':3})
{u'1': 2, u'2': 3}
Can now see that this is not directly related to h2o, but keeping post up anyway so others with this problem may find, since did not immediately think to do this from just reading the popup docs for the method (and also since the other SE post commented in the example that I used to actually use variables as **kwarg keywords was not even on the first page of a Google search of "How to use python variable as keyword for kwargs parameter?" so would like to add more avenues to it).

Related

Multiclass confusion matrix problem ValueError: multilabel-indicator is not supported

I have successfully created a pytorch NN with 10 inputs and two output classes (B & S). So B is either 0 or 1, and S is either 0 or 1. So Y_test is B(0),B(1),S(0),S(1). Y_Pred will output B(0...1) and S(0...1). The net trains without error...
Now I want to create a confusion matrix and I am confused.
This is my code:
cm = confusion_matrix(y_test, y_pred)
print (cm)
It generates this error message:
"Traceback (most recent call last):
File "C:/Users/user/PycharmProjects/3_indexes_NN/3_indexes_NN.py", line 386, in "
[line 386 is cm = confusion_matrix(y_test, y_pred)]
cm = confusion_matrix(y_test, y_pred)
File "C:\Users\user\anaconda3\envs\PIMA\lib\site-packages\sklearn\metrics_classification.py", line 309, in confusion_matrix
raise ValueError("%s is not supported" % y_type)
ValueError: multilabel-indicator is not supported
I am completely lost. Can anyone help me understand where I've gone wrong?
Thank you in advance for throwing me a life-line!!
Can both S and B be 1 simultaneously? In this case, this is indeed a multilabel task, making confusion matrix an unsuitable metric.
Otherwise, you may work it around using something like y_pred.argmax(axis=1) for both.

I'm trying to call multiple parameters (self, other) in a __str__() function defined in a class but I keep getting an error

As stated above, I'm currently trying to print multiple values inside of a string function using the (self, other) process, but I keep getting this error:
TypeError: str() takes exactly 2 arguments (1 given)
Here is my relevant code block:
def __str__(self, enemy):
s = "{} vs {}\n\n".format(self.name, enemy.name)
s += "Your move set: "
for move in self.moves.keys():
s += move + " - "
s += "\n\n"
s += "Current health: {}\n\n".format(self.health)
s += "Enemy health: {}\n\n".format(enemy.health)
return s
This is how I'm calling the function, obviously with the fat trimmed out.
c1 = Fighter("Gunsmith" , "gunsmith.gif")
Main.character = c1
statsList.insert(END, str(self.character))
The code works if I delete enemy from the parameters and all other enemy.x parameters.
https://pastebin.com/7dWi2DpB
my full code, as its too detailed to link multiple parts.
heres the full error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1547, in __call__
return self.func(*args)
File "C:\Users\CornTortilla\Desktop\Comp. Science\CSC132\Github\teamProject\Pi.py", line 197, in chooseGunsmith
self.fightWindow()
File "C:\Users\CornTortilla\Desktop\Comp. Science\CSC132\Github\teamProject\Pi.py", line 180, in fightWindow
statsList.insert(END, str(self.character))
TypeError: __str__() takes exactly 2 arguments (1 given)

FileNotFoundError: No such file: 'someones_epi.nii.gzip'

I am trying to load an MRI, I keep getting the following error:
Traceback (most recent call last):
File "F:/Study/Projects/BTSaG/Programs/t3.py", line 2, in <module> epi_img = nib.load('someones_epi.nii.gzip')
File "C:\Users\AnkitaShinde\AppData\Local\Programs\Python\Python35-32\lib\site-packages\nibabel\loadsave.py", line 38, in load raise FileNotFoundError("No such file: '%s'" % filename)
FileNotFoundError: No such file: 'someones_epi.nii.gzip'
The code is used is as follows:
import nibabel as nib
epi_img = nib.load('someones_epi.nii.gzip')
epi_img_data = epi_img.get_data()
epi_img_data.shape(53, 61, 33)
import matplotlib.pyplot as plt
def show_slices(slices):
""" Function to display row of image slices """
fig, axes = plt.subplots(1, len(slices))
for i, slice in enumerate(slices):
axes[i].imshow(slice.T, cmap="gray", origin="lower")
slice_0 = epi_img_data[26, :, :]
slice_1 = epi_img_data[:, 30, :]
slice_2 = epi_img_data[:, :, 16]
show_slices([slice_0, slice_1, slice_2])
plt.suptitle("Center slices for EPI image")
I have also updated the loadsave.py file in nibabel but it didn't work. Please help.
Edit:
The earlier error was resolved. Now another error has been encountered.
Traceback (most recent call last):File "F:\Study\Projects\BTSaG\Programs\t3.py", line 2, in <module> epi_img = nib.load('someones_epi.nii.gzip')
File "C:\Users\AnkitaShinde\AppData\Local\Programs\Python\Python35-32\lib\site-packages\nibabel\loadsave.py", line 47, in load filename)
nibabel.filebasedimages.ImageFileError: Cannot work out file type of "someones_epi.nii.gzip"
This is an old question, however I may have the solution for it.
I just figured out that nibabel.save() does not allow me to have dot . or dash - in the folder names. These can exist in filenames however. In your case, the current path is:
C:\Users\AnkitaShinde\AppData\Local\Programs\Python\Python35-32\Lib\site-packages\nibabel\someones_epi.nii.gzip
I would change it to:
C:\Users\AnkitaShinde\AppData\Local\Programs\Python\Python35_32\Lib\site_packages\nibabel\someones_epi.nii.gzip
This is just to give an example. Of course, I don't mean that you actually change the names of these package folders as it might cause other errors.
The actual solution would be to move the file someones_epi.nii.gzip to the user structure, something like:
C:\Users\AnkitaShinde\Desktop\nibabel\someones_epi.nii.gzip

Python ode first order, how to solve this using Sympy

When I try to solve this first ode by using Sympy as it shows below:
import sympy
y = sympy.Function('y')
t = sympy.Symbol('t')
ode = sympy.Eq(y(t).diff(t),(1/y(t))*sympy.sin(t))
sol = sympy.dsolve(ode,y(t))
csol=sol.subs([(t,0),(y(0),-4)]) # the I.C. is y(0) = 1
ode_sol= sol.subs([(csol.rhs,csol.lhs)])
print(sympy.pprint(ode_sol))
It gives me this error:
Traceback (most recent call last):
File "C:/Users/Mohammed Alotaibi/AppData/Local/Programs/Python/Python35/ODE2.py", line 26, in <module>
csol=sol.subs([(t,0),(y(0),-4)]) # the I.C. is y(0) = 1
AttributeError: 'list' object has no attribute 'subs'
Your problem is that this ODE does not have a unique solution. Thus it returns a list of solution, which you can find out from the error message and by printing sol.
Do the evaluation in a loop,
for psol in sol:
csol = psol.subs([(t,0),(y(0),-4)]);
ode_sol = psol.subs([(csol.rhs,csol.lhs)]);
print(sympy.pprint(ode_sol))
to find the next error, that substituting does not solve for the constant. What works is to define C1=sympy.Symbol("C1") and using
ode_sol= psol.subs([(C1, sympy.solve(csol)[0])]);
but this still feels hacky. Or better to avoid error messages for the unsolvability of the second case:
C1=sympy.Symbol("C1");
for psol in sol:
csol = psol.subs([(t,0),(y(0),-4)]);
for cc1 in sympy.solve(csol):
ode_sol= psol.subs([(C1, cc1)]);
print(sympy.pprint(ode_sol))

TypeError: hasattr(): attribute name must be string in pymc

I have looked at the following links but none of them provide the solution I am looking for
https://github.com/pymc-devs/pymc/issues/125
PyMC error : hasattr(): attribute name must be string
I have to write a function which given the priors (and other stuff like data etc) returns a pymc model.
eg
m = pym.Model([fittable_params.values(), rv])
return m
and the in the calling function, when I do mcmc = pymc.MCMC(model)
It gives a long error
Traceback (most recent call last):
File "model_constructor.py", line 81, in <module>
mcmc = pm.MCMC(model)
File "/usr/local/lib/python2.7/dist-packages/pymc-2.3.2-py2.7-linux-i686.egg/pymc/MCMC.py", line 81, in __init__
**kwds)
File "/usr/local/lib/python2.7/dist-packages/pymc-2.3.2-py2.7-linux-i686.egg/pymc/Model.py", line 195, in __init__
Model.__init__(self, input, name, verbose)
File "/usr/local/lib/python2.7/dist-packages/pymc-2.3.2-py2.7-linux-i686.egg/pymc/Model.py", line 98, in __init__
ObjectContainer.__init__(self, input)
File "/usr/local/lib/python2.7/dist-packages/pymc-2.3.2-py2.7-linux-i686.egg/pymc/Container.py", line 605, in __init__
conservative_update(self, input_to_file)
File "/usr/local/lib/python2.7/dist-packages/pymc-2.3.2-py2.7-linux-i686.egg/pymc/Container.py", line 548, in conservative_update
if not hasattr(obj, k):
TypeError: hasattr(): attribute name must be string
On the other hand , if in the function (which returns a model), if I do
m = pm.MCMC([fittable_params.values(), rv])
it is running fine, but the function should return a model so that the user can do whatever he wants with the model in other parts of code.
If the linked solutions don't work for you then as a last resort you can just delete the non-string attributes from the model, since they don't seem to be used anyway.
for key in m.__dict__.keys():
if not isinstance(key, basestring):
del m.__dict__[key]

Resources