'tuple' object does not support item assignment in torch.cat() - python

I am trying to use the torch.cat() to contenate the torch tensor. However, I face the error messagge with --> 'tuple' object does not support item assignment.
Here are my code:
inputs = tokenizer.encode_plus(txt, add_special_tokens=False, return_tensors="pt")
input_id_chunks = inputs["input_ids"][0].split(510)
mask_chunks = inputs["attention_mask"][0].split(510)
print(type(input_id_chunks))
for i in range(len(input_id_chunks)):
print(type(input_id_chunks[i]))
print(input_id_chunks[i])
input_id_chunks[i] = torch.cat([
torch.Tensor([101]), input_id_chunks[i], torch.Tensor([102])
])
The outputs looks fine, the inputs_id_chunks[i] is torch.Tensor:
`<class 'tuple'>
<class 'torch.Tensor'>`
But I got the following print and error message:
TypeError: 'tuple' object does not support item assignment
in torch.cat()
I have using the small testing code for torch.cat() and it works fine, but I don't know what is missing in my original codes.

you can't change tuple value, instead you can assign it to list, then append new value to it and then after all changes you want to implement, you should assign again it to tuple.
please check this link

Related

Calculating the Downside Deviation of an Array of Returns

I'm trying to calculate the downside deviation of an array of returns using the code below:
def downside_deviation(arr):
downside_returns = 0
arr.loc[arr < 0, 'downside_returns'] = arr
down_stdev = downside_returns**2
arraysize = downside_returns.count()
down_stdev = downside_returns.sum()/arraysize
down_stdev = np.sqrt(down_stdev)*np.sqrt(12)
return down_stdev
But I keep encountering the and AttributeError as below:
AttributeError: 'float' object has no attribute 'loc'
I'm wondering if anyone could me on this error as nothing I have tried has worked so far.
Thanks a million for the help in advance!
It seems like the arr variable should a Pandas DataFrame, but you passed the float object for the arr variable. So, it raises the AttributeError: 'float' object has no attribute 'loc'.
Additionally, I see this arr.loc[arr < 0, 'downside_returns'] = arr might raise the next error if your arr is actually a Pandas DataFrame. To use it correctly, you may need to read more in its documentation (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html) - for example, df.loc[df['shield'] > 6, ['max_speed']].
You're passing a float into the function, but it expects it to be a type that has a .loc attribute.
Python is "duck typed". You can pass anything you want as the argument, but when it comes time to use the members, if they are not present you will get an error like this.

'Tuple' object is not callable - Python

I'm using pygame and I'm using a function that set the selected position of a text
in PyGame :
def textPos(YPos , TextSize):
TextPosition.center(60,YPos)
print("Size : " + TextSize)
but when I run the program, I get an error:
TextPosition.center(60,YPos) : TypeError : 'Tuple' object is not callable
There's a way to solve this problem?
'Tuple' object is not callable error means you are treating a data structure as a function and trying to run a method on it. TextPosition.center is a tuple data structure not a function and you are calling it as a method. If you are trying to access an element in TextPosition.Center, use square brackets []
For example:
foo = [1, 2, 3]
bar = (4, 5, 6)
# trying to access the third element with the wrong syntax
foo(2) --> 'List' object is not callable
bar(2) --> 'Tuple' object is not callable
# what I really needed was
foo[2]
bar[2]

Attribute Error: list object has no attribute 'apply'

time_weight = list(100*np.exp(np.linspace(-1/divisor, -(num_steps-1)/divisor, num_steps))).apply(lambda x:int(x))
When I try this, I get the following error in Python 3.7.
AttributeError: 'list' object has no attribute 'apply'
Can anyone help with this?
As the error said, list type has no apply attribute.
This said, if you have a list l and you want to set to int type every element in it you may use:
l = [int(x) for x in l]
or
l = list(map(int,l))
As the error suggests, list has no apply method. If what you want to do is convert every element to an int, you could remove the lambda function and instead use astype(int):
time_weight = list((100*np.exp(np.linspace(-1/divisor, -(num_steps-1)/divisor, num_steps))).astype(int))

'ValuesViewHDF5' object is not subscriptable

I have tried many solutions but can't seem to solve the problem. This code is in Python 2.7 and I am using Python 3.7. While searching I find out that this gives an error in Python 3.7. Can anyone help me how to remove this error in Python 3.7?
print('Loading c3d features ...')
features = h5py.File(self._options['feature_data_path'], 'r')
self._feature_ids = features.keys()
self._features = {video_id:np.asarray(features[video_id].values()
[0]) for video_id in self._feature_ids}
This is the error I am getting:
E:\jupyter book\data_provider.py in <dictcomp>(.0)
---> 68 self._features
{video_id:np.asarray(features[video_id].values()[0]) for
video_id in self._feature_ids}
69
70
TypeError: 'ValuesViewHDF5' object is not subscriptable
Try moving the subscript [0] outside the np.asarray() bit:
self._features = {video_id:np.asarray(features[video_id].values())[0]
for video_id in self._feature_ids}
Or converting the group.values() object to a list:
self._features = {video_id:np.asarray(list(features[video_id].values())[0])
for video_id in self._feature_ids}
Calling features[video_id].values() with Py2 returns a list; on Py3, it returns a set-like object (http://docs.h5py.org/en/stable/high/group.html#Group.values). This means the group.values() object is no longer directly subscriptable in Py3. You'll need to convert it to a list or array-like object first via list(group.values()) or np.asarray(group.values()). The same applies to group.keys() etc.

TypeError: 'OpenStackNetwork' object does not support indexing

I have a function:
node = self.conn.NodeDriver.create_node(name = utils.VM_NAME %
(course_id, names[i], idx),
image = images[i],
size = sizes[i],
networks = network[i],
ex_keyname = key_pair.name)
self.nodes.append(node)
with networks parameter, I assign a list like this:
<OpenStackNetwork id="d271340d-a55c-4470-af22-42640072917f" name="n-89-net2" cidr="None">
when compile I get error:
networks = network[i],
TypeError: 'OpenStackNetwork' object does not support indexing
please teach me how to fix this. thank you.
you just assigned a single object to networks parameter, which definitely will not work, try something like [OpenStackNetwork()]
Note: put your real object instead of my example

Categories