I am trying to combine two ParameterLists in Pytorch. I've implemented the following snippet:
import torch
list = nn.ParameterList()
for i in sub_list_1:
list.append(i)
for i in sub_list_2:
list.append(i)
Is there any functions that takes care of this without a need to loop over each list?
You can use nn.ParameterList.extend, which works like python's built-in list.extend
plist = nn.ParameterList()
plist.extend(sub_list_1)
plist.extend(sub_list_2)
Alternatively, you can use += which is just an alias for extend
plist = nn.ParameterList()
plist += sub_list_1
plist += sub_list_2
In addition to #jodag's answer, one other solution is to unwrap the lists and construct a new list with them
param_list = nn.ParameterList([*sub_list_1, *sub_list_2])
Related
I have a below mentioned list:
a= ['1234,5678\n','90123,45678\n']
The expected output I'm working towards is this:
op = [['1234','5678'],['90123','45678']]
Basically a list of lists with individual elements referring to a particular column.
Using the below mentioned code i get the following output:
a = ['1234,5678\n','90123,45678\n']
new_list = []
for element in a:
#remove new lines
new_list.append(element.splitlines())
print(new_list)
output:[['1234,5678'], ['90123,45678']]
Any direction regarding this would be much appreciated.
Check this:
a= ['1234,5678\n','90123,45678\n']
a = ['1234,5678\n','90123,45678\n']
new_list = []
for element in a:
#remove new lines
new_list.append(element.strip("\n").split(","))
print(new_list)
Try this:
a = [i.strip("\n").split(",") for i in a]
Since the strings in your input list appears to follow the CSV format, you can use csv.reader to parse them:
import csv
list(csv.reader(a))
This returns:
[['1234', '5678'], ['90123', '45678']]
I am trying to add stop words into my stop_word list, however, the code I am using doesn't seem to be working:
Creating stop words list:
stopwords = nltk.corpus.stopwords.words('english')
CustomListofWordstoExclude = ['rt']
stopwords1 = stopwords.extend(CustomListofWordstoExclude)
Here I am converting the text to a dtm (document term matrix) with tfidf weighting:
vect = TfidfVectorizer(stop_words = 'english', min_df=150, token_pattern=u'\\b[^\\d\\W]+\\b')
dtm = vect.fit_transform(df['tweets'])
dtm.shape
But when I do this, I get this error:
FutureWarning: Pass input=None as keyword args. From version 0.25 passing these as positional arguments will result in an error
warnings.warn("Pass {} as keyword args. From version 0.25 "
What does this mean? Is there an easier way to add stopwords?
I'm unable to reproduce the warning. However, note that a warning such as this does not mean that your code did not run as intended. It means that in future releases of the package it may not work as intended. So if you try the same thing next year with updated packages, it may not work.
With respect to your question about using stop words, there are two changes that need to be made for your code to work as you expect.
list.extend() extends the list in-place, but it doesn't return the list. To see this you can do type(stopwords1) which gives NoneType. To define a new variable and add the custom words list to stopwords in one line, you could just use the built-in + operator functionality for lists:
stopwords = nltk.corpus.stopwords.words('english')
CustomListofWordstoExclude = ['rt']
stopwords1 = stopwords + CustomListofWordstoExclude
To actually use stopwords1 as your new stopwords list when performing the TF-IDF vectorization, you need to pass stop_words=stopwords1:
vect = TfidfVectorizer(stop_words=stopwords1, # Passed stopwords1 here
min_df=150,
token_pattern=u'\\b[^\\d\\W]+\\b')
dtm = vect.fit_transform(df['tweets'])
dtm.shape
Hi I starting learning python.
I have to do a small work to generate password using itertool. the only thing I don't understand how to convert this result :
itertools.product object at 0x03493BE8
to something readeable.
How can I convert it to get a string or something similar ?
Here is my code :
for CharLength in range(12):
words= (itertools.product(Alphabet, repeat=CharLength))
print(words)
itertools.product() returns a generator.
To print them you can use the * operator.
for char_len in range(12):
words = itertools.product(alphabet, repeat=char_len)
print(*words)
itertools.product returns a generator object. If you wish, you could go over it and convert it to a list so it's easier to view its contents, e.g. by using a list comprehension:
words = [w for w in itertools.product(Alphabet, repeat=CharLength)]
How do I access elements of a named list by name?
I have 3 functions, all of which return a ListSexpVector of class htest. One of them has 5 elements, ['method', 'parameter', 'statistic', 'p.value', 'data.name'], others have a different number, and order. I am interested in extracting the p.value, statistic and parameter from this list. In R I can use $, like so:
p.value <- fit$p.value
statistic <- fit$statistic
param <- fit$parameter
The best equivalent I found in rpy2 goes like:
p_val = fit[list(fit.do_slot('names')).index('p.value')]
stat = fit[list(fit.do_slot('names')).index('statistic')]
param = fit[list(fit.do_slot('names')).index('parameter')]
Which is quite long-winded. Is there a better (shorter, sweeter, Pythonic) way?
There is the good-old-fashioned integer based indexing:
p_val = fit[3]
stat = fit[2]
param = fit[1]
But it doesn't work when the positions are changed, and therefore is a serious limitation because I am fitting 3 different functions, and each return a different order.
The high-level interface is meant to provide a friendlier interface as the low-level interface is quite close to R's C-API. With it one can do:
p_val = fit.rx2('p.value')
or
p_val = fit[fit.names.index('p.value')]
If working with the low-level interface, you will essentially have to implement your own convenience wrapper to reproduce these functionalities. For example:
def dollar(obj, name):
"""R's "$"."""
return obj[fit.do_slot('names').index(name)]
I've got the following code on a Controller
def db = new Sql(dataSource)
def rawLines = db.rows("SELECT name FROM LINES")
def lines = []
/*(db.rows returns the values as [NAME:value] */
rawLines.each {
lines.add(it.name)
}
/*Then, use lines */
I can't keep away the impression that there is probably some way to do this in a more elegant way, something similar to a list comprehension in Python:
lines = [ l.name for l in db.rows("SELECT name FROM LINES") ]
Having to declare an empty list and then populate it doesn't seem the best way of doing things...
Is it possible to do something like this, or Groovy doesn't allow it?
Can't you just use the spread operator, and do:
lines = rawLines*.name
(see http://docs.groovy-lang.org/latest/html/documentation/index.html#_spread_operator)
tim_yates' answer is a clean solution when you want to call a method (or property) on each element of list in order to transform it e.g.:
[1,2,3]*.multiply(5)
but if you want to call a method from another object or do something more complex you can use collect:
[1, 2, 3].collect {Math.cos(it * Math.PI)}
Well, If you are using grails, why aren't you simply using the a model class together with the findAll method?
Using plain raw SQL should be done on exceptional cases.