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
9,100
66,090,385
Why parameters in prunning increases in tensorflow's tfmot
<p>I was prunning a model and came across a library TensorFlow model optimization so initially, we have <a href="https://i.stack.imgur.com/Ovnhq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ovnhq.png" alt="in this image my model have 20410 parameters in total" /></a></p> <p>I trained this model on...
<p>It is normal. Pruning doesn't change the original model's structure. So it is not meant to reduce the number of parameters.</p> <p>Pruning is a model optimization technique that eliminates not commonly used(by other words you can say unnecessary) values in the weights.</p> <p>2nd model summary shows the parameters a...
python|tensorflow|machine-learning|deep-learning|pruning
4
9,101
66,231,771
How to access the second to last row of a csv file using python Pandas?
<p>Want to know if I can access the second to last row of this csv file? Am able to access the very last using:</p> <pre><code>pd.DataFrame(file1.iloc[-1:,:].values) </code></pre> <p>But want to know how I can access the one right before the last?</p> <p>Here is the code I have so far:</p> <pre><code>import pandas as p...
<p>As simple as that :</p> <pre class="lang-py prettyprint-override"><code>df1.iloc[-2,:] </code></pre>
python|pandas|dataframe|csv
1
9,102
52,648,644
Filter outliers in DataFrame rows based on a recursive time-interval
<p>I have the following DataFrame <code>df</code>:</p> <pre><code>ds y 2018-10-01 00:00 1.23 2018-10-01 01:00 2.21 2018-10-01 02:00 6.40 ... ... 2018-10-02 00:00 3.21 2018-10-02 01:00 3.42 2018-10-03 02:00 2.99 ... ... </code></pre> <p>That means that...
<p>Try this:</p> <pre><code>g = df.groupby(df.index.floor('D'))['y'] df[(np.abs(df.y - g.transform('mean')) &lt;= (3*g.transform('std')))] </code></pre>
python|pandas|datetime64
0
9,103
46,385,999
Transform an image to a bitmap
<p>I'm trying to create like a bitmap for an image of a letter but I'm not having the desired result. It's been a few days that I started working with images. I tried to read the image, create a numpy array of it and save the content in a file. I wrote the code bellow:</p> <pre><code>import numpy as np from skimage im...
<p>Check this one out:</p> <pre><code>from PIL import Image import numpy as np img = Image.open('road.jpg') ary = np.array(img) # Split the three channels r,g,b = np.split(ary,3,axis=2) r=r.reshape(-1) g=r.reshape(-1) b=r.reshape(-1) # Standard RGB to grayscale bitmap = list(map(lambda x: 0.299*x[0]+0.587*x[1]+0.1...
python|numpy|computer-vision|scikit-image
14
9,104
58,305,385
Rolling mean with start date happens before
<p>this code gives me the rolling mean from 90d before up to today <code>df.rolling('90d', on='Date')['quantity'].mean()</code> what I want now is from 90d before up to 30d before, how to achieve that?</p>
<p>I would roll twice with <code>sum</code> and <code>count</code>:</p> <pre><code>roll90 = df.rolling('90d').quantity.agg({'sum','count'}) # you may want roll29 instead of roll30 roll30 = df.rolling('30d').quantity.agg({'sum','count'}) roll = roll90 - roll30 roll['mean'] = roll['sum']/roll['count'] </code></pre>
python|python-3.x|pandas
2
9,105
58,570,928
Check pandas for NaN and differing types
<p>In order to check, whether a pandas contains missing/nan values, one can use the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.isnull.html#targetText=Detect%20missing%20values%20for%20an,arrays%2C%20NaT%20in%20datetimelike" rel="nofollow noreferrer">isnull</a> function.</p> <pre><code>t...
<p>You could use a custom function with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.applymap.html" rel="nofollow noreferrer">applymap</a>:</p> <pre><code>def isfloat(x): return isinstance(x, float) print(df.applymap(isfloat)) </code></pre> <p><strong>Output</strong></p> ...
python-3.x|pandas
3
9,106
58,236,245
Where does Ray.Tune create the model vs implementing the perturbed hyperparameters
<p>I am new to using ray.tune. I already have my network written in a modular format and now I am trying to incorporate ray.tune, but I do not know where to initialize the model (vs updating the perturbed hyperparameters) so that the model and the weights are not re-initialized when a worker is truncated and replaced b...
<p>The create_model should be called in <code>_setup</code>. <code>_restore</code> will be called after <code>_setup</code>, and in <code>restore</code>, the model should be updated to the weights stored in the checkpoint.</p>
python|pytorch|hyperparameters|ray
1
9,107
58,558,172
Python/Numpy optimisation
<p>I have a simple python class which is approx 40 lines of calculations, given thereafter with a use case exemple, that perform a simple computation (independence testing based on L2 distance between densities), and it takes a lot of time to compute with only 100 points and 100 boostrap. Here is the code and some data...
<p>Generally, list comprehensions in python are slow and <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow noreferrer">broadcasting</a> is much more efficient. In your specific case, <code>np.array([np.sum(dat &lt;= u) for dat in data])</code> takes a lot of time and can be replaced...
python|numpy|micro-optimization
2
9,108
69,048,791
align two pandas dataframes on values in one column, otherwise insert NA to match row number
<p>I have two pandas DataFrames (<code>df1</code>, <code>df2</code>) with a different number of rows and columns and some matching values in a specific column in each <code>df</code>, with caveats (1) there are some unique values in each <code>df</code>, and (2) there are different numbers of matching values across the...
<p>You can first assign a helper column for <code>id1</code> and <code>id2</code> based on <code>groupby.cumcount</code>, then merge. Finally <code>ffill</code> values of <code>var1</code> based on the group <code>id1</code></p> <pre><code>def helper(data,col): return data.groupby(col).cumcount() out = df1.assign(k = ...
python|pandas
2
9,109
68,996,893
Python Pandas Fast Way to Divide Row Value by Previous Value
<p>I want to calculate daily bond returns from clean prices based on the logarithm of the bond price in t divided by the bond price in t-1. So far, I calculate it like this:</p> <pre><code>import pandas as pd import numpy as np #create example data col1 = np.random.randint(0,10,size=10) df = pd.DataFrame() df[&quot;col...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.shift.html" rel="nofollow noreferrer"><code>Series.shift</code></a> by <code>col1</code> column with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.div.html" rel="nofollow noreferrer"><code>Series.d...
python|pandas|dataframe
2
9,110
69,089,597
Check pandas df2.colA for occurrences of df1.id and write (df2.colB, df2.colC) into df1.colAB
<p>I have two pandas <code>df</code> and they do not have the same length. <code>df1</code> has unique id's in column <code>id</code>. These id's occur (multiple times) in <code>df2.colA</code>. I'd like to add a list of all occurrences of <code>df1.id</code> in <code>df2.colA</code> (and another column at the matching...
<p>You could use Pandas <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.apply.html#pandas-dataframe-apply" rel="nofollow noreferrer"><code>apply</code></a> to iterate over each row of <code>df1</code> value while creating a list with all the indices in <code>df2.colA</code>. This can be achieved ...
python|pandas|dataframe|merge|matching
1
9,111
69,246,853
How to split comma separated cell values in a list in pandas?
<p>I hope you are doing well!</p> <p>Code:</p> <pre><code>df = pd.read_excel('Grade.xlsx') df = df.loc[df['Current year'] ==&quot;Final Year&quot;] Num = df['Available Number'].values </code></pre> <p>Sample data:</p> <pre><code>Sr no. Name Current Year City Available Number 1 joe First...
<p>Use a loop to convert the strings into list of int:</p> <pre><code>df['Available Number'] = df['Available Number'] \ .apply(lambda x: [int(i) for i in x.split(',')]) </code></pre> <p>Output:</p> <pre><code> Sr no. Name Current Year City Available Number 0 1 joe First Ye...
python|pandas|split
-1
9,112
68,885,217
How can I add a resizing by scale layer to a model in tensorflow or keras
<p>How can I add a resizing by scale layer to a model using tensorflow or keras ? ( not by fixed output dimensions) for example i want to resize image shape (100, 100, 3) by up scale of 2 , so the output shape of that layer will be (200, 200, 3) resizing layer should use interpolation methods like ( &quot;bilinear&quot...
<p>You can't really be dynamic about image shapes within a dataset. To generate high speed execution on GPU, your images need to be fixed size.</p> <p>That said, if all your images are a certain size within a dataset, but you want your model to generalize to different datasets, each with a different image size, you can...
python|tensorflow|keras|interpolation|resize-image
-1
9,113
44,662,406
Tensorflow exhausted resource
<p>I've wrote a Tensorflow program, that reads <code>128x128</code> images. The program runs kind of OK on my laptop,which I use to check if the code is ok. The 1st programm is bases on MNIST Tutorial , the 2nd ist using MNIST example for convNN. when I try to run them on GPU, I get the following error message: </p> ...
<p>The problem seems to be that everything in the graph is done on GPU. You should use the CPU resources for preprocessing functions and the rest of the graph on GPU. So make the input processing functions like getImage() and queues to be run on CPU instead of GPU. Basically when GPU is working on tensors the CPU shoul...
python|tensorflow
2
9,114
60,796,928
Can tensorboard display an interactive plot or 3D plot
<p>I have to visualize the interactive 3D plot on tensorboard. Can the tensorboard visualize this or is there any way to display this on tensorboard. Thank you.</p>
<p>Yes, you can use the mesh plugin on TensorBoard. It'll allow you to create a visualization similar to those found on Three.js . You pass in the vertices, colors, and faces of the 3D data and TensorBoard will create a 3D interactive visualization. There are other options such as projections but those are mainly used ...
tensorflow|pytorch|tensorboard|visualize|tensorboardx
0
9,115
61,003,467
How to convert a list of different-sized tensors to a single tensor?
<p>I want to convert a list of tensors with different sizes to a single tensor. </p> <p>I tried <code>torch.stack</code>, but it shows an error.</p> <pre><code>--------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) &lt;ip...
<p>I agree with @helloswift123, you cannot stack tensors of different lengths. </p> <p>Also, @helloswift123's answer will work only when the total number of elements is divisible by the shape that you want. In this case, the total number of elements is <code>19</code> and in no case, it can be reshaped into something ...
python|pytorch|tensor
1
9,116
71,716,193
Pandas: How to create a new column that adds selected columns across rows
<p>I would like to create a new column called &quot;Excess Return&quot; that is =('SPX TR'-'3M Govt'), and I want to place it to the right of the '3M Govt' column. How do I do that?</p> <p>Please call the following table &quot;df&quot;</p> <pre><code> Date SPX TR 3M Govt Div Yield Real Dividends </code></p...
<pre><code>df['Val_Diff'] = dfB['SPX TR'] - dfB['3M Govt'] </code></pre> <p>after this sort your columns</p> <pre><code>df = df[['SPX TR', '3M Govt', 'Val_Diff', 'Div Yield', 'Real Dividends']] </code></pre>
pandas|dataframe|calculated-columns|subtraction
0
9,117
71,492,896
Django CeleryTask return GeoDataFrames leads to TypeError: Object of type int64 is not JSON serializable
<p>I am trying to build a web app in which I make use of celery to tackle a long running process. I need to pass to the view that called the task a couple of GeoDataFrame and an epsg projection value.</p> <pre><code>return {'Working_area_final': Working_area_final.to_json(), 'PoI_buffer_small': PoI_buffer_small.to_json...
<p>Have created a MWE with what you describe. It does not fail (as expected) when serialised as JSON (actually GEOJSON). I suggest that you provide more details on</p> <ol> <li>how you are using <strong>osmnx</strong></li> <li>how you are doing CRS projection</li> </ol> <pre><code>import geopandas as gpd import osmn...
json|django|celery|task|geopandas
0
9,118
71,520,565
Access columns of a dataframe based on column names using a 'for' loop
<p>Let's say I have data frame consisting of column names <code>M1out1</code>, <code>M1out2</code>, ..., <code>M1out120</code>, <code>0</code>, <code>1</code>, ..., <code>120</code>.</p> <p>Is there a way in which I can access the columns based on these names using a <code>for</code> loop?</p> <p>Like <code>for i in ra...
<p>You can create a slice of the dataframe by a range of columns, and get the list of columns names for that slice:</p> <pre><code>for col in df.loc[:, 'M1out0':'M1out15'].columns: print(col) </code></pre> <p>Output:</p> <pre><code>M1out0 M1out1 M1out2 M1out3 M1out4 M1out5 M1out6 M1out7 M1out8 M1out9 M1out10 M1out1...
python|pandas
0
9,119
42,273,246
How does tensorflow implement the embedding_column?
<p>I'm learning tensorflow's wide_n_deep_tutorial these days, and I'm a little bit confused with the <em>tf.contrib.layers.embedding_column</em>. I wonder how does tensorflow implement the embedding column? </p> <p>For example, suppose I have an sparse input with dimension 1000 and I want to embed it into a dense feat...
<p>There are 3 combiner in the embedding_column function:</p> <p>"sum": do not normalize "mean": do l1 normalization "sqrtn": do l2 normalization. see more tf.embedding_lookup_sparse</p> <p>There are not using FM to modulate/transform the dimensions.</p>
tensorflow|embedding
1
9,120
69,797,734
Removing entire rows from a dataframe for which a specified column value contains null
<p>Using python and pandas I am trying to remove entire rows from a dataframe where a value in a specific column is a null: I have tried the following code using a for loop:</p> <pre><code>for row in dataframe.index: if pd.isnull(dataframe['Column'][i]): dataframe[.drop([i], axis=0, inplace=False) </code></...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dropna.html" rel="nofollow noreferrer"><code>pandas.DataFrame.dropna</code></a>:</p> <p>In your case, it would be like this:</p> <pre><code>dataframe.dropna(subset=['Column'], inplace=True, axis=0) </code></pre>
python|pandas|dataframe|for-loop
1
9,121
69,912,650
create new DataFrame resulted from processing N rows of other DataFrame
<p>I want to process each N rows of a DataFrame separately.<br />If my data has 15 row indexed from 0 to 14 I want to process rows from index 0 to 3 , 4 to 7, 8 to 11, 12 to 15 <br /> for example let's say for each 4 rows I want the sum(A) and the mean(B)</p> <div class="s-table-container"> <table class="s-table"> <the...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.agg.html" rel="nofollow noreferrer"><code>GroupBy.agg</code></a> with integer division by <code>4</code> by index:</p> <pre><code>#default RangeIndex df = df.groupby(df.index // 4).agg({'A':'sum', 'B':'mean'}) #any in...
python|pandas|dataframe
1
9,122
70,016,547
How to plot each year as a line with months on the x-axis
<p>I have a question, I have the following dataframe containing multiple years and months with an total sum:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd data = {'Bedrag': [210406.49, 191369.87, 118458.65, 81682.95, 90571.61, 196374.53, 223619.85, 144773.64, 240221.67, 110666.73, 108633.49, ...
<ul> <li>The clearest way to make seasonal observations is to plot each year as a separate line, with the x-axis as the months</li> <li>Set the month column as ordered categorical with <a href="https://pandas.pydata.org/docs/reference/api/pandas.Categorical.html" rel="nofollow noreferrer"><code>pd.Categorical</code></a...
python|pandas|dataframe|plot|seaborn
1
9,123
69,973,357
Finding a match in two files and merging the data
<p><strong>Input: file1</strong></p> <pre><code>0 1 EXE sldk EXE1 vkrk TPO dlfk EXE2 sdfs </code></pre> <p><strong>Input: file2</strong></p> <pre><code>0 1 DD=CMD asldkjfalsdkfj DD=EXE mbnwjnjcxjic DD=DMFF pklckwkflkdf DD=EXE2 okvwokmvfv DD=EXE1 ksdjfokwoek...
<p>You could create a temporary variable from <code>file2</code>, without the <code>DD=</code>, and merge data found in both DataFrames in the first column (<code>0</code>) using the <code>on</code> parameter.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df1 = pd.read_csv('file1.csv', sep='\...
python|pandas|file|merge|extract
0
9,124
69,803,718
Keras Custom loss Penalize more when actual and prediction are on opposite sides of Zero
<p>I'm training a model to predict percentage change in prices. Both MSE and RMSE are giving me up to 99% accuracy but when I check how often both actual and prediction are pointing in the same direction <code>((actual &gt;0 and pred &gt; 0) or (actual &lt; 0 and pred &lt; 0))</code>, I get about 49%.</p> <p>Please how...
<p>I will leave it up to you to define your exact logic, but here is how you can implement what you want with <code>tf.cond</code>:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf y_true = [[0.1]] y_pred = [[0.05]] mse = tf.keras.losses.MeanSquaredError() def custom_loss(y_true, y_pred): ...
python|tensorflow|keras|loss-function|mse
1
9,125
69,864,279
Python Pandas print Dataframe.describe() in default format in JupyterNotebook
<h2>Output format without print function</h2> <p>If I run a JupyterNotebook cell with</p> <pre><code>dataframe.describe() </code></pre> <p>a pretty fromatted table will be printed like that: <a href="https://i.stack.imgur.com/byrgO.png" rel="nofollow noreferrer">VSCode JupyterNotebook dataframe.describe() solo cell pri...
<p>There are multiple things to say here:</p> <ol> <li><p>Jupyter Notebooks can only print out one object at a time when simply calling it by name (e.g. <code>dataframe</code>). If you want, you can use one cell per command to get the right format.</p> </li> <li><p>If you use the function <code>print</code>, it will pr...
python|pandas|dataframe|printing|describe
1
9,126
72,296,566
Generating 3 columns from one with .apply on dataframe
<p>I want to extract some data from each row, and make that new columns of existing or new dataframe, without repeatedly doing the same operation of re. match.</p> <p>Here's how one entry of the dataframe looks:</p> <pre><code>00:00 Someones_name: some text goes here </code></pre> <p>And i have a regex that successfull...
<p>you can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.extract.html" rel="nofollow noreferrer">str.extract</a> with your pattern</p> <pre><code>df[['time','name', 'text']] = df['col1'].str.extract(r&quot;^(\d{2}:\d{2}) (.*): (.*)$&quot;) print(df) # ...
python|pandas|dataframe|data-science|series
2
9,127
72,435,759
Pandas: Setting a value in a cell when multiple columns are empty
<p>I've been looking for ways to do this natively for a little while now and can't find a solution.</p> <p>I have a large dataframe where I would like to set the value in other_col to 'True' for all rows where one of a list of columns is empty.</p> <p>This works for a single column page_title:</p> <p><code>df.loc[df['p...
<p>This will allow you to set which columns you want to determine if np.nan is present and set a True/False indicator</p> <pre><code>data = { 'Column1' : [1, 2, 3, np.nan], 'Column2' : [1, 2, 3, 4], 'Column3' : [1, 2, np.nan, 4] } df = pd.DataFrame(data) df['other_col'] = np.where((df['Column1'].isna()) | (...
python|pandas
0
9,128
72,415,365
Exponential moving average (EMA) with different number of observations per day but equally weighted observations
<p>I have a <code>DataFrame</code> <code>df1</code> with observations according to one specific <code>ID</code>. The number of observations per <code>ID</code> varies over time. For each <code>ID</code>, I try to calculate an exponential moving average (EMA) over 3 days. Each observation should be weighted equally with...
<p>Sorry, as I am new, I do not have the option to leave a comment. But, you can try pandas <code>.emw</code> similar to SMA right? <code>pivot.ewm(span=3, min_periods=3).mean()</code>.</p> <p>I'm not exactly sure what <code>RollingSum</code> does in your code; but try this:</p> <pre><code>EMA = pivot.ewm(span=3, min_p...
python|pandas|dataframe
1
9,129
50,430,083
how to see a full image of deep neural network
<p>How it is possible to see in Keras or Tensorflow the graphical structure of deep neural network? I made its model and see output of "plot_model" but I want to see the graphical similar to this image.</p> <p><img src="https://i.stack.imgur.com/auqqO.png" alt="click to see the image"></p>
<p>For Tensorflow at least, you can use Tensorboard <a href="https://www.tensorflow.org/programmers_guide/summaries_and_tensorboard" rel="nofollow noreferrer">Tutorial and Explanation</a></p> <p>It also features <a href="https://www.tensorflow.org/programmers_guide/graph_viz" rel="nofollow noreferrer">Graph visualizat...
python-3.x|tensorflow|graphics|keras|deep-learning
-1
9,130
50,515,935
Python rolling sum taking data from to columns
<p>The below is a part of a dataframe which consists of football game results.</p> <p>FTHG stands for "Full time home goals"</p> <p>FTAG stands for "Full time away goals"</p> <pre><code> Date HomeTeam AwayTeam FTHG FTAG FTR 14/08/93 Arsenal Coventry 0 3 A 14/08/93 Aston...
<p>you can combine those columns together and then apply groupby</p> <pre><code>tmp1 = df[['Date','HomeTeam', 'FTHG']] tmp2 = df[['Date','AwayTeam', 'FTAG']] tmp1.columns = ['Date','name', 'score'] tmp2.columns = ['Date','name', 'score'] tmp = pd.concat([tmp1,tmp2]) tmp.sort_values(by='Date').groupby("name")["score"...
python|pandas
0
9,131
50,358,767
get the last output for non-padded entry from tf.nn.dynamic_rnn
<p>I want to use an RNN in an all-to-one mode (only one output at the end). In TensorFlow, one can use:</p> <pre><code>lstm_cell = tf.nn.rnn_cell.LSTMCell(lstm_num_units) output, _ = tf.nn.dynamic_rnn(lstm_cell, embed, dtype=tf.float32) </code></pre> <p>Where the output contains the output at all time steps <code>[0,...
<p>Modifying your code:</p> <pre><code>_, state = tf.nn.dynamic_rnn(lstm_cell, embed, dtype=tf.float32, sequence_length=some_placeholder) last_output = state.h </code></pre> <p>Don't forget to add a <code>sequence_length</code> parameter in the call to <code>dynamic_rnn</code> if you want the sequence lengths to va...
python|tensorflow
0
9,132
45,522,945
Pandas adding length column to dataframe after converting list to tuple
<p>I have two dataframes, the <code>test_df</code> was a list whereas the <code>product_combos</code> df was tuples. I changed the <code>test_df</code> to tuples as well like so:</p> <pre><code>[in] print(testing_df.head(n=5)) [out] product_id transaction_id 001 ...
<p>it's working fine</p> <pre><code>df = pd.DataFrame([[1,['a','b']],[2,['a','b','c']],[3,['c','b']],[4,['b','d']],[5,['c','a']]]) </code></pre> <p>df:</p> <pre><code> 0 1 0 1 [a,b] 1 2 [a, b, c] 2 3 [c, b] 3 4 [b, d] 4 5 [c, a] df[1] = df[1].apply(tuple) df['length'] = df[1].apply(len) </...
python|pandas|dataframe
0
9,133
45,680,391
Create a dictionary by grouping by values from a dataframe column in python
<p>I have a dataframe with 7 columns, as follows:</p> <pre><code> Bank_Acct Firstname | Bank_Acct Lastname | Bank_AcctNumber | Firstname | Lastname | ID | Date1 | Date2 B1 | Last1 | 123 | ABC | EFG | 12 | Somedate | Somedate B2 | Las...
<p>You could define your columns and functions in a list</p> <pre><code>In [15]: cols = [ ...: {'col': 'Bank_Acct Firstname', 'func': pd.Series.nunique}, ...: {'col': 'Bank_Acct Lastname', 'func': pd.Series.nunique}, ...: {'col': 'Bank_AcctNumber', 'func': lambda x: x.value_counts().to_dict(...
python|pandas|dictionary|dataframe|group-by
2
9,134
62,633,568
Flatten JSON-response
<p>I have issues with flattening this JSON due to the ending of it which I actually don't need so I could potentially remove it (before or after flattern the JSON). I would like to do this in Python and have tried json_normalized and Panda for export to CSV.</p> <p>What's special, the last three items, TotalNumberOfMun...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.json_normalize.html" rel="nofollow noreferrer"><code>pd.json_normalize</code></a>:</p> <pre><code>df = pd.json_normalize(d, 'Municipalities') print (df) Name NumberOfCitizens Id Attributes \ 0 Stockholm ...
python|json|pandas|csv|flatten
2
9,135
62,679,380
How do you detect and delete infinite values from a time series in a pandas dataframe?
<p>I can't calculate the mean of a variable because it has infinite values in it, but I can't find and fix them:</p> <pre><code>perc_df[['variable']].mean() variable inf dtype: float64 </code></pre> <p>I've never dealt with infinite values before, is there an equivalent to &quot;isna()&quot; and &quot;dropna()&quot...
<p>You can try to filter out the infinite values with <a href="https://numpy.org/doc/1.18/reference/constants.html#numpy.Inf" rel="nofollow noreferrer"><code>numpy.inf</code></a>. The code is following:</p> <pre><code>import numpy as np perc_df[perc_df.variable != np.inf].variable.mean() </code></pre>
python|pandas|infinite
2
9,136
62,842,509
Does model.compile() go inside MirroredStrategy
<p>I have a network for transfer learning and want to train on two GPUs. I have just trained on one up to this point and am looking for ways to speed things up. I am getting conflicting answers about how to use it most efficiently.</p> <pre><code>strategy = tf.distribute.MirroredStrategy(devices=[&quot;/gpu:0&quot;, &q...
<p>It does not matter where it goes because under the hood, <code>model.compile()</code> would create the optimizer,loss and accuracy metric variables under the strategy scope in use. Then you can call <code>model.fit</code> which would also schedule a training loop under the same strategy scope.</p> <p>I would suggest...
python|tensorflow|keras|multi-gpu
0
9,137
54,522,336
How do custom input_shape for Inception V3 in Keras work?
<p>I know that the <code>input_shape</code> for Inception V3 is <code>(299,299,3)</code>. But in Keras it is possible to construct versions of Inception V3 that have custom <code>input_shape</code> if <code>include_top</code> is <code>False</code>.</p> <blockquote> <p>"input_shape: optional shape tuple, only to be ...
<p>This is possible because the model is fully convolutional. Convolutions don't care about the image size, they're "sliding filters". If you have big images, you have big outputs, if small images, small outputs. (The filters, though, have a fixed size defined by <code>kernel_size</code> and input and output filters) <...
python|tensorflow|machine-learning|keras|conv-neural-network
1
9,138
54,449,406
Find column values that are present for multiple months in pandas
<p>how to filter the ids which are existed into multiple months with DateTime in Pandas, Python 3 </p> <pre><code>DateTime ID 2011-01-30 08:00:59 367341093 2011-01-30 08:03:00 367341093 2011-02-01 08:03:59 367341093 2011-02-01 08:05:00 367341093 2011-03-12 08:...
<p>You can do this with <code>groupby</code> and <code>nunique</code>:</p> <pre><code>u = df['DateTime'].dt.month.groupby(df.ID).nunique() u ID 367341012 1 367341034 1 367341045 2 367341093 3 Name: DateTime, dtype: int64 u.index[u &gt; 1] # Int64Index([367341045, 367341093], dtype='int64', name='ID') </c...
python|pandas|filter|group-by|pandas-groupby
2
9,139
54,682,457
requires_grad of params is True even with torch.no_grad()
<p>I am experiencing a strange problem with PyTorch today.</p> <p>When checking network parameters in the <code>with</code> scope, I am expecting <code>requires_grad</code> to be <code>False</code>, but apparently this is not the case unless I explicitly set all params myself.</p> <p><strong>Code</strong></p> <p>Lin...
<p><code>torch.no_grad()</code> will disable gradient information for the <em>results</em> of operations involving tensors that have their <code>requires_grad</code> set to <code>True</code>. So consider the following:</p> <pre><code>import torch net = torch.nn.Linear(4, 3) input_t = torch.randn(4) with torch.no_gr...
python|neural-network|pytorch
4
9,140
54,460,092
Matching dictionaries with columns and indices in DataFrame | python
<p>I have a DataFrame with column names as on example and the indices from 0 to 1000. The dataframe is filled with zeros.</p> <pre><code>House 1 | House 2 | House 5 | House 8 | ... 0 1 2 3 4... </code></pre> <p>Then, I have dictionary, e.g.:</p> <pre><code>dict_of_houses = {'House 1':[100,201,306,387,500,900],'Hous...
<p>You can use a <code>for</code> loop:</p> <pre><code>for house, indices in dict_.items(): df.loc[indices, house] = 1 </code></pre>
python|pandas|dictionary|dataframe|indexing
0
9,141
54,391,166
reshaping of an nparray returned "IndexError: tuple index out of range"
<p>reshaping of an nparray returned "IndexError: tuple index out of range"</p> <p>Following "<a href="https://machinelearningmastery.com/time-series-prediction-lstm-recurrent-neural-networks-python-keras/" rel="nofollow noreferrer">https://machinelearningmastery.com/time-series-prediction-lstm-recurrent-neural-network...
<p>Unlike in Matlab, numpy arrays can be one-dimensional, so there is only one value from shape parameter.</p> <pre><code>a = np.array([1,2,3,4]) a.shape[0] # ok a.shape[1] # error </code></pre>
python|numpy
3
9,142
71,112,423
python define function that retrieves data from API and then put into dataframe
<p>I need to get data from an API and then convert into a pandas dataframe. So far I am able to achieve that using for loops (that was efficient when I had one dataset). Now that I have several dataframes, I was wondering how can i write a function that extracts the data from the API and builds a dataframe.</p> <p>Samp...
<p>Maybe you can try storing the data in dictionaries.</p> <p>In my example below, I created one dictionary for a list of sensors per motion. And one dictionary where we can store a dictionary per motion. In that nested dictionary you link the results to the sensors.</p> <p>I haven't tested it, but maybe you can try it...
python|pandas|function|loops
1
9,143
52,436,394
How to convert a pandas value_counts into a python list
<p>I have a pandas series and I am taking its value count using <code>value_counts</code>.I need to get it into a list. I tried <code>to_list()</code> but got error.</p> <pre><code>df['AAA'].value_counts(sort=True).to_list() </code></pre> <p>If I run, <code>df['AAA'].value_counts(sort=True)</code> , I will get somet...
<p>Try <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.tolist.html" rel="nofollow noreferrer"><code>tolist()</code></a> not <code>to_list()</code> (without <code>_</code>): </p> <pre><code>df['AAA'].value_counts(sort=True).tolist() </code></pre>
python|pandas|list|numpy|dataframe
3
9,144
52,273,322
Snakemake and pandas syntax
<p>I have a input file as follow </p> <pre><code>SampleName Run Read1 Read2 A run1 test/true_data/4k_R1.fq test/true_data/4k_R2.fq A run2 test/samples/A.fastq test/samples/A2.fastq B run1 test/samples/B.fastq test/samples/B2.fastq C run1 test/samples/C.fastq test/samples/C5.fastq D </code></pre> <p>So I am getting al...
<p><code>lambda</code> function can be used to get that value.</p> <pre><code>input: lambda wildcards, output: sample_table.Read2[wildcards.ID_sample] </code></pre> <p>Also, based on your <code>rule all</code>, your <code>output</code> needs to be <code>test/fltr/{ID_sample}.fq</code>. And, you have to use comma ...
pandas|snakemake
0
9,145
60,758,929
Trying to load a tflite model fails with java.io.FileNotFoundException - what am I doing wrong?
<h1>My issue</h1> <p>I'm trying to run my TensorFlow model (which manipulates images) on Android as tflite, but I keep getting <strong>java.io.FileNotFoundException</strong>.</p> <p>Don't bother reading all the Java code - it fails before it even starts, when trying to load the model:</p> <pre><code> // Initi...
<p>I was stuck on this for 3 days, scanned the entire internet... and solved it a few hours after posting this...</p> <p><strong>I deleted my assets folder and re-created it</strong>. This solved my issue.</p> <p>I have no time to research into this, and I have no idea why this was what helped (since I've already tri...
java|android|tensorflow|tensorflow-lite
4
9,146
60,708,252
Pandas two dataframes for loop: how to set value to old value + 1
<p>There are two dataframe <strong>roads</strong> and <strong>bridges</strong>. </p> <p>If the kilometre point of a bridge falls between the chainage begin and end of a road segment, it should be checked which condition this bridge is in (this is A, B, C or D). </p> <p>If the condition is <strong>'A'</strong> (this i...
<p>You should never use <code>df.column[row_index]</code> nor <code>df[column][row_index]</code>. It works when you read a value but is error prone when you try to set a value. The only robust syntax is</p> <pre><code>df.loc[row_index, col] = ... </code></pre> <p>So here you should use:</p> <pre><code> if bri...
python|pandas|loops|dataframe|for-loop
0
9,147
60,374,258
How to implement a .tranpose() as .T (like in numpy)
<p>Let's say I have the following class containing a Numpy array <code>a</code>.</p> <pre class="lang-py prettyprint-override"><code>class MyClass(): def __init__(self,a,b): self.a = a self.other_attributes = b def transpose(self): return MyClass(self.a.T,self.other_attributes) </code><...
<p>Use a <code>property</code> to compute attributes. This can also be used to cache computed results for later use.</p> <pre><code>class MyClass(): def __init__(self, a, b): self.a = a self.other_attributes = b @property def T(self): try: return self._cached_T # attem...
python|numpy|class|transpose
0
9,148
72,565,029
Shape of data changing in Tensorflow dataset
<p>The shape of my data after the mapping function should be (257, 1001, 1). I asserted this condition in the function and the data passed without an issue. But when extracting a vector from the dataset, the shape comes out at (1, 257, 1001, 1). Tfds never fails to be a bloody pain.</p> <p>The code:</p> <pre><code>def ...
<p>Although I still can't explain why I'm getting that output, I did find a workaround. I simply reshaped the data in another mapping like so:</p> <pre><code>def read_npy_file(data): # 'data' stores the file name of the numpy binary file storing the features of a particular sound file # as a bytes string. #...
tensorflow|machine-learning|deep-learning|tensorflow-datasets
0
9,149
59,628,494
Merge two data frame based on specific condition in pandas
<p>I have two dataframe as shown below</p> <p>df1 - Inspector ID and assigned place</p> <p>df1: </p> <pre><code>Inspector_ID Assigned_Place 1 ['Bangalore', 'Chennai'] 2 ['Bangalore', 'Delhi', 'Chennai'] 3 ['Bangalore', 'Delhi'] 4 ['Chennai', 'Mumbai'] </code...
<p>First convert column filled by lists by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html" rel="nofollow noreferrer"><code>DataFrame.explode</code></a>, then <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge.html" rel="nofollow noreferrer">...
pandas|merge|pandas-groupby
2
9,150
59,847,919
Failing to load native tensorflow runtime
<p>I have been using tensorflow (via Keras) to do some simple image classification tasks. It was working fine late last year (mid-december), but now I have done some package updates and get this error when attempting to run my code:</p> <pre><code>Traceback (most recent call last): File "C:\Python\lib\site-packages\...
<p>Common solution for this issue is you need to install/update Microsoft Visual C++ 2015-2019 Redistributable (x64) from <a href="https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads" rel="nofollow noreferrer">here</a></p> <p>For more details please refer similar question answered ...
python|tensorflow|keras
0
9,151
59,718,130
What are C classes for a NLLLoss loss function in Pytorch?
<p>I'm asking about C classes for a <a href="https://pytorch.org/docs/stable/nn.html?highlight=nllloss#torch.nn.NLLLoss" rel="noreferrer">NLLLoss</a> loss function.</p> <p>The documentation states:</p> <blockquote> <p>The negative log likelihood loss. It is useful to train a classification problem with C classes.</...
<p>Basically you are missing a concept of <code>batch</code>.</p> <p>Long story short, every input to loss (and the one passed through the network) requires <code>batch</code> dimension (i.e. how many samples are used).</p> <p>Breaking it up, step by step:</p> <h1>Your example vs documentation</h1> <p>Each step wil...
python|machine-learning|neural-network|pytorch
5
9,152
59,644,859
AttributeError: module 'tensorflow_core.compat.v1' has no attribute 'contrib'
<pre><code>x = tf.placeholder(dtype = tf.float32, shape = [None, 28, 28]) y = tf.placeholder(dtype = tf.int32, shape = [None]) images_flat = tf.contrib.layers.flatten(x) logits = tf.contrib.layers.fully_connected(images_flat, 62, tf.nn.relu) loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits( lab...
<p><code>tf.contrib</code> was removed from TensorFlow once with TensorFlow 2.0 alpha version. </p> <p>Most likely, you are already using TensorFlow 2.0.</p> <p>You can find more details here: <a href="https://github.com/tensorflow/tensorflow/releases/tag/v2.0.0-alpha0" rel="noreferrer">https://github.com/tensorflow/...
python|tensorflow|jupyter|tensorflow2.0
11
9,153
61,637,754
Python: Overlapping date ranges into time series
<p>My data set is much larger so I have simplified it.</p> <p>I want to convert the dataframe into a time-series.</p> <p>The bit I am stuck on:</p> <p>I have overlapping date ranges, where I have a smaller date range inside a larger one, as shown by row 0 and row 1, where row 1 and row 2 are inside the date range of...
<p>I prepared two consecutive columns of data with minimum and maximum dates and ran updates from the original DF.</p> <pre><code> import pandas as pd import numpy as np import io data=''' date1 date2 reduction 0 2016-01-01 2016-01-05 7.0 1 2016-01-02 2016-01-03 5.0 2 2016-01-03 2016-01-04 6.0 3 2016-01-05 2016-01...
python|pandas|time-series
1
9,154
55,045,752
handwriting text recognition (CNN + LSTM + CTC) RNN explanation required
<p>I am trying to understand the following code, which is in python &amp; tensorflow. Im trying to implement a handwriting text recognition. I am referring to the following code <a href="https://github.com/githubharald/SimpleHTR/blob/master/src/Model.py" rel="nofollow noreferrer">here</a></p> <p>I dont understand why ...
<p>The input to CTC loss layer will be of the form B x T x C</p> <p>B - Batch Size T - Max length of the output (twice max word length due to blank char) C - number of character + 1 (blank char)</p> <p>Input to atrous is of shape (B x T x 1 X 2T) == (batch, height ,width ,channel) filter we are using is (1,1,2T,C) ==...
python|tensorflow|deep-learning|handwriting
1
9,155
54,772,063
Numpy next element minus previous
<p>I would like to subtract the next element from current element in a specific axis from numpy array. But, I know how to do that using a lot of loops. My question is: How to do that in the most efficient way? Maybe using numpy?</p> <p>My Python code below:</p> <pre><code>import numpy as np np.random.seed(0) myarr ...
<p>There are a few good ways of doing this. If you did not care about the last element being NaN, you could use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.diff.html" rel="noreferrer"><code>np.diff</code></a></p> <pre><code>myarr = np.random.rand(20, 7, 11, 151, 161) newarr = np.diff(myarr, axi...
python|numpy
9
9,156
55,008,961
How to set different excel files to different variales from the same folder using Python?
<p>I want to load different xls files from the same folder and set them to different variables. I've done that manually but I wonder that that should be a better way to do it. </p> <p>Here is my code:</p> <pre><code>import os import pandas as pd os.chdir('/home/marlon/ShiftOne/Previsao_insumos_construcao/dados_de_s...
<p>Another way of doing this might be to store the xls files in a dictionary with the desired names as the keys. For example:</p> <pre><code>my_dict = {} my_dict['insumos_mai2004'] = pd.read_excel('Custos_Unitarios_Edificacoes_Maio2004.xls') </code></pre> <p>However, this won't really fix the core problem: your namin...
python|excel|pandas|dataset|xls
0
9,157
55,022,536
Tensorflow indexing into python list during tf.while_loop
<p>I have this annoying problem and i dont know how to solve it.</p> <p>I am reading in batches of data from a CSV using a dataset reader and am wanting to gather certain columns. The reader returns a tuple of tensors and, depending on which reader i use, columns are either indexed via integer or string.</p> <p>I can...
<p>Does this fit your requirement somewhat ? It does nothing apart from print the value. </p> <pre><code>import tensorflow as tf from tensorflow.python.framework import tensor_shape some_data = [11,222,33,4,5,6,7,8] def func( v ): print (some_data[v]) return some_data[v] with tf.Session() as sess: r = t...
tensorflow
1
9,158
54,728,783
How to create a dataframe from another dataframe based on GroupBy condition
<p>I don't know how can i create a dataframe based on another dataframe using a groupby conditions. For example, i have a dataframe that if i apply the function:</p> <p><code>flights_df.groupby(by='DepHour')['Cancelled'].value_counts()</code></p> <p>I obtain something like this</p> <pre><code>DepHour Cancelled 0.0 ...
<p>There might be a cleaner way (probably without using <code>groupby</code> twice) but this should should work:</p> <pre><code>flights_df.groupby('DepHour') \ .filter(lambda x: (x['Cancelled'].unique()==[0]).all()) \ .groupby('DepHour')['Cancelled'].value_counts() </code></pre>
python|pandas|dataframe
1
9,159
49,618,242
Visualize vector value at each step with Tensorflow
<p>For debugging purposes I want to visualize the output vector of the NN at each step of the training process.</p> <p>I tried to use TensorBoard with a tf.summary.tensor_summary:</p> <pre><code>available_outputs_summary = tf.summary.tensor_summary(name='Probability of move', tensor=available_outputs) </code></pre> ...
<p>First, your picture is the graph visualization. I believe graph visualization is not supposed to have any summaries - it just shows you the graph.</p> <p>TensorBoard has other tabs for summaries including "scalar", "histogram", "distribution". Normally, you would look in these tabs for visualizations. However, base...
python-3.x|tensorflow|tensorboard
1
9,160
49,560,347
Random crop and bounding boxes in tensorflow
<p>I want to add a data augmentation on the WiderFace dataset and I would like to know, how is it possible to random crop an image and only keep the bouding box of faces with the center inside the crop using tensorflow ?</p> <p>I have already try to implement a solution but I use TFRecords and the TfExampleDecoder and...
<p>You can get the shape, but only at runtime - when you call sess.run and actually pass in the data - that's when the shape is actually defined.</p> <p>So do the random crop manually in tesorflow, basically, you want to reimplement <code>tf.random_crop</code> so you can handle the manipulations to the bounding boxes....
python|tensorflow
0
9,161
73,245,840
scipy convert coo string directly to numpy matrix
<p>I already have a string in coo matrix format(row, col, value):</p> <pre><code>0 0 -1627.761282 0 1 342.811259 0 2 342.811259 0 3 171.372276 0 4 342.744553 0 5 342.744553 </code></pre> <p>Now I want to convert my string directly to numpy matrix. Currently I have to write my string to file, then create a numpy matrix ...
<p>You could use <a href="https://docs.python.org/3/library/io.html#text-i-o" rel="nofollow noreferrer">StriongIO</a> as follows.</p> <pre><code>import numpy as np from scipy.sparse import coo_matrix import io with io.StringIO(matrix_str) as ss: rows, cols, data = np.loadtxt(ss).T matrix = coo_matrix((data.astype(...
numpy|scipy|sparse-matrix
0
9,162
73,488,906
pandas: replace values at specifc index in columns of list of strings
<p>I have a dataframe as follows.</p> <pre><code>import pandas as pd df = pd.DataFrame({&quot;first_col&quot;:[[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;],[&quot;a&quot;,&quot;b&quot;],[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]], &quot;second_col&quot;:[[&quot;the&quot;,&quot;house&quot;,&...
<p>You need to use a list comprehension:</p> <pre><code>df['first_col'] = [ [b if b.startswith('[') and b.endswith(']') else a for a, b in zip(A, B)] for A, B in zip(df['first_col'], df['second_col']) ] </code></pre> <p>output:</p> <pre><code> first_col second_col 0 [a, b, c, [blue]] ...
python|pandas|list|indexing
1
9,163
67,479,667
Calculate simple historical average using pandas
<p>I have a dataframe like as shown below</p> <pre><code>data = pd.DataFrame({'day':['1','21','41','61','81','101','121','141','161','181','201','221'],'Sale':[1.08,0.9,0.72,0.58,0.48,0.42,0.37,0.33,0.26,0.24,0.22,0.11]}) </code></pre> <p>I would like to fill the values for <code>day 241</code> by computing the average...
<p>It sounds like you're looking for an expanding mean:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd df = pd.DataFrame({'day': ['1', '21', '41', '61', '81', '101', '121', '141', '161', '181', '201', '221'], 'Sale': [1.08, 0.9, ...
python|pandas|dataframe|numpy|time-series
6
9,164
67,309,518
InvalidArgumentError on a mixed CNN
<p>I'm very new to Tensorflow/Keras and deep learning, so my apologies in advance.</p> <p>I'm creating a basic mixed convolutional neural net to classify images and metadata. I've created the following using the Keras Functional API:</p> <pre><code># Define inputs meta_inputs = tf.keras.Input(shape=(2065,)) img_inputs ...
<p>AUC metrics need probabilities in [0,1].</p> <p>In your model, this not happen due to the sum you do in <code>merged</code> layer. You can solve for example using an average instead of a sum:</p> <pre><code>merged = tf.keras.layers.Average()([meta_output_layer, img_output_layer]) </code></pre>
tensorflow|keras|deep-learning|conv-neural-network
0
9,165
67,434,966
why scipy.sparse.linalg.LinearOperator has different behaviors with @, np.dot and np.matmul
<p>I thought that when it comes to matrix-vector multiplication, the <code>@</code> operator and the functions <code>np.dot</code> and <code>np.matmul</code> were all 3 equivalent. They give the same result when the matrix is a <code>np.ndarray</code>:</p> <pre class="lang-py prettyprint-override"><code>import numpy as...
<p><code>lM</code> is not a <code>numpy</code> array, or subclass of that. <code>np.array(lM)</code> produces <code>()</code> shape object dtype array. That's why it doesn't work in <code>matmul</code>. <code>lM@a</code> and <code>lM.dot(a)</code> delegate the task to lM methods. The others make the erroneous conversio...
arrays|numpy|scipy
1
9,166
65,409,958
pandas:calculate jaccard similarity for every row based on the value in multiple columns
<p>I have a dataframe that looks like the following, but with more rows. for each document in the fist column there are some similar labels in the second column and some strings in the last column.</p> <pre><code>import pandas as pd data = {'First': ['First doc', 'Second doc','Third doc','First doc', 'Second doc','Th...
<p>ok, I figured how to do that with help from <a href="https://stackoverflow.com/questions/65308769/pandascalculate-jaccard-similarity-for-every-row-based-on-the-value-in-another">this response by Amit Amola</a> so what I did was to refine the code to get all combinations:</p> <pre><code>from itertools import combinat...
python|pandas|similarity
0
9,167
65,362,523
How to select a minimum validation dataset that represents all variance?
<p>I have a dataset of 2000 256 x 256 x 3 images to train a CNN model (with approximately 30 million trainable parameters) for pixel wise binary classification. Before training it I would like to divide it into validation and test set. Now, I have gone thru all the answers from <a href="https://stackoverflow.com/questi...
<p>Tried and refused:</p> <p><strong>1. Feature detectors and descriptors</strong> - Detectors won't be a good approximation of an image and descriptors were long vectors. I discarded this because at this time I did not know about the desired solution. This can be rethinked upon.</p> <p><strong>2. Autoencoders</strong>...
python|tensorflow|deep-learning
0
9,168
65,320,588
Defined Nelson-Siegel function not callable in Python
<p>I am trying to replicate the Nelson-Siegel (1987) model of the Yield Curve. I am new of Python (previously working in R) and I wrote the following function:</p> <pre><code>def nelson_siegel(tau, beta1, beta2, beta3, lambda1): return ( beta1 + beta2*(1-np.exp(-tau/lambda1))/(tau/lambda1) + beta3((...
<pre><code>def nelson_siegel(tau, beta1, beta2, beta3, lambda1): return ( beta1 + beta2*(1-np.exp(-tau/lambda1))/(tau/lambda1) + beta3 * ((1-np.exp(-tau/lambda1))/(tau/lambda1)-np.exp(-tau/lambda1)) ) </code></pre> <p>You haven't used <code>*</code> operator after beta3</p>
python|function|numpy|scipy
1
9,169
65,085,091
Dask - return a dask.dataframe on map_partition call
<p>I'm wondering How can I return a dask Dataframe when I call a <code>map_partitions</code> instead of a pd.Dataframe in order to avoid memory issues.</p> <p>Input Dataframe</p> <pre><code>id | name | pet_id --------------------- 1 Charlie pet_1 2 Max pet_2 3 Buddy pet_3 4 Oscar pet_4 </code...
<p>Short answer: no (sorry)</p> <p>The purpose of <code>map_partitions</code> is to act on each of the constituent pandas dataframes of a dask dataframe. The expectation is, that you will be making a new dataframe of the same number of partitions as the original. I think you are wanting to split each partition into man...
python-3.x|pandas|dataframe|dask|dask-dataframe
0
9,170
50,195,341
Tensorflow: is there a way to load a pretrained model without having to redefine all the variables?
<p>I'm trying to split my code into different modules, one where the model is trained, another which analyzes the weights in the model. </p> <p>When I save the model using </p> <pre><code>save_path = saver.save(sess, "checkpoints5/text8.ckpt") </code></pre> <p>It makes 4 files, ['checkpoint', 'text8.ckpt.data-00000-...
<p>For just accessing variables in checkpoints, please checkout the <a href="https://www.github.com/tensorflow/tensorflow/blob/r1.8/tensorflow/python/training/checkpoint_utils.py" rel="nofollow noreferrer"><code>checkpoint_utils</code></a> library. It provides three useful api function: <code>load_checkpoint</code>, <c...
tensorflow
1
9,171
49,991,670
How can I turn data imported into python from a csv file to time-series?
<p>I want to turn data imported into python through a .csv file to time-series. </p> <pre><code>GDP = pd.read_csv('GDP.csv') [87]: GDP Out[87]: GDP growth (%) 0 0.5 1 -5.2 2 -7.9 3 -9.1 4 -10.3 5 -8.8 6 -7.4 7 -10.1 8...
<p>Use <code>set_index</code></p> <pre><code>df gdp 0 0.5 1 -5.2 2 -7.9 3 -9.1 4 -10.3 5 -8.8 6 -7.4 7 -10.1 8 -8.4 9 -8.7 10 -7.9 11 -4.1 df = df.set_index(pd.date_range(start = '01-2010', end = '01-2013',freq = 'Q')) gdp 2010-03-31 0.5 2010-06-30 -5.2 2010-09-30 -7.9 2010-1...
python|pandas|csv|time-series|date-range
2
9,172
50,029,927
pandas groupby multiple functions
<p>I want summarize the <code>integer_transaction</code> by <code>EMP_NAME</code>. </p> <ol> <li>why does my first command fail? How to modify it</li> <li>in case of the second command how to avoid the warning?</li> <li>Is there any way to put <code>EMP_NAME</code> in a column instead of the index</li> </ol> <p>I wan...
<p>Try</p> <pre><code> df.groupby(['EMP_NAME'])['integer_transaction'].agg(["count", "sum"]) count sum EMP_NAME a 2 1 b 1 0 </code></pre> <p>If you really want, you can rename the columns using an additional <code>.rename("count": "Frequency_count", "sum": "Freque...
python|pandas|group-by
5
9,173
46,681,909
Change SSD network (Single Shot Multibox Detector) for two class detection
<p>I have used this link: <a href="https://github.com/albanie/wider2pascal" rel="nofollow noreferrer">https://github.com/albanie/wider2pascal</a> to change Widerface dataset annotations to Pascalvoc format, because SSD network is originally written for PascalVoc dataset. Now we want to run SSD network. What should we ...
<p><a href="https://github.com/pierluigiferrari/ssd_keras" rel="nofollow noreferrer">This SSD implementation</a> provides tools and a tutorial on how to use a trained SSD for transfer learning on your own dataset. The solution (or at least one possible solution, the tutorial explains multiple alternatives) is to sub-sa...
python-3.x|tensorflow|deep-learning|face-detection|object-detection
0
9,174
67,837,239
Why this PyTorch regression program reaches zero loss with periodic oscillations?
<p>There is one x and one t with with dimensions 3x1. I am trying to find the w (3x3) and b (3,1) so they can please this equation:</p> <pre><code>t = w*x + b </code></pre> <p>The program below does oscillate. I tried to debug it with no success. Can someone else take a look? What did I miss?</p> <p><a href="https://i....
<p>You need to reset the gradient to 0 after each backprop. By default, pytorch accumulates gradients when you call <code>loss.backward()</code>.</p> <p>Replacing the last 2 instructions of your loop with the following lines should fix the issue :</p> <pre><code>with torch.no_grad(): model.w.data = model.w.data - a...
pytorch|linear-regression
1
9,175
67,822,416
Extract co-occurrence data from dataframe
<p>I have something like this:</p> <pre><code> fromJobtitle toJobtitle size 0 CEO CEO 65 1 CEO Vice President 23 2 CEO Employee 56 3 Vice President CEO 112 4 Employee CEO 20 </code><...
<p>Try:</p> <pre><code>df.groupby(lambda x: tuple(sorted(df.loc[x, ['fromJobTitle', 'toJobTitle']]))).sum() </code></pre> <p>Here is the result:</p> <pre><code> size (CEO, CEO) 65 (CEO, Employee) 76 (CEO, Vice President) 135 </code></pre>
python|pandas|dataframe|find-occurrences
2
9,176
67,869,032
Error when trying to find a string in a column
<p>I am trying to find an ID in a dataframe column.</p> <p>If it exists then the new df will be converted to the correspondent one, but it raises an error.</p> <p>Where could be the mistake?</p> <pre class="lang-py prettyprint-override"><code>df = pd.read_excel('somefile.xlsx') ids = df['ID'].to_list() for id in ids: ...
<p><code>df[&quot;ID&quot;]</code> will try to access the ID column - that you <strong>don't</strong> have.</p> <p>If you refer to the rows index, then you can just change this statement with:</p> <pre class="lang-py prettyprint-override"><code>ids = df.index.to_list() </code></pre>
python|pandas
1
9,177
61,522,442
Input not compatible
<p>I am training the dataset for Amazon fine foods review. The code that I have written for it is showing an error as-<br> Encoder_Decoder LSTM... /opt/conda/lib/python3.7/site-packages/ipykernel_launcher.py:66: UserWarning: Update your <code>LSTM</code> call to the Keras 2 API: <code>LSTM(10, return_sequences=True, re...
<p>Normally in the traceback you obtain after the error you get will guide you to the error's origin (line of code). And the traceback is usually sequential by depth, i.e. the last one corresponds the most shallow call that gave the error. Normally the most shallow call in you case should be line 198 <code>trained_mode...
python|pandas|numpy|keras
0
9,178
61,459,111
How to apply a Pandas filter on a data frame based on entries in a column from a different data frame (no join)
<p>As an example, I have one data frame (df_1) with one column which contains some text data. The second data frame (df_2) contains some numbers. How do I check if the text contains the numbers from the second data frame?</p> <p><strong>df_1</strong></p> <pre><code> Note 0 The code to this is 1...
<p>Do this:</p> <pre><code>df_1.loc[df_1['Note'].apply(lambda x: any(str(number) in x for number in df_2['Code_Number']))] </code></pre>
python|pandas|data-analysis
1
9,179
61,302,847
Pandas: How to merge two data frames and fill NaN values using values from the second data frame
<p>I have a pandas dataframe (df1) that looks like this: </p> <pre><code>No car pl. Value Expected 1 Toyota HK 0.1 0.12 1 Toyota NY 0.2 NaN 2 Saab LOS 0.3 NaN 2 Saab UK 0.4 ...
<p>Since we have two key columns where we want to match on and update our <code>df1</code> dataframe, we can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>set_index</code></a> with <a href="https://pandas.pydata.org/pandas-docs/s...
python|pandas|dataframe|merge|fillna
2
9,180
68,746,406
How to find the index of a given item in a list in a pandas column and extract the address from a column
<p>I have a list</p> <pre><code>In [1]:list=['AM','PM','MT'] </code></pre> <p>and i have a df like this</p> <pre><code>In [1]:d= {'Date': ['8/10/2021','8/10/2021','8/11/2021','8/11/2021','8/11/2021','8/11/2021','8/11/2021'], 'Name': [ 'John','Jason','Derek','Foley','Jason','Derek J','Derek M'], 'Notes':['John i...
<p>Maybe something like this will work?</p> <pre><code>import pandas as pd # create a simple data frame df = pd.DataFrame(np.ones((5,5)), columns={'a','b','c','d','e'}, index={'1/1/2020', '2/1/2020', '3/1/2020', '4/1/2020','5/1/2020'}) # add some values to look for df['g'] = [6,7...
python|regex|pandas|dataframe|indexing
0
9,181
68,589,507
How to compare dates in 2 DFs and count number of event occurred within 30 days
<p>I have 2 dataframes:</p> <ol> <li>df1</li> </ol> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;"></th> <th style="text-align: left;">client_id</th> <th style="text-align: left;">prediction_date</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">0</td> <t...
<p>Idea is use broadcasting for compare columns converted to numpy arrays, subtract and compare if between 0 and 30 days, last <code>sum</code> for counter:</p> <pre><code>df1['prediction_date'] = pd.to_datetime(df1['prediction_date']) df2['Opened'] = pd.to_datetime(df2['Opened']) arr = (df1['prediction_date'].to_num...
python|pandas
2
9,182
68,538,765
Compute Weighted Profit Total for Each Item Sold
<p>I'm currently working through some sales data in Pandas and I'm attempting to find the most profitable item (We sell a range of various items), but this is weighted in order to truely find the item that generates the most profit. This may be a NumPy question. The equation looks like this:</p> <pre><code> (Individ...
<p>try via <code>groupby()</code> and <code>sum()</code> and <code>count()</code> method:</p> <pre><code>g=df.groupby('Item Type',sort=False) out=g['Profit'].sum()*(g['Profit'].count()/len(df)) #Since the sum of total counts is equal to the length of df so we are using len(df) #OR #g['Profit'].sum()*(g['Profit'].count(...
python|pandas|dataframe
0
9,183
68,452,598
difference between df.loc[:, columns] and df.loc[:][columns]
<p>I want to normalize some columns of a pandas data frame using <code>MinMaxScaler</code> in this way:</p> <pre><code>scaler = MinMaxScaler() numericals = [&quot;TX_TIME_SECONDS&quot;,'TX_Amount'] </code></pre> <p>while I do in this way:</p> <pre><code>df.loc[:][numericals] = scaler.fit_transform(df.loc[:][numericals]...
<p><code>df.loc[:][numericals]</code> selects all rows and then selects columns &quot;TX_TIME_SECONDS&quot; and 'TX_Amount' of the <strong>returning object</strong>, and assigns some value to it. The problem is, the returning object might be a copy so this may not change the actual DataFrame.</p> <p>The correct way of ...
python|pandas|dataframe
1
9,184
53,055,027
Find the two most recent dates for each customer in Python using pandas
<p>I have a pandas dataframe with purchase date of of each customer. I want to find out most recent purchase date and second most recent purchase date of each unique customer. Here is my dataframe:</p> <pre><code> name date ab1 6/1/18 ab1 6/2/18 ab1 6/3/18 ab1 6/4/18 ab2 6/...
<p>To get the two most recent purchase date for each customer, you can first sort your dataframe in descending order by date, then groupby the name and convert the aggregated dates into individual columns. Finally just take the first two of these columns and you'll have just the two most recent purchase dates for each ...
python|pandas
5
9,185
52,949,798
python - how to delete duplicate list in each row (pandas)?
<p>I have a list contained in each row and I would like to delete duplicated element by keeping the highest value from a score. </p> <p>here is my data from data frame df1</p> <pre><code> pair score 0 [A , A ] 1.0000 1 [A , F ] 0.9990 2 [A , G ] 0.9985 3 [A , G ] 0.9975 4 [A , H ] 0...
<p>First I think working with <code>list</code>s in pandas is not <a href="https://stackoverflow.com/a/52563718/2901002">good idea</a>.</p> <p>Solution working if convert lists to helper column with tuples - then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nof...
python|pandas|list
1
9,186
53,227,491
Number of missing entries when merging DataFrames
<p>In an exercise, I was asked to merge 3 DataFrames with inner join (df1+df2+df3 = mergedDf), then in another question I was asked to tell how many entries I've lost when performing this 3-way merging.</p> <pre><code>#DataFrame1 df1 = pd.DataFrame(columns=["Goals","Medals"],data=[[5,2],[1,0],[3,1]]) df1.index = ['Arg...
<p>I've found a simple but effective solution:</p> <h2>Merging the 3 DataFrames, inner and outer:</h2> <pre><code>df1 = Df1() df2 = Df2() df3 = Df3() inner = pd.merge(pd.merge(df1,df2,on='&lt;Common column&gt;',how='inner'),df3,on='&lt;Common column&gt;',how='inner') outer = pd.merge(pd.merge(df1,df2,on='&lt;Common c...
python|pandas|dataframe
4
9,187
52,924,546
How to convert a ndarray into opencv::Mat using Boost.Python?
<p>I am reading an image in Python and passing that numpy array to C++ using Boost.Python and receiving that in <code>ndarray</code>.</p> <p>I need to convert the same into <code>cv::Mat</code> to perform operations in OpenCV C++. </p> <p>How do I do that?</p>
<p>Finally I found the solution for that from the documentations:</p> <p>We Have to receive the numpy array as <code>numeric::array</code> in C++ and have to do the following steps to easily convert the numpy into <code>cv::mat</code> efficiently.</p> <pre><code>void* img_arr = PyArray_DATA((PyObject*)arr.ptr()); </c...
python-3.x|c++11|boost-python|mat|numpy-ndarray
1
9,188
65,898,885
Failed to construct interpreter TensorflowLite
<p>I am using `</p> <blockquote> <p>Cuda 10.1, cudnn 7.6, Tensorflow 2.3.0, keras 2.4.3</p> </blockquote> <p>When training model I use <code>save_weights_only=True</code>, and a folder is saved including:</p> <blockquote> <p>assets, variables and saved_model.pb</p> </blockquote> <p>When i am converting the model to a t...
<p>Problem resolved through changes of packages versions.</p> <blockquote> <p>Tensorflow = 2.0.0 &amp; Keras = 2.3.1</p> </blockquote>
python-3.x|tensorflow|keras
0
9,189
65,810,901
Remove selected area from picture PILLOW
<pre><code>import numpy from PIL import Image, ImageDraw im = Image.open(&quot;image.jpg&quot;).convert(&quot;RGBA&quot;) imArray = numpy.asarray(im) polygon = [(700,150),(1200,150),(1200,450),(1000,650),(700,650)] maskIm = Image.new('L', (imArray.shape[1], imArray.shape[0]), 0) ImageDraw.Draw(maskIm).polygon(polygo...
<p>It seems like you need to invert your mask - currently, you have 0 around your polygon and 1 inside.</p> <p>try to change <code>newImArray[:,:,3] = mask*255</code> to <code>newImArray[:,:,3] = (1-mask)*255</code></p>
python|python-3.x|numpy|python-imaging-library
1
9,190
63,399,155
Adding columns in one dataframe from calculations based on other dataframe using pandas library
<p>I have a dataframe df1 like:</p> <pre><code> cycleName quarter product qty price sell/buy 0 2020 q3 wood 10 100 sell 1 2020 q3 leather 5 200 buy 2 2020 q3 wood 2 200 buy 3 2020 q4 wood 12 40 se...
<p>You can map <code>sell</code> as 1 and <code>buy</code> as -1 using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>pd.Series.map</code></a> then multiply columns <code>qty</code>, <code>price</code> and <code>sell/buy</code> using <a href="...
python|pandas|dataframe
1
9,191
53,395,329
Should Dropout masks be reused during Adversarial Training?
<p>I am implementing adversarial training with the FGSM method from <a href="https://arxiv.org/abs/1412.6572" rel="nofollow noreferrer">Explaining and Harnessing Adversarial Examples</a> using the custom loss function:</p> <p><a href="https://i.stack.imgur.com/RG7eB.png" rel="nofollow noreferrer"><img src="https://i.s...
<p>I tried out reusing the dropout masks during the adversarial training step's feed-forward pass with a simple CNN on MNIST. I chose the same network architecture as the one used in this <a href="https://github.com/tensorflow/cleverhans/blob/master/cleverhans_tutorials/mnist_tutorial_keras_tf.py" rel="nofollow norefer...
python|tensorflow|keras|neural-network|conv-neural-network
2
9,192
72,032,964
rearrange dataframe multi-level columns by inverting the levels
<p>Given a <code>pandas.DataFrame</code> with a column <code>MultiIndex</code> as follows</p> <pre><code>A B C X Y Z X Y Z X Y Z </code></pre> <p>how to rearrange the columns into this format?</p> <pre><code>X Y Z A B C A B C A B C </code></pre> <p>(I tried <code>.columns.swaplevel(0,1)</code>, but ...
<p><code>df.swaplevel</code> with <code>axis=1</code> (for columns) is what you need.</p> <pre><code>&gt;&gt;&gt; df.swaplevel(0,1, axis=1) X Y Z X Y Z X Y Z A A A B B B C C C 0 x x x x x x x x x </code></pre> <p>You can use <code>sort_index</code> to sort:</p> <pre><code>&gt;&gt;&gt; df....
python|pandas|dataframe|multi-index
3
9,193
71,816,710
Selecting random values from a pandas dataframe and adding constant to them
<p>let's say I have a pandas dataframe, I want to select a column of the dataframe and add values to its existing values randomly, in other words, I want to select random values from that column and add some constant to them. What I did is I selected a sample with</p> <pre><code>df['column_in_question'].sample(frac=0.2...
<p>You can get the sampled indexes and adding value by selecting with these indexes</p> <pre class="lang-py prettyprint-override"><code>indexes = df['column_in_question'].sample(frac=0.2, random_state=1).index df.loc[indexes, 'column_in_question'] += 1000 # or df['Number'] = df['Number'].mask(df.index.isin(indexes)...
python|pandas|dataframe
1
9,194
71,875,550
Scraping non-interactable table from dynamic webpage
<p>I've seen a couple of posts with this same question but their scripts usually waits until one of the elements (buttons) is clickable. Here is the table I'm trying to scrape:</p> <p><a href="https://ropercenter.cornell.edu/presidential-approval/highslows" rel="nofollow noreferrer">https://ropercenter.cornell.edu/pres...
<p>Maybe more cheating, but easier solution, which indeed solves your problem, but in other way, would be to take a look what frontend does (using developer tools), and discover it calls the api, which returns JSON value, so no selenium is really needed. <code>requests</code> and <code>pandas</code> are enough.</p> <pr...
python|pandas|selenium|web-scraping|geckodriver
2
9,195
55,487,921
Markevry in df.pyplot
<p>I have a problem with function <code>markevry</code> in dataframe plot in pandas. I want to mark the max value in every column on the plot. I tried compile this in Pycharm on python 3. My code as follow:</p> <pre><code>#projektII import pandas as pd import matplotlib.pyplot as plt dane = pd.read_table('xxx.txt', n...
<p>1st Change: try adjust these:</p> <pre><code>markers_on = data['kroliki'].max markers_on2 = data['lisy'].max markers_on3 = data['marchewki'].max </code></pre> <p>to this:</p> <pre><code>markers_on = data['kroliki'].max() markers_on2 = data['lisy'].max() markers_on3 = data['marchewki'].max() </code></pre> <p>2n...
python|pandas|dataframe
0
9,196
56,464,739
Sampling from tensorflow Dataset into same tensor multiple times per single session.run() call
<p>Consider the following example:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf import numpy as np X = np.arange(4).reshape(4, 1) + (np.arange(3) / 10).reshape(1, 3) batch = tf.data.Dataset.from_tensor_slices(X) \ .batch(2).make_one_shot_iterator().get_next() def foo(x): r...
<p>Yes, it's possible.</p> <p>A couple of insights on what you've tried so far:</p> <ol> <li>You can use the dataset iterator returned from <code>make_one_shot_iterator()</code> each time you need a new value from the dataset</li> <li>You can make your own function that is part of the tf graph to pass the result thro...
python|tensorflow|tensorflow-datasets
0
9,197
66,848,540
(tensorflow 2.4.1)how to get a ragged tensor has determinate last dimension shape?
<p>like this:<br /> '''</p> <pre><code>a = [1.0, 2.0, 3.0] b = [[a, a, a, a], [a, a, a], [a, a, a, a, a, a, a], [a, a]] c = tf.ragged.constant(b, dtype=tf.float32) </code></pre> <p>''' I got a tensor with shape : [4, None, None], but i expect [4, None, 3],</p>
<p>According to the documentation (<a href="https://www.tensorflow.org/api_docs/python/tf/RaggedTensor#uniform_inner_dimensions_2" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/RaggedTensor#uniform_inner_dimensions_2</a>), to get a uniform inner dimension on a ragged tensor, you need to start ...
tensorflow|ragged-tensors
2
9,198
67,065,069
Having an issue creating a separate quantile column based on a condition
<p>I am trying to create a new column that contains quantile information. The one condition I have for this new column is that I only need to produce a quantile value for rows where it equals a certain value from another column. I thought the code below would filter the data to the specific value (&quot;Below&quot;) an...
<p>You need to assign the values, to the rows where the condition is met. Try:</p> <pre><code>rsh_df.loc[rsh_df['ind_comp'] == &quot;Below&quot;, 'pcf_q'] = ( rsh_df .loc[rsh_df['ind_comp'] == &quot;Below&quot;, 'pcf'] .quantile(0.05) ) </code></pre>
pandas
0
9,199
47,369,827
How to join Multi-level dataframe on values in single-level dataframe
<p>what I have so far is a normal transactional dataframe with the following columns:</p> <pre><code>store | item | year | month | day | sales </code></pre> <p>'year' can be 2015, 2016, 2017. </p> <p>With that I created a summary dataframe:</p> <pre><code>store_item_years = df.groupby( ['store','item','year'])['sal...
<p>I think you need first remove <code>unstack</code> and then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.join.html" rel="nofollow noreferrer"><code>join</code></a> for left join:</p> <pre><code>store_item_years = df.groupby( ['store','item','year'])['sales'].agg( [np.sum, np.m...
pandas|join|dataframe|merge|multi-index
2