Transform List to Tensor more accurat - list

I want to return in the Dataloader a list.
But to return it, its need to be a tensor right?
So I transform it but in this process information is lost, is there another way to do this?
pt_tensor_from_list = torch.tensor(pose_transform)
pt_tensor_from_list = torch.FloatTensor(pose_transform)
I excpect the output:
([[-0.0003000000142492354, -0.0008999999845400453,
0.00039999998989515007, 0], [0.0010000000474974513, -0.00019999999494757503, 0.0003000000142492354, 0], [0.00019999999494757503, -0.0005000000237487257,
-0.0008999999845400453, 0], [5.484399795532227, -24.28619956970215, 117.5000991821289, 1])
But it is:
([[ -0.0003, -0.0009, 0.0004, 0.0000],
[ 0.0010, -0.0002, 0.0003, 0.0000],
[ 0.0002, -0.0005, -0.0009, 0.0000],
[ 5.4844, -24.2862, 117.5001, 1.0000]])

You are not losing any information during such conversion. The reason why it looks like that, more compactly, is as when you are printing a tensor, it invokes __str__() or __repr__() methods and it makes your tensor looks more pretty. As you can find here torch.Tensor uses a kind of internal tensor formatter called _tensor_str. If you look inside the code link you will find that by default parameter precision is set to 4:
precision: Number of digits of precision for floating point output (default = 4).
That's why you have only 4 digits for tensor values when printing the tensor. But actually, values stored in a tensor are the same as in original list.
Here is small example to get an idea:
Code:
import torch
test_list = ([[-0.0003000000142492354, -0.0008999999845400453, 0.00039999998989515007, 0],
[0.0010000000474974513, -0.00019999999494757503, 0.0003000000142492354, 0],
[0.00019999999494757503, -0.0005000000237487257, -0.0008999999845400453, 0],
[5.484399795532227, -24.28619956970215, 117.5000991821289, 1]])
print('Original values:')
for i in test_list:
for j in i:
print(j)
pt_tensor_from_list = torch.FloatTensor(test_list)
print('When printing FloatTensor:')
print(pt_tensor_from_list.dtype, pt_tensor_from_list, sep='\n')
print('When printing each value separately:')
for i in pt_tensor_from_list:
for j in i:
print(j.item())
Output:
Original values:
-0.0003000000142492354
-0.0008999999845400453
0.00039999998989515007
0
0.0010000000474974513
-0.00019999999494757503
0.0003000000142492354
0
0.00019999999494757503
-0.0005000000237487257
-0.0008999999845400453
0
5.484399795532227
-24.28619956970215
117.5000991821289
1
When printing FloatTensor:
torch.float32
tensor([[-3.0000e-04, -9.0000e-04, 4.0000e-04, 0.0000e+00],
[ 1.0000e-03, -2.0000e-04, 3.0000e-04, 0.0000e+00],
[ 2.0000e-04, -5.0000e-04, -9.0000e-04, 0.0000e+00],
[ 5.4844e+00, -2.4286e+01, 1.1750e+02, 1.0000e+00]])
When printing each value separately:
-0.0003000000142492354
-0.0008999999845400453
0.00039999998989515007
0.0
0.0010000000474974513
-0.00019999999494757503
0.0003000000142492354
0.0
0.00019999999494757503
-0.0005000000237487257
-0.0008999999845400453
0.0
5.484399795532227
-24.28619956970215
117.5000991821289
1.0
As you can see, we are getting the same values when printing each value separately.
BUT you can lose some info if you choose the wrong tensor types, for example HalfTensor instead of FloatTensor. Here is an example:
Code:
pt_tensor_from_list = torch.HalfTensor(test_list)
print('When printing HalfTensor:')
print(pt_tensor_from_list.dtype, pt_tensor_from_list, sep='\n')
print('When printing each value separately:')
for i in pt_tensor_from_list:
for j in i:
print(j.item())
Output:
When printing HalfTensor:
torch.float16
tensor([[-2.9993e-04, -8.9979e-04, 4.0007e-04, 0.0000e+00],
[ 1.0004e-03, -2.0003e-04, 2.9993e-04, 0.0000e+00],
[ 2.0003e-04, -5.0020e-04, -8.9979e-04, 0.0000e+00],
[ 5.4844e+00, -2.4281e+01, 1.1750e+02, 1.0000e+00]],
dtype=torch.float16)
When printing each value separately:
-0.0002999305725097656
-0.0008997917175292969
0.0004000663757324219
0.0
0.0010004043579101562
-0.00020003318786621094
0.0002999305725097656
0.0
0.00020003318786621094
-0.0005002021789550781
-0.0008997917175292969
0.0
5.484375
-24.28125
117.5
1.0
As you can notice now the values are (a little bit) different. Visit pytorch tensor docs to learn more about different types of torch.tensor.

Related

Array of real to binary (0/1)

I have an array :
0.3 0.4 0.65 1.45
-1.2 6.0 -3.49 3.9
And I would like to have 0 if value is negative and 1 if positive :
1 1 1 1
0 1 0 1
Is there a way to do this without a loop like:
DO X=1,Xmax
Do Y=1,Ymax
IF(Array(X,Y)>0)THEN
Array(X,Y)=1
END IF
END DO
END DO
I'm a fan of the where approach as given by Vladimir F, but I can also suggest a related one.
merge is an intrinsic elemental function which takes two sources and a mask:
array = MERGE(0., 1., array.lt.0.)
As a slight correction to Vladimir F's sign:
array = SIGN(0.5, array) + 0.5
Note the switching of order compared with the other answer.
With the elemental nature of merge and sign it is possible to mix scalar desired values with the array and array mask.
As both of these can naturally be modified to assign the value to another variable (even creating an integer one), I'll show an alternative where for completeness:
where (array.lt.0.)
another_array=0
elsewhere
another_array=1
end where
for another_array appropriately shaped.
I'm having way too much fun with this. This one does not require that the numbers fit into integers:
ARRAY = 0.5 * ARRAY / ABS(ARRAY) + 0.5
The most straight forward
where (array>=0)
array = 1
else where
array = 0
end where
it is not very handy that the sign function needs another array for the magnitudes, because
array = sign(array, halfs) + 0.5
requires an array with 0.5's of the same shape as array.
Actually it should be array = sign(0.5, array) + 0.5 as shown by francescalus. I even looked into the manual and then switched the arguments anyway...
It's ugly, but if you want a one-liner:
ARRAY = CEILING( ARRAY / CEILING(ABS(ARRAY)) )
Vladimir wants FAST!
REAL(KIND=8) :: ARRAY(4,2) = RESHAPE ( &
(/ 0.3, 0.4, 0.65, 1.45, -1.2, 6.0, -3.49, 3.9 /), (/4,2/) )
INTEGER(KIND=8) :: IARRAY(4,2)
EQUIVALENCE (ARRAY, IARRAY)
ARRAY = 1 - IBITS( IARRAY,63,1 )
:D

# function that given an array A consisting of N integers, returns the sum of all two -digit numbers.

function that given an array A consisting of N integers, returns the sum of all two -digit numbers.
def solution(A):
# write your code in Python 2.7
sum = 0
for i in A:
if i in range(0,1000):
sum = sum+i
return sum
A = [47,1900,1,90,45]
why would i get 183 instead of 182,please assist
Running solution...
Compilation successful.
Example test: [1, 1000, 80, -91]
WRONG ANSWER (got 81 expected -11)
Example test: [47, 1900, 1, 90, 45]
WRONG ANSWER (got 183 expected 182)
Detected some errors.
I think that in the first case you are just considering positive numbers and single digit numbers, which is in turn the problem for the second case.
test 1) 1+80=81
test 2) 47+1+90+45=183

How to use lists

I have never programmed before and I am trying to do an assignment.
I have to construct a change machine, that will give change to 1 euro, given an input, e.g input = 70, change = 30. The machine wants to give as few coins as possible among the coins with values 50, 20, 10, 5, 2 and 1 cent. So if the input is 65, the machine will give: 20 10 5.
The computation is run in a while-Loop, that runs until the remaining change needed is 0. In each loop body, I have to determine the largest coin still fitting in the remaining change needed. All the coins should be added to a list. Finally, the contents of that list should be displayed to the user.
So, I created the button to start the computation and the code should look like and I called my input money.
to compute-change
Create empty list
while [ remaining change > 0] [
Determine largest coin c, such that remaining change - c >= 0
Update the list with the chosen coin
Update the remaining change to be determined
]
end
So, I know how to create an empty list, i.e. [], and I know what the change is gonna be: 100-money; I also think I understood what the while means, however, even by following the skeleton of the report I don't know how to go on.
Can you help me?
Edit: How can I do this in NetLogo?
I downloaded and installed Netlogo and had a look at how the language works. I created a solution that you can use as base for your development (don't worry, I will explain it):
globals [
remaining_change
biggest_coin
possible_coins
returned_coins
]
to compute_change
set remaining_change 57
set returned_coins []
set possible_coins [1 2 5 10 20 50]
while [ remaining_change > 0 ] [
foreach possible_coins
[
if( remaining_change - ? >= 0 )
[
set biggest_coin ?
]
]
;Print next result
print "Return a coin of value: "
print biggest_coin
print "Remaining change: "
print remaining_change
;Append coins to list
set remaining_change remaining_change - biggest_coin
set returned_coins lput biggest_coin returned_coins
]
print returned_coins
end
How does it work?
Let us begin with the first block:
globals [
remaining_change
biggest_coin
possible_coins
returned_coins
]
At this point, I create a few variables I use for data storage:
remaining_change is the amount of change that needs to be returned.
biggest_coin is the value of the coin that will be returned next (the biggest possible value)
possible_coins is a list of all coins-sizes available
returned_coins is a list of all returned coins.
So, with these variables we can now start initializing them:
set remaining_change 57 we use an amount of 57 cents to return as example
set returned_coins [] initialize returned_coins with an empty list (nothing is yet returned)
set possible_coins [1 2 5 10 20 50] this is a list of our types of coins. The ascending order is important as we will see later.
Lets do stuff!
We start of with a while loop around the computation, that will keep returning coins, untilthere is no more change left to return.
while [ remaining_change > 0 ] [
]
After that, we need to determine which coin would be next to return to the user. We doo that by examining every possible coin with a foreach loop.
Basically, what we do next translates to:
"Let us look at this coin. Is it less or equal than what we need to
return? Yes? Then this is currently the biggest coin to give back. But
what about the next biggest coin?
Speaking in code, that looks like this:
foreach possible_coins
[
if( remaining_change - ? >= 0 )
[
set biggest_coin ?
]
]
do not let yourself get confused by the ?. It is just Netlogos way of saying "This is the currently examined item in your foreach loop" - so it is your current coin-value.
Let us tell the user what is going on!
This is not necessary for your computation, but nice for understanding whats going on. Its simply some output of what we calculated for the user to see.
;Print next result
print "Return a coin of value: "
print biggest_coin
print "Remaining change: "
print remaining_change
Finally, return the coin!
It is now time to return the next coin:
set remaining_change remaining_change - biggest_coin first, decrease our left amount of change by the value of our biggest coin.
set returned_coins lput biggest_coin returned_coins after that, append our value to the resulting list.
And there you go!
You have successfully computed a list of coins, that you can simply print returned_coins.
I am by no means an expert on NetLogo, but I tried this code and it works just fine. There are other ways of doing this, some probably simpler, but this code will provide you with a good starting point.
Base answer:
You basically need to understand the following concepts:
conditionals
Example in pseudo code:
if( remainingChange >= 50 )
{
output.append(new FiftyCentCoin());
remainingChange -= 50;
}
else
{
...
}
What happens here?
The if statement (or a slight variation, depending on your language) - also known as conditional - evaluates a boolean expression. Based on the result (true or false) it can execute a block of statements, basically using this algorithm:
if (*this is true*)
*do this*
else
*do that*
The example compares the amount of change to be returned with the value 50 (your biggest coin). If you need to return this amount of money or more, 50 cents will be subtracted from the leftover Change and a new FiftyCentCoin is appended to your output.
looping
Example in pseudo code:
while ( remainingChange > 0 )
{
returnACoin();
}
What happens here?
The while statement is a variation of a conditional, that will evaluate an expression, and repeat a block of code, as long as the expression holds true - using this algorithm:
while(*this is true*)
*do this*
The given example performs the action returnACoin again and again, until the amount of remainingChange is 0.
Using these basic blocks you can create your algorithm:
Be aware, that I have given you just a short introduction, and you should still read through multiple tutorials to get to know your language and its syntax.
In the following you can find some pseudo code (as you did not tell what language you are using) that you can use as rough guideline for your development:
price = 1.33 //1.33€ as example
sumPaid = 2 //amount of money the user paid
changeToReturn = sumPaid - price
changeCoins = []
while( changeToReturn > 0 )
{
if( changeToReturn >= 50 )
{
changeCoins[] = 50
changeToReturn -= 50
}
else if( changeToReturn >= 20 )
{
changeCoins[] = 20
changeToReturn -= 20
}
...
}

Understanding this python code

This code was on an exam and it asked what it's output was going to be.
I got it wrong unfortunately and put it was all 1's.
I'm a little confused with what this program is doing specifically with the if/else statement.
I'm a C programmer, so if possible could someone please translate the if/else statement into C code so I can understand what is going on. Thank you!
EDIT: to clarify, I'm not sure what the condition means "if x in d"
def somefunction(L):
d = {}
for x in L:
if x in d:
d[x] = d[x] + 1
else:
d[x] = 1
return d
L = [6, 10, -2, 2, 6, 4, -2, 6]
print somefunction(L)
output: {10: 1, 2: 1, 4: 1, -2: 2, 6: 3}
in in Python performs a containment check. It looks at the right-hand operand to see if it contains the left-hand operand.
>>> 2 in [1, 2, 4]
True
>>> 3 in [1, 2, 4]
False
I'd encourage you NOT to translate everything into C. Python is considerably different and trying to keep things in a C frame of mind will make things harder to understand.
One thing that is great is that Python is interpreted, so you can type "python" and then enter commands to see what they do. You can exam all the variables as things are manipulated. For example, you can do:
L = [6, 10, -2, 2, 6, 4, -2, 6]
for x in L:
print x
To see what the "in" does. Likewise for the rest of the code. Also, there are great online tutorials on Python, Google "Dive into Python", for example.
See Basically in this code what you are doing is you are making a count of no of times the element is repeated in the list..you are using dictionary as a means to take the count..
First of all in the if-else block you are checking whether the element is present or not..if its present then you are incrementing the count using the element as key..else you are creating a new key,key being the element and default value being 1...
Thus you iterate all over the list and check the count of each element in the list..
d[i]=j
#i is key,j is value.
And at last you print your findings by printing the dictionary..!!

Dividing List by integer and checking if any element in list is integer (PYTHON)

Hey I am a beginner at python, I wrote this code but its not working, i'm sure its something small that I cant see.
myList = [10,22,30,40]
myInt = 3.0
newList = [x/myInt for x in myList]
if any(isinstance(y,int) for y in newList):
print newList
else:
print "None are integers"
Since 30/3 =10 and 10 is integer, it should print out newList which is [3.33, 7.33, 10.0, 13.33], but its printing "None are integers".
I am certain there is a problem with "if any(isinstance(y,int) for y in newList):" but cannot figure out what.
In 2.7+, you can check to see if a float can be represented as an int:
myList = [10,22,30,40]
myInt = 3.0
divided = (el / myInt for el in myList) # generator over floats
is_integer = [el for el in divided if el.is_integer()] # filter ints only
# [10.0]
So your check would be:
if any((el / myInt).is_integer() for el in myList):
# do something
Here is your basic problem:
>>> 30/3
10
>>> 30/3.0
10.0
>>> type(10.0)
<type 'float'>
An integer is a whole number, without a fractional component. A float is a number, but with a fractional component (a decimal point), even if its .0 as the case above.
Although they are both numbers, for Python they are two different types.
Since you are dividing by a float, all results will be floats. Therefore your check fails because although they are numbers they are not integers.
Type is a strict feature in Python. Any operation involving a float produces another float, even if the value could be represented exactly as an integer. Something like this might work for you:
myList = [10,22,30,40]
myInt = 3
newList = [x%myInt for x in myList] # A list of remainders now, not quotients
if any(y == 0 for y in newList):
print [ x/(1.0*myInt) for x in myList ] # Reproduce your original myList
else:
print "None are integers"