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
600
48,378,015
Compare values in single column
<p>I have a single column </p> <pre><code>df = pd.DataFrame({'Name': ['Harry', 'John', 'Peter', 'Stan', 'Petra'], 'Score': [10, 9, 5, 7, 8]}) </code></pre> <p>I can use itertools to get a matrix</p> <pre><code>for a, b in itertools.combinations(df['Score'], 2): print (a, b) </code></pre> <p>What is the best wha...
<p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.outer.html" rel="nofollow noreferrer"><code>np.subtract.outer</code></a> with <code>DataFrame</code> constructor:</p> <pre><code>df = pd.DataFrame(np.subtract.outer(df['Score'], df['Score']), index=df['Name'], ...
python|pandas
1
601
48,081,927
Adding a new column based on values of another column in Pandas(python)
<p>Given a dataframe that looks something like</p> <pre><code>Vote A Vote B 1 4 3 2 1 5 </code></pre> <p>I want to add a new column named <code>Winner</code> that compares the value between two columns <code>Vote A</code> and <code>Vote B</code> and specify the winner.</p> <pre...
<p>You could use</p> <pre><code>def winner(row): if row['Vote A'] &gt; row['Vote B']: return 'A' elif row['Vote A'] &lt; row['Vote B']: return 'B' else: return '' df['Winner'] = df[['Vote A','Vote B']].apply(winner, axis=1) </code></pre> <p>Which yields</p> <pre><code>Vote A Vot...
python|pandas
2
602
48,186,074
Renaming MultiIndex columns is not working
<p>I am trying to rename the columns of my data frame on the fly. The reason is I want to do something like</p> <pre><code>df.rename(..).plot() </code></pre> <p>This is how I attempt to do it:</p> <pre><code>import pandas as pd import numpy as np np.random.seed(42) cols = [(100,i) for i in range(1, 6)] cols_replac...
<p>Try using <code>rename</code> with a <code>level</code> argument - </p> <pre><code>df = df.rename(columns='Sensor {}'.format , level=1) </code></pre> <p>Thanks to Zero for the shorthand improvement. Alternatively,</p> <pre><code>i = df.columns.levels[1] # OP's suggestion, for more flexibility! j = ['Sensor ' ...
python|pandas|dataframe|rename|multi-index
2
603
48,402,780
Web Scraping a Forum Post in Python Using Beautiful soup and lxml, saving results to a pandas dataframe
<p>I was looking at a past stackoverflow post but I am having trouble to build on top of it.</p> <p>I want to get :</p> <ol> <li>users of who posted it in the form</li> <li>forum post content</li> <li>save it all to a dataframe</li> </ol> <p>Something like</p> <p>Dateframe</p> <pre><code>col1 col2 johnsmi...
<p>I only parsed the webpage the URL you included in the question.</p> <p>The <code>posts</code> list may need some data clean up by eliminating the new line, tabs, and etc.</p> <p>Code:</p> <pre><code>import requests, re from bs4 import BeautifulSoup import pandas as pd headers = {'User-Agent': 'Mozilla/5.0 (Windo...
python|pandas|beautifulsoup
1
604
48,725,520
Get dataframe values by down instead of across?
<pre><code> 0 2 0 -0.089329 -0.945867 1 -0.932132 0.017587 2 -0.016692 0.254161 3 -1.143704 1.193555 4 -0.077118 -0.862495 </code></pre> <p><code>df.values</code> gives</p> <pre><code>[[-0.089329, -0.945867], [-0.932132, 0.017587], ...] </code></pre> <p>But I want:</p> <pre><code>[[-0.089329, -0...
<p>You need transpose numpy array or pandas DataFrame:</p> <pre><code>df.values.T </code></pre> <p>Or:</p> <pre><code>df.T.values </code></pre>
python|pandas
3
605
48,832,364
How to keep partitions after performing a group-by aggregation in dask
<p>In my application I perform an aggregation on a dask dataframe using groupby, ordered by a certain id. </p> <p>However I would like that the aggregation maintains the partition divisions, as I intend to perform joins with other dataframe identically partitioned.</p> <pre><code>import pandas as pd import numpy as n...
<p>You probably can't maintain <em>the same</em> partitioning, because dask will need to aggregate counts between partitions. Your data will necessarily have to move around in ways that depend on the values of your data.</p> <p>If you're looking to ensure that your output has many partitions then you might choose to ...
python|pandas|dataframe|distributed|dask
2
606
48,689,700
Combination of matrix elements giving non-zero value (PYTHON)
<p>I have to evaluate the following expression, given two quite large matrices A,B and a very complicated function F: <a href="https://i.stack.imgur.com/8k9rR.gif" rel="nofollow noreferrer">The mathematical expression</a></p> <p>I was thinking if there is an efficient way in order to first find those indices i,j that...
<p>My guess would be NO: you cannot avoid the for-loops. In order to find all the indices <code>ij</code> you need to loop through all the elements which defeats the purpose of this check. Therefore, you should go ahead and use simple array elementwise multiplication and dot product in <code>numpy</code> - it should be...
python|numpy|for-loop|matrix|indices
0
607
70,990,715
Gather data by year and also by industry
<p>I have this very large Dataframe containing statistics for various firms for years 1950 to 2020. I have been trying to divide the data first by year and then by industry code (4 digits). Both 'year' and 'industry_code' are columns from the Dataframe. I have created a dictionary in order to obtain data by year, but t...
<p>Try using dict comprehension + <code>groupby</code>:</p> <pre><code>dct = {key1: {key2: df2 for key2, df2 in df1.groupby('industry_code')} for key1, df1 in df.groupby('year')} </code></pre> <p>Now try accessing one:</p> <pre><code>firm_year_df = dct[1994]['My Firm'] </code></pre>
pandas|dataframe|dictionary|if-statement|pandas-groupby
0
608
51,661,239
Error when checking target: expected dense_1 to have shape (1,) but got array with shape (256,)
<p>I am trying to learn tensorflow, and I was following a demo tutorial (<a href="https://www.tensorflow.org/tutorials/keras/basic_text_classification" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/keras/basic_text_classification</a>)</p> <p>The error report is telling me </p> <p>"Error when checking...
<p>The error is in these lines</p> <pre><code>y_val = train_data[:10000] partial_y_train = train_data[10000:] </code></pre> <p>But the tutorial says it should be</p> <pre><code>y_val = train_labels[:10000] partial_y_train = train_labels[10000:] </code></pre> <p><code>train_data</code> represents each written review...
numpy|machine-learning|neural-network|keras
0
609
41,809,308
Use pandas with Spark
<p>I have a Noob Question on spark and pandas. I would like to use pandas, numpy etc.. with spark but when i import a lib i have an error. can you help me plz? This is my code</p> <pre><code>from pyspark import SparkContext, SQLContext from pyspark import SparkConf import pandas # Config conf = SparkConf().setAppName...
<p>Spark has it's own <a href="http://spark.apache.org/docs/latest/sql-programming-guide.html#datasets-and-dataframes" rel="noreferrer">Dataframe</a> object that can be created from RDDs.</p> <p>You can still use libraries such as numpy but you must install them first. </p>
python|pandas|pyspark|importerror
7
610
64,571,500
Pandas: Sort a Multiindex Dataframe's multi-level column with mixed datatypes
<p>Below is my dataframe:</p> <pre><code>In [2804]: df = pd.DataFrame({'A':[1,2,3,4,5,6], 'D':[{&quot;value&quot;: '126', &quot;perc&quot;: None, &quot;unit&quot;: None}, {&quot;value&quot;: 324, &quot;perc&quot;: None, &quot;unit&quot;: None}, {&quot;value&quot;: 'N/A', &quot;perc&quot;: None, &quot;unit&quot;: None},...
<p>Create helper column filled by numeric and sorting by this column:</p> <pre><code>df['tmp'] = pd.to_numeric(df[('D','E')].str.get('value'), errors='coerce') df1 = df.sort_values('tmp', ascending=False).drop('tmp', axis=1) print (df1) A D E ...
python|python-3.x|pandas|dataframe
1
611
64,423,343
AWS lambda task timed out issue with large data while processing data from S3 bucket
<p>I have 120 mb file of data in my S3 bucket and i am loading it in lambda by python pandas and processing it but after 15 mins(the time set in timeout option of basic settings) it is giving me an error of task timed out and stopping the process.The same process i am doing in basic sublime text and terminal is taking ...
<p>You should try to take a look at the resourcing used within your local machine if you believe that it takes a significantly less period of time. <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-console.html" rel="nofollow noreferrer">Increasing the amount of memory</a> available to your Lambda can...
pandas|amazon-web-services|amazon-s3|aws-lambda|aws-lambda-layers
0
612
47,626,579
Creating new column with letters v from beginning to last row
<p>How do I add a new empty column with the letters 'v' from beginning to the last row.</p> <p>df1:</p> <pre><code> AM 0 MA 1 Ming 2 Mo </code></pre> <p>Desired output for df1:</p> <pre><code> AM C 0 MA v 1 Ming v 2 Mo v </code></pre> <p>I get error: Attri...
<p>d = {'one' : pd.Series([1., 2., 3.], index=['a', 'b', 'c'])}</p> <p>dd = pd.DataFrame(d)</p> <p>print dd</p> <p>one</p> <p>a 1</p> <p>b 2</p> <p>c 3</p> <p>dd = pd.DataFrame(d)</p> <p>dd['df'] = 'test'</p> <p>print dd</p> <p>one df</p> <p>a 1 test</p> <p>b 2 test</p> <p>c 3 test<...
python|python-3.x|pandas
0
613
47,841,405
How to manually create text summaries in TensorFlow?
<p>First of all, I already know <em>how to manually add float or image summaries</em>. I can construct a <code>tf.Summary</code> protobuf manually. But what about text summaries? I look at the definition for summary protobuf <a href="https://github.com/tensorflow/tensorflow/blob/r1.4/tensorflow/core/framework/summary.p...
<p>TensorBoard's text plugin offers a <code>pb</code> method that lets you create text summaries outside of a TensorFlow environment. <a href="https://github.com/tensorflow/tensorboard/blob/master/tensorboard/plugins/text/summary.py#L74" rel="nofollow noreferrer">https://github.com/tensorflow/tensorboard/blob/master/t...
tensorflow|tensorboard
2
614
47,895,225
Tensorflow Combining Two Models End to End
<p>In tensorflow it is fairly easy to load trained models back into tensorflow through the use of checkpoints. However, this use case seems oriented towards users that want to either run evaluation or additional training on a checkpointed model.</p> <p>What is the simplest way in tensorflow to load a pre-trained mode...
<p>The most straightforward solution would be to freeze the pre-trained model variables using this function:</p> <pre><code>def freeze_graph(model_dir, output_node_names): """Extract the sub graph defined by the output nodes and convert all its variables into constant Args: model_dir: the root fol...
tensorflow
10
615
49,298,488
How to extract hour, minute and second from Series filled with datetime.time values
<p>Data:</p> <pre><code>0 09:30:38 1 13:40:27 2 18:05:24 3 04:58:08 4 09:00:09 </code></pre> <p>Essentially what I'd like to do is split this into three columns [hour, minute, second]</p> <p>I've tried the following code but none seem to be working:</p> <pre><code>train_sample.time.hour AttributeErro...
<p>Use list comprehension with extract attributes of <code>time</code>s:</p> <pre><code>import datetime as datetime df = pd.DataFrame({'time': [datetime.time(9, 30, 38), datetime.time(13, 40, 27), datetime.time(18, 5, 24), datetime....
python|pandas|datetime|series
10
616
49,131,972
Why was my dataframe column changed?
<p>My code</p> <pre><code>import pandas as pd import numpy as np series = pd.read_csv('o1.csv', header=0) s1 = series s2 = series s1['userID'] = series['userID'] + 5 s1['adID'] = series['adID'] + 3 s2['userID'] = s1['userID'] + 5 s2['adID'] = series['adID'] + 4 r1=series.append(s1) r2=r1.append(s2) print(r2) </co...
<p>IIUC need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.copy.html" rel="nofollow noreferrer"><code>copy</code></a> if need new object <code>DataFrame</code>:</p> <pre><code>s1 = series.copy() s2 = series.copy() </code></pre> <p><strong>Sample</strong>:</p> <pre><code>print (df) ...
python|pandas
2
617
49,252,387
encounter error during deeplab v3+ training on Cityscapes Semantic Segmentation Dataset
<p>all,</p> <p>I start the training process using deeplab v3+ following this <a href="https://github.com/tensorflow/models/blob/master/research/deeplab/g3doc/cityscapes.md" rel="nofollow noreferrer">guide</a>. However, after step 1480, I got the error: </p> <pre><code>Error reported to Coordinator: Nan in summary his...
<p>Based on the log, it seems that you are training with batch_size = 1, fine_tune_batch_norm = True (default value). Since you are fine-tuning batch norm during training, it is better to set batch size as large as possible (see <a href="https://github.com/tensorflow/models/blob/master/research/deeplab/train.py#L93" re...
tensorflow|semantic-segmentation
7
618
70,068,792
how to conditionally remove rows from a pandas expanding window
<p>I have a series in which I want to take the cumulative median of all non-zero values, resulting in a series the same length as the original.</p> <p><code>my_series.expanding().median()</code> gives me a series the same length as <code>my_series</code> which is close to what I want, but before I take the median of ea...
<p>You can replace 0 values with nan while calculating, so they won't be used in the median calculations.</p> <pre><code> my_series.replace(0, np.nan).expanding().median() </code></pre> <p>Output:</p> <pre><code>0 NaN 1 1.0 2 1.5 3 1.5 4 2.0 5 51.0 dtype: float64 </code></pre>
python|pandas
3
619
70,037,505
"ValueError: Columns must be same length as key" when filtering dataframe with isin(list)
<p>I am trying to filter a column in my dataframe based on values from a list, here is the snippet of my code where it's going wrong (replaced values for simplicity's sake)</p> <pre><code>import pandas as pd from pandas import Series df['Campaign']=df['Location'] campaign_list = ['a', 'b'] df['Campaign']=df[df['Campai...
<p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.where.html?highlight=where#pandas.Series.where" rel="nofollow noreferrer"><code>Series.where</code></a></p> <pre><code>df['Campaign'] = df['Campaign'].where(lambda camp: camp.isin(campaign_list)) </code></pre> <p>or</p> <pre><code>df['Campaign']...
python|pandas|list|dataframe|isin
1
620
56,099,314
What is a replacement for tf.losses.absolute_difference
<p>My question is about in <code>TF2.0</code>. There is no <code>tf.losses.absolute_difference()</code> function and also there is no <code>tf.losses.Reduction.MEAN</code> attribute.</p> <p>What should I use instead? Is there a list of deleted <code>TF</code> functions in <code>TF2</code> and perhaps their replacement...
<p>You still can access this function via <code>tf.compat.v1</code>:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf labels = tf.constant([[0, 1], [1, 0], [0, 1]]) predictions = tf.constant([[0, 1], [0, 1], [1, 0]]) res = tf.compat.v1.losses.absolute_difference(labels, ...
python|tensorflow2.0
3
621
56,096,399
Creating model throws "AttributeError: 'Tensor' object has no attribute '_keras_history'"
<p>When I created a model using keras.models.Model(), I have the following error:</p> <blockquote> <p>AttributeError: 'Tensor' object has no attribute '_keras_history'</p> </blockquote> <p>I created 3 MLP in my model, and intents is a tensor with shape(6040,100).</p> <p>The code and full traceback like this:</p> ...
<p>You cannot use backend functions directly in Keras tensors, every operation in these tensors must be a layer. You need to wrap each custom operation in a Lambda layer and provide the appropriate inputs to the layer.</p>
python|tensorflow|keras
0
622
56,371,432
Transpose all rows in one column of dataframe to multiple columns based on certain conditions
<p>I would like to convert one column of data to multiple columns in dataframe based on certain values/conditions.</p> <p>Please find the code to generate the input dataframe</p> <pre><code>df1 = pd.DataFrame({'VARIABLE':['studyid',1,'age_interview', 65,'Gender','1.Male', '2.Female', ...
<p>Use <code>itertools.groupby</code> and then construct <code>pd.DataFrame</code>:</p> <pre><code>import pandas as pd import itertools l = ['studyid',1,'age_interview', 65,'Gender','1.Male', '2.Female', 'Ethnicity','1.Chinese','2.Indian','3.Malay'] l = list(map...
python|python-3.x|pandas|dataframe|transpose
1
623
55,977,204
Creating a new column based on three existing columns
<p>I have a data frame with three columns, <code>target_degrees</code>, <code>low_degrees</code>, and <code>high_degrees</code>. I would like to make a new column labeled success that checks to see if target_degrees is located between <code>low_degrees</code> and <code>high_degrees</code>.</p> <p>example dataframe:</p>...
<p>Use multiple conditions:</p> <pre><code>df['success'] = np.where(((df['target_degrees'] &gt;= df['low_degrees']) &amp; (df['target_degrees']&lt;= df['high_degrees'])), 1, 0) </code></pre> <p><strong>output</strong>:</p> <pre><code> target_degrees low_degrees high_degrees success 0 10 ...
python|python-3.x|pandas|numpy|dataframe
1
624
55,675,170
pandas equivalent for excels 'file origin'
<p>Have csv files. When open in excel or pandas, foreign letters turns in gibberish. </p> <p>In excel, I go to </p> <p>Data --> From Text --> Specify File --> Step 1 and change 'File Origin' and it solved the problem.</p> <p>How do I do this while importing file into dataframe?</p> <p><a href="https://i.stack.imgur...
<p>You could simply use the <code>encoding</code> parameter while reading the csv file as follows </p> <p>df = pd.read_csv('filename.csv', encoding="SHIFT-JIS")</p>
excel|pandas
1
625
64,775,042
Group object based on attributes and combine rest of the columns in a list gives me unhashable type: 'list'
<p>I am having this object :</p> <pre><code>obj = [ {&quot;mode&quot;:1,&quot;items&quot;:[{&quot;id&quot;:1}],&quot;people&quot;:[{&quot;id&quot;:8888}],&quot;value&quot;:{&quot;v&quot;:1000}}, {&quot;mode&quot;:1,&quot;items&quot;:[{&quot;id&quot;:1}],&quot;people&quot;:[{&quot;id&quot;:8888}],&quot;value&quo...
<p>You can't group by columns that contain lists or dicts as they are not hashable. So in fact the <code>people</code> column is not the problem, but the columns <code>item</code> and <code>value</code> are. The easiest solution would be to convert them to strings so they can be used for grouping.</p> <p>This sample sh...
python|pandas
2
626
64,727,450
how do I reassign new values to python dataframe?
<p>i'm trying to convert prices like &quot; €565K &quot; to integers and I know that pandas dataframes require reassigning, so I wrote the code like this :</p> <pre><code>def to_int(cols): for column in cols: column = column.astype(str) for i in range(len(column)): if column[i][-1] == 'M...
<p>You can try this using <code>apply</code></p> <pre><code>def to_int(x): if x[-1] == 'M': return float(x[1:-1])*1000000 elif x[-1] == 'K': return float(x[1:-1])*1000 df['col_with_price'] = df['col_with_price'].apply(to_int) print(df) </code></pre>
python|pandas
0
627
64,933,175
Maximum of calculated pandas column and 0
<p>I have a very simple problem (I guess) but don't find the right syntax to do it :</p> <p>The following Dataframe :</p> <pre><code> A B C 0 7 12 2 1 5 4 4 2 4 8 2 3 9 2 3 </code></pre> <p>I need to create a new column D equal for each row to max (0 ; A-B+C)</p> <p>I tried a np.maximum(df.A-df.B+df...
<p>Let us try</p> <pre><code>df['D'] = df.eval('A-B+C').clip(lower=0) Out[256]: 0 0 1 5 2 0 3 10 dtype: int64 </code></pre>
pandas|dataframe|max
1
628
64,997,947
What is the difference between these backward training methods in Pytorch?
<p>I am a 3-month DL freshman who is doing small NLP projects with Pytorch.<br> Recently I am trying to reappear a GAN network introduced by a paper, using my own text data, to generate some specific kinds of question sentences. <br></p> <blockquote> <p>Here is some background... If you have no time or interest about i...
<p>First of all:</p> <p><code>loss.backward()</code> backpropagates the error and assigns a gradient for every parameter along the way that has <code>requires_grad=True</code>.</p> <p><code>optimizer.step()</code> updates the model parameters using their stored gradients</p> <p><code>optimizer.zero_grad()</code> sets t...
machine-learning|deep-learning|pytorch
0
629
40,014,645
Is there a theano operation equivalent to numpy "broadcast_to" method?
<p>Since I need to repeat over a specific axis, I want to avoid unnecessary memory reallocation as much as possible.</p> <p>For example, given a numpy array <code>A</code> of shape (3, 4, 5), I want to create a view named <code>B</code> of shape (3, 4, 100, 5) on the original <code>A</code>. The 3rd axis of <code>A</c...
<p>There is a nice method dimshuffle, which makes a theano variable broadcastable over some dimension</p> <pre><code>At = theano.tensor.tensor3() Bt = At.dimshuffle(0,1,'x',2) </code></pre> <p>Now you've got a tensor variable with shape (3,4,'x',5), where 'x' means any dimension you want to add.</p> <pre><code>Ct=th...
numpy|theano|broadcast
0
630
39,973,243
Randomly select list from list of lists in python depending on weights
<p>I have a list of lists, where each list is associated with a score/weight. I want to produce a new list of lists by randomly selecting from the first one so that those with higher scores will appear more often. The line below works fine when <code>population</code> is just a normal list. But I want to have it for a ...
<p>Instead of passing the actual list, pass a list with indexes into the list.</p> <p><code>np.random.choice</code> already allows this, if you pass an int <code>n</code> then it works as if you passed <code>np.arange(n)</code>.</p> <p>So</p> <pre><code>choice_indices = np.random.choice(len(population), 10, replace=...
python|list|numpy|random
9
631
44,266,139
Pandas dataframe left-merge with different dataframe sizes
<p>I have a toy stock predictor, and from time to time save results using dataframes. After the first result set I would like to append my first dataframe. Here is what I do: </p> <ol> <li>Create first dataframe using predicted results</li> <li>Sort descending to predicted performance</li> <li><p>Save to csv, without...
<p>From the sample result, it works as expected, the new data don't have numbers for all the tickers so some of the predictions are missing. So what exactly do you want to achieve? If you only need stocks with all the predictions, use inner join.</p>
python|pandas|dataframe
0
632
44,325,179
Tensorflow/LSTM machanism: How to specify the previous output of first time step of LSTM cells
<p>Just started using TensorFlow to build LSTM networks for multiclass classification</p> <p>Given the structure shown below: <a href="https://i.stack.imgur.com/zChh2.png" rel="nofollow noreferrer">A RNN model</a> Let's Assume each node A represents TensorFlow BasicLSTMcell.</p> <p>According to some popular examples ...
<p>LSTM cells, or RNN cells in general, have an internal state that gets updated after each time step is processed. Obviously, you cannot go infinitely back in time, so you gotta start at some point. The general convention is to begin with a cell state full of zeros; in fact, RNN cells in TensorFlow have a <code>zero_s...
tensorflow|deep-learning|lstm|recurrent-neural-network|gated-recurrent-unit
1
633
69,660,258
Split Dataframe dates into individual min max date ranges by group
<p>I have a dataframe which looks something like this:</p> <pre><code>S.No date origin dest journeytype 1 2021-10-21 FKG HYM OP 2 2021-10-21 FKG HYM PK 3 2021-10-21 HYM LDS OP 4 2021-10-22 FKG HYM OP 5 2021-10-22 FKG HYM PK 6 2...
<p>If possible specified consecutive values by compare differencies if greater like <code>1</code> per groups use:</p> <pre><code>df['date'] = pd.to_datetime(df['date']) g = df.groupby(['origin','dest','journeytype'])['date'].diff().dt.days.gt(1).cumsum() df = (df.groupby(['origin','dest','journeytype', g], sort=Fals...
python|pandas|dataframe|group-by
1
634
69,620,035
TypeError: Dimension value must be integer or None in keras VQ-VAE example
<p>I tried <a href="https://keras.io/examples/generative/vq_vae/" rel="nofollow noreferrer">keras example on VQ-VAE</a> in colab and also in my environment. In both I encountered the same error:</p> <pre class="lang-py prettyprint-override"><code>-------------------------------------------------------------------------...
<p>Yes this is an unfortunate side-effect of not documenting package versions and jupyter environments. The tensorflow-probability package is still in a pre-1.0 phase, which causes things to shift underneath you, unless you pin package versions.</p> <p>In this case, I looked up which version Sayak Paul was likely to ha...
python|python-3.x|tensorflow|keras
0
635
41,002,879
Image classification by small object
<p>I'm trying to participate in a challenge for classifying dashboard camera images (for car) with labels being -traffic light red / green / non-existent. Traffic lights are small part of the image, and no bounding box is supplied.</p> <p>I'm trying to fine-tune the image as suggested <a href="https://github.com/tenso...
<p>I suggest instead of using the entire image at once, take crops of the image with a sliding window with overlap. You need to label the crops as well.</p>
tensorflow|deep-learning|tf-slim
0
636
53,818,563
Cropping image in numpy array
<p>I want to crop RGB images such that the upper half part of the image is removed. After cropping I want to concatenate the image to a numpy array (here images). But I get the following error <code>ValueError: all the input array dimensions except for the concatenation axis must match exactly</code>. I tried multiple ...
<p>You should do </p> <pre><code>images = np.zeros((1, 32, 64, 3)) image = get_image() # has shape 1, 64, 64, 3 # removing the first coordinate didn't change the error. images = np.concatenate([images, image[:, 32:, :, :]], axis=0) </code></pre> <p>As 32:63 leaves out the last element. (32:64 would be possible too...
python|image|numpy
1
637
54,069,863
Swap two rows in a numpy array in python
<p>How to swap xth and yth rows of the 2-D NumPy array? x &amp; y are inputs provided by the user. Lets say x = 0 &amp; y =2 , and the input array is as below:</p> <pre><code>a = [[4 3 1] [5 7 0] [9 9 3] [8 2 4]] Expected Output : [[9 9 3] [5 7 0] [4 3 1] [8 2 4]] </code></pre> ...
<p>Put the index as a whole:</p> <pre><code>a[[x, y]] = a[[y, x]] </code></pre> <p>With your example:</p> <pre><code>a = np.array([[4,3,1], [5,7,0], [9,9,3], [8,2,4]]) a # array([[4, 3, 1], # [5, 7, 0], # [9, 9, 3], # [8, 2, 4]]) a[[0, 2]] = a[[2, 0]] a # array([[9, 9, 3], # [5, 7, 0], ...
python|arrays|numpy|swap
65
638
53,884,001
How do I fix dimension error in a simple Autoencoder?
<p>I am new to python and autoencoders. I just wanted to build a simple autoencoder to start with, but I keep getting this error:</p> <pre><code>ValueError: Error when checking target: expected conv2d_39 to have 4 dimensions, but got array with shape (32, 3) </code></pre> <p>Is there a better way to get my own data, ...
<p>Since you are building an autoencoder and therefore the output of the model must be the same as the input, there are two problems with your code:</p> <ol> <li><p>You must set the <code>class_mode</code> argument of generators to <code>'input'</code> to let the labels generated be the same as the generated inputs.</...
python|tensorflow|machine-learning|keras|autoencoder
2
639
53,948,123
I am not able to build .so file
<p>I am trying to make an app for object detection using tensorflow and I am following the instructions as listed in this website: </p> <p><a href="https://www.skcript.com/svr/realtime-object-and-face-detection-in-android-using-tensorflow-object-detection-api/" rel="nofollow noreferrer">https://www.skcript.com/svr/rea...
<p>I SOLVED IT! I found the problem was that i was using the ndk-bundle from under Android Studio's folder and it was the latest ndk. I downloaded an older ndk version android_ndk_r15c and ran the command:</p> <pre><code>bazel build -c opt //tensorflow/contrib/android:libtensorflow_inference.so --crosstool_top=//exter...
android|python|windows|tensorflow|bazel
1
640
54,231,398
add new column based on the several rows which have the same date
<p>I have one data frame as below. At first,they have three columns<code>('date','time','flag')</code>. I want to add one column which based on the flag and date which means when I get <code>flag=1</code> in one day at first, then this row target is <code>1</code>, the other target in this day is <code>0</code>.</p> <...
<p>Compare <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.cumsum.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.cumsum</code></a> by <code>1</code> and chain codition compare <code>flag</code> by <code>1</code> with <code>bitwise AND</code> and convert to int...
python|pandas
1
641
54,146,761
tensorflow: output layer with a single neuron, expected float output [0.0,1.0]
<p>I try to build a nn with an output layer consisting of a single neuron only. My input data contain 500 floats assigned to a "0" or "1". The final nn should output a "probability" value [0.0, 1.0]. Since I'm new to tensorflow, I have taken an MNIST example from Aurélien Géron's excellent book and modified it accordin...
<ol> <li>Logits should not have an activation.</li> <li>Loss should be sigmoid capable of handling logits, <code>tf.nn.sigmoid_cross_entropy_with_logits</code> is the one.</li> <li>You can calculate accuracy by checking whether final logit is less than zero or more than zero. If the first case, classify it as 0, if sec...
python|tensorflow
0
642
65,987,202
Equations related to indexing with Numpy Python
<p>I am trying to make a function that calculates the difference between the previous array and the current array. So the first 2 numbers in the <code>Numbers</code> array is <code>52599, 52575</code>, the previous number is <code>52599</code> with the label <code>U</code> and the current number is <code>52575</code>...
<p>I think you want the <a href="https://numpy.org/doc/stable/reference/generated/numpy.roll.html" rel="nofollow noreferrer">np.roll()</a> function. You need to be careful with the first and/or last entry, but as long as you handle those edge cases then:</p> <p><code>Numbers - np.roll(Numbers, -1)</code></p> <p>will gi...
python|arrays|function|numpy|indexing
0
643
66,051,785
numpy get values in col2 given an array of values matching col1
<p>How can I extract values in Col1 whose Col0 matches any values in a numpy array. I have an np array A, idx. Get me all values in Col1 of array A, whose Col0 values are 1 or 4.</p> <pre><code>A = np.array([[1, 11], [2, 12], [3, 13], [4,14]]) idx = [1, 4] </code></pre> <p>I can get for 1 value like this.. but I don't...
<p>1st part:</p> <pre><code>idx = [1, 4] A[np.isin(A[:,0], idx), 1] </code></pre> <hr /> <pre><code>array([11, 14]) </code></pre> <hr /> <p>2nd part:</p> <pre><code>idx = [1, 3] A[idx,1] </code></pre> <hr /> <pre><code>array([12, 14]) </code></pre>
python|arrays|numpy
1
644
52,765,294
Unable to compile Tensorflow from source on Ubuntu 18.04
<p>When I attempt to compile TensorFlow from source I get the following error. I'm using the GPU Docker image to run the build. Which in theory has all of the proper dependencies set up. </p> <p>The host machine(s) is Ubuntu 18.04. I'm receiving this issue on two different machines that both have the latest Nvidia dri...
<p>it seems it was solved on this commit <a href="https://github.com/tensorflow/tensorflow/commit/08af8cac22af4cc430e092b6218ca77736efb82c" rel="nofollow noreferrer">here</a>.</p> <p>Check also the thread where it was mentioned in the first place <a href="https://github.com/tensorflow/tensorflow/issues/22583" rel="nofo...
tensorflow
2
645
46,342,959
Python - How to combine / concatenate / join pandas series variables ignoring the empty variable
<p>With the help of .loc method, I am identifying the values in a column in a Panda data frame based on values in the another column of the same data frame.</p> <p>The code snippet is given below for your reference :</p> <pre><code>var1 = output_df['Player'].loc[output_df['Team']=='India'].reset_index(drop=True) var2...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> with <code>apply</code> for remove <code>NaN</code>s by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dropna.html" rel="nofollow norefer...
python|python-3.x|pandas
2
646
46,389,373
When running gym, sanity check returns attribute error for numpy __version__
<p>I am trying to get open AI gym working, but i am facing a very persistent error.<br/> When I run my programme (just the simple demo cartpole solver) I get this error. (The file "gperm.py" is the cartpole solver)</p> <pre><code>File "gperm.py", line 1, in &lt;module&gt; import gym File "/Users/sonyaferraro/Desktop/d...
<p>Based on your terminal output, I think you're using MacOS with brew.</p> <p><code>brew link --overwrite numpy</code> seems to have fixed the issue for me.</p>
python|numpy|openai-gym
2
647
58,588,604
Numpy array indexing unexpected behavior
<p>Consider the following:</p> <pre><code>import numpy as np X = np.ones((5,5)) print(X[:,0].shape) print(X[:,0:1].shape) </code></pre> <ul> <li><p><code>X[:,0].shape</code> returns <code>(5,)</code></p></li> <li><p><code>X[:,0:1].shape</code> returns <code>(5,1)</code>.</p></li> </ul> <p>In both cases the same co...
<p>This behaviour is explained by the fact that, as opposed to indexing with a slice, integer indexing with say <code>i</code>, will return the same values as a slice <code>i:i+1</code> but with the dimensionality of the returned object reduced by <code>1</code>. This is explained in the <a href="https://docs.scipy.org...
python|numpy
1
648
69,295,963
Color Negative Values on Matplotlib Bar Plots Differently
<p>I am trying to color the bar plots of the negative values differently. Any pointer to accomplish this is much appreciated. Thanks.</p> <pre><code>import matplotlib.pyplot as plt import numpy as np city=['a','b','c','d'] pos = np.arange(len(city)) Effort =[4, 3, -1.5, -3.5] plt.barh(pos,Effort,color='blue',edgeco...
<p>Just color a second plot differently:</p> <pre class="lang-py prettyprint-override"><code>city = ['a', 'b', 'c', 'd'] pos = np.arange(len(city)) Effort = np.array([4, 3, -1.5, -3.5]) plt.barh(pos[Effort &gt;= 0], Effort[Effort &gt;= 0], color='blue', edgecolor='black') # positive values in blue plt.barh(pos[Effort...
python|pandas|matplotlib|visualization
1
649
69,235,383
pytorch custom loss function nn.CrossEntropyLoss
<p>After studying autograd, I tried to make loss function myself. And here are my loss</p> <pre><code>def myCEE(outputs,targets): exp=torch.exp(outputs) A=torch.log(torch.sum(exp,dim=1)) hadamard=F.one_hot(targets, num_classes=10).float()*outputs B=torch.sum(hadamard, dim=1) return torch.sum(A-...
<p><code>torch.nn.CrossEntropyLoss</code> is different to your implementation because it uses a trick to counter instable computation of the exponential when using numerically big values. Given the logits output <code>{l_1, ... l_j, ..., l_n}</code>, the softmax is defined as:</p> <pre><code>softmax(l_i) = exp(l_i) / s...
python|pytorch|loss-function|cross-entropy
1
650
69,156,439
pandas dataframe groupby conditional count on multi-level column
<p>Let's say we have dataframe like this</p> <pre><code>np.random.seed(123) df = pd.DataFrame(np.random.randint(100,size=(4, 4)),columns = pd.MultiIndex.from_product([['exp0','exp1'],['rnd0','rnd1']],names=['experiments','rnd_runs'])) df['grp1','cat'] = ['A','A','B','B'] df['grp2','cat2'] = ['C','C','C','B'] experime...
<p>The only ways to select MultiIndex columns from a groupby is with a <em>list</em> of tuples or a MultiIndex (as indicated by the Error Message):</p> <p>So, instead of <code>[('exp0', 'rdn')]</code> it needs to be <code>[[('exp0', 'rdn')]]</code>, then it just needs to be a valid column name like <code>('exp0', 'rnd0...
python|pandas|dataframe|pivot-table|multi-index
2
651
68,982,444
select_dtypes(include=['number']) does not select the first column
<p>I am reading an excel file like so:</p> <pre><code>df = pd.read_excel(r&quot;C:file.xlsx&quot;, sheet_name='first') </code></pre> <p><code>df</code></p> <pre><code>category 1 2 3 4 A 105 200 54 49 B 18 9 8 74 </code></pre> <pre><code># then I want to multiply the numbers...
<p>First columns is filled by numbers saved like strings, check it by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dtypes.html" rel="nofollow noreferrer"><code>DataFrame.dtypes</code></a>:</p> <pre><code>print (df.dtypes) category object 1 object 2 int64 3 ...
python|pandas
1
652
44,724,228
Efficiently check rows that match certain values in Pandas DataFrame and add it to another dataframe
<p>I have a dataframe (called: data) which has list of customers and their purchases - looks like this:</p> <p><code>ID product 1 orange 1 banana 2 apple 2 orange 2 banana 3 banana 3 apple 4 apple 5 apple 5 orange 5 banana </code> what I would like ...
<p><code>pd.get_dummies</code> my friend</p> <p>have a look here <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html</a></p>
python|pandas|dataframe
3
653
44,791,932
Convert string tensor to lower case
<p>Is there any way to convert a string tensor to lower case, without evaluating in the session ? Some sort of <code>tf.string_to_lower</code> op ?</p> <p>More specifically, I am reading data from <code>tfrecords</code> files, so my data is made of tensors. I then want to use <code>tf.contrib.lookup.index_table_from_*...
<p>Here's an implementation with tensorflow ops:</p> <pre><code>def lowercase(s): ucons = tf.constant_initializer([chr(i) for i in range(65, 91)]) lcons = tf.constant_initializer([chr(i) for i in range(97, 123)]) upchars = tf.constant(ucons, dtype=tf.string) lchars = tf.constant(lcons, dtype=tf.string...
tensorflow
1
654
60,896,818
question about asterik in curve fitting code
<p>In this following example where it is trying to curve fit a sigmoid function to data I don't understand what does * in <code>*ppot</code> in line 11 mean</p> <pre><code>from scipy.optimize import curve_fit import numpy as np import matplotlib.pyplot as plt def sigmoid(x, Beta_1, Beta_2): y = 1 / (1 + np.exp(-B...
<p>The <code>curve_fit</code> method returns <code>popt</code> as a list of values, in this case, a list of 2 values (optimal values for the parameters).</p> <p>Adding the <code>*</code> before a list splits the list into its values each assigned to a parameter of the function.</p> <p>Example</p> <pre class="lang-py...
numpy|scikit-learn|user-defined-functions
1
655
60,859,500
How to fix Python/Pandas too many indexers error?
<p>I have tried the run the code below in Python 3.7 to loop through every combination of data columns in the dataframe 'Rawdata' to create a subset of regression models using statsmodel library and returns the best one. The code does not throw up any errors until I run the last line: best_subset(X, Y). It returns : "I...
<p>Your looping variable subset can be a tuple of length n_features. If, for example, the subset is (0, 1), your regression reads as</p> <pre><code>lin_reg = sm.OLS(Y, X.iloc[:, (0, 1)]).fit() </code></pre> <p>Pandas does not know how to handle this (see <a href="https://stackoverflow.com/questions/30781037/too-many-...
python-3.x|pandas|python-3.7|statsmodels
0
656
71,742,794
Validation of a conditional rule in a column and duplication in another
<p>I have a database of products and I have to validate if the product ID repeats in a column and also validate if it's 'True' or 'False' in another column. Then set all to 'True' if at least one of the duplicated rows are 'True'.</p> <p>I found a way in this link: <a href="https://stackoverflow.com/questions/67164011/...
<p>You can conveniently use <code>max</code> in a <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html" rel="nofollow noreferrer"><code>groupby.transform</code></a>:</p> <pre><code>df['Active'] = df.groupby('ID')['Active'].transform('max') </code></pre> <p>Or <code>a...
python|pandas
2
657
71,688,024
How to calculate conditional aggregate measure for each row in dataframe?
<p>I have a table like this...</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Date</th> <th>PlayerId</th> <th>Goals</th> </tr> </thead> <tbody> <tr> <td>June 1</td> <td>A</td> <td>1</td> </tr> <tr> <td>June 14</td> <td>A</td> <td>1</td> </tr> <tr> <td>June 15</td> <td>B</td> <td>2</td> </t...
<p>I change your solution to custom function per groups with mask created by broadcasting and <code>sum</code> values of <code>Goals</code> column per groups if match:</p> <pre><code>#if necessary #df['Date'] = pd.to_datetime(df['Date'], format='%B %d') def f(x): d1 = x['Date'] d2 = d1 - pd.to_timedelta(30,uni...
python|pandas|conditional-statements|aggregate
1
658
71,576,695
Parse a JSON column in a df and extract specific key value
<p>I have a pandas DataFrame containing one column with a nested JSON dict. I want to normalize the JSON column ('media') and extract the value for the key 'url' when it is present. The 'media' json payload has three types of possible media objects all included in the example data set. I need to extract from the 'Messa...
<p>The problem is that value in media column is string type. You can apply <code>ast.literal_eval</code> to media column to convert it value to python dict.</p> <pre class="lang-py prettyprint-override"><code>import ast pd.json_normalize(df['media'].apply(ast.literal_eval), max_level=1) </code></pre>
python|json|pandas|dataframe|json-normalize
1
659
71,668,181
Add a column in a Pandas dataframe and input a certain name
<p>I am working with a dataset using Pandas (Python/Jupyter notebook).</p> <p>I want to search one column in dataset imported and if some of the text appears add a new column with particular details and input a particular name eg</p> <p>I want to search the following dataset so if Tom appears in the set add column name...
<p>Jupyter notebook is just an interface which allows you to combine python lines with markup for something that is easy to read. As for your problem, it might help to be a little descriptive.</p> <p>What are you using to create the table? Is it pandas library? If it is you could do something like</p> <pre><code>df[&qu...
python|pandas|dataframe|jupyter-notebook|jupyter
2
660
42,578,096
Low accuracy in Deep Neural Network with Tensorflow
<p>I am following the third Jupyter notebook on <a href="https://github.com/jdwittenauer/ipython-notebooks/blob/master/notebooks/tensorflow/Tensorflow-3-Regularization.ipynb" rel="nofollow noreferrer">Tensorflow examples</a>.</p> <p>Running problem 4, I tried to implement a function which builds automatically a number...
<p>Weight regularization is stronger with more layers. Therefore you could try to reduce the regularization and see if the accuracy increases.</p>
python|machine-learning|tensorflow|deep-learning
0
661
42,135,056
How to get only nonzero values from Sparse Tensor
<p>Utilizing TensorFlow's HashTable lookup implementation i get my SparseTensor back with the default value supplied. I'd like to clean that off and get a final SparseTensor without the default value.</p> <p>How can I clean that default value? I don't mind what the default value will be in order to make this happen. ...
<p><code>tf.sparse_retain</code> should work:</p> <pre><code>def sparse_remove(sparse_tensor, remove_value=0.): return tf.sparse_retain(sparse_tensor, tf.not_equal(a.values, remove_value)) </code></pre> <p>As an example:</p> <pre><code>import tensorflow as tf a = tf.SparseTensor(indices=[[1, 2], [2, 2]], values=[...
tensorflow
0
662
42,514,206
TensorFlow : Enqueuing and dequeuing a queue from multiple threads
<p>The problem I am trying to solve is as follows : I have a list <code>trainimgs</code> of filenames. I have defined a </p> <ul> <li><code>tf.RandomShuffleQueue</code> with its <code>capacity=len(trainimgs)</code> and <code>min_after_dequeue=0</code>. </li> <li>This <code>tf.RandomShuffleQueue</code> is expected to b...
<p>I finally found out the answer. The problem was that multiple threads were clashing together on various points in the <code>work()</code> function. The following <code>work()</code> function works perfectly.</p> <pre><code>def work(coord, val, sess, epoch, maxepochs, incrementepoch, supplyimg, q, lock, close_op): ...
tensorflow|python-multithreading
2
663
42,451,155
Pandas merge column after json_normalize
<p>I have a list of dicts in a single column but for each row, a different <em>post_id</em> in a separate column. I've gotten the dataframe I am looking for via <code>pd.concat(json_normalize(d) for d in data['comments'])</code> but I'd like to add another column to this from the original dataframe to attach the origin...
<p>Consider first outputting dataframe <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_json.html" rel="nofollow noreferrer"><code>to_json</code></a> then run <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.io.json.json_normalize.html" rel="nofollow norefe...
python|pandas
4
664
42,542,790
pandas slice rows based on joint condition
<p>consider the below dataframe -df</p> <pre><code> one two three four five six seven eight 0 0.1 1.1 2.2 3.3 3.6 4.1 0.0 0.0 1 0.1 2.1 2.3 3.2 3.7 4.3 0.0 0.0 2 1.6 0.0 0.0 0.0 0.0 0.0 0.0 0.0 3 0.1 1.2 2.5 3.7 4.4 0.0 0.0 0.0 4 1.7 2.1 ...
<p>You can do the following in short:</p> <pre><code>df.eq(3.2).any(axis=1) &amp; ~df.isin([0.1, 1.2]).any(axis=1) </code></pre> <p>Or here more explicitly:</p> <pre><code>contains = df.eq(3.2).any(axis=1) not_contains = ~df.isin([0.1,1.2]).any(axis=1) print(df[contains &amp; not_contains]) one two three ...
python|pandas|numpy
4
665
70,002,979
Create return dataframe from price dataframe
<p>I try to figure out an efficient way to create a DataFrame of returns (ReturnTable) based on prices (PriceTable). Is there a more efficient way than just iterating with a for loop over the columns?</p> <p>Here I have a small example:</p> <pre><code>import pandas as pd PriceTable = pd.DataFrame({ 'Dates':['2021-0...
<p>You could use <code>shift</code> and a division:</p> <p><em>NB. <code>'NaN'</code> are strings, so you first need to convert to <code>float('nan')</code></em></p> <pre><code>PriceTable = PriceTable.replace('NaN', float('nan')) cols = PriceTable.select_dtypes('number').columns ReturnTable = PriceTable.copy() Return...
python|pandas|dataframe
2
666
69,915,768
Bias grad in linear regression remains small compared to weight grad, and intercept is not properly learnt
<p>I have thrown together a dummy model to showcase linear regression in pytorch, but I find that my model is not properly learning. It's doing well when it comes to learning the slope, but the intercept is not really budging. Printing out the grads at every epoch tells me that, indeed, the grad is a lot smaller for th...
<p>It's a bit of a non-answer, but just use more epochs or add more datapoints. When you have 100 datapoints with noise as significant as you had (if you just plot the initial data it becomes obvious) the model will struggle with MSE as a loss.</p> <p>I can't see your image (work blocked imgur...) but I found it looked...
python-3.x|deep-learning|neural-network|pytorch
1
667
69,999,194
Reverse operation of torch.unique
<p>In pytorch , unique (with return_count is True) operation do like this</p> <pre><code>[1,1,2,2,3,3] =&gt; ([1,2,3],[2,2,2]) </code></pre> <p>Are there any reverse operations of torch.unique() ? i.e Given a unique list and its count , return the original list like</p> <pre><code>([1,2,3],[2,2,2]) = &gt; [1,1,2,2,3,3]...
<p>You probably want <a href="https://pytorch.org/docs/stable/generated/torch.repeat_interleave.html" rel="nofollow noreferrer">torch.repeat_interleave()</a>. You can use it like this:</p> <pre class="lang-py prettyprint-override"><code> &gt;&gt;&gt; x = torch.tensor([1, 1, 2, 3, 3, 3]) &gt;&gt;&gt; v, c = torch.uniqu...
pytorch
0
668
69,669,956
python, Iterate through a dataframe and check if a value from a list exist in a column in that dataframe
<p>I have a dataframe that contains a column with different submarkets from a city. I need to iterate through that column and check if a value in that row matches any of the entries that could be in the list. that list will then be added as a column to the original dataframe</p> <pre><code>submarket_list = [ 'South Fin...
<pre><code>test_df[&quot;Submarket&quot;].isin(submarket_list) </code></pre> <p>will give you a column of booleans. It's all you need</p>
python|pandas|dataframe
2
669
72,289,714
How to validate Hugging Face organization token?
<p><code>/whoami-2</code> endpoint returns <code>Unauthorized</code> for organization tokens, the ones that start with <code>api_...</code>.</p> <pre><code>$ curl https://huggingface.co/api/whoami-2 -H &quot;Authorization: Bearer api_&lt;token&gt;&quot; &gt; { &quot;error&quot;: &quot;Unauthorized&quot; } </code></pre>...
<p>you are requesting to the wrong endpoint. It seems the endpoint is updated and I got a similar error with sending requests to the older endpoint (<code>whoami</code>).</p> <p>just send the request to <code>whoami-v2</code> like:</p> <pre><code>$ curl https://huggingface.co/api/whoami-v2 -H &quot;Authorization: Beare...
curl|huggingface-transformers|huggingface
1
670
72,385,968
Detecting duplicates in pandas when a column contains lists
<p>Is there a reasonable way to detect duplicates in a Pandas dataframe when a column contains lists or numpy nd arrays, like the example below? I know I could convert the lists into strings, but the act of converting back and forth feels... wrong. Plus, lists seem more legible and convenient given <a href="https://www...
<p>With <code>map</code> <code>tuple</code></p> <pre><code>out = df[df.assign(rating = df['rating'].map(tuple)).duplicated(keep=False)] Out[295]: author date rating 0 Jefe98 1423112400 [ingredA, ingredB, ingredC] 1 Jefe98 1423112400 [ingredA, ingredB, ingredC] </code></pre>
python|pandas|dataframe|duplicates
1
671
50,256,918
Plot a pandas categorical Series with Seaborn barplot
<p>I would like to plot the result of the <code>values_counts()</code> method with <code>seaborn</code>, but when I do so, it only shows one of the variables.</p> <pre><code>df = pd.DataFrame({"A":['b','b','a','c','c','c'],"B":['a','a','a','c','b','d']}) counts = df.A.value_counts() sns.barplot(counts) </code></pre> ...
<p>You can do this:</p> <pre><code># Sorting indices so it's easier to read counts.sort_index(inplace=True) sns.barplot(x = counts.index, y = counts) plt.ylabel('counts') </code></pre> <p><a href="https://i.stack.imgur.com/9V0wG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9V0wG.png" alt="enter image d...
python|pandas|seaborn
7
672
50,553,605
Extract rule path of data point through decision tree with sklearn python
<p>I'm using decision tree model and I want to extract the decision path for each data point in order to understand what caused the Y rather than to predict it. How can I do that? Couldn't find any documentation. </p>
<p>Here is an example using the <code>iris dataset</code>.</p> <pre><code>from sklearn.datasets import load_iris from sklearn import tree import graphviz iris = load_iris() clf = tree.DecisionTreeClassifier() clf = clf.fit(iris.data, iris.target) dot_data = tree.export_graphviz(clf, out_file=None, ...
python|decision-tree|sklearn-pandas
1
673
45,590,507
Install TensorFlow & Tensorboard from source
<p>I want to install Tensorflow (CPU)(py 3.6) for windows, my company uses a proxy, so i can't install through pip, i have to build it from source. I unzipped tensorflow/tensorboard/protobuf.tar.gz in my Anaconda3 folders.</p> <p>When i use the setup.py files, it occurs that i need tensorboard for installing tensorfl...
<p>You can use pip with proxy. I was struggling with company proxy too and that was the solution for me: Run a command prompt as administrator and type the following:</p> <p>pip install --proxy <a href="http://username:password@proxy_url:port" rel="nofollow noreferrer">http://username:password@proxy_url:port</a> tenso...
python|tensorflow|tensorboard
1
674
62,641,280
generate binary list of minutes which indicates wheter or not said minute is in a given time range
<p>I have a list of ranges that looks like this:</p> <pre><code> [(Timestamp('2018-12-17 07:30:45', freq='S'), Timestamp('2018-12-17 07:32:45', freq='S')), (Timestamp('2018-12-03 07:14:12', freq='S'), Timestamp('2018-12-03 07:15:39', freq='S')), (Timestamp('2018-12-03 07:32:47', freq='S'), Timestamp('2018-12...
<p>For test purpose, I took a shorter set of date / time pairs:</p> <pre><code>arr = np.array([ ('2018-12-17 23:40:45', '2018-12-17 23:45:45'), ('2018-12-18 00:14:12', '2018-12-18 00:20:39'), ('2018-12-18 00:30:47', '2018-12-18 00:34:10')], dtype='datetime64') </code></pre> <p>It is much easier to use <em>P...
numpy
1
675
62,542,232
calculate age from dob and given date in pandas and make age as zero if dob is missing in pandas
<p>I have a data frame as shown below. df:</p> <pre><code>cust_id lead_date dob 1 2016-12-25 1989-12-20 2 2017-10-25 1980-09-20 3 2016-11-25 NaN 4 2014-04-25 1989-12-20 5 2019-12-21 ...
<p>You can do:</p> <pre><code># convert to datetime type df['lead_date'] = pd.to_datetime(df.lead_date) df['dob'] = pd.to_datetime(df.dob) df['age'] = (df.lead_date.dt.year - df.dob.dt.year).fillna(0) </code></pre> <p>Output:</p> <pre><code> cust_id lead_date dob age 0 1 2016-12-25 1989-12-20 27.0 ...
pandas
1
676
62,636,267
How to aggregate goupby and discard the rows after appearing a certain value?
<p>Say I have a given dataframe as below</p> <pre><code>input = pd.DataFrame({&quot;id&quot;:[1,1,1,2,2,3,3,3,3,3], &quot;values&quot;:[&quot;l&quot;, &quot;m&quot;, &quot;c&quot;, &quot;l&quot;, &quot;l&quot;, &quot;l&quot;, &quot;l&quot;, &quot;c&quot;,&quot;c&quot;, &quot;c&quot;]}) </code></pre> <p>and I wanted to ...
<p>Create a <em>boolean mask</em> where <code>values</code> equals <code>c</code>, then use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>DataFrame.groupby</code></a> to group this mask on <code>id</code>, then transform it using <code...
python|pandas|pandas-groupby
2
677
62,545,134
How to use embedding models in tensorflow hub with LSTM layer?
<p>I'm learning tensorflow 2 working through the text classification with TF hub tutorial. It used an embedding module from TF hub. I was wondering if I could modify the model to include a LSTM layer. Here's what I've tried:</p> <pre><code>train_data, validation_data, test_data = tfds.load( name=&quot;imdb_reviews&...
<p>Finally figured out the way to link pre-trained embeddings to LSTM or other layers. Just post the steps here in case anyone feels helpful.</p> <p>Embedding layer has to be the first layer in the model. (hub_layer is the same as Embedding layer.) The not very intuitive part is that any text input to the hub layer wil...
tensorflow|keras|lstm
2
678
62,722,004
Roles of parameter servers and workers
<p>What exact role do <strong>parameter servers</strong> and <strong>workers</strong> have the during <strong>distributed training</strong> of neural networks? (e.g. in Distributed TensorFlow)</p> <p>Perhaps breaking it down as follows:</p> <ul> <li>During the forward pass</li> <li>During the backward pass</li> </ul> <...
<p><strong>Parameter Servers</strong> — This is actually same as a <code>worker</code>. Typically it’s a <code>CPU</code> where you store the <code>variables</code> you need in the <code>workers</code>. In my case this is where I defined the <code>weights variables</code> needed for my networks</p> <p><strong>Workers</...
tensorflow|deep-learning|tensorflow2.0|distributed-computing
1
679
62,635,974
Pandas concat multi level index dataframes and merge same name columns within same level
<p>I have two multi-level index dataframes. When I concat them, the same name columns become duplicated.</p> <p>df1</p> <pre><code>Column col1 col2 1 3 2 4 </code></pre> <p>I want to merge this with another df,</p> <p>df2</p> <pre><code>Column col3 5 6 </code></pre> <p>When I merge both us...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_index.html" rel="nofollow noreferrer"><code>DataFrame.sort_index</code></a>:</p> <pre><code>pd.concat([df1, df2], axis=1).sort_index(axis=1) </code></pre> <p>EDIT:</p> <pre><code>print (df1) Column col5 col2 0 ...
python|pandas
1
680
54,613,578
Assigning "list of directory" array on numpy
<p>I tried assigning a list of directories on a numpy array, but somehow the array only stores the first letter, not the full address of strings.</p> <pre><code>lasdir=np.array(range(4), dtype=str).reshape(2,2) i=0 for root, dirs, files in os.walk(source_dir): for file in files: if (file.lower().endswith("...
<p>When usings a <code>str</code> dtype, it uses fixed-length strings. As suggested <a href="https://stackoverflow.com/a/14639568/9291575">in this answer</a>, you're better off using dtype <code>object</code>.</p> <p>So your first line could transform to :</p> <pre><code>lasdir = np.empty((2,2), dtype=object) </code>...
python|numpy
0
681
73,618,309
Implement inverse of minmax scaler in numpy
<p>I want to implement inverse of min-max scaler in numpy instead of sklearn. Applying min max scale is easy</p> <pre><code>v_min, v_max = v.min(), v.max() new_min, new_max = 0, 1 v_p = (v - v_min)/(v_max - v_min)*(new_max - new_min) + new_min v_p.min(), v_p.max() </code></pre> <p>But once I got the scaled value, how c...
<p>Try Mathematic:</p> <pre><code>import numpy as np org_arr = np.array([ [2.0, 3.0], [2.5, 1.5], [0.5, 3.5] ]) # save min &amp; max min_val = org_arr.min(axis = 0) max_val = org_arr.max(axis = 0) scl_arr = (org_arr - min_val) / (max_val - min_val) print(scl_arr) # inverse of min-max scaler in numpy or...
python|numpy
2
682
73,660,261
What is the most efficient way to make a method that is able to process single and multi dimensional arrays in python?
<p>I was using pytorch and realized that for a linear layer you could pass not only 1d tensors but multidmensional tensors as long as the last dimensions matched. <a href="https://stackoverflow.com/questions/58587057/multi-dimensional-inputs-in-pytorch-linear-method">Multi dimensional inputs in pytorch Linear method?</...
<p><em>I tried looping over each item, but is that what pytorch does?</em></p> <p>The short answer is yes, loops are used, but it's more complicated than you probably think. If <code>input</code> is a 2D tensor (a matrix), then the output of a linear operation is computed as <code>input @ weight.T + bias</code> using a...
python|arrays|pytorch
0
683
71,223,050
How do I find last index of true value in a dataframe when applying condition to each row in an efficient way in python?
<p>Let us say I have pandas dataframe having two columns, <em>previous</em> and <em>current</em>. We can assume that values are non-decreasing and <em>current</em> values are always greater than <em>previous</em> value.</p> <p>Now, for each element in <em>previous</em> column, I want to look up index of last value of <...
<p>Since the values are non-decreasing, you can use numpy.broadcasting, <code>[:, None]</code>, to compare the current values with all previous values. We then take the sum and subtract 1 since counting starts at 0, giving us the index position of the last row with current value &lt; the previous value for all rows in ...
python|pandas|dataframe
3
684
71,319,951
extract items from column with pandas
<p>I have a DataFrame with the following structure:</p> <pre><code> id year name genres 238 2022 Adventure [{&quot;revenue&quot;: 1463, &quot;name&quot;: &quot;culture clash&quot;, 'runtime': 150, 'vote_average': 7}] 239 2020 Comedy [] </code></pre> <p>But what I need is this structure...
<p>You could try: In case the <code>genres</code> columns contains strings do</p> <pre><code>df[&quot;genres&quot;] = df[&quot;genres&quot;].map(eval) </code></pre> <p>fist. Then:</p> <pre><code>df = pd.concat( [df[[&quot;id&quot;, &quot;year&quot;]], pd.DataFrame(obj[0] if obj else {} for obj in df[&quot;genres&qu...
python|pandas
1
685
52,064,112
installing tensorflow_transform and apache_beam on Datalab
<p>I'm going over these example from google-cloud Coursera courses, and although they worked till a few weeks ago, I can't install tf.transform or apache_beam on Datalab anymore.</p> <p><a href="https://github.com/GoogleCloudPlatform/training-data-analyst/blob/master/courses/machine_learning/feateng/tftransform.ipynb"...
<p>The tensorflow version on my Datalab instance was 1.4. I had to add this one line of code to update tensorflow to 1.10.1</p> <pre><code>%bash pip install --upgrade --force-reinstall pip==10.0.1 pip install tensorflow==1.10.1 pip install tensorflow_transform </code></pre> <p>my environment: </p> <pre><code>apache-...
tensorflow|google-cloud-platform|apache-beam|google-cloud-datalab|tensorflow-transform
2
686
52,408,443
Specified Trace Colors not looping through entire Dash chart
<p>I have a dataframe that looks like this where I am plotting voter registration for political parties across the 27 districts of New York between the years 2014-2018:</p> <p><a href="https://i.stack.imgur.com/Sb5JI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Sb5JI.png" alt="enter image descrip...
<p>I removed the colors out of the list like this:</p> <p><code>marker=dict(color='rgb(3,67,223)'))</code></p>
python|pandas|plotly-dash
0
687
52,323,907
Some modules can be imported in python previously but now can only be imported in ipython2
<p>Previously I installed pytorch,PIL,numpy... using pip. After that I installed python3. Thus ipython switched from python2 to python3. I have to use ipython2 to start python2 kernel. These modules still works well in ipython2, but when I run a python script using python, python2, python2.7, they all raise ImportError...
<p>Make sure the python path that you given in bashrc is correct. Also it will be good to use conda environment to try out the same since there is confusion in python environments. For that you can follow the below steps:</p> <p>Create the environment and activate it using following commands:</p> <p>conda create -n t...
python|linux|python-2.7|numpy
0
688
60,684,643
nearest member aditional atribute analysis
<p>I have following dataframe df(sample):</p> <pre><code> lat lon crs Band1 x y 0 41.855584 20.619156 b'' 1568.0 468388.198606 4.633812e+06 1 41.855584 20.622590 b'' 1562.0 468673.173031 4.633811e+06 2 41.855584 20.626023 b'' 1605.0 468958.147443 4.633810e+0...
<p>IIUC, you can use <code>indices</code> to get the corresponding value in the column <code>Band1</code>, then use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html" rel="nofollow noreferrer"><code>np.argmax</code></a> with the parameter axis set to 1 to get the position of the highest va...
python|pandas|scikit-learn|sklearn-pandas
0
689
60,356,541
pivot table in specific intervals pandas
<p>I have a one column dataframe which looks like this:</p> <pre><code>Neive Bayes 0 8.322087e-07 1 3.213342e-24 2 4.474122e-28 3 2.230054e-16 4 3.957606e-29 5 9.999992e-01 6 3.254807e-13 7 8.836033e-18 8 1.222642e-09 9 6.825381e-03 10 5.275194e-07 11 2.224289e-06 12 2.259303e-09 13 2.014053e-0...
<p>Using <code>pivot_table</code>:</p> <pre><code>df.pivot_table(columns=df.index % 9, index=df.index // 9, values='Neive Bayes') 0 1 2 3 4 \ 0 8.322087e-07 3.213342e-24 4.474122e-28 2.230054e-16 3.957606e-29 1 6.825381e-03 5.275194e-07 2.22428...
python|python-3.x|pandas
2
690
60,480,686
pytorch model summary - forward func has more than one argument
<p>I am using torch summary </p> <pre><code>from torchsummary import summary </code></pre> <p>I want to pass more than one argument when printing the model summary, but the examples mentioned here: <a href="https://stackoverflow.com/a/56762410/5082406">Model summary in pytorch</a> taken only one argument. for e.g.:</...
<p>You can use the example given here: <a href="https://github.com/sksq96/pytorch-summary#multiple-inputs" rel="noreferrer">pytorch summary multiple inputs</a></p> <pre><code>summary(model, [(1, 16, 16), (1, 28, 28)]) </code></pre>
python|pytorch
14
691
61,780,927
Plot the correct point on x-axis
<p>I'd like to put the correct value of the point on x-axis not use the approximated number. For example, using pandas and matplotlib. </p> <p><a href="https://i.stack.imgur.com/kkw9B.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kkw9B.png" alt="enter image description here"></a></p> <p>I would l...
<p>You an do:</p> <pre><code>ax = plot_4.plot.line(logy=True, style=['+-','o-','.-','s-','x-'],grid=True,figsize=(10,6)).legend(title='algorithm', bbox_to_anchor=(1, 1), fontsize=12) ax.set_xticks(plot_4.index) </code></pre>
python|pandas|matplotlib
2
692
61,801,500
Convert date/month/year string variable to include time
<p>I have the following data with some Date/Month/Year string values:</p> <pre><code>import pandas as pd d = {'date': ["31/03/2019", "12/05/2020"]} df = pd.DataFrame(data=d) print(df) date 0 31/03/2019 1 12/05/2020` </code></pre> <p>I would like the <code>date</code> variable to be printed like this:</p> <pre><...
<p>You can try:</p> <pre><code>pd.to_datetime(df['date'], dayfirst=True).dt.strftime("%Y-%m-%dT%H:%M:%S.%fZ") </code></pre> <p>Output:</p> <pre><code>0 2019-03-31T00:00:00.000000Z 1 2020-05-12T00:00:00.000000Z Name: date, dtype: object </code></pre>
python|pandas|datetime
0
693
61,703,249
I was trying to create a video out of a numpy array but i was getting an error
<p>I was trying to create a video from a NumPy array, but i was getting this error all the time:</p> <pre><code>cv2.error: OpenCV(4.2.0) c:\projects\opencv-python\opencv\modules\imgproc\src\color.simd_helpers.hpp:94: error: (-2:Unspecified error) in function '__thiscall cv::impl::`anonymous-namespace'::CvtHelper&lt;st...
<p>I am only able to find a single RGB image in your link. Do you want to make a video with that single image of dimension 640x480x3? If you can ensure that the frame array here has multiple RGB images the following code should be enough:</p> <pre><code>import cv2 , time , numpy frame = numpy.asarray(the long list of ...
python|numpy|opencv|cv2
0
694
54,928,731
Pandas convert two separate columns into a single datetime column?
<p>I have two columns in a pandas dataframe that I want to convert into a single datetime column. The problem is that one of the columns is the week of the year and one is the actual year. It looks something like this:</p> <pre><code>WEEK_OF_YEAR | YEAR 1 2016 2 2016 ... 52 2016...
<p>If converting week of year is necesary define day of <a href="http://strftime.org/" rel="nofollow noreferrer">week by <code>%w</code></a>:</p> <blockquote> <p><strong>%w</strong> - Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.</p> </blockquote> <pre><code>#for Sundays is set value to 0 s = df...
python|pandas
3
695
54,798,223
Tensor conversion requested dtype int32 for Tensor with dtype int64 - while estimator.export_savedmodel
<p>Trying to export a model built using <a href="https://colab.research.google.com/github/google-research/bert/blob/master/predicting_movie_reviews_with_bert_on_tf_hub.ipynb" rel="nofollow noreferrer">https://colab.research.google.com/github/google-research/bert/blob/master/predicting_movie_reviews_with_bert_on_tf_hub....
<p>the bert model require input_ids,input_mask and segment_ids as type of tf.int32. In order to fix the bug, you have to convert them from tf.int64 to tf.int32 as below</p> <pre><code>def create_model(is_predicting, input_ids, input_mask, segment_ids, labels, num_labels): """Creates a classification model.""" inpu...
python|tensorflow
7
696
55,012,046
Trouble with ignore_index and concat()
<p>I'm new to Python. I have 2 dataframes each with a single column. I want to join them together and keep the values based on their respective positions in each of the tables.</p> <p>My code looks something like this:</p> <pre><code>huh = pd.DataFrame(columns=['result'], data=['a','b','c','d']) huh2 = pd.DataFrame...
<p>If you concatenate the DataFrames horizontally, then the column names are ignored. If you concatenate vertically, the indexes are ignored. You can only ignore one or the other, not both.</p> <p>In your case, I would recommend setting the index of "huh2" to be the same as that of "huh".</p> <pre><code>pd.concat([hu...
python|pandas
3
697
55,027,737
gRPC Name Resolution Failure
<p>While trying to run tensorflow-serving with docker, I am getting the following error issuing a client request using gRPC with following code:</p> <pre><code>`python client.py --server=172.17.0.2/16:9000 --image=./test_images/image2.jpg debug_error_string = "{"created":"@1551888435.208113000","description":"Failed ...
<p>This happens when the channel is in TRANSIENT_FAILURE and the load balancing policy can't find any ready backend to send the request. </p> <p>Please file an issue on <a href="https://github.com/grpc/grpc/" rel="nofollow noreferrer">https://github.com/grpc/grpc/</a> detailing what you did, hopefully with more log/tr...
docker|tensorflow-serving|grpc-python
1
698
49,641,753
how to match a character variable with a regex defined in another variable?
<p>Consider this simple example</p> <pre><code>import pandas as pd mydata = pd.DataFrame({'mystring' : ['heLLohelloy1', 'hAllohallo'], 'myregex' : ['hello.[0-9]', 'ulla']}) mydata Out[3]: myregex mystring 0 hello.[0-9] heLLohelloy1 1 ulla hAllohallo </code></pre> <p>...
<p>You can use <code>re library</code> and <code>apply function</code> do the following:</p> <pre><code>import re # apply function mydata['flag'] = mydata.apply(lambda row: bool(re.search(row['myregex'], row['mystring'])), axis=1) ### to convert bool to int - optional ### mydata['flag'] = mydata['flag'].astype(int) ...
python|regex|pandas
2
699
49,490,262
Combining graphs: is there a TensorFlow import_graph_def equivalent for C++?
<p>I need to extend exported models with a custom input and output layer. I have found out this can <em>easily</em> be done with:</p> <pre><code>with tf.Graph().as_default() as g1: # actual model in1 = tf.placeholder(tf.float32,name="input") ou1 = tf.add(in1,2.0,name="output") with tf.Graph().as_default() as g...
<p>It is not as easy as in Python.</p> <p>You can load a <code>GraphDef</code> with something like this:</p> <pre><code>#include &lt;string&gt; #include &lt;tensorflow/core/framework/graph.pb.h&gt; #include &lt;tensorflow/core/platform/env.h&gt; tensorflow::GraphDef graph; std::string graphFileName = "..."; auto sta...
python|c++|pointers|tensorflow|merge
2