I am trying to run this command python run.py --mode MLE
and got this error. I am not able to find the correct solution for it .
Traceback (most recent call last):
File "run.py", line 208, in <module>
train_MLE()
File "run.py", line 94, in train_MLE
encoder_input, decoder_input, weight = model.get_batch(d_valid, i)
File "C:\Users\Kriti Gupta\Desktop\GitHub_repo\Seq2seq-Chatbot-With-Deep-Reinforcement-Learning\seq2seq_model.py", line 342, in get_batch
encoder_input, decoder_input = random.choice(data[bucket_id])
File "C:\Users\Kriti Gupta\AppData\Local\Programs\Python\Python37\lib\random.py", line 261, in choice
raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence
Below is the code which contains the function
def get_batch(self, data, bucket_id, rand = True, order = False):
# data should be [whole_data_length x (source, target)]
# decoder_input should contain "GO" symbol and target should contain "EOS" symbol
encoder_size, decoder_size = self.buckets[bucket_id]
encoder_inputs, decoder_inputs = [], []
#print(bucket_id)
print(random.choice(data[bucket_id]))
encoder_input, decoder_input = random.choice(data[bucket_id])
c = 0
for i in xrange(self.batch_size):
if rand:
encoder_input, decoder_input = random.choice(data[bucket_id])
if order:
encoder_input, decoder_input = data[bucket_id][i]
c += 1
Please help!!
random.choice always raises IndexError on an empty sequence. I would suggest checking the data you are passing to the function
get_batch()
You can also add an 'if condition' in 'get_batch()' method to check if the data passed is empty or not.
Reference:
Python Bug Tracker
Related
The goal is to overlay pfp on top of template, and then place the string description underneath pfp. When I run the code, I get the error TypeError: argument must be sequence.
def edit(template, pfp, description):
x = (template.size[0] - image.size[0])/2
y = (template.size[1] - image.size[1])/2
Image.Image.paste(template, pfp, (round(x), round(y)))
draw = ImageDraw.Draw(template)
draw.text(round((template.size[0]/8), round(y-15)), description)
template.show()
return template
Full error message:
Traceback (most recent call last):
File "/Users/shalim/PycharmProjects/EDPtigerstars/main.py", line 30, in <module>
edit(background, image, x[1]).save(x[0])
File "/Users/shalim/PycharmProjects/EDPtigerstars/main.py", line 18, in edit
draw.text(round((template.size[0]/8), round(y-15)), description)
File "/Users/shalim/PycharmProjects/EDPtigerstars/venv/lib/python3.8/site-packages/PIL/ImageDraw.py", line 512, in text
draw_text(ink)
File "/Users/shalim/PycharmProjects/EDPtigerstars/venv/lib/python3.8/site-packages/PIL/ImageDraw.py", line 496, in draw_text
self.draw.draw_bitmap(coord, mask, ink)
TypeError: argument must be sequence
Process finished with exit code 1
Try putting your x, y coordinates inside a tuple:
draw.text((x,y)), "Text")
When executing my Python script, I'm receiving the following error...
Traceback (most recent call last):
File "/usr/local/bin/jira-cycle-extract", line 10, in <module>
sys.exit(main())
File "/usr/local/lib/python3.7/site-packages/jira_cycle_extract/cli.py", line 144, in main
cycle_data = q.cycle_data(verbose=args.verbose)
File "/usr/local/lib/python3.7/site-packages/jira_cycle_extract/cycletime.py", line 141, in cycle_data
for snapshot in self.iter_changes(issue, False):
File "/usr/local/lib/python3.7/site-packages/jira_cycle_extract/query.py", line 114, in iter_changes
last_status = status_changes[0].fromString if len(status_changes) != 0 else issue.fields.status.name
TypeError: object of type 'filter' has no len()
I've tried to address this by adding the following code based on other research, and changing from > 0 to not empty or other forms to check for an empty list, but had no luck.
This is the code in question...
status_changes = filter(
lambda h: h.field == 'status',
itertools.chain.from_iterable([c.items for c in issue.changelog.histories])
)
last_status = status_changes[0].fromString if len(status_changes) != 0 else issue.fields.status.name
last_resolution = None
You can use the next function with a generator expression and a default value instead. The code in your question can be re-written as:
last_status = next((h.fromString for c in issue.changelog.histories for h in c.items if h.field == 'status'), issue.fields.status.name)
last_resolution = None
I have a deep network using Keras and I need to apply cropping on the output of one layer and then send to the next layer. for this aim, I write the following code as a lambda layer:
def cropping_fillzero(img, rate=0.6): # Q = percentage
residual_shape = img.get_shape().as_list()
h, w = residual_shape[1:3]
blacked_pixels = int((rate) * (h*w))
ratio = int(np.floor(np.sqrt(blacked_pixels)))
# width = int(np.ceil(np.sqrt(blacked_pixels)))
x = np.random.randint(0, w - ratio)
y = np.random.randint(0, h - ratio)
cropingImg = img[y:y+ratio, x:x+ratio].assign(tf.zeros([ratio, ratio]))
return cropingImg
decoded_noise = layers.Lambda(cropping_fillzero, arguments={'rate':residual_cropRate}, name='residual_cropout_attack')(bncv11)
but it produces the following error and I do not know why?!
Traceback (most recent call last):
File "", line 1, in
runfile('E:/code_v28-7-19/CIFAR_los4x4convolvedw_5_cropAttack_RandomSize_Pad.py',
wdir='E:/code_v28-7-19')
File
"D:\software\Anaconda3\envs\py36\lib\site-packages\spyder_kernels\customize\spydercustomize.py",
line 704, in runfile
execfile(filename, namespace)
File
"D:\software\Anaconda3\envs\py36\lib\site-packages\spyder_kernels\customize\spydercustomize.py",
line 108, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File
"E:/code_v28-7-19/CIFAR_los4x4convolvedw_5_cropAttack_RandomSize_Pad.py",
line 143, in
decoded_noise = layers.Lambda(cropping_fillzero, arguments={'rate':residual_cropRate},
name='residual_cropout_attack')(bncv11)
File
"D:\software\Anaconda3\envs\py36\lib\site-packages\keras\engine\base_layer.py",
line 457, in call
output = self.call(inputs, **kwargs)
File
"D:\software\Anaconda3\envs\py36\lib\site-packages\keras\layers\core.py",
line 687, in call
return self.function(inputs, **arguments)
File
"E:/code_v28-7-19/CIFAR_los4x4convolvedw_5_cropAttack_RandomSize_Pad.py",
line 48, in cropping_fillzero
cropingImg = img[y:y+ratio, x:x+ratio].assign(tf.zeros([ratio, ratio]))
File
"D:\software\Anaconda3\envs\py36\lib\site-packages\tensorflow\python\ops\array_ops.py",
line 700, in assign
raise ValueError("Sliced assignment is only supported for variables")
ValueError: Sliced assignment is only supported for variables
could you please tell me how can I solve this error?
Thank you
h, w = residual_shape[1:3]
I'm not entirely sure what you're trying to do here, but Python interprets this as 'return between the 2nd element and the 4th'. Maybe you mean residual_shape[1], residual_shape[3]?
cropingImg = img[y:y+ratio, x:x+ratio].assign(tf.zeros([ratio, ratio]))
You are trying to use slice notation on a tensor. Slice notation may only be used on variables, as the error message says. In order to get the actual variable, try loading the previous layer output using tf.identity():
self.output = your_layer
self.output = tf.identity(self.output, name='output')
output = graph.get_tensor_by_name('output:0')
I'm a beginner with myhdl.
I try to translate the following Verilog code to MyHDL:
module ModuleA(data_in, data_out, clk);
input data_in;
output reg data_out;
input clk;
always #(posedge clk) begin
data_out <= data_in;
end
endmodule
module ModuleB(data_in, data_out, clk);
input [1:0] data_in;
output [1:0] data_out;
input clk;
ModuleA instance1(data_in[0], data_out[0], clk);
ModuleA instance2(data_in[1], data_out[1], clk);
endmodule
Currently, I have this code:
import myhdl
#myhdl.block
def ModuleA(data_in, data_out, clk):
#myhdl.always(clk.posedge)
def logic():
data_out.next = data_in
return myhdl.instances()
#myhdl.block
def ModuleB(data_in, data_out, clk):
instance1 = ModuleA(data_in(0), data_out(0), clk)
instance2 = ModuleA(data_in(1), data_out(1), clk)
return myhdl.instances()
# Create signals
data_in = myhdl.Signal(myhdl.intbv()[2:])
data_out = myhdl.Signal(myhdl.intbv()[2:])
clk = myhdl.Signal(bool())
# Instantiate the DUT
dut = ModuleB(data_in, data_out, clk)
# Convert tfe DUT to Verilog
dut.convert()
But it doesn't works because signal slicing produce a read-only shadow signal (cf MEP-105).
So, what is it the good way in MyHDL to have a writable slice of a signal?
Edit:
This is the error I get
$ python demo.py
Traceback (most recent call last):
File "demo.py", line 29, in <module>
dut.convert()
File "/home/killruana/.local/share/virtualenvs/myhdl_sandbox-dYpBu4o5/lib/python3.6/site-packages/myhdl-0.10-py3.6.egg/myhdl/_block.py", line 342, in convert
File "/home/killruana/.local/share/virtualenvs/myhdl_sandbox-dYpBu4o5/lib/python3.6/site-packages/myhdl-0.10-py3.6.egg/myhdl/conversion/_toVerilog.py", line 177, in __call__
File "/home/killruana/.local/share/virtualenvs/myhdl_sandbox-dYpBu4o5/lib/python3.6/site-packages/myhdl-0.10-py3.6.egg/myhdl/conversion/_analyze.py", line 170, in _analyzeGens
File "/usr/lib/python3.6/ast.py", line 253, in visit
return visitor(node)
File "/home/killruana/.local/share/virtualenvs/myhdl_sandbox-dYpBu4o5/lib/python3.6/site-packages/myhdl-0.10-py3.6.egg/myhdl/conversion/_analyze.py", line 1072, in visit_Module
File "/home/killruana/.local/share/virtualenvs/myhdl_sandbox-dYpBu4o5/lib/python3.6/site-packages/myhdl-0.10-py3.6.egg/myhdl/conversion/_misc.py", line 148, in raiseError
myhdl.ConversionError: in file demo.py, line 4:
Signal has multiple drivers: data_out
You can use an intermediate list of Signal(bool()) as placeholder.
#myhdl.block
def ModuleB(data_in, data_out, clk):
tsig = [myhdl.Signal(bool(0)) for _ in range(len(data_in))]
instances = []
for i in range(len(data_in)):
instances.append(ModuleA(data_in(i), tsig[i], clk))
#myhdl.always_comb
def assign():
for i in range(len(data_out)):
data_out.next[i] = tsig[i]
return myhdl.instances()
A quick (probably non-fulfilling) comment, is that the intbv is treated as a single entity that can't have multiple drives. Two references that might help shed some light:
http://jandecaluwe.com/hdldesign/counting.html
http://docs.myhdl.org/en/stable/manual/structure.html#converting-between-lists-of-signals-and-bit-vectors
I am reading the book Machine Learning in Action.
One example in Chapter 2 converts string to int for classification use. For example, 'student' = 1, 'teacher' = 2, engineer = 3.
See the code below in Line 12. While an error comes up while I execute it:
invalid literal for int() with base 10: 'largeDose'
Where is my problem.
def file2matrix(filename):
fr = open(filename)
numberOfLines = len(fr.readlines()) #get the number of lines in the file
returnMat = zeros((numberOfLines,3)) #prepare matrix to return
classLabelVector = [] #prepare labels return
fr = open(filename)
index = 0
for line in fr.readlines():
line = line.strip()
listFromLine = line.split('\t')
returnMat[index,:] = listFromLine[0:3]
classLabelVector.append(int(listFromLine[-1]))
index += 1
return returnMat,classLabelVector
caller code:
from numpy import *
import kNN
datingDataMat,datingLabels = kNN.file2matrix('datingTestSet.txt')
import matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
#ax.scatter(datingDataMat[:,1], datingDataMat[:,2])
ax.scatter(datingDataMat[:,1], datingDataMat[:,2], array(datingLabels), array(datingLabels))
plt.show()
Traceback and error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 714, in runfile
execfile(filename, namespace)
File "C:\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 74, in execfile
exec(compile(scripttext, filename, 'exec'), glob, loc)
File "C:/Users/Zhiming Zhang/Documents/Machine Learning/kNN/execute.py", line 10, in <module>
datingDataMat,datingLabels = kNN.file2matrix('datingTestSet.txt')
File "kNN.py", line 48, in file2matrix
classLabelVector.append(int(listFromLine[-1]))
ValueError: invalid literal for int() with base 10: 'largeDoses'
You try to convert a string like "largeDose" to an int using the conversion function int(). But that's not how this works. The function int() converts only strings which look like integer numbers (e. g. "123") to integers.
In your case you can use either an if-elif-else cascade or a dictionary.
Cascade:
if listFromLine[-1] == 'largeDose':
result = 1
elif listFromLine[-1] == 'teacher':
result = 2
elif …
…
else:
result = 42 # or raise an exception or whatever
Dictionary:
conversion = {
'largeDose': 1,
'teacher': 2,
… }
# ...
# later, in the loop:
classLabelVector.append(conversion[listFromLine[-1]])
# The above will raise a KeyError if an unexpected value is given.
# Ir in case you want to use a default value:
classLabelVector.append(conversion.get(listFromLine[-1], 42))