How do I use fbcunn nn.HSM - neural-network

I'd love a simple example of how to use the nn.HSM hierarchical softmax module in fbcunn.
The documentation is nonexistent (see here). I did find this user group post which describes what the cluster "mapping" should look like, and there are some tests lying around for the module and its corresponding criterion but none of them use the module in a "normal" way, e.g. as the final layer in a simple feed-forward neural network.

Here's a small example that should work:
require 'torch'
require 'fbcunn'
hidden_dim = 10
input_dim = 20
batch_size = 1
gpuid = 0
function to_cuda(x) return gpuid >= 0 and x:cuda() or x end
inputs = to_cuda(torch.rand(batch_size, input_dim))
targets = to_cuda(torch.ones(batch_size):long())
-- #mapping should equal the number of possible outputs, in our case 8
-- this mapping defines 4 clusters, two size 2, one size 3, one size 1
mapping = { {1, 1}, {1, 2}, {2, 1}, {2, 2}, {2, 3}, {3, 1}, {4, 1}, {4, 2} }
linear = to_cuda(nn.Sequential():add(nn.Linear(input_dim,hidden_dim)))
hsm = to_cuda(nn.HSM(mapping, hidden_dim))
h_out = linear:forward(inputs)
s_out, err = hsm:forward(h_out, targets)
df_ds = hsm:backward(h_out, targets)
linear:backward(inputs, df_ds)
Note that as of this posting, the above example will only work on a GPU (cannot run on CPU, aka gpuid=-1); See this issue.
Additionally, the GPU must have compute capability 3.5 or greater; the example at the link above provides an even smaller example that will run on a GPU with compute capability 3.0.

Related

How to set proper arguments to build keras Convolution2D NN model [Text Classification]?

I am trying to use 2D CNN to do text classification on Chinese Article and have trouble on setting arguments of keras Convolution2D. I know the basic flow of Convolution2D to cope with image, but stuck by using my dataset with keras.
Input data
My data is 9800 Chinese Article, max sentence length is 6810,with 200 word2vec size.
So the input shape is `(9800, 1, 6810, 200)`
Code for building model
MAX_FEATURES = 6810
# I just randomly pick one filter, seems this is the problem?
nb_filter = 128
input_shape = (1, 6810, 200)
# each word is 200 (word2vec size)
embedding_size = 200
# 3 word length
n_gram = 3
# so stride here is embedding_size*n_gram
model = Sequential()
model.add(Convolution2D(nb_filter, n_gram, embedding_size, border_mode='valid', input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(100, 1), border_mode='valid'))
model.add(Dropout(0.5))
model.add(Activation('relu'))
model.add(Flatten())
model.add(Dense(hidden_dims))
model.add(Dropout(0.5))
model.add(Activation('relu'))
model.add(Dense(1))
model.add(Activation('sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy'])
# X is (9800, 1, 6810, 200)
model.fit(X, y, batch_size=32,
nb_epoch=5,
validation_split=0.1)
Question 1. I have problem to set Convolution2D arguments. My reseach is below,
The official docs do not contain an exmaple for 2D CNN text classifacation(though has 1D CNN).
Convolution2D defination is here https://keras.io/layers/convolutional/:
keras.layers.convolutional.Convolution2D(nb_filter, nb_row, nb_col, init='glorot_uniform', activation=None, weights=None, border_mode='valid', subsample=(1, 1), dim_ordering='default', W_regularizer=None, b_regularizer=None, activity_regularizer=None, W_constraint=None, b_constraint=None, bias=True)
nb_filter: Number of convolution filters to use.
nb_row: Number of rows in the convolution kernel.
nb_col: Number of columns in the convolution kernel.
border_mode: 'valid', 'same' or 'full'. ('full' requires the Theano backend.)
Some research about the arguments:
This issue https://github.com/fchollet/keras/issues/233 is about 2D CNN for text classification, I read all comments and pick:
(1) https://github.com/fchollet/keras/issues/233#issuecomment-117427013
model.add(Convolution2D(nb_filter=N_FILTERS, stack_size=1, nb_row=FIELD_SIZE,
nb_col=1, subsample=(STRIDE, 1)))
(2) https://github.com/fchollet/keras/issues/233#issuecomment-117700913
sequential.add(Convolution2D(nb_feature_maps, 1, n_gram, embedding_size))
But it seems has some diference to current keras version, also the arguments naming by different people are in a mess (I hope keras has an easy understandable argument expanation).
Another comment I see about current api:
https://github.com/fchollet/keras/issues/1665#issuecomment-181181000
The current API is as below:
keras.layers.convolutional.Convolution2D(nb_filter, nb_row, nb_col, init='glorot_uniform', activation='linear', weights=None, border_mode='valid', subsample=(1, 1), dim_ordering='th', W_regularizer=None, b_regularizer=None, activity_regularizer=None, W_constraint=None, b_constraint=None)
So (36,1,7,7) seems the reason, the correct arguments would be (36,7,7,...).
By above research, on my understanding of convolution, Convolution2D create a (nb_filter, nb_row, nb_col) filter , by sliding a stride to get one filter result, recurse sliding, finally combine the result into array with shape (1, one_sample_article_length[6810] / nb_filter), and go to the next layer, is that right? Is my code below set nb_row and nb_col correct ?
Question 2. What is the proper MaxPooling2D arguments? (for my dateset or for commonm, either is OK)
I refer this issue https://github.com/fchollet/keras/issues/233#issuecomment-117427013 to set the argument, there are two kinds:
MaxPooling2D(poolsize=(((nb_features - FIELD_SIZE) / STRIDE) + 1, 1))
MaxPooling2D(poolsize=(maxlen - n_gram + 1, 1))
I have no idea why they calculate MaxPooling2D argument like that.
Question 3. Any recommendation for batch_size and nb_epoch to do such text classification? I have no idea at all.

How to merge two tensors at the beginning of a network in Torch?

Given the following beginning of a network
local net = nn.Sequential()
net:add(SpatialConvolution(3, 64, 4, 4, 2, 2, 1, 1))
with an input tensor input
local input = torch.Tensor(batchSize, 3, 64, 64)
// during training
local output = net:forward(input)
I want to modify the network to accept a second tensor cond as input
local cond = torch.Tensor(batchSize, 1000, 1, 1)
// during training
local output = net:forward({input, cond})
I modified the network by adding a JoinTable before the SpatialConvolution is added, like so:
local net = nn.Sequential()
net:add(nn.JoinTable(2, 4))
net:add(SpatialConvolution(3, 64, 4, 4, 2, 2, 1, 1))
This is not working because both tensors have different sizes in dimensions 2, 3, and 4. Giving the cond tensor as size of (batchSize, 1000, 64, 64) is not an option since its a waste of memory.
Is there any best practise for merging two different tensors at the beginning of a network to be feed into the first layer.
There is no such thing as "merging" tensors which do not have compatible shapes. You should simply pass a table of tensors and start your network with SelectTable operation and work with nngraph, not simple Sequential. In particular - how would you expect Spatial Convolution to work on such odd "tensor" which "narrows down" to your cond? There is no well defined operation in mathematics for such use case, thus you have to be more specific (which you will achieve with nngraph and SelectTable).

How do I enumerate and deduplicate 9 items allocated in triplets to each of 3 inheritors... and beyond?

This question is related to the context described in Seeking a solution or a heursitic approxmation for the 3-partition combinatorial situation. The task is distribute approximately 48 pieces of inherited jewelry, each with its appraised value, to 3 inheritors so as to give each inheritor equal or nearly equal value. That question has been sufficiently answered for my legalistic purposes.
This new question arises out of my pursuit of solving this by enumeration. Totally unnecessary legally. Just an intellectual challenge now.
The problem now:
Assign to each item a unique index: probably just the integers 1 through 48. Now allocate these 48 to each of the 3 inheritors and eliminate the duplicates.
To make this example case simpler, assert that there are only 9 items and each inheritor is to receive exactly 3 items. (Note that this diverges from the previous goal of making the 3 bins of nearly equal value.)
How to eliminate the duplications in the sequence of items-to-bins?
Example:
Let bin 1 contain items {1,2,3}
Let bin 2 contain items {4,5,6}
Let bin 3 contain items {7,8,9}
There will be 6 duplications of the final values of this triplet-of-triplets:
{1,2,3}{4,5,6}{7,8,9}
{4,5,6}{1,2,3}{7,8,9}
{4,5,6}{7,8,9}{1,2,3}
{7,8,9}{1,2,3}{4,5,6}
{7,8,9}{4,5,6}{1,2,3}
etc.
Again, how to eliminate the duplications in the sequence of items-to-bins? Without enumerating the entire set of permutations-of-triplets. No, that's not quite right. I might have to temporarily grind out all the permutations-of-triplets. How to quickly eliminate the duplicated combinations-of-triplets based on what has been done a priori?
I can imagine something like inventing a function which, given any combination of 3 items, returns a unique value. Something using prime numbers? Except that many pairs of prime numbers sum to another prime number.
I crossposted the original question on mathoverflow. I apologize for not understanding the relationship between stackoverflow and mathoverflow.
One can show that the total number of restricted partitions is
, which equals 280.
This can be reordered as:
You can get this by taking the first third of the (ordered) combinations you obtain by taking three out of nine list members and the first half of the combinations you get when you take three out of the remaining six for each choice of the first three. There's no free choice for the last three of course.
With Mathematica you might generate this as:
list = Range[9];
l1 = Subsets[list, {3}, Binomial[9, 3]/3];
l2 = Subsets[Complement[list, #], {3}, Binomial[6, 3]/2] & /# l1;
Flatten[
Outer[
Function[{ll1, ll2}, {ll1, ll2, Complement[list, ll1, ll2]}],
{#1}, #2, 1, 1
] & ### ({l1, l2}\[Transpose]),
2]
This is a good question. It is essentially a restricted set partition problem.
Here is one way in which you may approach this. I am not certain that it is optimal, but it is many magnitudes more efficient than brute force (generating all permutations and then removing duplicates).
I will be using curly brackets to represent lists, as this is familiar to me.
Start with this template, which represents zero items in three bins:
{ {{}, {}, {}} }
For each list within the outermost (i.e. just {{}, {}, {}} here):
Append 1 to each sub-list, skipping any lists that are full (contain three elements), and append only to the first empty {} list if there is more than one.
Keep a copy of the entire list for each replacement that is made, and join these together at the end of the step.
This process will then be repeated for 2, 3, etc., until all items are in bins or all bins are full. Example steps:
{ {{}, {}, {}} }
{ {{1}, {}, {}} }
{ {{1, 2}, {}, {}}, {{1}, {2}, {}} }
{ {{1, 2, 3}, {}, {}}, {{1, 2}, {3}, {}}, {{1, 3}, {2}, {}}, {{1}, {2, 3}, {}}, {{1}, {2}, {3}} }
{ {{1, 2, 3}, {4}, {}}, {{1, 2, 4}, {3}, {}}, {{1, 2}, {3, 4}, {}}, {{1, 2}, {3}, {4}}, {{1, 3, 4}, {2}, {}}, {{1, 3}, {2, 4}, {}}, {{1, 3}, {2}, {4}}, {{1, 4}, {2, 3}, {}}, {{1}, {2, 3, 4}, {}}, {{1}, {2, 3}, {4}}, {{1, 4}, {2}, {3}}, {{1}, {2, 4}, {3}}, {{1}, {2}, {3, 4}} }

Selecting with Cases

Please Consider :
Subsets[Flatten[ParallelTable[{i, j}, {i, 1, 96}, {j, 1, 4}], 1], {4}]
I need to select all the Sublist such that the the i value is never the same within each sublist of 4
{{3,1},{4,1},{5,1},{6,1}} should be accepted while {{1,1},{1,2},{2,3},{6,1}} should be rejected. The Value 1 for i being repeated 2 times.
I know I could do this with Cases, but don`t understand the Syntax of it, and find the help on Cases rather empty compared to its potential applications.
Assuming your data is in the variable data, the following should do it:
Select[data, Length#Union[#[[All, 1]]] === 4 &]
This takes the "i"-value (i.e. first element), and checks that the 4 values are all different (i.e. if we remove the duplicates we still have 4 of them)
This response assumes that the input data is a list of tuples of four pairs each, e.g.:
$data = {{{3, 1}, {4, 1}, {5, 1}, {6, 1}} , {{1, 1}, {1, 2}, {2, 3}, {6, 1}}};
Using Cases, one could name and compare the first elements of each pair to ensure that they are unequal:
Cases[
$data
, {{a_, _}, {b_, _}, {c_, _}, {d_, _}} /; Unequal[a, b, c, d]
]
Another use of Cases compares the first elements of each pair without naming them:
Cases[
$data
, tuple_ /; Unequal ## tuple[[All, 1]]
]
Alternatively, one could use DeleteCases and exclude tuples with at least two pairs with the same initial value:
DeleteCases[
$data
, {___, {a_, _}, ___, {a_, _}, ___}
]
One might think that this last expression could be:
(* warning: does not work *)
Cases[$data, Except[{___, {a_, _}, ___, {a_, _}, ___}]]
... but Except does not permit named patterns in the first argument.
WReach already covered Cases well, so here is another approach.
Pick[data, Signature /# data[[All, All, 1]], 1 | -1]
It is faster than most of the other methods, but still not as fast as the fixed-length Cases method.

How to plot a gene graph for a DNA sequence say ATGCCGCTGCGC?

I need to generate a random walk based on the DNA sequence of a virus, given its base pair sequence of 2k base pairs. The sequence looks like "ATGCGTCGTAACGT". The path should turn right for an A, left for a T, go upwards for a G and downwards for a C.
How can I use either Matlab, Mathematica or SPSS for this purpose?
I did not previously know of Mark McClure's blog about Chaos Game representation of gene sequences, but it reminded me of an article by Jose Manuel Gutiérrez (The Mathematica Journal Vol 9 Issue 2), which also gives a chaos game algorithm for an IFS using (the four bases of) DNA sequences. A detailed description may be found here (the original article).
The method may be used to produce plots such as the following. Just for the hell of it, I've included (in the RHS panels) the plots generated with the corresponding complementary DNA strand (cDNA).
Mouse Mitochondrial DNA (LHS) and its
complementary strand (cDNA) (RHS).
These plots were generated from GenBank Identifier gi|342520. The sequence contains 16295 bases.
(One of the examples used by Jose Manuel Gutiérrez. If anyone is interested, plots for the human equivalent may be generated from gi|1262342).
Human Beta Globin Region (LHS) and its cDNA (RHS)
Generated from gi|455025| (the example
used my Mark McClure). The sequence contains 73308 bases
There are pretty interesting plots! The (sometimes) fractal nature of such plots is known, but the symmetry obvious in the LHS vs RHS (cDNA) versions was very surprising (at least to me).
The nice thing is that such plots for any DNA sequence may be very easily generated by directly importing the sequence (from, say, Genbank), and then using the power of Mma.
All you need it the accession number! ('Unknown' nucleotides such as "R" may need to be zapped) (I am using Mma v7).
The Original Implimenation (slightly modified) (by Jose Manuel Gutiérrez)
Important Update
On the advise of Mark McClure, I have changed Point/#Orbit[s, Union[s]] to Point#Orbit[s, Union[s]].
This speeds things up very considerably. See Mark's comment below.
Orbit[s_List, {a_, b_, c_, d_}] :=
OrbitMap[s /. {a -> {0, 0}, b -> {0, 1}, c -> {1, 0},
d -> {1, 1}}];
OrbitMap =
Compile[{{m, _Real, 2}}, FoldList[(#1 + #2)/2 &, {0, 0}, m]];
IFSPlot[s_List] :=
Show[Graphics[{Hue[{2/3, 1, 1, .5}], AbsolutePointSize[2.5],
Point # Orbit[s, Union[s]]}], AspectRatio -> Automatic,
PlotRange -> {{0, 1}, {0, 1}},
GridLines -> {Range[0, 1, 1/2^3], Range[0, 1, 1/2^3]}]
This gives a blue plot. For green, change Hue[] to Hue[{1/3,1,1,.5}]
The following code now generates the first plot (for mouse mitochondrial DNA)
IFSPlot[Flatten#
Characters#
Rest#Import[
"http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=\
nucleotide&id=342520&rettype=fasta&retmode=text", "Data"]]
To get a cDNA plot I used the follow transformation rules (and also changed the Hue setting)
IFSPlot[ .... "Data"] /. {"A" -> "T", "T" -> "A", "G" -> "C",
"C" -> "G"}]
Thanks to Sjoerd C. de Vries and telefunkenvf14 for help in directly importing sequences from the NCBI site.
Splitting things up a bit, for the sake of clarity.
Import a Sequence
mouseMitoFasta=Import["http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=342520&rettype=fasta&retmode=text","Data"];
The method given for importing sequences in the original Mathematica J. article is dated.
A nice check
First#mouseMitoFasta
Output:
{>gi|342520|gb|J01420.1|MUSMTCG Mouse mitochondrion, complete genome}
Generation of the list of bases
mouseMitoBases=Flatten#Characters#Rest#mouseMitoFasta
Some more checks
{Length#mouseMitoBases, Union#mouseMitoBases,Tally#mouseMitoBases}
Output:
{16295,{A,C,G,T},{{G,2011},{T,4680},{A,5628},{C,3976}}}
The second set of plots was generated in a similar manner from gi|455025. Note that the sequence is long!
{73308,{A,C,G,T},{{G,14785},{A,22068},{T,22309},{C,14146}}}
One final example (containing 265922 bp), also showing fascinating 'fractal' symmetry. (These were generated with AbsolutePointSize[1] in IFSPlot).
The first line of the fasta file:
{>gi|328530803|gb|AFBL01000008.1| Actinomyces sp. oral taxon 170 str. F0386 A_spOraltaxon170F0386-1.0_Cont9.1, whole genome shotgun sequence}
The corresponding cDNA plot is again shown in blue on RHS
Finally, Mark's method also gives very beautiful plots (for example with gi|328530803), and may be downloaded as a notebook.
Not that I really understand the "graph" you want, but here is one literal interpretation.
None of the following code in necessarily in a final form. I want to know if this is right before I try to refine anything.
rls = {"A" -> {1, 0}, "T" -> {-1, 0}, "G" -> {0, 1}, "C" -> {0, -1}};
Prepend[Characters#"ATGCGTCGTAACGT" /. rls, {0, 0}];
Graphics[Arrow /# Partition[Accumulate#%, 2, 1]]
Prepend[Characters#"TCGAGTCGTGCTCA" /. rls, {0, 0}];
Graphics[Arrow /# Partition[Accumulate#%, 2, 1]]
3D Options
i = 0;
Prepend[Characters#"ATGCGTCGTAACGT" /. rls, {0, 0}];
Graphics[{Hue[i++/Length#%], Arrow##} & /#
Partition[Accumulate#%, 2, 1]]
i = 0;
Prepend[Characters#"ATGCGTCGTAACGT" /.
rls /. {x_, y_} :> {x, y, 0.3}, {0, 0, 0}];
Graphics3D[{Hue[i++/Length#%], Arrow##} & /#
Partition[Accumulate#%, 2, 1]]
Now that I know what you want, here is a packaged version of the first function:
genePlot[s_String] :=
Module[{rls},
rls =
{"A" -> { 1, 0},
"T" -> {-1, 0},
"G" -> {0, 1},
"C" -> {0, -1}};
Graphics[Arrow /# Partition[#, 2, 1]] & #
Accumulate # Prepend[Characters[s] /. rls, {0, 0}]
]
Use it like this:
genePlot["ATGCGTCGTAACGT"]
It sounds like you might be talking about CGR, or the so called Chaos Game Representation of a gene sequence described in the 1990 paper "Chaos game representation of gene structure" by Joel Jefferey. Here's an implementation in Mathematica:
cgrPic[s_String] := Module[
{},
chars = StringCases[s, "G"|"A"|"T"|"C"];
f[x_, "A"] := x/2;
f[x_, "T"] := x/2 + {1/2, 0};
f[x_, "G"] := x/2 + {1/2, 1/2};
f[x_, "C"] := x/2 + {0, 1/2};
pts = FoldList[f, {0.5, 0.5}, chars];
ListPlot[pts, AspectRatio -> Automatic]]
Here's how to apply it to a gene sequence taken from Mathematica's GenomeData command:
cgrPic[GenomeData["FAT4", "FullSequence"]]
You might also try something like this...
RandomDNAWalk[seq_, path_] :=
RandomDNAWalk[StringDrop[seq, 1],
Join[path, getNextTurn[StringTake[seq, 1]]]];
RandomDNAWalk["", path_] := Accumulate[path];
getNextTurn["A"] := {{1, 0}};
getNextTurn["T"] := {{-1, 0}};
getNextTurn["G"] := {{0, 1}};
getNextTurn["C"] := {{0, -1}};
ListLinePlot[
RandomDNAWalk[
StringJoin[RandomChoice[{"A", "T", "C", "G"}, 2000]], {{0, 0}}]]
Assuming that the sequence S has been mapped already*) to integer array then the actual computation of movements is straightforward based on rules R:
R =
1 -1 0 0
0 0 1 -1
S =
1 2 3 4 3 2 4 3 2 1 1 4 3 2
T= cumsum(R(:, S), 2)
T =
1 0 0 0 0 -1 -1 -1 -2 -1 0 0 0 -1
0 0 1 0 1 1 0 1 1 1 1 0 1 1
*) You need to elaborate more on the actual sequence. Is it represented as single string, or perhaps as cell array, or something else?
Edit:
Assuming your sequence is represented as string, then you'll map it to integer sequence S like:
r= zeros(1, 84);
r(double("ATGC"))= [1 2 3 4];
S= r(double("ATGCGTCGTAACGT"))
And to plot it:
plot([0 T(1, :)], [0 T(2, :)], linespec)
where linespec is the desired line specification.
This question seems to have been well answered already, but I thought I'd add that what you are describing has been previously published under the banner of DNA walks among a collection of numerical representation methods for DNA sequences, which are discussed in our preprint.
It turns out that DNA walks aren't very useful in practice, yet permit intuitive visualisation. I don't have it to hand, but I'd imagine my colleague would be more than happy to provide the Matlab code used to generate the below figure.