basic python query. NameError in __init__ method - python

NameError: name 'the_shape' is not defined
I get the following error when I try to import my KMeans module containing the class named KMeansClass. The KMeans.py module has the following structure:
import numpy as np
import scipy
class KMeansClass:
#takes in an npArray like object
def __init__(self,dataset,the_shape=5):
self.dataset=dataset
self.mu = np.empty(shape=the_shape)
and in ipython when I try
import KMeans
I get the NameError: name 'the_shape' is not defined
I am really new to python OOP and don't know why this is happening as all I'm doing is passing arguments to init and assigning those arguments to instance variables.
Any help would be appreciated.
Thanks in advance!
Full Traceback:
NameError Traceback (most recent call last)
<ipython-input-2-44169aae5584> in <module>()
----> 1 import kmeans
/Users/path to file/kmeans.py in <module>()
1 import numpy as np
2 import scipy
----> 3 class KMeansClass:
4 #takes in an npArray like object
5 def __init__(self,dataset,the_shape=5):
/Users/path_to_file/kmeans.py in KMeansClass()
5 def __init__(self,dataset,the_shape=5):
6 self.dataset=dataset
----> 7 self.mu = np.empty(shape=the_shape)
8
9
NameError: name 'the_shape' is not defined

Related

How to save pyprover object with pickle

I want to save logical expressions of pyprover with pickle.
The following is the code I wrote in google corabolatory.
!pip install pyprover
import pickle
from pyprover import *
logic = ~A & B
print(1,logic)
print(2,type(logic))
print(3,type(A))
with open("test.pickle","wb") as f:
pickle.dump(logic,f)
with open("test.pickle","rb") as f:
logic2 = pickle.load(f) # error
print(logic2)
The output is below
1 ~A & B
2 <class 'pyprover.logic.And'>
3 <class 'pyprover.logic.Prop'>
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-27-4cd4fe38fcb4> in <module>
12
13 with open("test.pickle","rb") as f:
---> 14 logic2 = pickle.load(f) # error
15
16 print(logic2)
AttributeError: 'Top' object has no attribute 'elems'
How can I save the logical expression with pickle?
pyprover github
If you know how to save the object, I do not care about whether or not it uses pickle. I tried dill,only to get the same result as pickle.
I wrote an dill issue here
I tried to import modules like this but it didn't solve the problem.
import dill
import pyprover
from pyprover import *
from pyprover.logic import *
from pyprover.parser import *
from pyprover.constants import *
from pyprover.atoms import *
from pyprover.util import *
from pyprover.tools import *
from pyprover.__coconut__ import *
from pyprover.__init__ import *

name 'FillMissing' is not defined

When I run following code:
df = pd.read_csv('../input/marketingrar/marketing.csv')
df.head()
dep_var = 'Revenue'
cat_names = ['Day_Name','Promo']
cont_names = ['Date','Week','Month','Month_ID','Year','Visitors','Marketing Spend']
procs = [FillMissing, Categorify, Normalize]
I got this error bellow:
NameError Traceback (most recent call
last) in
----> 1 procs = [FillMissing, Categorify, Normalize]
NameError: name 'FillMissing' is not defined
P.S. I'm using Kaggle notebook. Why this error occurs and how to solve it?
from fastai.tabular.all import *
is the only working solution for me
With this code, you are trying to initiate a list named procs with the 3 references to FillMissing, Categorify and Normalise, but you never created those references before.
Did you maybe want to create a list of 3 strings? Then you forgot the '', compare the other lists like cat_names or cont_names
Maybe it could also help to include
from fastai import *
from fastai.tabular import *

'numpy.ndarray' object has no attribute 'append' [duplicate]

This question already has answers here:
Concatenate a NumPy array to another NumPy array
(12 answers)
Closed 3 years ago.
I am making a model using word2vec. After training the model i was using cosine similarity. But i am getting the following error.
I am using python 3
The code I used is as follows:
import numpy as np
from sklearn.metrics.pairwise import cosine_distances
cos_dist =[]
cos_dist =[cos_dist]
cos_dist = np.array(cos_dist).reshape(1, -1)
for vec in data[:-1]:
cos_dist.append(float(cosine_distances(vec,data[-1])))
I am getting the following error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call
last)
<ipython-input-14-ef6e7efe7eaa> in <module>
5 cos_dist = np.array(cos_dist).reshape(1, -1)
6 for vec in data[:-1]:
----> 7 cos_dist.append(float(cosine_distances(vec,data[-1])))
8
9
AttributeError: 'numpy.ndarray' object has no attribute 'append'
You can use np.append which doesn't work inplace:
cos_dist = np.append(cos_dist, [float(cosine_distances(vec,data[-1]))])
You can use numpy.concatenate(list1, list2) or numpy.append().
There's a similar discussion in this thread

TypeError: 'module' object is not callable in python and pandas

I imported the module correctly into pandas and called it correctly using import main and then main.main(data, 1,10,2.5) but I am getting an error:
TypeError Traceback (most recent call last)
<ipython-input-52-e9913b227737> in <module>()
----> 1 main.main(data, 1, 10, 2.5)
38 dat_sh = data.shape[0]
39 #Z = random.sample(range(0,U),k_max)
---> 40 Z = cf.centroid_finder(data,sp_atr,k_max)
41
42 prototypes = {i: data[j:j+1].values.tolist()[0] for i,j in enumerate(Z)}
11 for i in range(dat_sh):
12 for j in range(dat_sh):
---> 13 D[i][j] = ed(sub_atr[i],sub_atr[j])
14
15
TypeError: 'module' object is not callable
ed is euclidean:
def ed(X2, X1):
return sqrt(sum(np.subtract(X1,X2)**2))
There may be some confusion regarding the importing of modules vs functions.
It's possible to recreate your error with a simple example, assuming that module/function importing has gotten mixed up somewhere along the way. Consider a case where we pass initial values a and b through a centroid_finder() function, which lives in cf.py:
# import cf.py as cf
import cf
a, b = ([1,2,3], [2,3,4])
cf.centroid_finder(a, b)
But centroid_finder() calls ed(), which lives in ed.py:
## cf.py
# import ed.py as ed
import ed
def centroid_finder(a, b):
print(ed(a, b))
## ed.py
from numpy import sqrt, sum
import numpy as np
def ed(X2, X1):
return sqrt(sum(np.subtract(X1,X2)**2))
Here, calling centroid_finder() will give the error you observed:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-1-e76ec6a0496c> in <module>()
3 a, b = ([1,2,3], [2,3,4])
4
----> 5 cf.centroid_finder(a, b)
cf.py in centroid_finder(a, b)
2
3 def centroid_finder(a, b):
----> 4 print(ed(a, b))
TypeError: 'module' object is not callable
That's because you imported a module, ed.py as ed...but what you wanted was to call the ed() function that lives inside of ed.py. That's ed.ed()!
Changing centroid_finder() to call ed.ed() produces the desired result:
# cf.py
import ed
def centroid_finder(a, b):
print(ed.ed(a, b))
Now, from the main script:
cf.centroid_finder(a, b)
# 1.73205080757
There's at least one undisclosed import shorthand in your example code, where you call sqrt in ed(). There isn't a natural sqrt() in Python, it most likely is imported from either math or numpy, e.g. from numpy import sqrt. That's not a problem, per se, but given the error you're getting about modules being non-callable, you might benefit from explicitly calling functions in your code from the modules they live in.
For example, using import numpy as np, call np.sqrt() instead of just importing sqrt() directly. This is a defensive programming posture that will prevent similar confusion in the future. (You do this already with np.subtract() in ed(); it's unclear why sqrt() doesn't get the same treatment.)

'numpy.float64' object is not callable

For some reason that I can't wrap my head around, it says TypeError: 'numpy.float64' object is not callable for the following code:
import pylab as pl
import scipy as sp
import numpy as num
import scipy.integrate as spi
import matplotlib.pyplot as mat
import scipy.optimize as spo
from itertools import cycle
from matplotlib.font_manager import FontProperties
rs=.14
ra=0.0027
Mz=91.
ja=0.81
js=-.033
Gz=2.5
k=10**6
def sig_a(s,Gz):
return (sp.pi)*((s*ra+(s-Mz**2)*ja)/((s-Mz**2)**2+Mz**2*Gz**2))
def sig_s(s,Gz):
return (4*sp.pi/3)*(1/s+(s*rs+(s-Mz**2)*js)/((s-Mz**2)**2+Mz**2*Gz**2))
cos_theta=num.arange(-0.95,0.95,0.05)
E=num.arange(20,140,.1)
s=E**2
def f_theta(x,s):
ans=k*(sig_s(s,Gz)*(1+(x)**2)+sig_a(s,Gz)*x)
return and
d=num.arange(0.05,1.80,0.25)
x1=[]
for t in cos_theta:
m=((t+t+0.05)/2)
x1.append(m)
x01=num.array(x1)
def N_mu1(x0,sig_a,sig_s): #<-------d=0.05
n=(k*(sig_s*((x0**2.)*0.05+(0.05/4.)+(0.05**3.)/(12.))+sig_a(2.*x0*0.05)))
return n
idealN=[]
randomN=[]
est_sig_a=[]
est_sig_s=[]
ratio_error=[]
for i in s:
for j in cos_theta:
n=(spi.quad(f_theta,j,j+0.05,args=i))
idealN.append(n[0])
for k in idealN:
r=num.random.poisson(k,1)
randomN.append(r[0])
siga=sig_a(i,Gz)
sigs=sig_s(i,Gz)
R=num.array(randomN)
Error=(R**0.5)
po,po_cov=spo.curve_fit(N_mu1,x01,R,[siga,sigs],Error)
est_sig_a.append(po[0])
est_sig_s.append(po[1])
e=((((po_cov[0])/(po[0]))+((po_cov[1])/(po[1])))*((po[0])/(po[1])))
ratio_error.append(e)
idealN=[]
randomN=[]
And the error show was:
TypeError Traceback (most recent call last)
118 R=num.array(randomN)
119 error=(R**0.5)
--> 120 po,po_cov=spo.curve_fit(N_mu1,x01,R,[siga,sigs],error)
121 est_sig_a.append(po[0])
122 est_sig_s.append(po[1])
TypeError: 'numpy.float64' object is not callable
I am struggling to find the mistake in the code.
The problem is here:
def N_mu1(x0,sig_a,sig_s): #<-------d=0.05
n=(k*(sig_s*((x0**2.)*0.05+(0.05/4.)+(0.05**3.)/(12.))+sig_a(2.*x0*0.05)))
return n # ^ argument is an array not function
sig_a is an argument to your function so it doesn't refer to the sig_a function you defined, and in this function it is being called as if it was.
In f_theta Changing return ans Into return and.
Also sig_a(2.*x0*0.05) should be changed into sig_a*(2.*x0*0.05) in N_mu1.
These changes will make your program executable.

Categories