Unnamed: 0 int64 0 378k | id int64 49.9k 73.8M | title stringlengths 15 150 | question stringlengths 37 64.2k | answer stringlengths 37 44.1k | tags stringlengths 5 106 | score int64 -10 5.87k |
|---|---|---|---|---|---|---|
7,100 | 49,019,241 | Execute trained tensorflow model using linear algebra only | <p>I'm training the image classification model as per : <a href="https://www.tensorflow.org/tutorials/image_recognition" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/image_recognition</a></p>
<p>I aim to extract the learned weight values ( based on : <a href="https://stackoverflow.com/questions/45562... | <p>If you look closely at <code>run_inference_on_image</code> and the whole <code>classify_image.py</code> script, it doesn't define a model. It is just a runner script that loads a <strong>pre-trained model</strong> from disk (see <code>create_graph</code>) and executes it according to certain conventions (<code>run_i... | python|image-processing|tensorflow|neural-network|deep-learning | 2 |
7,101 | 48,971,879 | Python for sum operation by groupby, but exclude the non-numeric data | <p>How to do a sum operation using groupby from csv file in python, but exclude some non-numeric data from that groupby? E.g. I have the csv file:</p>
<pre><code>id | filename | #Line_Changed
-----------------------------------------------
1 | analyze/dir_list.txt | 16
2 | metrics... | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html" rel="nofollow noreferrer"><code>to_numeric</code></a> with parameter <code>errors='coerce'</code> for convert non numeric to <code>NaN</code>s, then <code>groupby</code> + <code>sum</code> omit this rows:</p>
<pr... | python|pandas|csv|dataframe|sum | 3 |
7,102 | 49,183,759 | pandas groupby and update the sum of the number of times the values in one column is greater than the other column | <p>I have a dataset in the following format</p>
<pre><code>df = pd.DataFrame([[1, 'Label1', 0, 8, 2], [1, 'Label3', 0, 20, 5], [2, 'Label5', 1, 20, 2], [2, 'Label4', 1, 11, 0],
[5, 'Label2', 0, 0, -4],[1, 'Label2', 1, 8, 2], [2, 'Label5', 0, 20, 5], [3, 'Label2', 1, 20, 2], [4, 'Label4', 0, 1, 0],
... | <p>A simple grouping operation on a masked comparison should do:</p>
<pre><code>v = df.Coeff.gt(df.result).where(df.Status.astype(bool)).groupby(df.ID).sum()
</code></pre>
<p>Or (to retain <code>dtype=int</code>, thanks piR!),</p>
<pre><code>v = df.Coeff.gt(df.result).where(df.Status.astype(bool), 0).groupby(df.ID).... | python|pandas|pandas-groupby | 1 |
7,103 | 49,250,225 | Python: List Nested Dictionary to pandas DataFrame Issue | <p>I am struggling with some simple from_dict conversion. I have a list nested dictionaries in dictionary as below. (quite confusing to me as well)</p>
<pre><code>dict_total = {'Jane' : {'a1' : [1.1,1.3,1.4,1.9],
'a2' : [3.1,2.4,2.3,1.2],
'a3' : [4.3,2.3,1.5,5.3],
... | <p>I think need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> with dict comprehension, last remove first level by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow norefer... | python|pandas|dictionary|dataframe|nested | 3 |
7,104 | 58,847,542 | Why does diff on these Pandas groupby results in Nan? | <p>The example dataframe I have is-</p>
<pre><code>>>> new_df
date country score
0 2018-01-01 ch 50
1 2018-01-01 es 100
2 2018-01-01 us 150
3 2018-01-02 ch 10
4 2018-01-02 gb 100
5 2018-01-02 us 125
6 2018-01-03 us 160
</code></pre>
<p>Why do... | <p>As you can see the size of each group is <strong>1</strong>,
then the subnetting of the subtraction is <code>NaN</code> because to make the subtraction a minuend and a subtraend are needed, that is to say <strong>size at least equal to 2</strong>:</p>
<pre><code>df.groupby(['date','country']).size()
date co... | python|pandas|pandas-groupby | 2 |
7,105 | 58,864,253 | Pandas vectorization for a multiple data frame operation | <p>I am looking to increase the speed of an operation within pandas and I have learned that it is generally best to do so via using vectorization. The problem I am looking for help with is vectorizing the following operation.</p>
<p>Setup:</p>
<p><code>df1 =</code> a table with a date-time column, and city column</p>... | <p>I think what you need is <code>merge()</code> with <code>numpy.where()</code> to achieve the same result. </p>
<p>Since you don't have a reproducible sample in your question, kindly consider this:</p>
<pre><code>>>> df1 = pd.DataFrame({'time':[24,20,15,10,5], 'city':['A','B','C','D','E']})
>>> df... | python|pandas | 0 |
7,106 | 70,193,405 | How to refer to Excel index using Python Pandas ILOC? | <pre><code>import pandas as pd
import re
file_name = "example.xlsx" #name of the excel file
sheet = "sheet" #name of the sheet
df = pd.read_excel(file_name, sheet_name = sheet, usecols = "A:F")
select_rows = df.iloc[516-2:] #specify rows
</code></pre>
<p>My question is why if I want ... | <p>@Samuel You are already 'minus one' because of zero-based index in Pandas. However, what isn't clear until reading the Pandas documentation for pd.read_excel is that there is a parameter called 'header' that is set to 0 by default (i.e. the first row (row 1 in Excel) is used as your header for column names). To demo... | python|pandas | 1 |
7,107 | 70,122,842 | BERT Pre-Training MLM + NSP | <p>I want to pre-train BERT for the tasks MLM + NSP. When I run the code below, threw me an error:</p>
<p>RuntimeError: The size of tensor a (882) must match the size of tensor b (512) at non-singleton dimension 1
1%|▊ ... | <p>The error <code>The size of tensor a (882) must match the size of tensor b (512) at non-singleton dimension</code> most probably means that the maximal text size that the model supports is 512 tokens, but you try to pass a text with 882 tokens to it. To bypass this, you can enable truncation somewhere in your pipeli... | nlp|huggingface-transformers|bert-language-model | 1 |
7,108 | 70,173,655 | Dataframe faster cosine similarity | <p>I have a dataframe consisting of individual tweets (id, text, author_id, nn_list) where nn_list is a list of other tweet indices which were previously identified as potential nearest neighbours. Now I have to calculate the cosine similarity of the index and every single entry of this list by looking at the index in ... | <p>The following code should work assuming you have not a too large range of IDs:</p>
<pre><code>import pandas as pd
import numpy as np
from scipy.sparse import csr_matrix
from sklearn.metrics.pairwise import cosine_similarity
df = pd.DataFrame({"nn_list": [[1, 2], [1,2,3], [1,2,3,7], [11, 12, 13], [2,1]]})
... | python|pandas|dataframe|performance|loops | 0 |
7,109 | 56,407,591 | Preprocess n files concurrently with tf.data API | <p>I want to use <code>tf.data.experimental.parallel_interleave</code> to preprocess n files concurrently. <code>cycle_length</code> argument is used for this purpose but what is the maximum value of this argument? My CPU has 8 cores and 16 threads.</p> | <p>As per official docs on <a href="https://www.tensorflow.org/api_docs/python/tf/data/experimental/parallel_interleave" rel="nofollow noreferrer">tf.data.experimental.parallel_interleave</a></p>
<blockquote>
<p>Unlike tf.data.Dataset.interleave, it gets elements from cycle_length
nested datasets in parallel</p>
</bloc... | tensorflow|tensorflow-datasets | 1 |
7,110 | 56,212,672 | Create a new column by concating two string columns together | <p>Looking to combine two string columns into a new column in a dataframe.</p>
<p>For instance - </p>
<pre><code>>>> df = pd.DataFrame({'Primary Type':['a','b','c'],'Description':['1','2','3']})
>>> df
Primary Type Description
0 a 1
1 b 2
2 c ... | <pre><code>df['combined'] = df['Primary Type'].map(str) + ' ,' +
df['Description'].map(str)
df
Primary Type Description combined
a 1 a ,1
b 2 b ,2
c 3 c ,3
</code></pre> | python|python-3.x|pandas | 1 |
7,111 | 56,081,166 | Calculating difference in minutes based on 30 minute interval? | <p>I had a df such as </p>
<pre><code>ID | Half Hour Bucket | clock in time | clock out time | Rate
232 | 4/1/19 8:00 PM | 4/1/19 7:12 PM | 4/1/19 10:45 PM | 0.54
342 | 4/1/19 8:30 PM | 4/1/19 7:12 PM | 4/1/19 7:22 PM | 0.23
232 | 4/1/19 7:00 PM | 4/1/19 7:12 PM | 4/1/19 10:45 PM | 0.54
</code></pre>
<p>I w... | <p>Realised my first answer probably wasn't what you wanted. This version, hopefully, is. It was a bit more involved than I first assumed!</p>
<p><strong>Create Data</strong></p>
<p>First of all create a dataframe to work with, based on that supplied in the question. The resultant formatting isn't quite the same b... | python|python-3.x|pandas|data-science|python-datetime | 1 |
7,112 | 55,869,511 | groupby and join result has indices and data type included in output | <p>The objective is to take a data frame that looks like this:</p>
<pre><code>keywords group
word1 x
word2 x
word3 x
</code></pre>
<p>with group and keywords as strings within a pandas dataframe.</p>
<p>and create a dataframe that looks like this:</p>
<pre><code>x |word1|word2|word3
</cod... | <p>Use:</p>
<pre><code>df.groupby('group')['keywords'].apply(lambda x: '|'+'|'.join(x))
</code></pre>
<hr>
<pre><code>group
x |word1|word2|word3
</code></pre> | python|pandas | 2 |
7,113 | 56,007,553 | How to use loop to get values out of Pandas dataframe? | <p>I would like to loop through each value in <code>startDayValStr</code>, <code>endDayValStr</code>, <code>startTimeValStr</code>, <code>endTimeValStr</code> and use the values as parameters in a URL string. I am using every other value as my <code>end</code> variables, i.e. <code>06:00:00</code> is a <code>startTime... | <p>If using <code>Python 3.x</code>, try <a href="https://docs.python.org/3.4/library/string.html#string-formatting" rel="nofollow noreferrer"><code>string.format</code></a> method, with <a href="https://docs.python.org/2/library/datetime.html#datetime.date.strftime" rel="nofollow noreferrer"><code>date.strftime</code>... | python|pandas|datetime | 1 |
7,114 | 64,845,318 | How do I send a test request with an image to my deployed model on Google Cloud? | <p>I've uploaded my trained model to the Google Cloud Platform that I trained and exported on lobe.ai. Now I want to send a test request with an image to it so I can use it on my web application. How do I do this?</p> | <p>With your tensorflow (<em>I deduce this from your tags</em>) model, you have 2 solutions</p>
<ul>
<li>Either your <a href="https://cloud.google.com/ai-platform/prediction/docs/deploying-models#test_your_model_with_local_predictions" rel="nofollow noreferrer">test locally</a></li>
<li>Or you can <a href="https://clou... | tensorflow|google-cloud-platform | 1 |
7,115 | 40,141,856 | How can I manipulate strings in a slice of a pandas MultiIndex | <p>I have a <code>MultiIndex</code> like this:</p>
<pre><code> metric
sensor variable side
foo Speed Left Left speed
Right Right speed
bar Speed Left Left_Speed
Right Right_Speed
baz Speed Left ... | <p>I found the following method, but i think/hope there must be a more elegant way to achieve that:</p>
<pre><code>In [101]: index_saved = df.index
</code></pre>
<p>Let's sort index in order to get rid of <code>KeyError: 'MultiIndex Slicing requires the index to be fully lexsorted tuple len (3), lexsort depth (0)'</c... | python|pandas | 1 |
7,116 | 40,104,946 | How to get date after subtracting days in pandas | <p>I have a dataframe:</p>
<pre><code>In [15]: df
Out[15]:
date day
0 2015-10-10 23
1 2015-12-19 9
2 2016-03-05 34
3 2016-09-17 23
4 2016-04-30 2
</code></pre>
<p>I want to subtract the number of days from the date and create a new column.</p>
<pre><code>In [16]: df.dtypes
Out[16]:
date dat... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_timedelta.html" rel="noreferrer"><code>to_timedelta</code></a>:</p>
<pre><code>df['date1'] = df['date'] - pd.to_timedelta(df['day'], unit='d')
print (df)
date day date1
0 2015-10-10 23 2015-09-17
1 2015-12-19 9 ... | python|pandas | 45 |
7,117 | 44,145,297 | tensorflow: [NOT FOUND] error in RStudio | <p>I tried running the following code in <code>RStudio</code>:</p>
<pre><code>library(tensorflow)
x_data <- runif(100, min=0, max=1)
y_data <- x_data * 0.1 + 0.3
W <- tf$Variable(tf$random_uniform(shape(1L), -1.0, 1.0))
</code></pre>
<p>But the last line is throwing the following error:</p>
<pre><code>Err... | <p>I realize that I installed the <code>python 3</code> version of <code>tensorflow</code> instead of the <code>python 2</code> version, which is what my error message was telling me that <code>RStudio</code> is using. Using the install instructions found <a href="https://www.tensorflow.org/versions/r0.10/get_started/o... | python|r|tensorflow|rstudio | 2 |
7,118 | 69,596,473 | Get all values to a numeric value | <p>As you can see my df contains a price list with values like <code>$106.00</code> and <code>'1,190.00</code>. I want to get the values to a numeric value. So I want to replace the $ sign. But that didn't work.</p>
<pre><code>df = pd.DataFrame({'id':['A', 'B', 'C', 'D', 'E'], 'price':['$106.00', '$156.00',
'$166.00', ... | <p>You can use <code>regex</code> and replace <code>'\$'</code> and <code>','</code> with <code>''</code> then convert to numeric like below: <em>(we use <code>'|'</code> for search <code>$</code> or <code>,</code>)</em></p>
<pre><code>>>> df.price = pd.to_numeric(df.price.str.replace(r"\$|,","&... | python|pandas | 0 |
7,119 | 69,520,266 | How do you match strings with different values in pandas? | <p>I'm trying to compare the values in 2 dataframes. This is my code :</p>
<pre><code>for i in df1['Searches']:
for j in df['Tags']:
if i == j:
print(i,j)
</code></pre>
<p>The code works. However, I want to account for cases where the strings don't entirely match, due to spacing, misspelling,... | <p>You are getting into fuzzy string matching. One way to do that is to use a similarity metric such as <code>jaro_similarity</code> from the Natural Language Toolkit (NLTK):</p>
<pre class="lang-py prettyprint-override"><code>from nltk.metrics.distance import jaro_similarity
df['jaro_similarity'] = df.apply(lambda row... | python|pandas|string|dataframe|matching | 3 |
7,120 | 41,178,761 | Tensorflow: DropoutWrapper leads to different output? | <p>I build a LSTM like:</p>
<pre><code>lstm_cell = tf.nn.rnn_cell.LSTMCell(n_hidden, forget_bias=1.0, state_is_tuple=True, activation=tf.nn.tanh)
lstm_cell = tf.nn.rnn_cell.DropoutWrapper(lstm_cell, output_keep_prob=0.5)
lstm_cell = tf.nn.rnn_cell.MultiRNNCell([lstm_cell] * 3, state_is_tuple=True)
</code></pre>
<p>Th... | <p>Try using the <code>seed</code> keyword argument to <code>DropoutWrapper(...)</code>:</p>
<pre><code>lstm_cell = tf.nn.rnn_cell.DropoutWrapper(lstm_cell, output_keep_prob=0.5, seed=42)
</code></pre>
<p>See the docs <a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/rnn_cell/rnn_cell_wrappers__rnnce... | python|tensorflow|lstm | 1 |
7,121 | 54,088,999 | Groupby and flatten lists | <p>I have a pandas dataframe with the following form:</p>
<pre><code>import pandas as pd
p = pd.DataFrame({"int" : [1, 1, 1, 1, 2, 2],
"cod" : [[1,1], [2,2], [1,2], [3,9], [2,2], [2,2]]})
</code></pre>
<p>I want to group by <code>int</code>, which gives me a bunch of lists. I th... | <p>Use <code>sum</code>:</p>
<pre><code>df = p.groupby("int", as_index=False)["cod"].sum()
</code></pre>
<p>Or <code>list comprehension</code>:</p>
<pre><code>df = p.groupby("int")["cod"].apply(lambda x: [z for y in x for z in y]).reset_index()
</code></pre>
<hr>
<pre><code>df = p.groupby("int")["cod"].apply(lambd... | python|pandas | 4 |
7,122 | 53,826,377 | Numpy apply where operation to specific index range of an image | <p>I have an 2000X3000 binary rgb image, i want to get the number of pixels that match certain color (say blue(0,0,255)) on a given coordinate points ((x,y)(xmax,ymax)).</p>
<p>I know how to calculate for the whole image using np masks, but not sure how to do this on only a certain range of an array</p> | <p>You can loop through your array and check:</p>
<pre><code>if (part_of_array == blue).all():
number_of_blue_pixels += 1
</code></pre>
<p><code>All ()</code> returns true when all values are equal.</p> | python|numpy|opencv | 0 |
7,123 | 66,210,323 | pd DataFrame, need to add columns, parsing text string date_time into pandas year, dayOfWeek, etc in one pass | <p><strong>Need Statement</strong>: I have performed a cursor.fetchall Select from a SQLite database, returning 'id' and 'date_time', the later of which is text. I want to create additional columns using pd.to_date of year, dayOfWeek, dayOfYear, hourOfDay</p>
<p><strong>Issue:</strong> Following the example of a <a hre... | <p>You could try with the <code>pd.to_datetime</code> function in a single column, for example:</p>
<p><code>splitDatepd["pd_datetime"] = pd.to_datetime(splitDatepd["date_time"])</code></p>
<p>PS: Remember that functions names use underscode, I mean, it is <code>pd.to_datetime</code> not <code>pd.to... | pandas|dataframe|sqlite|datetime|to-date | 1 |
7,124 | 65,957,307 | Compare values of multiple pandas columns | <p>let's say I have four columns with strings in each column (pandas df).
If I want to compare if they are all the same, I came up with something like this:</p>
<pre><code>df['same_FB'] = np.where( (df['FB_a'] == df['FB_b']) & (df['FB_a'] == df['FB_c']) & (df['FB_a'] == df['FB_d']), 1,0)
</code></pre>
<p>It wor... | <p>You can use <strong><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.eq.html" rel="nofollow noreferrer"><code>DataFrame.eq</code></a></strong> + <strong><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.all.html" rel="nofollow noreferrer"><code>D... | python|pandas|dataframe | 2 |
7,125 | 58,496,938 | Automated legend creation in a matplotlib scatter plot with legend_elements() | <p>I have tried to change the code that is given at the following link, but have come up short. I am just a simple minded brut trying to learn to code in an elegant manner. Please help.</p>
<p><a href="https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/scatter_with_legend.html#sphx-glr-gallery-lines-bars-an... | <p>I think you just have some mistakes in your initial import lines.</p>
<p>Try this as your first three lines, followed by <code>y</code> and <code>x</code> definition etc.:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
N = 365
</code></pre>
<p>The functions mentioned at the bottom of the matplo... | python|pandas|matplotlib | 0 |
7,126 | 69,229,335 | Pandas restrucutring to longform | <p>I have a dataframe in this format:</p>
<pre><code>{'April': {0: 3266.0, 3: 3044.0, 6: 3607.0},
'May': {0: 3767.0, 3: 3708.0, 6: 3709.0},
'June': {0: 4114.0, 3: 3539.0, 6: 4416.0},
'July': {0: 4544.0, 3: 5176.0, 6: 5298.0},
'August': {0: 4912.0, 3: 5424.0, 6: 5217.0},
'September': {0: 5358.0, 3: 5027.0, 6: 5262... | <p>You need <code>melt</code>:</p>
<pre><code>df.melt('year', var_name='month')
year month value
0 2015 April 3266.0
1 2016 April 3044.0
2 2017 April 3607.0
3 2015 May 3767.0
4 2016 May 3708.0
5 2017 May 3709.0
6 2015 June 4114.0
...
</code></pr... | python-3.x|pandas|dataframe | 1 |
7,127 | 44,723,608 | Displaying data frame rows in sentence structure | <p>I have a simple pandas data frame with 3 columns: Num, Question, Answer:</p>
<pre><code>Num Question Answer
1 What is your favorite color? Green
2 Favorite sport? Basketball
</code></pre>
<p>Basically I just want to present each row of this dataframe in a sentence structure like the following:</p>
<pr... | <p>You can use <code>iterrows</code>.</p>
<pre><code>df = pd.DataFrame({"Question": ['What is your favorite color?', 'Favorite sport?'],
"Answer": ['Green', 'Basketball'],
"Num": [1, 2]})
for _, row in df.iterrows():
print("Question #{0}: {1} Answer: {2}".format(
row[... | python|pandas | 1 |
7,128 | 60,927,618 | Set row maximum to 1 and other values to 0 | <p>I have a matrix</p>
<pre><code>x = array([[ 1, 2, 4, 6],
[ 8, 29, 11, 35],
[18, 16, 28, 25],
[26, 28, 53, 52]])
</code></pre>
<p>I want to get the maximum and minimum along row and column and make it 1 and rest 0. I do in the followoing way to get max and min along column:</p>
<pre><code>g... | <p>The axes to be compared are not aligned in the second case, you need to ensure the dimensions of both arrays are the same. So for that you have <code>keepdims</code>, which is precisely aimed at preserving the input shape. Also there's no need for <code>np.where</code>, you can just cast to <code>int</code>:</p>
<p... | python|numpy | 2 |
7,129 | 61,021,004 | Add columns from an old dataset to a new one | <p>I have the following dataset: </p>
<pre><code>df=pd.read_csv('/path/text.csv')
</code></pre>
<p>that has columns <code>A B C D</code> (shown by using <code>print(df.columns)</code>)</p>
<p>What I have tried to do is to create new columns using columns from that file as follows: </p>
<pre><code>for index, row in ... | <p>I think the function merge would be helpful for you.</p>
<p>If you have two dataframes you can "join" them vertically or horizontally. Merge can help you to join horizontally. The function should be used this way:</p>
<pre><code>df1.merge(df2, left_on='lkey', right_on='rkey')
</code></pre>
<p>What you should cons... | python|pandas|csv|dataframe | 0 |
7,130 | 61,069,643 | tensorflow object detection from image not from live Camera | <p>Hi i want to try myself on object detection on Android in images not in live camera previews and i've seen that there is tensorflow lite. Sadly the tutorials i could find are all for live camera previews and not for images. So does anyone know about a tutorial or something for tensorflow lite or some other way to de... | <p>I think generally it's two steps:</p>
<ol>
<li>Get image (no matter from preview or photos or anything), convert it to <code>android.graphics.Bitmap</code></li>
<li>Do Object detection from <code>Bitmap</code></li>
</ol>
<p>The part (1) is more like an Android question. For (2), you could checkout <a href="https:/... | android|image|tensorflow-lite | 0 |
7,131 | 71,525,890 | How to replace character into multiIndex pandas | <p>I have a dataset with severals columns containing numbers and I need to remove the ',' thousand separator.</p>
<p>Here is an example: <code>123,456.15</code> -> <code>123456.15</code>.</p>
<p>I tried to get it done with multi-indexes the following way:</p>
<pre><code>toProcess = ['col1','col2','col3']
df[toProces... | <p>Use:</p>
<pre><code>df[toProcess] = df[toProcess].replace(',','', regex=True)
</code></pre> | pandas|dataframe|multi-index | 1 |
7,132 | 71,484,472 | Tensorflow Probability VI: Discrete + Continuous RVs inference: gradient estimation? | <p>See <a href="https://github.com/tensorflow/probability/issues/1534" rel="nofollow noreferrer">this tensorflow-probability issue</a></p>
<pre class="lang-sh prettyprint-override"><code>tensorflow==2.7.0
tensorflow-probability==0.14.1
</code></pre>
<h2>TLDR</h2>
<p>To perform VI on discrete RVs, should I use:</p>
<ul>... | <p>So the ides was not to make a Q&A but I looked into this issue for a couple days and here are my conclusions:</p>
<ul>
<li>solution A -REINFORCE- is a possibility, it doesn't introduce any bias, but as far as I understood it it has high variance in its vanilla form -making it prohibitively slow for most real-wor... | tensorflow|tensorflow2.0|tensorflow-probability | 0 |
7,133 | 71,743,482 | Python numpy: iterate random.rand() without using loop | <p>I'm trying to have randomize number between 0-1 until the sum of those are >=1. This process iterate for nTime. Code below:</p>
<pre><code>from random import random
def funct(n): #10_000
media = 0
for _ in range(n):
result = 0
count = 0
while result < 1:
x = random(... | <p>I don't think you'll find any significant improvements by trying to avoid a loop here. If you for some reason need a significantly faster version of this simple system, would probably recommend simply using a faster language than Python.</p> | python|arrays|python-3.x|numpy|optimization | 0 |
7,134 | 71,521,735 | Not able to switch off batch norm layers for faster-rcnn (PyTorch) | <p>I'm trying to switch off batch norm layers in a faster-rcnn model for evaluation mode.</p>
<p>I'm doing a sanity check atm:</p>
<pre><code>@torch.no_grad()
def evaluate_loss(model, data_loader, device):
val_loss = 0
model.train()
for images, targets in data_loader:
# check that all layers are in ... | <p>So, after further investigation and after printing out all modules provided by the faster-rcnn, instead of <code>BatchNorm2d</code>, <code>FrozenBatchNorm2d</code> is used by the pretained model.</p>
<p>Furthermore, unlike what's currently stated by the documentation, you must call <code>torchvision.ops.misc.FrozenB... | python|deep-learning|pytorch|batch-normalization|faster-rcnn | 0 |
7,135 | 42,521,114 | Python: element-wise comparison of array to non-array | <p>I'm trying to plot some complex functions using numpy. Example of some working code:</p>
<pre><code>import numpy as np
from PIL import Image
size = 1000
w = np.linspace(-10, 10, size)
x, y = np.meshgrid(w, w)
r = x + 1j*y
def f(q):
return np.angle(q)
z = f(r)
normalized = ((255/(np.amax(z) - np.amin(z)))*(... | <p>The key is to return an array value instead of trying to coerce an array into a single bool, which is what <code>if (some_array):</code> keeps trying to do. There being no unambiguous way to decide what single boolean <code>np.array([True, False])</code> should convert to, it doesn't even try.</p>
<p>So don't even... | python|arrays|numpy|elementwise-operations | 0 |
7,136 | 42,403,765 | Multiply filtered rows by constant in pandas | <p>I checked <a href="https://stackoverflow.com/questions/33768122/python-pandas-dataframe-how-to-multiply-entire-column-with-a-scalar">this answer</a> but it only applies to entire columns.</p>
<p>I have a dataframe with 3 columns (name, date, value)</p>
<pre><code> Name Dt Value
0 aaaa 2018-01-01 ... | <p>Use <code>loc</code> and <code>map</code></p>
<pre><code>d = {2018: 100, 2019: 1000, 2020: 10000}
df.loc[
(df.Name == 'aaaa') & (df.Dt.dt.year == 2018), 'Value'
] *= df.Dt.dt.year.map(d)
print(df)
Name Dt Value
0 aaaa 2018-01-01 10000.0
1 bbbb 2018-07-02 200.0
2 aaaa 2019-01-01 30... | python|pandas | 3 |
7,137 | 42,252,878 | Count number of occurrences of an array without overlap in another array | <p>I have a <code>mxn</code> matrix <code>A</code>, where <code>m%t = n%t = 0</code>, so that a smaller <code>txt</code> matrix <code>B</code> tiles the matrix without borders or overlaps. I want to check if <code>A</code> consists entirely of tiles from <code>B</code> without calculating a tiling as an intermediate st... | <p><strong>Appproach #1 :</strong> It seems we are counting the number of occurrences of B in A as distinct blocks. So, we can use <a href="http://scikit-image.org/docs/dev/api/skimage.util.html#skimage.util.view_as_blocks" rel="nofollow noreferrer"><code>skimage.util.view_as_blocks</code></a> -</p>
<pre><code>from sk... | python|performance|numpy | 3 |
7,138 | 69,838,931 | How to plot heatmap from standard deviation of binned data? | <p>I am trying to make a heatmap of standard deviations (stdv) from gridded data, i.e. data which I have divided up into cells like a grid and I want to obtain stdv from each of those cells and plot its value as in each cell, colour-coded as a heatmap. Below is the code i used to divide the x -y plane into 4 equal bins... | <p>Do you mean:</p>
<pre><code>k=2
cells = [[[] for yi in range(k)] for xi in range(k)]
stds = [[[] for yi in range(k)] for xi in range(k)]
for ycell in range(k):
for xcell in range(k):
cells[ycell][xcell] = v[(yi == xcell) & (xi == ycell)]
# replace invalid (np.nan) with 0
stds[ycell]... | python|numpy|statistics|heatmap|binning | 1 |
7,139 | 69,853,940 | ValueError : Cannot setitem on a Categorical with a new category, set the categories first | <p>I have a column with the values changing from 0 to 600 and I want to group that values from 0 to 9.2 by 0.4 increments and 1 group between 9.2 and 600 values as outlier.I tried the following code ;</p>
<pre><code>bin_labels = ['0-0.4', '0.4-0.8', '0.8-1.2', '1.2-1.6',
'1.6-2.0', '2.0-2.4','2.4-2.8', '2.8-... | <p>You can append <code>float("inf")</code> to the <code>bins</code> and include "9.2-more" in the <code>bin_labels</code>:</p>
<pre><code>bin_labels = [ '0-0.4', '0.4-0.8', '0.8-1.2', '1.2-1.6',
'1.6-2.0', '2.0-2.4', '2.4-2.8', '2.8-3.2',
'3.2-3.6', '3.6-4.0', '4.0-4.4'... | python|pandas|numpy|fillna|linspace | 1 |
7,140 | 43,417,090 | Apply multiple functions at one time to Pandas groupby object | <p>Variations of this question have been asked (see <a href="https://stackoverflow.com/questions/40532024/pandas-apply-multiple-functions-of-multiple-columns-to-groupby-object">this question</a>) but I haven't found a good solution for would seem to be a common use-case of <code>groupby</code> in Pandas. </p>
<p>Say I... | <p>Consider the following approach:</p>
<pre><code>funcs = {
'running_time': {'rt_med':'median', 'rt_min':'min'},
'num_cores': {'nc_avg':'mean'},
'elapsed_time': {'et_max':'max'}
}
x = lasts.groupby('user').agg(funcs)
x.columns = x.columns.droplevel(0)
formulas = """
custom_column_1 = rt_med - nc_avg
custom_co... | python|pandas|dataframe|group-by | 5 |
7,141 | 72,325,139 | The markers in my plot are far away from where they should be in the image | <p>I have the following code, which plots a normal plt.plot with markers in each value, however the markers text is far away from the marker point as seen in the image. Is there something I can do? Does it depends in the figure size? because I also tried with different figure sizes.</p>
<p><a href="https://i.stack.imgu... | <p>You're counting your X values from 1 and your Y values from 0. You can see that in the plot -- the values are right, but they're shifted one x column to the right.</p>
<pre><code>def add_value_label(x_list,y_list):
for i,xv in enumerate(x_list):
plt.text(xv,y_list[i],y_list[i])
</code></pre> | python|pandas|matplotlib|plot | 1 |
7,142 | 72,232,480 | Pandas rolling window cumsum, with incomplete series | <p>I have a pandas df as follows:</p>
<pre><code>YEAR MONTH USERID TRX_COUNT
2020 1 1 1
2020 2 1 2
2020 3 1 1
2020 12 1 1
2021 1 1 3
2021 2 1 3
2021 3 1 4
</code></pre>
<p>I want to <code>sum</co... | <p>Looking at the logic and expected output, you are looking for more of rolling sum than cumsum. You want to roll 12 months and sum the number of <code>TRX_COUNT</code>. <code>cumsum</code> would cumulatively adding up the previous calculations.</p>
<p>Anyway, a few things that is complicated in your dataset. 1. inter... | pandas | 1 |
7,143 | 72,258,450 | Deep Convolutional Autoencoder for movie similarity | <p>i am new to python and i have a dataset that contains movie descriptions and i am trying to create a model that can calculate movie similarity based on these descriptions.
so i started by turning each movie description into a Word2Vec vector where each word has a size 100,since the longest movie description in my da... | <p>I was able to reproduce the error with dummy data. Changing the decoder model as follows will help.</p>
<pre><code>decoder_input=tf.keras.layers.Conv1D(8, 3, activation='relu', padding='same')(x)
x = tf.keras.layers.UpSampling1D(2)(decoder_input)
x = tf.keras.layers.Conv1D(16, 3, activation='relu')(x)
x = tf.keras.... | tensorflow|keras|deep-learning|word2vec|autoencoder | 0 |
7,144 | 72,403,450 | Change values of a timedelta column based on the previous row | <p>Let it be the following Python Panda Dataframe:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>code</th>
<th>visit_time</th>
<th>flag</th>
<th>other</th>
<th>counter</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>NaT</td>
<td>True</td>
<td>X</td>
<td>3</td>
</tr>
<tr>
<td>0</td>
<td>1 ... | <p>You can use <code>.mask</code> to set the <code>'flag'</code> values to the <code>.shift</code>ed version of itself where <code>'visit_time'</code> values are <code>notnull</code>.</p>
<pre class="lang-py prettyprint-override"><code>out = df.assign(
flag=df['flag'].mask(df['visit_time'].notnull(), df['flag'].shi... | python|pandas|dataframe|timedelta | 2 |
7,145 | 45,388,800 | Python: data argument can't be an iterator | <p>I'm trying to replicate the code that is provided here:
<a href="https://github.com/IdoZehori/Credit-Score/blob/master/Credit%20score.ipynb" rel="noreferrer">https://github.com/IdoZehori/Credit-Score/blob/master/Credit%20score.ipynb</a></p>
<p>The function given below fails to run and give error. Can someone help m... | <p>zip cannot be used directly, you should give the result as a list i.e.:</p>
<pre><code>x = pd.DataFrame(list(zip(data, vote)), columns=['annual_income', 'outlier'])
</code></pre>
<p><strong>Edit</strong> (from <a href="https://stackoverflow.com/a/57223112/6655211">bayethierno</a> answer) :<br>
Since the release 0... | python|pandas|numpy | 19 |
7,146 | 62,534,751 | How to properly setup a data set for training a Keras model | <p>I am trying to create a dataset for audio recognition with a simple Keras sequential model.</p>
<p>This is the function I am using to create the model:</p>
<pre><code>def dnn_model(input_shape, output_shape):
model = keras.Sequential()
model.add(keras.Input(input_shape))
model.add(layers.Flatten())
m... | <p>The fit function is going to exhaust your generator, that is to say, once it will have yielded all your 8623 batches, it wont be able to yield batches anymore.</p>
<p>You want to solve the issue like this:</p>
<pre class="lang-py prettyprint-override"><code>def generator(x_dirs, y_dirs, hmm, sampling_rate, parameter... | python|tensorflow|keras | 1 |
7,147 | 54,448,529 | Selectig entries in a pandas data frame with an array | <p>I have a pandas data frame built on an object with multiple attributes. Lets call this data1. data1 has an array x which associates every entry in the data frame with a set of values and arrays y and z which do the same. My code looks as follows. </p>
<pre><code>x = (3, 5, 2, 8, 9)
y = (4, 9, 0, 2, 1)
z = (0, 3, 6,... | <p>Something like this (remember index start at 0):</p>
<pre><code>import pandas as pd
x = (3, 5, 2, 8, 9)
y = (4, 9, 0, 2, 1)
z = (0, 3, 6, 0, 2)
df = pd.DataFrame()
df['x'] = x
df['y'] = y
df['z'] = z
print(df);print()
idx = [1, 4, 2]
cols = ['x', 'y', 'z']
print(df.loc[idx, cols])
x y z
1 5 9 3
4 9 1 ... | linux|python-3.x|pandas|dataframe | 0 |
7,148 | 54,338,133 | Aggregate rows based on two identifiers | <p>I have the following data set</p>
<pre><code>df = pd.DataFrame({'A' : ['E1', 'E1', 'E1', 'E2', 'E2'],
'B' : ['R1', 'R1', 'R2', 'R2', 'R2'],
'C' : [100, 100, 300, 250, 250]})
</code></pre>
<p>I now want to aggregate the rows using <code>A</code> and <code>B</code> as the shared... | <p>Using <code>groupby</code> with <code>agg</code></p>
<pre><code>df.groupby(['A','B']).C.agg(['sum','mean','count']).reset_index()
A B sum mean count
E1 R1 200 100 2
E2 R2 300 300 1
E2 R2 500 250 2
</code></pre> | python|pandas|dataframe|merge | 1 |
7,149 | 54,545,054 | Cleaner way to whiten each image in a batch using keras | <p>I would like to whiten each image in a batch. The code I have to do so is this:</p>
<pre><code>def whiten(self, x):
shape = x.shape
x = K.batch_flatten(x)
mn = K.mean(x, 0)
std = K.std(x, 0) + K.epsilon()
r = (x - mn) / std
r = K.reshape(x, (-1,shape[1],shape[2],shape[3]))
return r
#
</... | <p>Let's see what the <code>-1</code> does. From the Tensorflow documentation (Because the documentation from Keras is scarce compared to the one from Tensorflow):</p>
<blockquote>
<p>If one component of shape is the special value -1, the size of that dimension is computed so that the total size remains constant.</p... | tensorflow|keras | 1 |
7,150 | 54,432,459 | How to add rows to a dataframe based on the diff of two columns | <p>I am struggling with this one.</p>
<p>Let's assume a dataframe that looks like this:</p>
<pre><code>df = pd.DataFrame({'col0':['string1', 'string2'],
'col1':['some string','another string'],
'start':[100,1],
'end':[107,5]})
col0 col1 start... | <p>1st Create the list column using for loop with <code>range</code>, then the problem become <a href="https://stackoverflow.com/questions/53218931/how-do-i-unnest-explode-a-column-in-a-pandas-dataframe/53218939#53218939">unnesting</a> </p>
<pre><code>df['New']=[list(range(y,x+1)) for x , y in zip(df.pop('end'),df.pop... | python|python-3.x|pandas | 2 |
7,151 | 54,283,085 | Why am I getting strange triplication of video using Webcam and Tensorflow.js? | <p>I have a keras model trained and now I want to run this on the web. I thought this might be a good way to attempt testing out Tensorflow.js. I downloaded the Tesnroflow.js "Webcam-transfer-learning" tutorial and then modified it to get what I currently have. The working keras model performs emotion classification af... | <p><code>drawframe</code> is drawing the image three times.
It has to do with the shape of the input image and the way <code>height</code> and <code>width</code> are used to crop the image. If the input image were of shape [298, 160], the canvas will not be rendered as there will be an error when trying to access index... | python-3.x|tensorflow|keras|tensorflow.js | 1 |
7,152 | 54,685,300 | How to transfer the y (const y= await tf.toPixels(image)) to the webworker use webworker.postMessage? | <p>I want to use the webworker to deal with some tasks.</p>
<p>Main Thread:
Firstly,I use tf.loadFrozenModel() to load pre-train model.Secondly,I use model.predict() to predict a image(size:512*512*4).When I use <code>const data = await tf.toPixels(image)</code> to get the image pixels, it takes a lot of time, cau... | <p>Instead of sending the tensor object to the webworker, you can send a typed array. </p>
<p>From version 15 onward, the typed array has the same shape as the tensor using <code>tensor.array</code>. </p>
<pre><code>webworker.postMessage({headpackage:await y.array()})
// Webworker
tf.toPixels(tf.tensor(dataMessa... | web-worker|tensorflow.js | 1 |
7,153 | 54,647,711 | Barplot 2 categorical variables | <p>I got two categorial variables and I want to plot something like this:</p>
<p><a href="https://i.stack.imgur.com/saxK5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/saxK5.png" alt="Plot"></a></p> | <p>You've tagged your question with pandas so I'm going to assume that your data is stored in a pandas dataframe. </p>
<p>Here I'm going to make some data which may or may not resemble your data:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt... | python|pandas|matplotlib | 2 |
7,154 | 73,832,058 | pandas dataframe column manipulation | <p>I have a dataframe that look like this:</p>
<pre><code>Letter num
A 5
B 4
A 3
B 3
</code></pre>
<p>I want to add 3 if letter = A and 2 if letter = B
I tried this:</p>
<pre><code>for i in df:
if df['Letter'] == A:
df['num'] = df['num'] + 3
else:
df['num']... | <p>here is one way to do it</p>
<pre><code># dictionary of the letters and associated values to add
d = {'A' : 3, 'B':2}
# map the letter to get the value and add to the num
df['num']=df['num'] + df['Letter'].map(d)
df
</code></pre>
<pre><code> Letter num
0 A 8
1 B 6
2 A 6
3 B 5
</code></pre> | python|pandas | 3 |
7,155 | 73,707,529 | iterating through index list of list using list comprehension | <pre><code>next_df = df.shift(-1)
next_waypt = next_df.values.tolist()
waypt=df.values.tolist()
</code></pre>
<p>So I have these 2 lists of lists from a dataframe in pandas. I want to create a new list using values from those 2 lists in a function. I do not know how to iterate over the first index however</p>
<pre><cod... | <p>I think your problem is that when you use your list comprehension, you are iterating over the elements of the list and not the index of it</p>
<p>your code should look something like this:</p>
<pre class="lang-py prettyprint-override"><code>y = [math.sin(y[1] - next_waypt[val][1])*math.cos(next_waypt[val][0]) for va... | python|pandas|dataframe | 1 |
7,156 | 71,344,455 | Custom loss functions in Keras with penalty depending on the values of y_pred and y_true | <p>I need a custom loss functions in Keras for a regression problem.
I have to predict two values (y1, y2) but I want to penalize the error if:</p>
<pre><code>if y1_pred > v1 and y1_true < v1:
or
if y2_pred < v2 and y2_true > v2:
</code></pre>
<p>I need something similar to:</p>
<pre><code>if y1_pred >... | <p>Try <code>tf.where</code>:</p>
<pre><code>import tensorflow as tf
def custom_loss1(v1 = 0.7, v2 = 1, k =0.5):
def combined_loss(y1_true, y1_pred):
return tf.where(tf.logical_and(tf.greater(y1_pred, v1), tf.less(y1_true, v1)),
tf.reduce_mean(tf.math.square(y1_pred - y1_true) * (1 + (k * (y... | python|tensorflow|keras | 0 |
7,157 | 52,273,857 | Counting number of first time binary indicators in a time series | <p>I have a dataframe that uses binary indicators to reflect whether a customer is live during a particular month. If the customer is live, there is a 1, if not there is a 0. The dataframe looks like the below:</p>
<pre><code>Customer A B C D E F G H I J
11/30/2015 1 0 1 0 0 1 1 0 ... | <p>By defining a custom <code>new</code> function and using <code>DataFrame.expanding</code>. I'm not sure why the result of <code>expanding().apply(new)</code> requires casting from <code>float</code> to <code>int</code>, but hey, it works:</p>
<pre><code>def new(column):
return column[-1] and not any(column[:-1]... | python|pandas|time-series | 1 |
7,158 | 60,394,977 | Pandas: How to remove non-alphanumeric columns in Series | <p>A Pandas' Series can contain invalid values:</p>
<pre><code>a b c d e f g
1 "" "a3" np.nan "\n" "6" " "
</code></pre>
<pre><code>df = pd.DataFrame([{"a":1, "b":"", "c":"a3", "d":np.nan, "e":"\n", "f":"6", "g":" "}])
row = df.iloc[0]
</code></pre>
<p>I want to produce a clean ... | <p>Convert values to strings and chain another mask by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.notna.html" rel="nofollow noreferrer"><code>Series.notna</code></a> with bitwise <code>AND</code> - <code>&</code>:</p>
<pre><code>row = row[row.astype(str).str.isalnum() & ro... | python|pandas|dataframe|series | 2 |
7,159 | 60,406,738 | pandas merge dataframes move new column from the end | <p>I'm merging two data frames which works fine but the new column is placed on the end. I would like it to be the 3rd column or index 2. So far I have this which works but I'm wondering if there is a better way.</p>
<pre><code>overlap = overlap.merge(df_comp, how='left')
cols = overlap.columns.tolist()
cols.insert(2... | <p>One quick hack is to set the first 2 columns and the last added columns as index, then reset the index, which will place them as the first 3 columns:</p>
<pre><code>import numpy as np
overlap.set_index(overlap.columns[np.r_[0:2,-1]].to_list()).reset_index()
</code></pre>
<p><code>np.r_[0:2, -1]</code> essentially... | python|pandas|multiple-columns | 1 |
7,160 | 60,535,238 | Numpy boolean indexing if number is in list | <p>I have the following array:</p>
<pre><code>x = np.array([
[2, 0],
[5, 0],
[1, 0],
[8, 0],
[6, 0]])
</code></pre>
<p>I've learned that you can use boolean operations to change selected values in a numpy array. If I want to change the value of the 2nd column to 1 for the rows where the 1st value ... | <p>You can use numpy's <code>isin</code> method:</p>
<pre><code>x[np.isin(x[:, 0], [2, 5, 8]), 1] = 1
</code></pre> | python|arrays|numpy|boolean-operations | 0 |
7,161 | 72,576,712 | Remove the intersection between two curves | <p>I'm having a curve (parabol) from 0 to 1 on both axes as follows:</p>
<p><a href="https://i.stack.imgur.com/O3td2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/O3td2.png" alt="enter image description here" /></a></p>
<p>I generate another curve by moving the original curve along the x-axis and c... | <p>First off, I would have two different parabola functions such that:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-1, 1, 100)
y1 = np.add(x, 0.3)**2 # Parabola centered at -0.3
y2 = np.add(x, -0.3)**2 # Parabola centered at 0.3
</code></pre>
<p>You can choose your own offsets for... | python|numpy|matplotlib | 3 |
7,162 | 72,607,575 | How to create subplots of all column combinations from two dataframes | <p>I have a made a function which plots input variables against predicted variables.</p>
<pre><code>dummy_data = pd.DataFrame(np.random.uniform(low=65.5,high=140.5,size=(50,4)), columns=list('ABCD'))
dummy_predicted = pd.DataFrame(np.random.uniform(low=15.5,high=17.5,size=(50,4)), columns=list('WXYZ'))
##Plot test inp... | <ul>
<li>Use <a href="https://docs.python.org/3/library/itertools.html#itertools.product" rel="nofollow noreferrer"><code>itertools.product</code></a> from the standard library, to create all combinations of column names, <code>combos</code>.</li>
<li>Use the <a href="https://docs.python.org/3/library/functions.html#le... | python|pandas|matplotlib|data-visualization|subplot | 2 |
7,163 | 72,493,319 | How can I upload this DataFrame into an excel file? | <p>I am trying to upload this DataFrame to an excel file, but it keeps returning the error "could not broadcast input array from shape (50,56) into shape (50,)"
I am not sure how to change the shape though</p>
<p>Here is my code:</p>
<pre><code>from selenium import webdriver
from bs4 import BeautifulSoup
impo... | <p>What you did here:</p>
<pre><code>writer = pd.ExcelWriter('2021 Data.xlsx')
new_storage.to_excel(writer, '2021')
</code></pre>
<p>Is unclear, but doesn't work because it's like writing:</p>
<pre><code>new_storage.to_excel(pd.ExcelWriter('2021 Data.xlsx'), '2021')
</code></pre>
<p>which doesn't mean anything.</p>
<p>... | python|excel|pandas|dataframe|beautifulsoup | 0 |
7,164 | 59,870,386 | Understanding code from official tensorflow page | <p>I am confused about code on <a href="https://www.tensorflow.org/tutorials/structured_data/imbalanced_data" rel="nofollow noreferrer">this page</a>.</p>
<p>question1) </p>
<p>Code block below shows output from that page. Before this step I dont see any code that trains our data using <code>model.fit</code> function... | <p>Answer 1: Yes, these predictions are from model after compiling but before training it. </p>
<p>Answer 2: Yes, they are random weights, for example, in Dense layer they are initialised using <code>glorot_uniform</code> . <a href="https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/keras/layers/Dense#__init_... | python|tensorflow|keras|classification|tensorflow2.0 | 1 |
7,165 | 61,622,273 | How to move paired data from one data frame column to another dataframe while keeping the same order | <p>I have a csv file with a list of NBA players and their average fantasy draft positions. I'm trying to add this 'ADP' value to a data frame that has all of their stats for the season. However, the players are not in the same order in both files so I must iterate through them and compare the list of players, only addi... | <pre><code>data = data.join(adp, on=SOME_COLUMN)
</code></pre>
<p>You might need to do a bit more than this depending on your data frames; I don't know what your column names are. </p> | python-3.x|pandas | 0 |
7,166 | 61,899,392 | How to check if value from one column is equal to value in another columns data-frame | <p>I have two separate data frames df and xls. Xls is a data frame that contain unique IDs that I would like to see how many times occur in my df data frame (~650,000 rows) and then create an occurrence column that would keep track of the amount of times that our unique IDs from our xls dataframe are appearing in the d... | <p><code>df.groupby('Contingency').count()</code> should produce the Series you are looking for, without the need for the xls dataframe containing the unique IDs.</p>
<p>Edit:</p>
<p>If your 'df' dataframe only has the 'Contingency' column, you'll need a second column to apply the count() to, like this:</p>
<pre><co... | python|pandas|dataframe | 5 |
7,167 | 61,826,649 | Train Test Split sklearn based on group variable | <p>My X is as follows:
EDIT1:</p>
<pre><code>Unique ID. Exp start date. Value. Status.
001 01/01/2020. 4000. Closed
001 12/01/2019 4000. Archived
002 01/01/2020. 5000. Closed
002 12/01/2019 5000. Archived
</code></pre>
<p>I want to m... | <p>I believe you need <code>GroupShuffleSplit</code> (<a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GroupShuffleSplit.html" rel="nofollow noreferrer">documentation here</a>).</p>
<pre><code>import numpy as np
from sklearn.model_selection import GroupShuffleSplit
X = np.ones(shape=(... | python|scikit-learn|sklearn-pandas|train-test-split | 2 |
7,168 | 54,879,395 | Check if a value exists in pandas dataframe | <p>I have a pandas dataframe which consists of 3000 latitude longitude values. I want to check if a lat-long exists in the dataframe or not.</p>
<p>The data frame looks like the following:</p>
<pre><code>lat long
31.76 77.84
31.77 77.84
31.78 77.84
32.76 77.85
</code></pre>
<p>Now, I want to check i... | <p>Working with <code>float</code>s, so need <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.isclose.html" rel="nofollow noreferrer"><code>numpy.isclose</code></a> for check both columns, chain with <code>&</code> for bitwise <code>AND</code> and test with <a href="http://pandas.pydata.org/panda... | python|pandas|dataframe | 2 |
7,169 | 55,065,431 | Pandas row-wise aggregation with multi-index | <p>I have a pandas dataframe where there's three levels of row indexing. The last level is a datetime index. There are nan values and I am trying to fill them with the average of each row at the datetime level. How can I go about doing this?</p>
<pre><code>data_df
Level 0 | Level 1 | Level 2 |
A ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.mask.html" rel="nofollow noreferrer"><code>DataFrame.mask</code></a> with <code>mean</code> per rows and last convert only <code>NaN</code>s rows by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFr... | python|pandas | 0 |
7,170 | 54,777,895 | tensorflow scaler.inverse_transform ValueError: operands could not be broadcast together with shapes (342,22) (23,) (342,22) | <p>Looking for some help here... so stuck.. Below is my code and the error I'm getting. Thanks for all your help.</p>
<pre><code>def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):
"""
Frame a time series as a supervised learning dataset.
Arguments:
data: Sequence of observations as a li... | <p>Tough this would sound weird, it did help me fix the error.</p>
<p>If in case u are using "excel" to tamper "csv training data" file and if you are deleting a column from the excel,</p>
<p>you would end up with a blank ",," value in your csv data which would cause the issue for me. Guess it helps. </p>
<p>Removin... | python|tensorflow|keras | 0 |
7,171 | 49,471,437 | Custom loss function in tensorflow | <p>I have a seq2seq model where my inputs are short sentences like</p>
<pre><code>x = "The XYZ pub near Cafe ABC has a 5 star rating. Prices start at £30."
</code></pre>
<p>and my outputs are semantic info extracted from the input sentence like:</p>
<pre><code>y_true = name[XYZ], type[pub], price[moderate], rating[... | <p>Absolutely, and in fact it's quite simple to do. For a single sample you are computing a vector of 5 loss values, something like <code>losses = [1.2, 0.3, 1.5, 3.3, 0.6]</code>. Note that this result is before you perform any <code>tf.reduce_mean</code> functions on your loss.</p>
<p>Now build yourself a function i... | python|tensorflow|machine-learning | 0 |
7,172 | 49,400,500 | passing 1 or 2 d numpy array to c throw cython | <p>I am writing an extension to my python code in c and cython, by following <a href="https://github.com/cython/cython/wiki/tutorials-NumpyPointerToC" rel="nofollow noreferrer">this</a> guide.</p>
<p>my c function signature is </p>
<pre><code>void c_disloc(double *pEOutput, double *pNOutput, double *pZOutput, double... | <p>I'd accept an untyped argument, check that it's a C contiguous array and then use <code>np.ravel</code> to get a flat array (this returns a view, not a copy, when passed a C contiguous array). It's easy to create that as a cdef function:</p>
<pre><code>cdef double* get_array_pointer(arr) except NULL:
assert(arr... | numpy|cython|python-c-api | 3 |
7,173 | 49,712,419 | Reading data without headers in Python | <p>I would like to know how to read a .txt file with Python, so that I can plot the data.</p>
<p>The file is this form:</p>
<pre><code>1. " Experiment 1 1 1
2. Date: 04/04/18
3. data A B C
4. 1 12.5 0 3
5. 2 13 1 4.6
6. 3 14 10 5
7. . . . .
. . . . "
</code></pre>
<p>Thanks</p> | <p>Try to import with pandas</p>
<pre><code>import pandas as pd
df = pd.read_csv('yourfile.txt', sep=' ', skiprows=3, names=['col1', 'col2', 'col3'])
</code></pre>
<p>If you do not want to add column names on import </p>
<pre><code>df = pd.read_csv('yourfile.txt', sep=' ', skiprows=3, header=None)
</code></pre> | python|pandas|numpy|header | 0 |
7,174 | 73,415,328 | Why keyerror when header is in df - renamed header but same keyerror | <p>While working on a summery of data from train passages I would like to .sum() the monthly df from a sensor. Target is the df "Total weight (T)" column.</p>
<pre><code> Date Total weight (T) Axle passages ... Average speed (km/h)
0 2022-07-01 95652.12 6048 ... ... | <p>See <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer">https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.loc.html</a>.</p>
<p>You are using only one argument, thus selecting dataframe index. You want to select a column.</p>
<p>Here are possible work... | python|pandas|dataframe | 0 |
7,175 | 67,513,818 | how to read through multiple .tsv files located in different sub-directories | <p>I have multiple .tsv files located in a directory located in a sub-directory w/ different names (sub-directory different names)</p>
<p>I'm trying to read each of the .tsv files and perform this command:</p>
<pre><code>df_1 = pd.read_csv("C:/Car/0NN/car.tsv", delimiter='\t', encoding="utf-8-sig")
... | <p>You can use python's inbuilt <code>glob</code> module to recursively read all the files inside the directory. Assuming every file is named <code>car.tsv</code> and is inside any subdirectory of <code>C:/Car/</code></p>
<pre><code>all_car_tsv_files = glob.glob("C:/Car/**/car.tsv", recursive=True)
</code></p... | python|pandas|dataframe|glob | 0 |
7,176 | 67,249,427 | What do I do if ValueError: x and y must have same first dimension, but have shapes (32,) and (31, 5)? | <pre class="lang-py prettyprint-override"><code>csv_data = pd.read_csv("master.csv")
df = pd.DataFrame(csv_data,
columns=['year', 'suicides/100k pop', 'age', 'country', 'sex'])
us_rates = df['country'].values == 'United States'
df_us_rates = df.loc[us_rates]
teen_rates = df_us_rates['age... | <p>You are trying to plot:</p>
<ul>
<li><code>no_dups</code>, which is a 1D list of 32 values</li>
<li>against <code>df_boy_rates</code> which is a 2D dataframe with 31 rows and 5 columns</li>
</ul>
<p>Assuming that the column you're interested in is 'suicides/100k pop', modify your code like this:</p>
<pre><code>df_bo... | python-3.x|pandas|dataframe|csv | 0 |
7,177 | 60,083,111 | Multiclass Dataset Imbalance | <pre><code>from tensorflow.keras.preprocessing.image import ImageDataGenerator
import tensorflow as tf
train_path = 'Skin/Train'
test_path = 'Skin/Test'
train_gen = ImageDataGenerator(rescale=1./255)
train_generator = train_gen.flow_from_directory(train_path,target_size=
(300... | <p>You can, instead, use a <code>class_weight</code> argument in your fit method.
For upsampling, you need a lot of manual work, that's inevitable.</p>
<p>Assuming you have an output with shape <code>(anything, 9)</code>, and you know the totals of each class:</p>
<pre><code>totals = np.array([500,100,500,500,96,90,...... | keras|tensorflow2.0|tensorflow-datasets | 2 |
7,178 | 59,969,782 | Pandas and seaborn plot unexpected time frame on x axis | <p>I'm attempting to create a simple scatter plot using pandas and seaborn. This code : </p>
<pre><code>import pandas as pd
import seaborn as sns
lst = ['2019-01-31', '2019-02-25', '2019-03-31']
lst2 = [11, 22, 33]
df = pd.DataFrame(list(zip(lst, lst2)),
columns =['date', 'count'])
df['date'] = ... | <p>You can use <code>set_xlim</code> to manually specify the range of the x-axes, e.g.:</p>
<pre><code>f = sns.scatterplot(x='date', y='count', data=df)
f.set_xlim('2019-01-01', '2019-12-31')
</code></pre> | python|pandas | 1 |
7,179 | 60,170,082 | How to add new rows of values for a distinct column value in pandas | <p>I have data frame like </p>
<pre><code> ORDER STATUS DATE
23412 200 7-2-2020
23412 300 8-2-2020
23412 400 10-2-2020
91234 300 8-2-2020
91234 400 9-2-2020
671234 200 10-3-2020
</code></pre>
<p>I want add static row for each distinct <code>order</code> ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop_duplicates.html" rel="nofollow noreferrer"><code>DataFrame.drop_duplicates</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.assign.html" rel="nofollow noreferrer"><code>Data... | python-3.x|pandas|dataframe | 2 |
7,180 | 60,252,049 | Spacing timestamp in pandas plot using seaborn | <p>Please my code is shown below. I want to space the timestamp as the plot looks so squeezed. </p>
<pre><code> import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv('../Data/User/DataSample.csv')
dataset.head(10)
Grade Time
0 Pass 2020-02... | <p>Thanks for including a sample dataset.</p>
<p>Give this a shot:</p>
<pre><code>import matplotlib.dates as mdates
ax = sns.scatterplot(x='Time',y='Grade',hue='Grade',data=df)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M'))
ax.xaxis.set_major_locator(mdates.HourLocator())
plt.gcf().autofmt_xdat... | python|pandas|plot|seaborn | 0 |
7,181 | 65,254,938 | Simple GAN predicts NaN in Tensorflow after 2 steps | <p>I'm implementing a basic GAN based on the one in the <a href="https://www.tensorflow.org/tutorials/generative/dcgan" rel="nofollow noreferrer">Tensorflow documentation</a>.</p>
<p>After 2 training steps, the prediction from the generator is all NaN.</p>
<p>I don't know why it happens, but I noticed that the gradient... | <p>I used RTX3080 which only works with CUDA 11, and I was using CUDA 10.1. With 10.1 it works without warnings but produces garbage/nan values</p> | python|tensorflow|keras | 0 |
7,182 | 65,209,035 | Renaming column names from a data set in pandas | <p>I am trying to rename column names from a DataFrame that have space in the name. DataFrame (<strong>df</strong>) consists of 45 columns and the majority have spaces in the name. For instance: <code>df.column.values [1] = 'Date Release'</code>, and the name should be changed to <code>'Date_Release'</code>. I tried <c... | <pre><code>import pandas as pd
df.columns = [i.replace(' ','_') for i in df.columns]
</code></pre> | python|pandas|rename | 1 |
7,183 | 65,307,308 | ValueError: Unknown layer: Functional Keras load_model | <pre><code>model = tf.keras.models.load_model(model_path)
</code></pre>
<p>is giving me error as,</p>
<pre><code>ValueError('Unknown ' + printable_module_name + ': ' + class_name) ValueError: Unknown layer: Functional
</code></pre>
<p>I tried setting path <code>model_path = "{}{}".format(Path().absolute(),&qu... | <blockquote>
<p>ValueError: Unknown layer: Functional</p>
</blockquote>
<p>You are getting above error, because you trained the model using <code>Tensorflow 2.2.0</code> and then tried to accessing the saved model( i.e <code>model_new.h5</code>) using different version of Tensorflow.</p>
<p>To fix above problem you can... | tensorflow|keras | 0 |
7,184 | 49,929,378 | Unpack list of dicts into list in pandas dataframe | <p>I have a pandas dataframe that includes a column of lists of dictionaries.</p>
<pre><code> list_dicts
id
a1 [{name:'cat'}, {name:'dog'}]
a2 [{name:'toy'}, {name:'boy'}]
a3 [{name:'jack'},{name:'jill'},{name:'sam'}]
a4 [{name:'pig'}]
</code></pre>
<p>Every key in the list of dicts is 'name'. I want to c... | <p>You could do this with list comprehension and without a lambda function in just one line:</p>
<pre><code>df['list_from_dict'] = [[x['name'] for x in list_dict] for list_dict in df['list_dicts']]
</code></pre> | python|list|pandas|dictionary|dataframe | 3 |
7,185 | 49,993,361 | Creating a new 2 column numpy array from filtering through the first coumn/array | <p>I am trying to create a new 2 dimensional or 2 column array, which will consist of (data value <=20000) from the first column, and their associated ID values in the second column. Mathematically I am doing the following:
I am reading data from a text file. I am finding distance to all the points from the last poi... | <p>Between the question you asked, and the code you have provided, I am still somewhat unclear on what you what to accomplish. But I can at least show you where there are errors in the code, and perhaps give you the tools you need.</p>
<p>As your code is now, x, y, z are all vectors. So the result of the neighbors dis... | python|arrays|numpy | 1 |
7,186 | 50,062,936 | Select columns periodically on pandas DataFrame | <p>I'm working on a Dataframe with <code>1116 columns</code>, how could I select just the columns in <strong>a period of 17</strong> ?
More clearly select the 12th, 29th,46th,63rd... columns </p> | <p>You can use <code>range</code> syntax:</p>
<pre><code>cols = range(12, 1116, 17)
</code></pre>
<p>Then use this to feed <code>pd.DataFrame.iloc</code>:</p>
<pre><code>df = df.iloc[:, cols]
</code></pre>
<p>Just remember that Python indexing begins at 0, so the first column with index 12 will be the 13th. This ca... | python|pandas|dataframe | 1 |
7,187 | 50,205,096 | Mean of grouped data | <p>I have data in a dataframe regarding salaries of employees. Each employee also has data stored about their sex, discipline, years since earning phd, and years working at the current employer. An example of the data is as follows.</p>
<pre><code> rank dsc phd srv sex salary
1 Prof B 19 18 Male ... | <p>You can groupby multiple columns with a list as the first argument, so instead of just one:</p>
<pre><code>In [11]: df.groupby(pd.cut(df['srv'], np.arange(0, 70, 10)))['salary'].mean()
Out[11]:
srv
(0, 10] 88375.0
(10, 20] 140300.0
(20, 30] 175000.0
(30, 40] 115000.0
(40, 50] 144632.5
(50, 60] ... | python|pandas|numpy | 4 |
7,188 | 64,038,547 | Extracting Text Value if exists in another column or array | <p>I have a code that extracts the string in a column that has @ before the string, like below:</p>
<pre><code>df['new_column'] = df[text].str.extract(r"@([A-Za-z]+)")
</code></pre>
<p>But what if sometimes the text column contains the string I want to extract that might be missing the @ sign in front of it? ... | <p>The regex pattern depends on which character you want to capture. By your desired output, you need to change the pattern as follows:</p>
<pre><code>df['new_column'] = df['text'].str.extract(r"@([A-Za-z_]+([0-9]+)*)")[0]
Out[51]:
text new_column
0 @bobby bobby
1 @... | python|python-3.x|regex|pandas | 1 |
7,189 | 63,896,884 | how to select values from multiple columns based on a condition | <p>I have a dataframe which has information about people with balance in their different accounts. It looks something like below.</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({'name':['John', 'Jacob', 'Mary', 'Sue', 'Harry', 'Clara'],
'accnt_1':[2, np.nan, 13, np.nan, np.n... | <p>If balanced means first not missing values after <code>name</code> you can convert <code>name</code> to index, then back filling missing values and select first column by position:</p>
<pre><code>df = df.set_index('name').bfill(axis=1).iloc[:, 0].rename('balance').reset_index()
print (df)
name balance
0 John ... | python-3.x|pandas|numpy | 0 |
7,190 | 63,809,217 | Pandas python - Find the minimum timedelta of each group | <p>I want to find the min timedelta of each group.
For example, I have the following data set:</p>
<pre><code>DataSet
Name TimeFromStart
Omri 442 days
Omri 480 days
Omri 443 days
Lior 115 days
Lior 80 days
Lior 0 days
Output:
Name MinTimeDelta:
Omri 1
Lior ... | <p>First sorting both columns by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer"><code>DataFrame.sort_values</code></a>, then use custom lambda functio with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.di... | python|pandas|group-by | 1 |
7,191 | 47,026,585 | unhashable type 'list' error with get_dumies | <p>I have a dataframe with data like the sample data below. I'm trying to create dummy variables for the values in the categories field using get_dummies but I'm getting the error below when I run the code below. What I would like is say for example with the first record, to have one column called "Ramen" with a 1 in... | <p>You can try this </p>
<pre><code>df=pd.DataFrame( {'categories':[['Restaurants', 'Ramen', 'Japanese'],['Chinese', 'Seafood', 'Restaurants']]})
pd.get_dummies(df.categories.apply(pd.Series).stack()).sum(level=0)
Out[1095]:
Chinese Japanese Ramen Restaurants Seafood
0 0 1 1 1 ... | python|pandas | 10 |
7,192 | 46,855,689 | ETL process with Python and SQL Server taking a really long time to load | <p>I'm looking for a technique that will increase the performance of a csv file SQL Server database load process. I've attempted various approaches but nothing I do seems to be able to break the 5.5 hour barrier. That's just testing loading a year of data which is about 2 million records. I have 20 years of data to loa... | <blockquote>
<p>Bulk load works REALLY fast but then I have to add the data for the extra columns and we're back to row level operations which I think is the bottleneck here.</p>
</blockquote>
<p>Sorry but I do not understand why you have row level operations. Try:</p>
<p>1) bulk load to stage table </p>
<p>2) <a ... | python|sql-server|pandas|csv|tsql | 2 |
7,193 | 67,822,077 | pandas: Removing rows from cumulative column after it reaches a threshold | <p>I am working with the following dataframe:</p>
<pre><code>id1 Val cum_val
3233 24 24
3233 12 36
3233 7 43
3233 6 49
3233 6 55
3233 3 58
3255 5 5
3255 44 49
3255 4 53
3255 8 61
3255 8 69
</code></pre>
<p>where the cum_val column is cumulative of Val within each ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.shift.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.shift</code></a> for shifting values per groups and test for less like <code>50</code> for matching also next group after <code>50</code>:</p>
<pre>... | python|pandas | 2 |
7,194 | 67,715,525 | rename the "name" value in pandas dataframe | <p>New to pandas</p>
<p>Here is the code that I am working on:</p>
<pre><code>import pandas as pd
import yahoo_fin.stock_info as si
def dividend(stocks):
for sName in stocks:
print(sName)
print('Dividend History: ')
df = si.get_dividends(sName, '01-01-2019').iloc[:, :1]
#df.rename(co... | <p>The column with no name, looking like dates with hour part, in your
source DataFrame, is probably the <strong>index</strong> of <em>object</em> type (actually
a string).</p>
<p>To confirm it, run <code>df.index</code> and you should get something like:</p>
<pre><code>Index(['2019-02-20 00:00:00', '2019-05-15 00:00:0... | python|pandas | 0 |
7,195 | 61,587,830 | Is there a way to make changing DataFrame faster in a loop? | <pre><code> for index, row in df.iterrows():
print(index)
name = row['name']
new_name = get_name(name)
row['new_name'] = new_name
df.loc[index] = row
</code></pre>
<p>In this piece of code, my testing shows that the last line makes it quite slow, really slow. It basically i... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.apply.html" rel="nofollow noreferrer"><code>Series.apply</code></a> for processing function for each value of column, it is faster like <code>iterrows</code>:</p>
<pre><code>df['new_name'] = df['name'].apply(get_name)
</code></pre>... | python|pandas|dataframe | 1 |
7,196 | 61,187,702 | Difference between two date column if and only values are present in both the columns | <p>I have two date column
PRIMARY CHILD diff
05-19-1945 01-13-1994 some value in years
03-01-1963<br>
05-33-1933 03-01-1955 some value in years
05-19-1944 06-11-1967 some value in years
04-22-2020 </p>
<p>I want to show difference in years if and only if value is present in ... | <p>Your error <code>AttributeError: Can only use .dt accessor with datetimelike values</code> has nothing to do with only subtracting dates where both values are available. Rather, it has to do with the data types in the columns you're using. At least one of them is not a "datetimelike" object – therefore, the <code>.d... | python|pandas|datetime | 0 |
7,197 | 68,695,012 | Pandas: Rank Games according to score | <p>I am fairly new to development in any platform. Trying to basics in Python - Pandas. When trying to practise about pandas groupby function, I am getting duplicate records. Please see the data, questions and code I tried. Appreciate any suggestions on the same.</p>
<ol>
<li>read game.csv, game_score.csv</li>
</ol>
<p... | <p>HeRe iS oNe iDeA...</p>
<p><strong>Try:</strong></p>
<pre><code>import pandas as pd
file_game = pd.read_csv('game.csv')
file_game_score = pd.read_csv('game_score.csv')
# make '...Battle For the Pacific' and '...Battle For The Pacific' the same
file_game_score['title'] = file_game... | python|pandas|csv | 0 |
7,198 | 68,585,329 | Is there a way to get around the 250 MB limit for an AWS lambda function? | <p>I'm working on a Lambda Function in AWS and I tried to use Layers to load the dependencies (which are statsmodels, scikit-learn, pyLDAvis, pandas, numpy, nltk, matplotlib, joblib, gensim, and eli5), but I'm not able to add them because I get an error saying that the maximum allowed size of the code and layers togeth... | <blockquote>
<p>Is there any way to add more space for the dependencies?</p>
</blockquote>
<p>If you package your lambda function as <a href="https://docs.aws.amazon.com/lambda/latest/dg/images-create.html" rel="nofollow noreferrer">container lambda image</a>, you will have <strong>10 GB</strong> for your dependencies.... | amazon-web-services|numpy|amazon-s3|aws-lambda|statsmodels | 1 |
7,199 | 53,010,465 | Bidirectional LSTM output question in PyTorch | <p>Hi I have a question about how to collect the correct result from a BI-LSTM module’s output.</p>
<p>Suppose I have a 10-length sequence feeding into a single-layer LSTM module with 100 hidden units:</p>
<pre><code>lstm = nn.LSTM(5, 100, 1, bidirectional=True)
</code></pre>
<p><code>output</code> will be of shape:... | <p>Yes, when using a BiLSTM the hidden states of the directions are just concatenated (the second part after the middle is the hidden state for feeding in the reversed sequence). <br>So splitting up in the middle works just fine. </p>
<p>As reshaping works from the right to the left dimensions you won't have any probl... | machine-learning|neural-network|deep-learning|lstm|pytorch | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.