Torch : How to select subset of tds data-structure? - torch

I am using the tds data-structure for some data manipulation purposes in Torch. I would like to know how can I select a subset of the value of this data structure.
eg. In Python,
> a = [1,2,3,4,5]
> a[1:3]
[2,3]
In Lua/Torch,
> a = torch.Tensor({1,2,3,4,5})
> a = [{{1,3}}]
1
2
3
What is the equivalent of the above operations in tds, if any?

Related

Access dictionary key value with variable in LUA

local function Numeral(roman)
local symbols = {}
local sum = 0
for i = 1,#roman do
local val = roman:sub(i,i)
sum = sum + symbols[val]
end
return sum
end
print(Numeral('II'))
Basically, I'm making a roman numeral to number converter. What I want to do is access a key in a dictionary with a variable like
local var = 'I'
local something = dictionary.var
But with what I'm doing, it may be a bit more complicated. Is it possible?
When using a table for the roman numbers then a metatable with the table functions in __index make things a bit easier.
This example show what i mean...
> _VERSION
Lua 5.4
> romans=setmetatable({},{__index=table})
> romans:insert('I')
> romans:insert('II')
> romans:insert('III')
> romans:insert('IV')
> romans:insert('V')
> romans:insert('VI')
> romans:insert('VII')
> romans:insert('VIII')
> romans:insert('VIIII')
> romans:insert('X')
> romans:concat(', ',1,10)
I, II, III, IV, V, VI, VII, VIII, VIIII, X
( Done in a interactive Lua console ( lua -i ) )
For more about doing converting from and to roman numbers you can read also...
https://gist.github.com/efrederickson/4080372
But be aware its not free of bugs.
You can do it better ;-)

ndgrid - input and output from cell array

I am converting some code from Matlab to Scilab and ran into trouble trying to use Scilab 'ndgrid' function with input and output from cell array.
Specifically, I use ndgrid with an a priori unknown number of vectors (contained in a cell array) and intend to get the output grid matrices in a cell array.
In Matlab the code looks like that:
v = {0:3,0:3}; // not necessarily of length 2 (dynamically set)
G = cell(1,2);
[G{:}] = ndgrid(v{:});
I can't obtain similar behaviour using Scilab (neither for the input, nor for the output).
For the input, Scilab returns ndgrid: Wrong type for argument #1: Booleans, Integers, Decimals, Complexes, Polynomials, Rationals or Texts expected.
I hope a workaround exists. Thanks for your help!
v = list(0:3, 0:2); // not necessarily of length 2 (dynamically set)
G = list();
c = strcat(msprintf("G(%i)\n",(1:length(v))'),",")
execstr("[" + c + "] = ndgrid(v(:))")
G
does it:
--> c = strcat(msprintf("G(%i)\n",(1:length(v))'),",")
c =
"G(1),G(2)"
--> execstr("[" + c + "] = ndgrid(v(:))")
--> G
G =
(1) : [4x3 constant]
(2) : [4x3 constant]

Why is Julia not taking the correct data in the function?

I started learning how to program in Julia, and I'm making a pretty simple code, but it's not working as I wish, and I'm lost because I can't find where's the error.
Basically, I have a vector like this one: (1,0,0,1,1) and I made two functions that will change the entries of the vector.
The first function needs to change every entry of the vector for 1.
The second function needs to change every entry as follows: if the entry is 1, then change it for 0, and vice versa.
I have the next code:
function vectorMethodOne(vector1)
for i = 1:length(vector1)
if vector1[i] == 0
vector1[i] = 1
end
end
return vector1
end
function vectorMethodTwo(vector1)
for i = 1:length(vector1)
if vector1[i] == 0
vector1[i] = 1
elseif vector1[i] == 1
vector1[i] = 0
end
end
return vector1
end
The problem happens when I run the code like this:
vectorEx = rand(0:1, 5)
println("Original Vector:")
println(string(vectorEx))
println("Vector using method 1:")
vectorM1 = vectorMethodOne(vectorEx)
println(string(vectorM1))
println("Vector using method 2:")
vectorM2 = vectorMethodTwo(vectorEx)
println(string(vectorM2))
The output looks like this:
> Original Vector:
> [1,0,0,1,1]
> Vector using method 1:
> [1,1,1,1,1]
> Vector using method 2:
> [0,0,0,0,0]
But I want that the output looks like this:
> Original Vector:
> [1,0,0,1,1]
> Vector using method 1:
> [1,1,1,1,1]
> Vector using method 2:
> [0,1,1,0,0]
If I only run the vectorMethodTwo, it works like I want, like this:
vectorEx = rand(0:1, 5)
println("Original Vector:")
println(string(vectorEx))
println("Vector using method 2:")
vectorM2 = vectorMethodTwo(vectorEx)
println(string(vectorM2))
And the output looks like this:
> Original Vector:
> [1,0,0,1,1]
> Vector using method 2:
> [0,1,1,0,0]
But I want that every function run over the original vector (1,0,0,1,1) but the vectorMethodTwo is running over the modified vector (1,1,1,1,1) and I can't understand where's the error in my code.
Let's look at your output:
> Original Vector:
> [1,0,0,1,1]
> Vector using method 1:
> [1,1,1,1,1]
> Vector using method 2:
> [0,0,0,0,0]
Odd. Method 2 looks like method 1 flipped. Let's check:
println(vectorMethodTwo([1,1,1,1,1]))
> [0,0,0,0,0]
Very suspicious! Why could this be happening? Please think about this before moving to the next section.
Your "functions" are mutating the vector. When you do this in vectorMethodOne,
vector1[i] = 1
, you are changing the contents of vector1 that was passed in. That vector1 refers to the same memory as vectorEx.
Do not write code that mutates your inputs (unless you name the function accordingly). Either create a copy of your vector before mutating it, or try a list comprehension:
function vectorMethodOne(vector1)
return [x == 0 ? 1 : x for x in vector1]
end
function vectorMethodTwo(vector1)
return [x == 0 ? 1 : x == 1 ? 0 : x for x in vector1]
end
These do not modify the contents of the input vector1 in any way.

How to do calculation between different rows of a csv file in Python

If I have this csv data:
(I am using Python-3.4, by the way)
['20150101','2','1'] # row 0
['20150102','10','3'] # row 1
['20150103','4','2'] # row 2
['20150104','5','4'] # row 3
['20150105','12','6'] # row 4
....
And I want to:
Multiply, say, (in pseudo-code) data[2] of row[1] (which is '3' in ['20150102','10','3']) with data[2] of row[0] (which is '1' in ['20150101','2','1']), and
Iterate the calculation to continue on with (in pseudo-code) data[2] of row[2] * data[2] of row[1], data[2] of row[3] * data[2] of row[2], data[2] of row[4] * data[2] of row[3], and so on until data[2] of row[-1] * data[2] of row[-2],
How can I do the above?
What I have experimented with:
import csv
f = open('file.csv','r')
r = csv.reader(f)
for i, n in enumerate(r):
print(int(n[1])*int(n[2]))
...which only calculates data within the same row.
But what I need to do is to calculate data from row[i] with data from row[i-1] (i.e. data from previous row), and then iterate the calculation the entire file to row[-1] (last row).
Note:
I don't want to import any module for this (except csv just for opening and reading the file).
And if possible to write the code with as few lines as possible.
Don't worry about where the result of the calculation will go or whether it will keep changing as the iteration progresses (it could be appended to a list or written to a separate csv file, etc, but that's not the problem at the moment).
You will have to create a Python list in a variable, and then loop over the rows while appending the column's data to the list. After looping, loop over the list to perform the calculation.
For example if you wanted to multiply all the numbers in column 2 of each row:
import csv
f = open('file.csv','r')
r = csv.reader(f)
myData = []
for i, n in enumerate(r):
myData.append(int(n[1])
product = 1
for num in myData:
product *= num

Create reference to an object

Question Does R contains the concept of reference to an object.
In python, an equal operator is, in fact, a copy by reference.
For example:
>> a = [1,2,3]
>> b = a
>> b[1] = 10
>> a
[1, 10, 3]
or in C++
vector a(3);
a[1] = 1;
vector& b = a;
b[1] = 10;
// now a[1] = 10
You should probably look at reference classes, but you can also just use plain old environments:
> a=new.env()
> a$data=c(1,2,3)
> b=a
> b$data
[1] 1 2 3
> a$data[1]=99
> b$data
[1] 99 2 3
a and b are the same environment:
> a
<environment: 0xa1799fc>
> b
<environment: 0xa1799fc>
so their contents are the same objects.
I think some of the other R OO systems (R.oo, proto?) use environments like this to implement OO objects and methods.
So, although you can just do this, action-at-a-distance effects like this can cause very hard to find bugs, and you probably shouldn't.
Yes, this feature is present in R, though I've never used it myself. Reference classes (or R5 classes as they are sometimes dubbed) have this kind of behaviour. Fairly detailed documentation are in the link below, along with an example
http://www.inside-r.org/r-doc/methods/ReferenceClasses
There are other questions on SE which link to various presentations which probably contain more examples
What is the significance of the new Reference Classes?

Resources