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
3,300
51,342,841
how to remove this warning in python 3
<p>trying to lower and strip a column in python 3 using panda, but getting the warning-- what is the right way so this warning will not come up </p> <pre><code>df["col1"] = df[["col1"]].apply(lambda x: x.str.strip()) df["col1"] = df[["col1"]].apply(lambda x: x.str.lower()) </code></pre> <p>The warning</p> <pre><code...
<p>To get rid of this warning apply it to a series instead of a dataframe. Using <code>df[["col1"]]</code> is creating a new dataframe that you are then setting to the column. If you instead just modify the column it'll be fine. Additionally, I chained the two together.</p> <pre><code>df["col1"] = df["col1"].str.stri...
python|python-3.x|pandas
1
3,301
51,405,517
How to iterate through tensors in custom loss function?
<p>I'm using keras with tensorflow backend. My goal is to query the <code>batchsize</code> of the current batch in a <strong>custom loss</strong> function. This is needed to compute values of the custom loss functions which depend on the index of particular observations. I like to make this clearer given the minimum re...
<p>As usual, don't loop. There are severe performance drawbacks and also bugs. Use only backend functions unless totally unavoidable (usually it's not unavoidable)</p> <hr> <h2>Solution for example 3:</h2> <p>So, there is a very weird thing there... </p> <blockquote> <p>Do you really want to simply ignore half of...
python|tensorflow|keras|loss-function
4
3,302
48,127,096
GroupBY frequency counts JSON response - nested field
<p>I'm trying aggregate the response from an API call that returns a JSON object and get some frequency counts.</p> <p>I've managed to do it for one of the fields in the JSON response, but a second field that I want to try the same thing isn't working</p> <p>Both fields are called "category" but the one that isn't wo...
<p>I think you will have the easiest time of it, if you expand the dict in the <code>"outcome_status"</code> column like:</p> <h3>Code:</h3> <pre><code>outcome_status = [ {'outcome_status_' + k: v for k, v in z.items()} for z in ( dict(category=None, date=None) if x is None else x for x in (y['out...
python|json|python-3.x|pandas|pandas-groupby
1
3,303
48,256,372
Neural Machine Translation model predictions are off-by-one
<p><strong>Problem Summary</strong></p> <p>In the following example, my NMT model has high loss because it correctly predicts <code>target_input</code> instead of <code>target_output</code>.</p> <pre><code>Targetin : 1 3 3 3 3 6 6 6 9 7 7 7 4 4 4 4 4 9 9 10 10 10 3 3 10 10 3 10 3 3 10 10 3 9...
<p>The core issue with the NMT model used to predict a language-like syntax with a repetitive structure is that it becomes incentivized to simply predict whatever the past prediction was. Since it is fed the correct previous prediction at each step by <code>TrainingHelper</code> to speed up training, this artificially ...
python|tensorflow|machine-learning|recurrent-neural-network|tensorflow-datasets
1
3,304
48,239,019
Shape must be rank 1 but is rank 0 for 'CTCLoss' (op: 'CTCLoss')
<p>I've successfully converted a Tensor into a SparseTensor with this code:</p> <pre><code>def dense_to_sparse(dense_tensor, out_type): indices = tf.where(tf.not_equal(dense_tensor, tf.constant(0, dense_tensor.dtype) values = tf.gather_nd(dense_tensor, indices) shape = tf.shape(dense_tensor, out_type=out_t...
<p>From the Tensorflow documentation <a href="https://www.tensorflow.org/versions/r0.12/api_docs/python/nn/connectionist_temporal_classification__ctc_#ctc_loss" rel="nofollow noreferrer">https://www.tensorflow.org/versions/r0.12/api_docs/python/nn/connectionist_temporal_classification__ctc_#ctc_loss</a></p> <blockquot...
tensorflow|lstm
1
3,305
48,020,122
Currently Animating Scatter Plot With Static Frames. Is there a way to animate over a moving window instead?
<p>I have an array of arrays with format <code>[2000][200,3]</code> that I am creating an animated scatter plot of. 2000 is the number of frames and the interior arrays have format <code>[length, [x,y,inten]]</code> which are the points to scatter. So for an example a single frame will look like:</p> <pre><code>Array...
<p>The code below steps continuously through my array of points with a given step size and window of 200 instead of discretely binning every 200.</p> <pre><code>stepsize=10 NewArray=np.ravel(Array) NewArray.reshape(2000*200,3) plt.ion() fig, ax = plt.subplots() norm = plt.normalize(NewArray[:,2].min(), NewArray[:,2]....
python|numpy|animation|matplotlib|plot
0
3,306
48,016,370
How to split a CSV column with repeated text into split 0-1 columns for each possible text variant?
<p>I have a CSV with a column like</p> <pre><code>LABEL a b a a c n o ye s </code></pre> <p>I want to split it into something like:</p> <pre><code>LABEL_a LABEL_b LABEL_c LABEL_n_o LABEL_ye_s 1 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 ...
<p>Using <code>get_dummies</code></p> <pre><code>s.str.get_dummies().add_prefix('label_') Out[19]: label_a label_b label_c label_n o label_ye s 0 1 0 0 0 0 1 0 1 0 0 0 2 1 0 0 0 0 3 1 ...
python|pandas|csv
3
3,307
48,335,755
df.loc is giving key error in linux environment where the same code is working fine in mac?
<p>I have a dataframe like this </p> <pre><code> key epic uname port 0 PORT-100 None user5 None 1 PORT-101 None user1 None 2 PORT-102 None NA None 3 PORT-103 None NA None 4 PORT-104 None user2 None 5...
<p>As noted in the comments, this may be due to different versions of pandas being used. At any rate, the more idiomatic way of doing this is to use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html#pandas.Series.map" rel="nofollow noreferrer"><code>Series.map</code></a>. You can re...
pandas|dataframe
3
3,308
48,713,967
Uploading CSV files to Fusion Tables through Python
<p>I am trying to grab data from looker and insert it directly into Google Fusion Tables using the MediaFileUpload so as to not download any files and upload from memory. My current code below returns a TypeError. Any help would be appreciated. Thanks! </p> <p>Error returned to me:</p> <pre><code>Traceback (most rece...
<p><a href="http://pandas.pydata.org/pandas-docs/version/0.13.1/generated/pandas.DataFrame.to_csv.html#pandas.DataFrame.to_csv%20Df" rel="nofollow noreferrer"><code>DataFrame.to_csv</code> is a void method</a> and any side effects from calling it are passed to <code>stream</code> and not <code>dataq</code>. That is, <c...
python-3.x|pandas|file-upload|stream|google-fusion-tables
1
3,309
48,750,682
Pandas - flattening a multiindex column containing tuples, but ignore missing values
<p>I have a multiindex pandas dataframe like this:</p> <pre><code>lst = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, 12), (13, 14), (21, 22)] df = pd.DataFrame(lst, pd.MultiIndex.from_product([['A', 'B'], ['1','2', '3', '4']])).loc[:('B', '2')] df["tuple"] = list(zip(df[0], df[1])) #df: 0 1 tuple A 1 ...
<p>Is this what you need ? </p> <pre><code>df.groupby(level=[0]).tuple.apply(list) Out[306]: A [(1, 2), (3, 4), (5, 6), (7, 8)] B [(9, 10), (11, 12)] Name: tuple, dtype: object </code></pre>
python|python-3.x|pandas|multi-index
3
3,310
48,554,149
How to rewrite a tensorflow's checkpoint files?
<p>I want to change a ckpt files's tensor's value by many other ckpt files's tensors, and use the modified ckpt files to restart TF training jobs. Hope you some advices! Thanks!</p>
<p>There are standalone utilities for reading checkpoint files (search for <code>CheckpointReader</code> or <code>NewCheckpointReader</code>) but not modifying them. The easiest approach is probably to load the checkpoint into your model, assign a new value to the variable you want to change, and save this new checkpoi...
tensorflow
1
3,311
48,701,827
numpy - 1 field value in 3d array from a 1d array
<p>I have this issue, I'm trying to build a 3D array where I need later to overwrite eg. [:,:,5] with a value from a 1D array. My arrays look like this in <code>numpy</code>:</p> <p>3D:</p> <pre><code>[[[ 0. 150. 10. 300. 25. 0.] [ 1. 25. 2. 75. 7. 0.] [ 4. 0. 0. 0. 0. 0...
<p>Your array <code>list_product_pricegroup</code> is 10x4x6 and <code>migrete_array</code> is a 1-D vector of 10. Since you index (5) the array <code>list_product_pricegroup</code> before assignment, it is now a 10x4 matrix. Then you need to promote <code>migrete_array</code> to a 2-D array of size 4x1 to be broadcast...
python|arrays|numpy
2
3,312
48,610,132
Tensorflow crash with CUDNN_STATUS_ALLOC_FAILED
<p>Been searching the web for hours with no results, so figured I'd ask here.</p> <p>I'm trying to make a self driving car following Sentdex's tutorial, but when running the model, I get a bunch of fatal errors. I've searched all over the internet for the solution, and many seem to have the same problem. However, none...
<p>In my case, the issue happened because another python console with <code>tensorflow</code> imported was running. Closing it solved the problem.</p> <p>I have Windows 10, the main errors were :</p> <blockquote> <p>failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED</p> <p>Could not create cudnn handle: CUDNN_S...
python|python-3.x|tensorflow|neural-network
12
3,313
48,716,906
Python - Concatenating two images and adding up their color channels
<p>I have two <code>500x500</code> images, and need to merge them together and add up their channels.</p> <p>When I used Numpy's concatenate function for instance, the returned output becomes <code>500x1000</code>, and not sure if the color channels are added at all. </p> <p>The output I'm looking for for merging two...
<p>a couple of options, if you want separate RGB or stuck together:</p> <pre><code>np.stack([np.zeros((2,2,3)), np.ones((2,2,3))], axis=2) Out[157]: array([[[[ 0., 0., 0.], [ 1., 1., 1.]], [[ 0., 0., 0.], [ 1., 1., 1.]]], [[[ 0., 0., 0.], [ 1., 1., 1.]], ...
python|numpy|opencv
0
3,314
70,973,324
What does it mean torch.rand(1, 3, 64, 64)?
<p>I am beginner in PyTorch. In one tutorial, I saw: <strong>torch.rand(1, 3, 64, 64)</strong>, I understand that it creates a Tensor with random numbers following standard normal distribution.</p> <p>The outputs looks like:</p> <pre><code>tensor([[[[0.1352, 0.5110, 0.7585, ..., 0.9067, 0.4730, 0.8077], [0.2...
<p>These parameters refer to the tensor dimension. In concrete, this code snippet will generate a 4-dimension tensor of random values between 0 and 1.</p>
python|pytorch
1
3,315
51,884,792
Pandas - Insert blank row for each group in pandas
<p>I have a dataframe</p> <pre><code>import pandas as pd import numpy as np df1=pd.DataFrame({'group':[1,1,2,2,2], 'value':[2,3,np.nan,5,4]}) df1 group value 0 1 2 1 1 3 2 2 NaN 3 2 5 4 2 4 </code></pre> <p>I want to add a row after each group in which the v...
<h3><code>concat</code> with <code>append</code></h3> <pre><code>s = df1.groupby('group') out = pd.concat([i.append({'value': np.nan}, ignore_index=True) for _, i in s]) out.group = out.group.ffill().astype(int) </code></pre> <h3><code>apply</code> with <code>append</code><sup>[1]</sup></h3> <pre><code>df1.groupby('...
python|pandas|dataframe
7
3,316
51,667,769
tf.Print not working if the graph is broken
<p>I'm trying to build a fully convolutional neural network. My problem is that at some phase the shape of the tensors no longer match, causing and Exception, and I would like to print the shape of the tensors after each step to be able to pin point the problem. However the problem is that the tf.Print does not seem to...
<p><code>tf.Print</code> only prints during runtime. It simply adds a node to the graph that upon execution prints something to the console. So, if your graph cannot be constructed, i.e. no computations can be executed, you will never see an output from <code>tf.Print</code>.</p> <p>At construction time, you can only ...
python|debugging|tensorflow
0
3,317
51,917,032
splitting csv files in pandas on python
<p>I am trying to load a spec column in pandas but it keep printing me the name of the column and also it skips the first part</p> <p>can anyone help me?</p> <p>this is the code i am using:</p> <pre><code>import pandas as pd pd.set_option('display.max_colwidth', -1) df_iter = pd.read_csv('tweets.csv', chunksize=10...
<p>Firstly, Since you are reading the csv in chunks, I would assume that the file is very large. You need to loop through those chunks to read all the data of the file. Then you can merge / concatenate all these chunks.</p> <p>Second thing, enumerate() is not for dataframes. You need iterrows().</p> <p>Something lik...
python|pandas
0
3,318
64,206,483
Creating python data frame from list of dictionary
<p>I have the following data:</p> <pre><code>sentences = [{'mary':'N', 'jane':'N', 'can':'M', 'see':'V','will':'N'}, {'spot':'N','will':'M','see':'V','mary':'N'}, {'will':'M','jane':'N','spot':'V','mary':'N'}, {'mary':'N','will':'M','pat':'V','spot':'N'}] </code></pre> <p>I want to create a data frame wh...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.value_counts.html" rel="nofollow noreferrer"><code>value_counts</code></a> per columns in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>DataFrame.appl...
python-3.x|pandas|dataframe
3
3,319
64,441,356
ModuleNotFoundError: No module named 'official'
<p>File &quot;/home/abir/.local/lib/python3.6/site-packages/object_detection/models/ssd_efficientnet_bifpn_feature_extractor.py&quot;, line 33, in from official.vision.image_classification.efficientnet import efficientnet_model ModuleNotFoundError: No module named 'official'</p>
<p>You need to install the module <code>tf-models-official</code>.</p> <ul> <li>First open Command Prompt in Windows or Terminal in Linux/Mac.</li> <li>In windows make sure <code>pip</code> is in path, then run:</li> </ul> <pre><code>pip install -U tf-models-official </code></pre> <ul> <li>If you have multiple versions...
python|tensorflow|keras|tensorflow2.0|object-detection
1
3,320
64,473,988
How to Create Partially Stacked Bar Plot
<p>I want to make a partially stacked bar plot of <em>n</em> elements where <em>n</em> - 1 elements are stacked, and the remaining element is another bar adjacent to the stacked bars of equal width. The adjacent bar element is plotted on a secondary y-axis and is typically a percentage, plotted between 0 and 1.</p> <p>...
<p>Let's try passing <code>align='edge'</code> and <code>width</code> to control the relative position of the bars:</p> <pre><code>ax = df.drop('D', axis=1).plot.bar(x='A', stacked=True, align='edge', width=-0.4) ax1=ax.twinx() df.plot.bar(x='A',y='D', width=0.4, align='edge', ax=ax1, color='C2') # manually set the ...
python|pandas|matplotlib
3
3,321
64,360,116
Error while installing Pandas and same kind of error while installing Datapane
<p>I am getting the following error when I try to install Pandas using pip install pandas. Python would install other modules correctly but not pandas and datapane. I am not sure what the error is saying, any help in fixing is appreciated.</p> <pre><code>Installing build dependencies ... error ERROR: Command errored ou...
<p>Maybe try installing it with pipwin.</p> <pre><code>pip install pipwin </code></pre> <p>then</p> <pre><code>pipwin install pandas </code></pre>
python|pandas|pip|datapane
0
3,322
64,356,199
Avoiding loops or list comprehension with numpy
<p>Is it possible to replace</p> <pre><code>np.concatenate([np.where(x == i)[0] for i in range(y)]) </code></pre> <p>with something that doesn't involve looping?</p> <p>I want to take an array x, e.g. [0, 1, 2, 0 , 2, 2], and a number y, e.g. 2 in this case, and output an array [0, 3, 1, 2, 4, 5]. E.g. for each integer...
<p>Here's an approach that uses <code>argsort</code>:</p> <pre><code># settings x = np.array([0, 1, 2, 0 , 2, 2]) y = 2 # sort the index u = np.argsort(x) # filter those that are larger than y mask = x[u]&lt;=y u[mask] </code></pre> <p>Output:</p> <pre><code>array([0, 3, 1, 2, 4, 5]) </code></pre>
python|performance|numpy
3
3,323
64,508,095
How to unstack after aggregation using Groupby in Pandas
<p>Hello Data Scientist and Pandas Experts,</p> <p>I need some help to figure out how to better organize my data after applying groupby aggregation method. I have tried unstack to new dataframe but it does not yield the intended results.</p> <p>Here is my data frame:</p> <pre><code>df = [{'Store': 's1', 'Date': Timest...
<p>The crux of your problem is that you need to restructure the data prior to using <code>.unstack()</code>, because your desired format is a matrix with the values being three repeated columns. So, you need to change your dataframe from wide to long and create a new column with these three values in one column <code>V...
python|pandas|dataframe|pandas-groupby
1
3,324
47,689,217
Attempting to append two Pandas DataFrames within a loop causes the first to be overwritten
<p>I have this function that (among other things) is supposed to read a baseball matches csv file create a list of all the teams (this part works). The file has away match data and home match data, the idea is to split the data change the columns and lastly append the matches data regardless of location (this last part...
<p>On each loop, you are reassigning the variable <code>noseclean_h</code>: </p> <pre><code>noseclean_h = df[df['Team {}'.format(located)].isin([unique[i]])] </code></pre> <p>Then, on each loop the <code>nosecleaned_h = nosecleaned_h.append(nosecleaned_h, ignore_index=False)</code> is replaced.</p>
python|pandas|dataframe|append|overlap
0
3,325
47,977,694
Getting the variance of each column in pandas
<p>I want to calculate the variance of features saved in a Train and Test file a followed :</p> <pre><code>col1 Feature0 Feature1 Feature2 Feature3 Feature4 Feature5 Feature6 Feature7 Feature8 Feature9 col2 26658 40253.5 3.22115e+09 0.0277727 5.95939 266.56 734.248 307.364 0.00...
<p>Just set the threshold to 0.0 and then use the <code>variances_</code> attribute of the VarianceThreshold object to get the variances of all your features, then you can identify which of them have lower variance.</p> <pre><code>from sklearn.feature_selection import VarianceThreshold X = [[0, 2, 0, 3], [0, 1, 4, 3],...
python|pandas|scikit-learn
2
3,326
48,900,977
Find all indexes of a numpy array closest to a value
<p>In a numpy array the indexes of all values closest to a given constant are needed. The background is digital signal processing. The array holds the magnitude function of a filter (<code>np.abs(np.fft.rfft(h))</code>) and certain frequencies (=indexes) are searched where the magnitude is e.g. 0.5 or in another case 0...
<pre><code>def findvalue(seq, value): diffseq = seq - value signseq = np.sign(diffseq) zero_crossings = signseq[0:-2] != signseq[1:-1] indices = np.where(zero_crossings)[0] for i, v in enumerate(indices): if abs(seq[v + 1] - value) &lt; abs(seq[v] - value): indices[i] = v + 1 ...
python|numpy|search
1
3,327
49,103,308
Pandas retrieve value in one column(s) corresponding to the maximum value in another
<p>Relatively new Python scripter here with a quick question about Pandas and DataFrames. There may be an easier method in Python to do what I am doing (outside of Pandas), so I am open to any and all suggestions.</p> <p>I have a large data-set (don't we all), with dozens of attributes and tens of thousands of entries...
<pre><code>np.random.seed(0) df = pd.DataFrame(np.random.randn(5, 3), columns=list('ABC')) df A B C 0 1.764052 0.400157 0.978738 1 2.240893 1.867558 -0.977278 2 0.950088 -0.151357 -0.103219 3 0.410599 0.144044 1.454274 4 0.761038 0.121675 0.443863 df.A.idxmax() 1 </code></pre> ...
python|pandas|dataframe
1
3,328
48,906,138
Pandas Dataframe: if row in column A, B or C contains “x” or "y", write “z” to new column
<p>Very similar to this question: <a href="https://stackoverflow.com/questions/30953299/pandas-if-row-in-column-a-contains-x-write-y-to-row-in-column-b">Pandas: if row in column A contains &quot;x&quot;, write &quot;y&quot; to row in column B</a></p> <p>I want to know if a row contains "x" or "y" in multiple different...
<p>Use <code>isin</code> with <code>any</code> and <code>astype</code></p> <pre><code>In [298]: cat_family = ["Cat", "Tiger", "Lion"] In [303]: df['CAT_FAMILY'] = df.isin(cat_family).any(1).astype(int) In [304]: df Out[304]: A B C CAT_FAMILY 0 Cat Dog Pig 1 1 Monkey Tiger Cat...
python|pandas|dataframe|contains
1
3,329
49,068,020
Filter DataFrame after sklearn.feature_selection
<p>I reduce dimensionality of a dataset (pandas DataFrame).</p> <pre><code>X = df.as_matrix() sel = VarianceThreshold(threshold=0.1) X_r = sel.fit_transform(X) </code></pre> <p>then I wanto to get back the reduced DataFrame (i.e. keep only ok columns)</p> <p>I found only this ugly way to do so, which is very ineffi...
<p>I think you need if return <code>mask</code>:</p> <pre><code>cols_OK = sel.get_support() df = df.loc[:, cols_OK] </code></pre> <p>and if return indices:</p> <pre><code>cols_OK = sel.get_support() df = df.iloc[:, cols_OK] </code></pre>
python|pandas|numpy|scikit-learn|dimensionality-reduction
2
3,330
58,792,421
Check which Python version Pandas is accessing
<p>My system is claiming that pandas requires a different Python, even though, that Python version is what's installed. How do I check which version of Python is being accessed by Pandas?</p> <pre><code>quinn@quinn-Lemur:~$ sudo -H pip3 install pandas Requirement already satisfied: pandas in /usr/local/lib/python3.5/d...
<p>Actually it says you have version <code>3.5.2</code> which is not high enough since <code>3.5.3</code> is needed.</p> <p>Try upgrading your Python first.</p>
python|pandas|pip
1
3,331
58,843,519
lemmatization issue using Spacy in pandas Series and Dataframe
<p>I am working on <a href="https://www.kaggle.com/crowdflower/twitter-airline-sentiment" rel="nofollow noreferrer">text data</a> having shape of (14640,16) using Pandas and Spacy for preprocessing but having issue in getting lemmetized form of text. Moreover, if I work with pandas series (i.e dataframe with one column...
<pre><code>#you can directly get your lemmatized token by running list comprehension in your lambda function df['parsed_tweets'] = df['text'].apply(lambda x: [y.lemma_ for y in nlp(x)]) </code></pre> <p><a href="https://i.stack.imgur.com/zgiN1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zgiN...
python|pandas|dataframe|series|spacy
4
3,332
58,850,101
Generate dataframe columns based on constraints in current dataframe
<p>I have a dataframe with the following columns : </p> <pre><code>Date_2 Date_1 is_B 02/08/2019 01/09/2019 1 02/08/2019 01/09/2019 1 02/08/2019 01/09/2019 0 02/08/2019 01/09/2019 0 . . . . . . . . . 31/08/2019 01/09/2019 0 31/08/2019 01/09/2019 0 31/08/2019 01/09/2019 0 31/08/2019 ...
<p>The answer has two parts.</p> <h3>Date parsing</h3> <p>It appears from the example, that date is <em>not</em> parsed - they are strings. They must be parsed to perform date operations.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd def dateparse(d): return pd.datetime.strptime(d, '%d...
python|pandas|numpy
4
3,333
58,979,824
How to do Cohen Kappa Quadratic Loss in Tensorflow 2.0?
<p>I'm trying to create the loss function according to:</p> <p><a href="https://stackoverflow.com/questions/54831044/how-can-i-specify-a-loss-function-to-be-quadratic-weighted-kappa-in-keras">How can I specify a loss function to be quadratic weighted kappa in Keras?</a></p> <p>But in tensorflow 2.0:</p> <pre><code>t...
<pre><code>def kappa_loss(y_pred, y_true, y_pow=2, eps=1e-10, N=4, bsize=256, name='kappa'): """A continuous differentiable approximation of discrete kappa loss. Args: y_pred: 2D tensor or array, [batch_size, num_classes] y_true: 2D tensor or array,[batch_size, num_classes] y_pow: int, e.g....
python|python-3.x|tensorflow|machine-learning|tensorflow2.0
4
3,334
58,672,185
Pytorch Hardware Requirement
<p><strong>What is the minimum Computation Capability required by the latest PyTorch version?</strong></p> <p>I have Nvidia Geforce 820M with computation capability 2.1. How can I run PyTorch models on my GPU <code>(if it doesn't support naturally)</code></p>
<p>Looking at <a href="https://pytorch.org/get-started/previous-versions/" rel="nofollow noreferrer">this page</a>, PyTorch (even the somewhat oldest versions) support CUDA upwards from version <code>7.5</code>. Whereas, looking at <a href="https://stackoverflow.com/questions/28932864/cuda-compute-capability-requiremen...
deep-learning|gpu|pytorch
4
3,335
58,951,331
How to do parallel GPU inferencing in Tensorflow 2.0 + Keras?
<p>Let's begin with the premise that I'm newly approaching to TensorFlow and deep learning in general.</p> <p>I have TF 2.0 Keras-style model trained using <code>tf.Model.train()</code>, two available GPUs and I'm looking to scale down inference times.</p> <p>I trained the model distributing across GPUs using the ext...
<p>Try to load model in <code>tf.distribute.MirroredStrategy</code> and use greater batch_size</p> <pre><code>mirrored_strategy = tf.distribute.MirroredStrategy() with mirrored_strategy.scope(): model = tf.keras.models.load_model(saved_model_path) result = model.predict(batch_size=greater_batch_size) </code></pre...
tensorflow|keras|predict|tensorflow2.0|multi-gpu
0
3,336
70,259,623
Define start and end date of several DataFrames with pandas
<p>I have many <code>DataFrames</code> which have a different period lengths. I am trying to create a <code>for loop</code> to define for all those DataFrames a specific start and end day.</p> <p>Here is a simple example:</p> <pre><code>df1: Dates ID1 ID2 0 2021-01-01 0 1 1 2021-01-02 0 0 2 2021-0...
<p>You can store your dataframes in a list, and then apply your <code>loc</code> formula on all the dataframes in the list using <code>list</code> comprehension, and return back a new list of the resulting filtered dataframes:</p> <pre><code># Create a list with your dataframes dfs = [df1 , df2] # Thresholds start = p...
python|pandas|dataframe|for-loop
3
3,337
70,078,251
Cannot run Carlini and Wagner Attack using foolbox on a tensorflow Model
<p>I am using the latest version of foolbox (3.3.1), and my code simply load a RESNET-50 CNN, adds some layers for a transferred learning application, and loads the weights as follows.</p> <pre><code>from numpy.core.records import array import tensorflow as tf from keras.applications.resnet50 import ResNet50, preproces...
<p>I think you might have mixed up the parameters of the <code>L2CarliniWagnerAttack</code>. Here is a simplified working example with dummy data:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf import numpy as np from tensorflow.keras.applications.resnet50 import ResNet50, preprocess_input...
python|tensorflow|keras|neural-network|adversarial-machines
1
3,338
70,368,812
how to compare columns of two dataframes (VLOOKUP) and add a value from other column to one dataframe?
<p>I have two dataframes of different sizes, both have many columns and I need to compare two columns that have a different name and if there is a match then add the value of another column to a new column. This is like a VLOOKUP in excel, search the ID of the dataframe 1 in the company_id of dataframe 2 and if there ...
<p>Use <code>merge</code>:</p> <pre><code>mapping = {'company_id': 'ID', 'Qty': 'extracted_qty'} out = df1.merge(df2.rename(columns=mapping)[['ID', 'extracted_qty']], on='ID') print(out) # Output: ID Area Dept extracted_qty 0 IDX1 A Dept 21 100 1 IDX2 B Dept 2 170 2 IDX3 ...
python|pandas
0
3,339
56,363,333
Tensorflow view graph from model.ckpt.meta file
<p>I have a <code>model.ckpt.meta</code> file and I just want to view the architecture/graph structure. I can't find how to do this from the <code>model.ckpt.meta</code> file.</p> <p>Following the code thanks to Milan:</p> <pre><code>tf.train.import_meta_graph("./model.ckpt.meta") for n in tf.get_default_graph().as_g...
<p>You can import the meta graph in python with <code>tf.train.import_meta_graph</code> and then traverse the nodes in the graph, for example:</p> <pre><code>import tensorflow as tf tf.train.import_meta_graph("./model.ckpt-200000.meta") for n in tf.get_default_graph().as_graph_def().node: print(n) </code></pre> <...
python|tensorflow
5
3,340
56,286,093
Write pandas dataframe into AWS athena database
<p>I have run a query using pyathena, and have created a pandas dataframe. Is there a way to write the pandas dataframe to AWS athena database directly? Like data.to_sql for MYSQL database. </p> <p>Sharing a example of dataframe code below for reference need to write into AWS athena database:</p> <pre><code>data=pd....
<p>Another modern (as for February 2020) way to achieve this goal is to use <a href="https://aws-data-wrangler.readthedocs.io/examples.html#typical-pandas-etl" rel="nofollow noreferrer">aws-data-wrangler</a> library. It's authomating many routine (and sometimes annoying) tasks in data processing.</p> <p>Combining the c...
python|database|pandas|amazon-athena
5
3,341
56,345,521
Replace dataframe multiple columns with id from another dataframe
<p>I have Pandas Dataframe <strong>df1</strong> as:</p> <blockquote> <pre><code>ID | c1 | c2 | c3 ----------------- 1 | A | B | 32 2 | C | D | 34 3 | A | B | 11 4 | E | F | 3 </code></pre> </blockquote> <p>And <strong>df2</strong>:</p> <blockquote> <pre><code>ID | c1 | c2 ------------ 1 | A | B 2 | C ...
<p>We could make a one liner out of your steps by making use of <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>suffixes</code></a> argument and <code>on</code> instead of <code>left_on, right_on</code> plus using <em>method chaining</em> ...
python|pandas|dataframe
2
3,342
56,088,665
Creating a new variable using other variables in an expression in a multiindexed Pandas dataframe
<p>I have the following multi-indexed Pandas dataframe:</p> <pre><code>toy.to_json() '{"["ISRG","Price"]":{"2004-12-31":10.35,"2005-01-28":10.35,"2005-03-31":14.15,"2005-04-01":14.15,"2005-04-29":14.15,"2005-06-30":15.51,"2005-07-01":15.51,"2005-07-29":15.51,"2005-09-30":20.77,"2005-10-28":20.77},"["ISRG","Price_high"...
<p>For output <code>MultiIndex DataFrame</code> is necessary same <code>MultiIndex</code> in selected DataFrames, so use <code>rename</code>:</p> <pre><code>idx = pd.IndexSlice Price_high = toy.loc[:, idx[:, 'Price_high']].rename(columns={'Price_high':'new'}) Price_low = toy.loc[:, idx[:, 'Price_low']].rename(column...
python-3.x|pandas|multi-index|assign
0
3,343
56,335,178
Merge levels of same variable which are in consecutive columns
<p>I have a csv data file which has 2 headers that means one header as a question and the second one as a sub header which has multiple levels or answers for the main header. Current csv look like below table</p> <pre> Header Which country do you live? Which country you previously visited? Users Canada US...
<p>First back filling missing values by <code>bfill</code>, then select first column and remove second level of <code>MultiIndex</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.droplevel.html" rel="nofollow noreferrer"><code>DataFrame.droplevel</code></a>:</p> <pre><code>p...
python|pandas|csv|data-transform
2
3,344
56,033,418
PyTorch and Chainer implementations of the Linear layer- are they equivalent?
<p>I want to use a Linear, Fully-Connected Layer as one of the input layers in my network. The input has shape (batch_size, in_channels, num_samples). It is based on the Tacotron paper: <a href="https://arxiv.org/pdf/1703.10135.pdf" rel="nofollow noreferrer">https://arxiv.org/pdf/1703.10135.pdf</a>, the Enocder prenet ...
<p>Chainer <code>Linear</code> layer (a bit frustratingly) does not apply the transformation to the last axis. Chainer flattens the rest of the axes. Instead you need to provide how many batch axes there are, <a href="https://docs.chainer.org/en/stable/reference/generated/chainer.links.Linear.html#chainer.links.Linear....
deep-learning|pytorch|linear-algebra|chainer
0
3,345
55,852,570
How can I get all the unique categories within my dataframe using python?
<p>im new to python and trying to work with dataframes manipulation:</p> <p>I have a df with unique categories: I am unable to paste the dataframe because I use Spyder IDE and it is not interactive does not display all fields.</p> <p>My input to get all these unique categories within a dataframe:</p> <pre><code>uc =...
<p>Try with</p> <pre><code> df['Category'].unique() </code></pre>
python|pandas
5
3,346
64,806,620
Pandas split data frames into multiple csv's based on value from column
<p>I have a question <a href="https://stackoverflow.com/questions/36192633/python-pandas-split-a-data-frame-based-on-a-column-value">similar to this one</a> but I need some further steps. The thing is my file contains like 50k+ lines. Each line have 4 values &quot;Indicator&quot;,&quot;Country&quot;,&quot;Date&quot; an...
<p>You can use groupby:</p> <pre><code>country_dfs = {k:v for k,v in df.groupby('Country')} </code></pre> <p>To save them in several csv files:</p> <pre><code>for k, v in df.groupby('Country'): v.to_csv(f'{k}.csv') </code></pre> <p>or from <code>country_dfs</code>:</p> <pre><code>for k, v in country_dfs.items(): ...
python|pandas|dataframe|csv
3
3,347
39,900,651
Pandas date difference in one column
<p>Here is my dataframe:</p> <pre><code>import pandas as pd df_manual = pd.DataFrame({'A': ['one', 'one', 'two', 'two', 'one'] , 'B': ['Ar', 'Br', 'Cr', 'Ar','Ar'] , 'C': ['12/15/2011', '11/11/2001', '08/7/2015', '07/3/1999','03/03/2000' ]}) </code></pre> <p>I would like to creat...
<p>Use <code>apply</code> instead of <code>transform</code>:</p> <pre><code>df_manual['diff'] = df_manual.groupby(['A'])['C'].apply(lambda x: x.diff()) </code></pre> <p>The resulting output:</p> <pre><code> A B C diff 0 one Ar 2011-12-15 NaT 1 one Br 2001-11-11 -3686 days 2 two Cr 2...
pandas|date-difference
4
3,348
40,062,641
Pandas time series: groupby and sum from noon to noon
<p>My pandas dataframe is structured like this (with 'date' as index):</p> <pre><code> starttime duration_seconds date 2012-12-24 11:52:00 31800 2012-12-23 0:28:00 35940 2012-12-22 2:00:00 26820 2012-12-21 1:57:00 23520...
<p><code>pd.TimeGrouper</code> is a custom groupby class for time-interval grouping of NDFrames with a <code>DatetimeIndex</code>, <code>TimedeltaIndex</code> or <code>PeriodIndex</code>. (If your dataframe index is using date-strings, you'll need to convert it to a DatetimeIndex first by using <code>df.index = pd.Date...
python-2.7|pandas
3
3,349
40,291,132
Comparing columns of 2 dataframes
<p>I am trying to get the columns that are unique to a data frame.</p> <p>DF_A has 10 columns DF_B has 3 columns (all three match column names in DF_A).</p> <p>Before I was using:</p> <p>cols_to_use = DF_A.columns - DF_B.columns.</p> <p>Since my pandas update, I am getting this error: TypeError: cannot perform <str...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.difference.html" rel="nofollow">difference</a> method:</p> <p>Demo:</p> <pre><code>In [12]: df Out[12]: a b c d 0 0 8 0 3 1 3 4 1 7 2 0 5 4 0 3 0 9 7 0 4 5 8 5 4 In [13]: df2 Out[13]: a d 0 4 3 ...
python|pandas|dataframe
1
3,350
69,384,465
pandas dataframe and/or condition syntax
<p>This pandas dataframe conditions work perfectly</p> <pre><code> df2 = df1[(df1.A &gt;= 1) | (df1.C &gt;= 1) ] </code></pre> <p>But if I want to filter out rows where based on 2 conditions</p> <pre><code>(1) A&gt;=1 &amp; B=10 (2) C &gt;=1 df2 = df1[(df1.A &gt;= 1 &amp; df1.B=10) | (df1.C &gt;= 1) ] </...
<p>One set of brackets is missing. Add brackets surrounding A and B individiually as well</p> <p>Try this</p> <pre><code>df2 = df1[((df1.A &gt;= 1) &amp; (df1.B==10)) | (df1.C &gt;= 1) ] </code></pre> <p>Example</p> <pre><code>df1 = pd.DataFrame({'A': [0,0,1,1,2,2], 'B': [0,10,0,10,0,10], 'C': [2,2,3,3,0,0]}) df1 A ...
pandas|python-3.7
1
3,351
69,437,233
Object detection model in a for loop - memory issue
<p>I've been trying to run object detection on a batch of images, but the graph keeps using more and more memory. I think the variables are not being removed (when reassigned) and just keep getting added. I tried resetting the default graph, clearing the session and manually deleting + garbage collection.</p> <p>this i...
<p>The <code>imgs</code> array could be taking a huge chunk of your memory as all the images are already loaded. You could try loading each image one by one and running the <code>detector()</code></p> <p>So your code has to change into something like this:</p> <pre><code>for name in image_names: # this function loa...
tensorflow|keras|tensorflow2.0|transfer-learning
0
3,352
69,655,047
How can I handles duplicates when plotting a csv?
<p>I have a csv file and a python script in which I use pandas and matplotlib to plot the values. The script is</p> <pre><code>#!/usr/bin/env python3 import matplotlib.pyplot as plt import numpy as np import pandas as pd import sys def main(argv): in_csv_file=argv[0] print(argv[0]) df= pd.read_csv(in_csv_...
<p>One way is to pivot you data and plot:</p> <pre><code>(df.assign(count=df.groupby('Frame').cumcount()) .pivot(index='Frame', columns='count', values='Confidence') .ffill(axis=1) .plot(color='C0', legend=None, ylabel='Confidence') ) </code></pre> <p>Which gives:</p> <p><a href="https://i.stack.imgur.com/EUrS...
python|pandas|matplotlib
2
3,353
69,622,199
Is there a way to achieve this with groupby/pivot table in pandas?
<p>How to transform this dataframe</p> <pre><code>Year Gender Count 2018 Female 4010 2018 Male 19430 2019 Female 3212 2019 Male 16138 </code></pre> <p>To</p> <pre><code>Year Male Female Ratio 2018 19430 4010 0.21 2019 16138 3212 0.20 </code></pre> <p>using gr...
<p>Something like this:</p> <pre><code>new_df = df.pivot(&quot;Year&quot;, &quot;Gender&quot;, &quot;Count&quot;).assign(Ratio=lambda r: r.Female / r.Male) # To remove the &quot;Gender&quot; name from column index new_df.columns.name = None # Reset row index as column new_df = new_df.reset_index() </code></pre> <p>R...
python|pandas
0
3,354
41,071,586
I got a error when I got the variables of convolution layers in tensorflow
<p>I want to got variables of convolution layers and to visualize it. Then my code is </p> <pre><code>d3 = de_conv(d2, weights2['wc2'], biases2['bc2'], out_shape=[batch_size , c2, c2, 128]) d3 = batch_norm(d3, epsilon=1e-5, decay=0.9) d3 = tf.nn.relu(d3) tf.add_to_collection('weight_2', weights2['wc3']) <...
<p>Weights for conv layers should be <code>[filter height, filter width, input channels, number of filters (output channels]</code>. Except for the first two dimensions, your weights fit. Is it just wrapped in two lists? E.g. <code>[[weights]]</code> instead of just <code>weights</code>.</p>
python|tensorflow|deep-learning
0
3,355
41,090,854
assign value of arbitrary line in 2-d array to nans
<p>I have a 2D numpy array, z, in which I would like to assign values to nan based on the equation of a line +/- a width of 20. I am trying to implement the Raman 2nd scattering correction as it is done by the eem_remove_scattering method in the eemR package listed here: <a href="https://cran.r-project.org/web/package...
<p>Use <code>np.where</code> in the form <code>np.where( "condition for intersection", np.nan, z)</code>:</p> <pre><code>zi = np.where( np.abs(-2*X/(0.00036*X-1) + 500 - Y) &lt;= 20, np.nan, z) </code></pre> <p>As a matter of fact, there are no intersections here because (0.00036*ex-1) is close to -1 for all your val...
python|arrays|numpy
1
3,356
41,070,549
Get index when looping through one column of pandas
<p>I have a simple dataframe:</p> <p>index, a, y 0 , 1, 2 1 , 4, 6 2 , 5, 8</p> <p>I want to loop through the "a" column, and print out its index for a specific value.</p> <pre><code>for x in df.a: if x == 4: print ("Index of that row") </code></pre> <p>What syntax should I use to obtain the in...
<p>A series is like a dictionary, so you can use the <code>.iteritems</code> method:</p> <pre><code>for idx, x in df['a'].iteritems(): if x==4: print('Index of that row: {}'.format(idx)) </code></pre>
python|pandas
11
3,357
53,808,834
python pandas dataframe adding total column with filtered criteria
<p>I have a file where I compare different pieces of information for different views of an underlying dataset. The goal is to list out the pieces of information and compare the totals.</p> <p>I have the following dataframe:</p> <pre><code>df = pandas.DataFrame({"Measures": ['Country','State','County','City'], "Gre...
<p>You can use <code>df</code> to mask the underlying dataframe's values before computing the sum.</p> <pre><code>m = df.eq('Included') # Assume df2 is your underlying DataFrame. v = df2[m].sum() # Assign the total back as a new row in df. df.loc['Total', :] = v[df2.dtypes != object] df Measures Gree...
python|pandas|dataframe
1
3,358
52,839,122
Reshaping/Pivoting Data with Date Value
<p>I need to pivot/reshape long form data 2 ways: 1) adding date columns(End-of_month) and filling in numeric value (total) 2) adding date columns(End-of_month) and filling in date value(day-of-month that reached the 'total' value in previous pivot)</p> <p>I can do 1 with:</p> <pre><code>data = pd.DataFrame({'date': ...
<h3><code>set_index</code> with <code>unstack</code></h3> <p>This assumes the combinations of <code>['country', 'tr_code', 'EOM']</code> are unique and will break if they are not. This is why an aggregation function is important. We need a rule if and when we get multiple observations of a combination.</p> <pre><co...
python-3.x|pandas
7
3,359
52,635,812
how to determine if any column has a particular value
<p>I have a dataframe that looks like this:</p> <pre><code>ID Column1 Column2 Column3 1 cats dog bird 2 dog elephant tiger 3 leopard monkey cat </code></pre> <p>I'd like t...
<p>The following should do the trick for you:</p> <pre><code>df['Column4'] = np.where((df.astype(np.object)=='cat').any(1), 'Yes', 'No') </code></pre> <p>Working example: </p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; d = {'ID': [1, 2, 3], 'Column1': ['cat', 'dog', 'leo...
python|string|pandas|row
3
3,360
46,237,149
Creating list of multiple copies from another list in python
<p>Any function in numpy can achieve this? Function <code>f</code> below is kind of awkward</p> <pre><code>def f(l,times): res=[] for i in range(len(l)): res+=[l[i]]*times[i] return res In [93]:f([1,2,3],[2,2,2]) Out [93]:[1, 1, 2, 2, 3, 3] </code></pre>
<p><code>np.repeat</code> does exactly this. Ex:</p> <pre><code>In [8]: a = np.arange(4) In [9]: b = np.array([1, 2, 1, 3]) In [10]: np.repeat(a, b) Out[10]: array([0, 1, 1, 2, 3, 3, 3]) </code></pre> <p>If you are working with >= 2 dimensional arrays, you can specify an axis parameter. See the doc <a href="https:/...
python|numpy
0
3,361
46,516,244
Why is a category column seen as a column of strings in pandas?
<p>I have a dataset containing ints, floats and strings. I (think I) converted all string to categories by the following statements:</p> <pre><code>for col in list (X): if X[col].dtype == np.object_:#dtype ('object'): X [col] = X [col].str.lower().astype('category', copy=False) </code></pre> <p>However, w...
<p>I should have read the docs more carefully ;-) Most statistical tests in sklearn do not handle categories, as they do in R. RandomForestClassifiers can handle categories without problems in theory, the implementation in sklearn does not allow it (for now). My mistake was to think that they could do so, because theor...
python|pandas|dataframe|categories
1
3,362
58,456,213
pandas dataframe to_html formatters - can't display image
<p>Im trying to add an up and down arrow to a pandas data frame with to_html for an email report.</p> <p>I'm using a lambda function to input an up and down arrow onto column values in my data frame, I know the image html works ok becasue I can put it in the body of the email and it works fine but when I use this func...
<h3><code>escape=False</code></h3> <p>By default, the <code>pandas.DataFrame.to_html</code> method escapes any html in the dataframe's values.</p> <pre><code>my_img_snippet = ( "&lt;img src='https://www.pnglot.com/pngfile/detail/" "208-2086079_right-green-arrow-right-green-png-arrow.png'&gt;" ) df = pd.DataF...
html|pandas|dataframe|email|formatter
1
3,363
68,947,153
Return column names if contains all zeros or NaNs in Pandas
<p>Say I have a dataframe as follows:</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame([[1, 0, np.NaN, 0], [0, 0, np.NaN, 0]], columns=['a', 'b', 'c', 'd']) print(df) </code></pre> <p>Out:</p> <pre><code> a b c d 0 1 0 NaN 0 1 0 0 NaN 0 </code></pre> <p>I would like to get the column...
<p>You can directly use <code>.any()</code> to detect <code>null</code> and <code>0</code></p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df a b c d 0 1 0 NaN 0 1 0 0 NaN 0 &gt;&gt;&gt; df.any() a True b False c False d False dtype: bool </code></pre> <p>You can use this as-i...
python-3.x|pandas|dataframe
1
3,364
68,875,464
Vintage / Static Pool Analysis in Pandas / Anaconda
<p>I'm looking to do vintage analysis in pandas with some csv data, and I'm wondering if I can streamline the process vs. iterating through a dataframe to create the vintage analysis. For example, I have a dataset similar to below in csv and I've read it into a dataframe <code>default</code>.</p> <div class="s-table-co...
<p>You should try:</p> <pre><code>df.set_index(['Origination',' Default Month']).unstack(level=1) </code></pre> <p>Alternatively, if you have duplicates, use <code>pivot_table</code>:</p> <pre><code>(pd.pivot_table(df, index='Origination', columns=['Default Month'], value...
python|pandas|dataframe|numpy
1
3,365
44,475,993
Pandas less than or equal to giving TypeError: invalid type comparison
<p>I have 4 lists based on what I want to continuously filter my Pandas data-frame </p> <pre><code>categoryList=['Parameter1', 'Parameter1', 'Parameter2', 'Parameter2'] conditionList=['b1', 'b41', 'm1', 'm2'] conditionDescList=['&gt;', 'btn', '&lt;=', 'btn'] conditionParamList=['1000', '2:3', '0.5', '0.1:0.3'] </code...
<p>The problem was data-frame column type was <code>float</code> and list is <code>string</code></p>
python|pandas
1
3,366
44,381,192
How do I aggregate the values from two columns and create a new column from it?
<p>How can I sum up the values in column "number" for each state and then create a new column from those values next to "number"?</p> <p>So far I have this to aggregate: </p> <pre><code>out_state_total['df']=df.groupby('State')['out-of-state'].sum(axis=1) </code></pre> <p>But for some reason I can't create a new col...
<p>Use Transform</p> <pre><code>df[['in_state_total','out_state_total']]=df.groupby('state')['in-state', 'out-of-state'].transform('sum') example state in-state out-of-state in_state_total out_state_total 0 red NJ 3000 99 3094 119 1 blue ND 43 ...
python|python-2.7|python-3.x|pandas
1
3,367
60,930,158
Tensorflow saving subclass model which has multiple arguments to call() method
<p>I am following the tensorflow neural machine translation tutorial: <a href="https://www.tensorflow.org/tutorials/text/nmt_with_attention" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/text/nmt_with_attention</a></p> <p>I am trying to save the Encoder and Decoder models which are subclasses of the t...
<p>You can export the model successfully if you package your inputs in a list. You also need to specify the input signatures to export your model, here your code with slight modifications which works</p> <pre><code>import tensorflow as tf from tensorflow.keras.layers import Embedding, LSTM import numpy as np print('Te...
python|tensorflow|machine-learning|keras|tf.keras
6
3,368
61,091,608
Visualize the model's training process taking into account ModelCheckpoint
<p>I am training a Tensorflow model, in which I include a checkpoint to save the best model (based on val_loss).</p> <pre><code>checkpoint = ModelCheckpoint(filepath, monitor='val_rmse', verbose=2, \ save_best_only=True, save_weights_only=False, \ mode='min', s...
<p>From <a href="https://keras.io/callbacks/" rel="nofollow noreferrer">documentation</a>: The <code>filepath</code> can contain named formatting options, which will be filled with the values of <code>epoch</code> and keys in <code>logs</code> (passed in on_epoch_end).</p> <p>For example: if <code>filepath</code> is w...
tensorflow
0
3,369
60,803,983
Remove groupbs with groupby if row does not contain a pattern in pandas
<p>Hel lo, I have a dataframe such as </p> <pre><code>col1 col2 G1 OP2 G1 OP0 G1 OPP G1 OPL_Lh G2 OII G2 OIP G2 IOP G3 TYU G4 TUI G4 TYUI G4 TR_Lh </code></pre> <p>and i would like to groupby and remove from the df tha groups that does not contain at leats one row in col2 that contain </p> <pre><code>'_Lh' </code><...
<p>IIUC,</p> <p>you can use a boolean test and <code>isin</code> to filter in the groups that contain <code>_Lh</code></p> <pre><code>m = df[df['col2'].str.contains('_Lh')]['col1'] df[df['col1'].isin(m)].groupby('col1')... </code></pre> <hr> <pre><code>print(df[df['col1'].isin(m)]) col1 col2 0 G1 OP2...
python|pandas
1
3,370
71,714,565
How to calculate percentages from multiple columns
<p>I want to create a table that looks like this:</p> <p><a href="https://i.stack.imgur.com/NiHTF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NiHTF.png" alt="1" /></a></p> <p>So far I have a table I created to get the value counts but I need help with creating a table that calculates the total va...
<p>IIUC,</p> <pre><code>import pandas as pd import numpy as np df = pd.read_csv('https://raw.githubusercontent.com/fivethirtyeight/data/master/bob-ross/elements-by-episode.csv') dfi = df.set_index(['EPISODE', 'TITLE']) (dfi.sum()/np.sum(dfi.to_numpy())) </code></pre> <p>Output:</p> <pre><code>APPLE_FRAME 0.00...
python|pandas
0
3,371
42,503,495
Creating a new column in pandas quantile using Quantile function
<p>I want to create a column Quantile, for each date. Calculated the Quantile for each unique value Sales value. Ie Category always corresponds to the same number in sales for each particular date.</p> <p>I have dataframe which is indexed by date. There are many dates and multiple of the same dates. Example of the sub...
<p>It seems you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.drop_duplicates.html" rel="noreferrer"><code>drop_duplicates</code></a>:</p> <pre><code>df['Quantile'] = df.Sales.groupby(df.index) .transform(lambda x: x.drop_duplicates().quantile()) print (df) ...
python|pandas|group-by|quantile
6
3,372
69,876,267
How to slice very large dataframe by days without walking the entire dataframe each time?
<p>I have two massive datetime indexed and sorted dataframes that I need compare groups from one to groups from another.</p> <pre><code>start, end = df.index.min(), df.index.max() for day in pd.date_range(start.date(), end.date()+a_day, freq='D'): current_df = df[df.index.date == day.date()] current_df2= df2...
<p>You can use <code>groupby_apply</code>. Normalize your datetime by keeping the date part.</p> <pre><code>def do_heavy_lift(df): # do stuff here return ... out = pd.concat([df1, df2], axis=1) \ .groupby(lambda x: x.normalize()) \ .apply(heavy_lift) </code></pre>
python|pandas|dataframe|python-datetime
1
3,373
43,152,803
How do I subtract the max element of each row of a 2D tensor from all elements of that row
<p>Originally, I asked this with the global max, but the solution of just subtracting <code>tf.reduce_max()</code> doesn't work when you put in dimensions. I'd want something like <code> mytensor - tf.reduce_max(mytensor, 1) </code> but this gives a dimension error.</p> <p>I can't use <code> tf.constant(value = tf.re...
<p>For global max, you can do:</p> <pre><code>import tensorflow as tf inp = tf.constant([[1, 2, 3],[4,5,6] ]) res=tf.reduce_max(inp) res1=inp-res sess = tf.Session() print(sess.run(res)) print(sess.run(res1)) </code></pre> <p>Then res is 6 and res1 is</p> <pre><code>[[-5 -4 -3] [-2 -1 0]] </code></pre> <p>If...
python|tensorflow
1
3,374
72,360,518
Merge two pandas dataframes with multiple columns per row
<p>I have a dataframe &quot;df1&quot; that look like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">company id</th> <th style="text-align: center;">company name</th> <th style="text-align: right;">dealid_1</th> <th style="text-align: right;">dealyear_1</th> ...
<p>You can use:</p> <pre><code>df3 = (df2.drop(columns='company name') .assign(col=df2.groupby('company name').cumcount().add(1).astype(str)) .pivot(index='company id', columns='col') ) df3.columns = df3.columns.map('_'.join) out = df1[['company id', 'company name']].merge(df3, on='company i...
python|pandas|dataframe|join|merge
0
3,375
72,280,550
Why matplotlib imshow shows different images by changing the order of the array?
<p>I have a test case that reshaping the array changes the result of <code>plt.imshow</code>:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from skimage import io file_raw_path = &quot;8258792/Fig5_ColorfulCell_raw.tif&quot; im = io.imread(file_raw_path) im= np.max(im, axis=0) im_reshaped = im.r...
<p><code>np.reshape()</code> doesn't move any data around; it just changes where the axes &quot;wrap around&quot;. You can think about it as first flattening the input array, then wrapping the data across the axes to fit the new shape.</p> <pre class="lang-python prettyprint-override"><code>&gt;&gt;&gt; arr = np.arange...
python|numpy|matplotlib
1
3,376
50,328,545
Stochastic Gradient Descent for Linear Regression on partial derivatives
<p>I am implementing stochastic gradient descent for linear regression manually by considering the partial derivatives (df/dm) and (df/db)</p> <p>The objective is we have to randomly select the w0(weights) and then converge them. As this is stochastic we have to take the sample of the data set on each run</p> <p>Lear...
<p>In the above case, using <code>StandardScaler</code> before processing on <code>xi</code> gives good results and use <code>w1</code> instead of <code>w0_random</code>.</p> <pre><code>from sklearn.preprocessing import StandardScaler import numpy as np bos['PRICE'] = boston.target X = bos.drop('PRICE', axis = 1) Y = ...
python|pandas|numpy|gradient-descent
2
3,377
45,276,830
Xcode version must be specified to use an Apple CROSSTOOL
<p>I try to build tensorflow-serving using bazel but I've encountered some errors during the building </p> <pre><code>ERROR:/private/var/tmp/_bazel_Kakadu/3f0c35881c95d2c43f04614911c03a57/external/local_config_cc/BUILD:49:5: in apple_cc_toolchain rule @local_config_cc//:cc-compiler-darwin_x86_64: Xcode version must be...
<pre><code>bazel clean --expunge sudo xcode-select -s /Applications/Xcode.app/Contents/Developer sudo xcodebuild -license bazel clean --expunge bazel build --config=opt //tensorflow/tools/pip_package:build_pip_package </code></pre>
tensorflow|bazel|tensorflow-serving
106
3,378
54,507,486
Merging two TRUE/FALSE dataframe columns keeping only TRUE
<p>I have two columns in a pandas dataframe, like below:</p> <pre><code>df[1] df[2] TRUE TRUE FALSE TRUE TRUE FALSE FALSE FALSE TRUE FALSE FALSE FALSE </code></pre> <p>From these two columns, how do I make the following new column:</p> <pre><code>df[3] TRUE TRUE TRUE FALSE TRUE FALSE </code></pre>
<p>Looks like you need the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.any.html" rel="nofollow noreferrer"><code>any</code></a> function, like that:</p> <pre><code>df['result_col'] = df.any(axis=1) </code></pre>
python|pandas|dataframe
3
3,379
73,839,377
The Adam optimizer is showing error in Keras Tensorflow
<p>I was training a neural network to recognize angry and happy emotion. The code:</p> <pre><code>import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.python.keras.optimizer_v1 import Adam from tensorflow.python.keras.models import Sequential from tensorflow.python.keras.layers import...
<p>Use <code>tf.keras.optimizers</code>, and remove <code>.python.</code> from the imports. I don't see anything about <code>tensorflow.python.keras</code> in the documentation, so I would not use it</p> <pre><code>from tensorflow.keras.optimizers import Adam from tensorflow.keras.models import Sequential from tensorfl...
python|tensorflow|machine-learning|keras|neural-network
1
3,380
73,647,160
How to select and combine different columns based on specific condition in pandas python?
<pre><code>df = pd.DataFrame(data={ &quot;id&quot;: ['a', 'a', 'b', 'b', 'a', 'c', 'c', 'b'], &quot;transaction_amount&quot;: [110, 0, 10, 30, 40.4, 62.2, 20, 20], &quot;principal_amount&quot;: [100, 0, 0, 0, 40, 60, 0, 0], &quot;interest_amount&quot;: [10, 0, 10, 0, 0.4, 0.6, 10, 0], ...
<p>One approach could be as follows.</p> <pre><code>import pandas as pd import numpy as np out = df.reset_index(drop=False).melt( id_vars=['index'], value_vars=list(df.columns)[1:], var_name='transaction_type', value_name='amount' ).set_index('index') out = out[out['amount'].gt(0)] out['v'] = o...
python|pandas
1
3,381
71,163,720
How to return all column in groupby in pandas?
<p>Given data frame:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Group</th> <th>count</th> <th>status</th> <th>Duration</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>2</td> <td>1</td> <td>2.4</td> </tr> <tr> <td>A</td> <td>4</td> <td>0</td> <td>7</td> </tr> <tr> <td>A</td> <td>2</td> ...
<p>You'll also need <code>as_index=False</code> to prevent the group columns from becoming the index in your output.</p> <pre><code>df.groupby(&quot;Group&quot;,as_index=False)[[&quot;count&quot;,&quot;status&quot;,&quot;Duration&quot;]].max() </code></pre>
python|pandas|dataframe|pandas-groupby
0
3,382
71,184,483
Changing the order of middle levels of a tensor (python)?
<p>Imagine I have the following numpy array:</p> <pre><code>array([[['Xa0', 'Ya0'], ['Xa1', 'Ya1'], ['Xa2', 'Ya2']], [['Xb0', 'Yb0'], ['Xb1', 'Yb1'], ['Xb2', 'Yb2']], [['Xc0', 'Yc0'], ['Xc1', 'Yc1'], ['Xc2', 'Yc2']]], dtype='&lt;U3') </code></pre> <p>How c...
<p>Well, I've just found the answer.</p> <p>By using numpy.flip(tensor, axis=1)</p>
python|pandas|numpy
1
3,383
71,422,940
Convert string date column with format of ordinal numeral day, abbreviated month name, and normal year to %Y-%m-%d
<p>Given the following <code>df</code> with string <code>date</code> column with ordinal numbers for day, abbreviated month name for month, and normal year:</p> <pre><code> date oil gas 0 1st Oct 2021 428 99 1 10th Sep 2021 401 101 2 2nd Oct 2020 189 ...
<p><code>pd.to_datetime</code> already handles this case if you don't specify the <code>format</code> parameter:</p> <pre><code>&gt;&gt;&gt; pd.to_datetime(df['date']) 0 2021-10-01 1 2021-09-10 2 2020-10-02 3 2020-01-10 4 2019-11-01 5 2019-08-30 6 2019-05-10 7 2018-08-24 8 2017-09-01 9 201...
python-3.x|pandas|datetime|python-dateutil
1
3,384
52,028,341
How to predict missing values in python using linear regression 3 year worth of data
<p>Hey guys so i have these 3 years worth of data from 2012~2014, however the 2014 have a missing value to it (100 rows), i'm really not too sure on how to deal with it, this is my attempt at it: </p> <pre><code>X = red2012Mob.values y = red2014Mob.values X = X.reshape(-1,1) y = y.reshape(-1,1) from sklearn.model_sele...
<p>There is two ways:</p> <ul> <li>Drop the instances with missing data (e.g. using <code>red2012Mob.dropna()</code>, or if it is time series, leave out complete blocks of missing data, e.g. start later in 2014).</li> <li>Impute the missing data. Here however, you won't get a one size fits all answer, as it really dep...
pandas|numpy|scikit-learn
3
3,385
52,077,487
Python Multilevel Indexing using pandas read_csv method
<p>I want to read the following table as a pandas dataframe</p> <p><a href="https://i.stack.imgur.com/MYOfd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MYOfd.png" alt="enter image description here"></a></p> <p>Say the dataframe is df, the purpose is to query df['acct_id']['A']['0-3_mon] should...
<p>Create <code>DataFrame</code> with <code>MultiIndex</code>, because <a href="http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dsintro-deprecate-panel" rel="nofollow noreferrer"><code>deprecate panel</code></a>:</p> <pre><code>df = pd.read_csv(file, header=[0,1], index_col=[0]) </code></pre> <p>And then sel...
python|pandas|csv|dataframe|data-science
3
3,386
60,673,109
Pandas - Drop row from list of values
<p>I have a simple dataframe:</p> <pre><code>df = pd.DataFrame({'ID': [100, 101, 134, 139, 192], 'Name': ['Tom', 'Dave', 'Steve', 'Bob', 'Jim']}) </code></pre> <p>and a list of values:</p> <pre><code>id_list = [100, 139] </code></pre> <p>I want to drop the rows from my dataframe if the 'ID' column ==...
<p>You can use <code>.isin()</code> for the <code>ID</code> series preceded with <code>~</code>. Essentialy this works like <em>"Not in"</em>:</p> <pre><code>output_df = df[~df['ID'].isin(id_list)] </code></pre> <p>Output:</p> <pre><code> ID Name 1 101 Dave 2 134 Steve 4 192 Jim </code></pre>
python|pandas
3
3,387
60,374,642
fill data in a dataframe when a certain condition is satisfied
<pre><code>id date idx comments 1 01-05-2018 0 null 2 02-05-2018 0 null 3 03-05-2018 Y null 4 04-05-2018 Y null </code></pre> <p>when <strong>idx</strong> = 0, <strong>comments</strong> column needs to be updated as <strong>'flow reported as ...
<p>Using <code>list comprehension</code> with <code>zip</code> and <code>f-strings</code>:</p> <pre><code>df['comments'] = [f'flow reported as null for id {i} and date {d}' if idx == '0' else 'NULL' for i, d, idx in zip(df['id'], df['date'], df['idx'])] id date idx ...
pandas
0
3,388
72,818,254
Collapse specific multiindex columns pandas dataframe
<p>I'm importing an Excel file which has the following structure:</p> <pre><code>| | Cat 1 | | | | Cat 2 | | | Total | |code| a | b | c | d | a | b | c | | |data| data |data|data|data| data |data|data| data | </code></pre> <p>I want to keep the information in the double header ro...
<p>You can re-create the MultiIndex and put the existing name in level 0 for all columns where any level contains <code>Unnamed</code>:</p> <pre><code>df.columns = pd.MultiIndex.from_tuples( [(c[1],'') if 'Unnamed' in c[0] else (c[0],'') if 'Unnamed' in c[1] else c for c in df.columns.to_list()]) <...
python|pandas|dataframe|multi-index
1
3,389
72,500,516
Why doesn't this Python pandas code work on my dataset?
<p>I am a newbie in data science, and I encountered a problem about pandas in Python. Basically, I want to substitute the value lower than 0 in a column with 0, and I wonder why this does not work:</p> <p>Image of my dataset: dataset:<br /> <a href="https://i.stack.imgur.com/7F13s.png" rel="nofollow noreferrer"><img sr...
<p>Your first attempt is equivalent to <code>submit[submit['score'] &lt; 0]['score'] = 0</code>. Whenever you see multiple <code>[</code> and <code>]</code> pairs in your pandas code, it might be a bad sign. In this case, with <code>submit[submit['score'] &lt; 0]</code> you're creating a copy of your dataframe, so you'...
python|pandas
1
3,390
72,584,994
Convert pandas df to orc bytes
<p>Following is generated by this line of code:</p> <pre><code>table_bytes = df.to_parquet() </code></pre> <pre><code>table_bytes: b'PAR1\x15\x04\x15@\x15DL\x15\x08\x15\x04\x12\x00\x00 |\x03\x00\x00\x00Tom\x04\x00\x00\x00nick\x05\x00\x00\x00krish\x04\x00\x00\x00jack\x15\x00\x15\x14\x15\x18,\x15\x08\x15\x04\x15\x06\x15\...
<p>I got it like this:</p> <pre><code>import pandas as pd import pyarrow as pa from pyarrow import orc df = pd.DataFrame({&quot;col1&quot;: [1, 2, 3]}) print(df.to_parquet()) # Wrote the table to a file and then read bytes from it. orc.write_table(pa.table({&quot;col1&quot;: [1, 2, 3]}), &quot;test.orc&quot;) with ...
python|python-3.x|pandas|orc
1
3,391
72,657,714
How can flag if column values had increase/decrease in last n months in time series data frame in python?
<p>I am working with customer data and need to flag customers who had decrease or increase in salary in last 6 and 12 months?</p>
<p>Not having a ton of information, let's assume your timeseries data is set up so each row consists of monthly data. i.e row 1 is January data, row 2 is February, etc.</p> <p>Here is an implementation <a href="https://www.statology.org/pandas-difference-between-rows/" rel="nofollow noreferrer">https://www.statology.or...
pandas|time-series
0
3,392
59,628,607
Sort values by columns and not rows
<p>I hope you can help me with this stupid problem.</p> <p>I need to sort my columns by highest values. My dataframe consist of 31 columns, with the first 7 looking like this. </p> <p><a href="https://i.stack.imgur.com/VbhVe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VbhVe.png" alt="enter imag...
<p>You can transpose, sort and transpose back</p> <pre><code>df = pd.DataFrame( { "name": ["messi"], "height": [170], "weight":[72], "attack_cross":[88] }) df.T[df.T.index != 'name'].sort_values(0,ascending = False).T </code></pre> <p>gives</p> <pre><code> height attack_cross weight 0 170 88 ...
python|pandas|sorting
2
3,393
54,771,985
Extract non-digit characters before certain character in pandas dataframe
<p>I have a pandas dataframe that looks like this:</p> <pre><code>&gt; row extract_column &gt; 0 412952266-desiredtext1»randtext-irrelevant &gt; 1 512952766-desiredtext1»randtext-irrelevant &gt; 2 212952766-desiredtext1»randtext-irrelevant &gt; 3 112953066-desiredtext1»randtext-irrelevant &gt; 4 712953066-desiredtex...
<p>Try with <code>extract</code></p> <pre><code>df.extract_column.str.extract(r'-([^\.]*)\»', expand=False) </code></pre>
python|regex|string|pandas
2
3,394
55,019,885
Resume Training tf.keras Tensorboard
<p>I encountered some problems when I continued training my model and visualized the progress on tensorboard.</p> <p><a href="https://i.stack.imgur.com/GsdB7.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GsdB7.png" alt="Tensorboard Training Visualization"></a></p> <p>My question is how do I resume trainin...
<p>You can set the parameter <code>initial_epoch</code> in the function <code>model.fit()</code> to the number of the epoch you want your training to start from. Take into account that the model trains until the epoch of index <code>epochs</code> is reached (and not a number of iterations given by <code>epochs</code>)....
python|tensorflow|machine-learning|keras|tensorboard
8
3,395
49,540,365
Keras composed neural network model from two neural network models
<p>I am using Keras with Tensorflow to implement my model (M). Lets suppose that I have the following input features F = {x,y, a1, a2, a3, ..., an} I want to build a deep model (M1) using only x and y. Then, the output of (M1) with all the remaining features (a1, a2, ..., an) will be the input of another model (M2). ...
<p>Use <a href="https://keras.io/getting-started/functional-api-guide/" rel="nofollow noreferrer">Keras functional api</a>.</p> <p>It's not entirely clear to me whether you mean to have a second model that is only trained on the output of first model, or something that could make both models trained jointly.</p> <p>I...
python|tensorflow|neural-network|keras
1
3,396
49,701,918
tf.layers.batch_normalization parameters
<p>I am not sure if it is only me who thinks that tensorflow documentation is a bit weak.</p> <p>I was planing to use the tf.nn.batch_normalization function to implement batch normalization but later recognized the tf.layers.batch_normalization function which seemingly should be the one to use for its simplicity. But...
<p>Q1) Initializing gamma as 1, beta as 0 means directly using the normalized inputs. Since there is no prior information about what the variance of a layer output should be, it is fair enough to assume standard Gaussian.</p> <p>Q2) During training phase (<code>training=True</code>), the batch is normalized with their...
python|tensorflow|machine-learning|neural-network
6
3,397
49,346,423
How to fill column in pandas.DataFrame using data from another pandas.DataFrame?
<p>I have the first pandas.DataFrame</p> <pre><code> first_key second_key 0 0 1 1 0 1 2 0 2 3 0 3 4 0 3 </code></pre> <p>and also the second pandas.DataFrame</p> <pre><code> ke...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow noreferrer"><code>map</code></a> by Series created from second <code>DataFrame</code>:</p> <pre><code>df['status'] = df['second_key'].map(df1.set_index('key')['status']) print (df) first_key second_key stat...
python|pandas
3
3,398
73,217,739
Variation in color representation using Matplotlib
<p>I am trying to represent the array <code>p</code> with different values on the grid as shown. I identify the <code>max,min</code> of <code>p</code> and set the colorbar according to <code>Amax,Amin</code>. However, I do not see color variation even though the values are quite different. I don't know if there is prob...
<p>You are scaling your <code>color_list</code> from [0, Amax] in stead of [Amin, Amax] You could use the <code>norm</code> to scale it.</p> <pre><code>for i in range(len(P)): color_list.append(color(norm(P[i]))) </code></pre> <p><a href="https://i.stack.imgur.com/Ezbtz.png" rel="nofollow noreferrer"><img src="http...
python|numpy|matplotlib
1
3,399
73,439,060
Extending a dataframe, filling in missing time, and keeping the other column values with the corresponding time?
<p>More about my problem, I have a 2 column dataframe (one information based, and one time based) that is ~190k rows long. I am missing some dates, and would like to fill in the missing dates while keeping the information with the correct date, and the come back and resample the missing information using the interpolat...
<p>Try a merge of 2 dfs instead of pd.Series.</p> <p>Time Series Range (using an 8 hr range for simplicity):</p> <pre><code>import pandas as pd import numpy as np s = pd.to_datetime(&quot;2022-08-01 00:00:00&quot;) e = pd.to_datetime(&quot;2022-08-01 08:00:00&quot;) data_res = pd.DataFrame(pd.period_range(s, e, freq =...
python|pandas|dataframe|time-series
1