I'm trying to find the correlation between my parameters using apriori but I get this error constantly, I tried using efficient_apriori but it only prints "2"
import pandas as pd
import numpy as np
from apriori import apriori
import matplotlib.pyplot as plt
%matplotlib inline
df = pd.read_csv('D:\\Project\\database\\2-Second Parameters chosen\\Half Year\\HalfYearCombine2.csv',header=None,low_memory=False)
data = []
for i in range(0,15578088):
data.append([str(df.values[i,j])
for j in range(0,14)])
dataset = apriori(data, min_length = 2,
min_support = 0.2, min_confidence = 0.2,
min_lift = 3)
if dataset:
print('not none!')
print(len(dataset))
else:
print('dataset is none!')
The error is:
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3296, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-13-de4fe3df3901>", line 5, in <module>
from apriori import apriori
File "C:\ProgramData\Anaconda3\lib\site-packages\apriori.py", line 79
print freqSet-conseq,'-->',conseq,'conf:',conf
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(freqSet-conseq,'-->',conseq,'conf:',conf)?
I don't know why it says missing parentheses in call to print while my print function looks fine?
Thank you.
Notice how "print freqSet-conseq,'-->',conseq,'conf:',conf" doesn't have brackets? That means it was written in python2. You must've installed apriori for python2, but you are using python3.
Install apriori for python3 and try again.
The reason why efficient_apriori prints 2 is because it returns a tuple with (itemsets, rules). To use efficient_apriori, you can do something like:
from efficient_apriori import apriori
itemsets, rules = apriori(data, min_support=min_support, min_confidence=min_confidence)
if rules:
print(len(rules))
Related
I have problem which when i run the code it shows an error:
Traceback (most recent call last):
File "C:\Users\server\PycharmProjects\Publictest2\main.py", line 19, in <module>
Distance = radar.route.distance(Starts, End, modes='transit')
File "C:\Users\server\PycharmProjects\Publictest2\venv\lib\site-packages\radar\endpoints.py", line 612, in distance
(origin_lat, origin_lng) = origin
ValueError: too many values to unpack (expected 2)
My Code:
from radar import RadarClient
import pandas as pd
API_key = 'API'
radar = RadarClient(API_key)
file = pd.read_excel('files')
file['AntGeo'] = Sourced[['Ant_lat', 'Ant_long']].apply(','.join, axis=1)
file['BaseGeo'] = Sourced[['Base_lat', 'Base_long']].apply(','.join, axis=1)
antpoint = file['AntGeo']
basepoint = file['BaseGeo']
for antpoint in antpoint:
dist= radar.route.distance(antpoint , basepoint, modes='transit')
dist= dist['routes'][0]['distance']
dist= dist / 1000
Firstly, your error code does not match your given code sample correctly.
It is apparent you are working with the python library for the Radar API.
Your corresponding line 19 is dist= radar.route.distance(antpoint , basepoint, modes='transit')
From the radar-python 'pypi manual', your route should be referenced as:
## Routing
radar.route.distance(origin=[lat,lng], destination=[lat,lng], modes='car', units='metric')
Without having sight of your dataset, file, one can nonetheless deduce or expect the following:
Your antpoint and basepoint must be a two-item list (or tuple).
For instance, your antpoint ought to have a coordinate like [40.7041029, -73.98706]
See the radar-python manual
line 11 and 13 in your code
file['AntGeo'] = Sourced[['Ant_lat', 'Ant_long']].apply(','.join, axis=1)
file['BaseGeo'] = Sourced[['Base_lat', 'Base_long']].apply(','.join, axis=1)
Your error is occuring at this part:
Distance = radar.route.distance(Starts, End, modes='transit')
(origin_lat, origin_lng) = origin
First of all check the amount of variables that "origin" delivers to you, it's mismatched with the expectation I guess.
Here is My Python Code is given below:-
import networkx as nx
import matplotlib.pyplot as plt
from random import choice
g=nx.Graph()
city_set=['Delhi','Lucknow','Indore','Kolkata','Hyderabad','Chennai',
'Tivandrum','Banglore','Pune','Mumbai','Surat','Ahmedabad','Jaipur']
for each in city_set:
g.add_node(each)
costs=[]
value =100
while(value<=2000):
costs.append(value)
value=value+70
while(g.number_of_edges()<24):
c1=choice(g.nodes())
c2=choice(g.nodes())
if c1!=c2 and g.has_edge(c1,c2)==0:
w=choice(costs)
g.add_edge(c1,c2,weight=w)
nx.draw(g,with_labels=1)
plt.show(g)
and while compiling the code I got the error stated below:-
$ python cities.py
Traceback (most recent call last):
File "cities.py", line 22, in <module>
c1=choice(g.nodes())
File "/usr/lib/python2.7/random.py", line 277, in choice
return seq[int(self.random() * len(seq))] # raises IndexError if seq
is empty
File "/usr/local/lib/python2.7/dist-
packages/networkx/classes/reportviews.py", line 178, in __getitem__
return self._nodes[n]
KeyError: 7
I also created vitual enviourment of Pyhton but again it shows the smae error.
Also, I tried finding some stuff on Google and check for the solution but no one has similar problem like this.
Change
c1=choice(g.nodes())
c2=choice(g.nodes())
into
c1=choice(list(g))
c2=choice(list(g))
should work.
g.nodes() returns a NodeView and not a list of nodes.
import random
import networkx as nx
costs = []
value=100
while(value<=2000):
costs.append(value)
value+=100
print (costs)
while(G.number_of_edges()<16):
c1 = random.choice(list(G.nodes()))
c2 = random.choice(list(G.nodes()))
if c1!=c2 and G.has_edge(c1,c2)==0:
w= random.choice(costs)
G.add_edge(c1,c2,weight = w)
Try this code as there is some error in the syntax of the random shown in the video. I have pasted my code, test it.
G.nodes() needs to return a list but here is returning a NodeView. Hence change G.nodes() to list(G.nodes())
I have written this code for vector addition using numba.SmartArrays. I am using this numba.SmartArrays for the first time. I am not sure how to use that.
This code is not working and it is throwing errors.
import numpy as np
from numba import SmartArray,cuda, jit, uint32
li1=np.uint32([1,2,3,4])
li=np.uint32([1,2,3,4])
b=SmartArray(li,where="host",copy=True)
a=SmartArray(li1,where="host",copy=True)
c=np.uint32([1,1,1,1])
print type(li)
print type(a)
#cuda.jit('void(uint32[:],uint32[:],uint32[:])',type="gpu")
def additionG(c,a,b):
idx=cuda.threadIdx.x+cuda.blockDim.x*cuda.blockIdx.x
if idx< len(a):
a[idx]=c[idx]+b[idx]
dA=cuda.to_device(a)
dB=cuda.to_device(b)
dC=cuda.to_device(c)
additionG[1, 128](c,a,b)
print a.__array__()
Errors:
<type 'numpy.ndarray'>
<class 'numba.smartarray.SmartArray'>
Traceback (most recent call last):
File "C:\Users\hp-pc\My Documents\LiClipse Workspace\cuda\blowfishgpu_smart_arrays.py", line 20, in <module>
dA=cuda.to_device(a)
File "C:\Anaconda\lib\site-packages\numba\cuda\cudadrv\devices.py", line 257, in _require_cuda_context
return fn(*args, **kws)
File "C:\Anaconda\lib\site-packages\numba\cuda\api.py", line 55, in to_device
to, new = devicearray.auto_device(obj, stream=stream, copy=copy)
File "C:\Anaconda\lib\site-packages\numba\cuda\cudadrv\devicearray.py", line 403, in auto_device
devobj.copy_to_device(obj, stream=stream)
File "C:\Anaconda\lib\site-packages\numba\cuda\cudadrv\devicearray.py", line 148, in copy_to_device
sz = min(_driver.host_memory_size(ary), self.alloc_size)
File "C:\Anaconda\lib\site-packages\numba\cuda\cudadrv\driver.py", line 1348, in host_memory_size
s, e = host_memory_extents(obj)
File "C:\Anaconda\lib\site-packages\numba\cuda\cudadrv\driver.py", line 1333, in host_memory_extents
return mviewbuf.memoryview_get_extents(obj)
TypeError: expected a readable buffer object
Its been a while since I posted this question. Still posting the answer so that someone may find it helpful in future.
import numpy as np
from numba import SmartArray,cuda, jit, uint32,autojit
li1=np.uint32([6,7,8,9])
li=np.uint32([1,2,3,4])
a=SmartArray(li1,where='host',copy=True)
b=SmartArray(li,where="host",copy=True)
c=np.uint32([1,1,1,1])
def additionG(a,c):
idx=cuda.threadIdx.x+cuda.blockDim.x*cuda.blockIdx.x
if idx < len(c):
a[idx]=a[idx]+c[idx]
cuda.syncthreads()
bpg=1
tpb=128
dC=cuda.to_device(c)
cfunc = cuda.jit()(additionG)
cfunc[bpg, tpb](a,dC)
print a.__array__()
It looks to me like cuda.to_device doesn't handle smart arrays, which would sort of make sense, because smart arrays are supposed to do away with explicit copy management.
If my reading of the documentation is correct (I have never tried SmartArray before), you should just be able to change this
dA=cuda.to_device(a)
dB=cuda.to_device(b)
dC=cuda.to_device(c)
additionG[1, 128](c,a,b)
to just
dC=cuda.to_device(c)
additionG[1, 128](dC,a.gpu(),b.gpu())
The .gpu() method should return a GPU resident object that the kernel can understand and access.
I'm trying to plot a histogram, but I'm keep getting this error;
Traceback (most recent call last):
File "<pyshell#62>", line 1, in <module>
plt.hist(a)
File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 2827, in hist
stacked=stacked, **kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 8312, in hist
xmin = min(xmin, xi.min())
File "/usr/lib/python2.7/dist-packages/numpy/core/_methods.py", line 21, in _amin
out=out, keepdims=keepdims)
TypeError: cannot perform reduce with flexible type
I'm very new to python and what I'm trying to do is this;
import numpy, matplotlib.pyplot
line = " "
a = []
b = []
c = []
alpha = []
beta = []
gama = []
while x.readline():
line = x.readline()
a.append(line[16:23])
b.append(line[25:32])
c.append(line[27:34])
alpha.append(line[40:47])
beta.append(line[49:54])
gama.append(line[56:63])
pyplot.hist(a)'
when ever I run this piece of code I'm getting that error. Where did I go wrong? I really appreciate a help
It looks like you are attempting to draw the histogram based on strings, rather than on numbers. Try something like this instead:
from matplotlib import pyplot
import random
# generate a series of numbers
a = [random.randint(1, 10) for _ in xrange(100)]
# generate a series of strings that look like numbers
b = [str(n) for n in a]
# try to create histograms of the data
pyplot.hist(a) # it produces a histogram (approximately flat, as expected)
pyplot.hist(b) # produces the error as you reported.
In general it is better to use a pre-written library to read data from external files (see e.g., numpy's genfromtxt or the csv module).
But at the very least, you likely need to treat the data you have read in as numerical, since readline returns strings. For instance:
for line in f.read():
fields = line.strip().split()
nums = [int(field) for field in fields]
now nums gives you a list of integers from that row.
i am sorry,i am just a beginner in python language,i am quite stuck in this problem quite long.actually,i want to make a descending and ascending of list that the user input by creating a module of the descending and the ascending.but i couldn't get it work.
the main python file is pythonaslab.py and the module for the ascending and the descending is selectionmodule.py..the code:
this is the selectionmodule:
import pythonaslab
def ascendingselection():
for q in range(len(b)):
w=q+1
for w in range(len(b)):
if b[q]>b[w]:
f=b[q]
b[q]=b[w]
b[w]=f
print b
def descendingselection():
for q in range(len(b)):
w=q+1
for w in range(len(b)):
if b[q]<b[w]:
f=b[q]
b[q]=b[w]
b[w]=f
print b
And this is the main file,the pythonaslab:
import selectionmodule
a = int(input())
b = [int(input()) for _ in range(a)]
print b
print "1.ascending 2.descending"
c=input()
if c==1:
selectionmodule.ascendingselection()
if c==2:
selectionmodule.descendingselection()
can you point me where's the cause of all this error i got?
Traceback (most recent call last):
File "E:\Coding\pythonaslab.py", line 1, in <module>
import selectionmodule
File "E:\Coding\selectionmodule.py", line 1, in <module>
import pythonaslab
File "E:\Coding\pythonaslab.py", line 16, in <module>
selectionmodule.descendingselection()
AttributeError: 'module' object has no attribute 'descendingselection'
You created a circular import; your pythonaslab module imports selectionmodule which imports the pythonaslab module. You end up with incomplete modules that way, don't do that.
Remove the import pythonaslab line from selectionmodule; you are not using pythonaslab in that module.
Also, another module cannot read your globals; you need to pass those in as arguments:
# this function takes one argument, and locally it is known as b
def ascendingselection(b):
# rest of function ..
then call that with:
selectionmodule.ascendingselection(b)
Note that you are not limited to one-letter variable names. Using longer, descriptive names makes your code more readable.
if you don't want to use module name such as:
selectionmodule.ascendingselection(b)
you should import :
from selectionmodule import *
then you can call:
ascendingselection(b) # without module name
Or you can import your module and assigne a alias name:
import selectionmodule as o
o.ascendingselection(b) # with alias name
for more information read: import confusaion