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
1,200
58,350,527
How to get activation values from Tensor for Keras model?
<p>I am trying to access the activation values from my nodes in a layer.</p> <pre><code>l0_out = model.layers[0].output print(l0_out) print(type(l0_out)) </code></pre> <pre><code>Tensor("fc1_1/Relu:0", shape=(None, 10), dtype=float32) &lt;class 'tensorflow.python.framework.ops.Tensor'&gt; </code></pre> <p>I've tri...
<p>Try to use <code>K.function</code> and feed one batch of <code>train_x</code> into the function. </p> <pre><code>from keras import backend as K get_relu_output = K.function([model.layers[0].input], [model.layers[0].output]) relu_output = get_relu_output([train_x]) </code></pre>
tensorflow|keras|tensorflow2.0
1
1,201
58,279,548
Using split-apply-combine to remove some values with a customized function and combine what's left
<p>So this isn't the dataset I need to work with but it's a template for a huge one I'm working with (~1.8 million data points) for a cancer research project, so I figured if I could get this to work with a smaller one, then I can adapt it for my large one! So as a sample, let's say I have the following data set:</p> ...
<p>EDIT: more general solution</p> <p>First, it would help to make a <code>closure</code> to define your configurations. This is under the assumption that you will have more configurations in the future:</p> <pre><code>def create_num_to_delete(p, alpha): """Create a num_to_delete function given p and alpha.""" ...
python|pandas|split-apply-combine
2
1,202
69,276,635
Pandas MultiIndex Dataframe Styling error when writing to Excel
<p>I am trying to write a multi-index data frame to excel using pandas styling and I am getting an error.</p> <pre><code>import pandas as pd import numpy as np df=pd.DataFrame(np.random.randn(9,4), pd.MultiIndex.from_product([['A', 'B','C'], ['r1', 'r2','r3']]), columns=[['E1','E1','E2','E2'],['d1','d2','d1','d2']]) ...
<p>Assuming we're looking for <code>highlight_max_value_by_condition</code> is meant to apply styles to cells which are both the max in the subset and fulfill the condition we can add an <code>&amp;</code> to combine the conditions:</p> <pre><code>def highlight_max_value_by_condition(value, condition, props=''): re...
pandas|multi-index|pandas-styles
0
1,203
61,108,307
unable to read csv file on jupyter notebook
<pre><code>import pandas as pd import os df=pd.read_csv(r"C:/Users/tom/Desktop/misc/number-of-motor-vehicles-2018-census-csv.csv") df </code></pre> <p>the above 4 lines are my code and im getting the error as shown below</p> <pre><code>FileNotFoundError: [Errno 2] File C:/Users/tom/Desktop/misc/number-of-motor-vehic...
<p>Have you made sure that the file does not have a second extension (possibly .txt)? This might happen when e.g. saving a file with Notepad and appending <code>.csv</code> to the file name but disregarding the dropdown box "Save as type" ...</p> <p>You could try</p> <ul> <li>go to the “View” tab on the ribbon in Win...
python|pandas|csv
1
1,204
60,915,294
How to plot graph where the indexes are strings
<p>I'm running with <code>python 3.7.6</code> and I have the following <code>dataframe</code>:</p> <pre><code> col_1 col_2 col_3 col_4 GP 1 1 1 1 MIN 1 1 1 1 PTS 1 1 1 1 FGM 1 1 0 1 FGA 0 1 0 ...
<p>I'm not sure about scatter, but you can use <code>imshow</code> to display the binary values:</p> <pre><code>fig, ax = plt.subplots() ax.imshow(df, cmap='gray') ax.set_xticks(range(df.shape[1])) ax.set_xticklabels(df.columns) ax.set_yticks(range(df.shape[0])) ax.set_yticklabels(df.index) plt.show() </code></pre> ...
python|pandas
5
1,205
61,152,043
Python: Calculate cumulative amount in Pandas dataframe over a period of time
<p>Objective: Calculate cumulative revenue since 2020-01-01. </p> <p>I have a python dictionary as shown below</p> <pre><code>data = [{"game_id":"Racing","user_id":"ABC123","amt":5,"date":"2020-01-01"}, {"game_id":"Racing","user_id":"ABC123","amt":1,"date":"2020-01-04"}, {"game_id":"Racing","user_id":"CDE123"...
<p>Here the very complicated part is to fill dates. I used an apply but I'm not sure this is the best way</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd data = [{"game_id":"Racing","user_id":"ABC123","amt":5,"date":"2020-01-01"}, {"game_id":"Racing","user_id":"ABC123","amt":1,"date":"...
python|pandas|numpy|dictionary
1
1,206
71,533,791
How to create a scatterplot of data using `matplotlib.pyplot.scatter`
<p>I've problem with <code>matplotlib.pyplot.scatter</code>.</p> <p>Firstly, I need to download the data on Iris classification and paste headlines.</p> <pre class="lang-py prettyprint-override"><code> import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns ...
<p>There is no problem with <code>iris</code> datasets, just with the part you defined the alpha argument in the scatter function. You should change the way of assigning value to arguments in the way you did:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd import matplotlib.py...
python|python-3.x|pandas|matplotlib
1
1,207
71,766,800
Select all rows between specific row values in a within columns
<p>Im trying to select all the rows of data between rows with these values in E01032739 and E01033708, does anyone know how to do this. Trying to do this so i can count the number of casualties between these area codes.</p> <p>At the minute i can find all of the data with each set of values but cannot modify the code t...
<p>Is this what you are looking for ?</p> <pre><code>accidents[(accidents['LSOA_of_Accident_Location'] &gt;= 'E01032739')&amp;(accidents['LSOA_of_Accident_Location'] &lt;= 'E01033708')] </code></pre>
python|pandas|dataframe
1
1,208
71,557,950
Why are non-trainable parameters zero in model's summary, despite loading the weights of the model?
<p>I used the command</p> <pre><code>torch.save(model.state_dict(), 'model.pth') </code></pre> <p>to save the parameters after training the model. But, when I use the commands</p> <pre><code>model = EfficientNetModel() MODEL_PATH = 'model.pth' model.load_state_dict(torch.load(MODEL_PATH, map_location=map_location)) mod...
<p>Saving and loading weights back on a model doesn't affect the fact they are <em>trainable</em> or not. Nontrainable params contain tensors that do not require gradient computation, and as such won't get modified by your optimizer during training.</p>
deep-learning|pytorch|computer-vision|transfer-learning|pre-trained-model
0
1,209
71,574,827
How to print the layers of the tensorflow 2 saved_model
<p>I am using tensorflow 2.6.2 and I downloaded the model from the <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf2_detection_zoo.md" rel="nofollow noreferrer">Tensorflow 2 Model zoo</a> I am able to load the model using this</p> <pre><code>import tensorflow as tf if __name...
<p>I was able to print using this</p> <pre><code> loaded = tf.saved_model.load(&quot;/home/user/git/models_zoo/ssd_mobilenet_v2_320x320_coco17_tpu-8/saved_model/&quot;) infer = loaded.signatures[&quot;serving_default&quot;] for v in infer.trainable_variables: print(v.name) </code></pr...
tensorflow|deep-learning|tensorflow2.0
0
1,210
69,936,753
Using Pandas Count number of Cells in Column that is within a given radius
<p>To set up the question. I have a dataframe containing spots and their x,y positions. I want to iterate over each spot and check all other spots to see if they are within a radius. I then want to count the number of spots within the radius in a new column of the dataframe. I would like to iterate over the index as I ...
<p>To do it in a vectorized way, you can use <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance_matrix.html" rel="nofollow noreferrer"><code>scipy.spatial.distance_matrix</code></a> to compute the distance matrix, <code>D</code>, between all the <code>N</code> row/position vectors ('x_...
python|pandas|dataframe
3
1,211
70,013,562
Inserting column with specifics
<p>I have a specific question: I need to create a column name called &quot;Plane type&quot; for a column that contains the first 4 characters of the &quot;TAIL_NUM&quot; column.</p> <p>How can I do this? I already imported the data and I can see it.</p> <p><a href="https://i.stack.imgur.com/tjD8b.png" rel="nofollow nor...
<p>Creating new columns with Pandas (assuming that's what you're talking about) is very simple. Pandas also provides common string methods. <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.html" rel="nofollow noreferrer">Pandas Docs</a>, <a href="https://stackoverflow.com/questions/32213330/split...
python|pandas|dataframe
0
1,212
43,214,978
How to display custom values on a bar plot
<p>I'm looking to see how to do two things in Seaborn with using a bar chart to display values that are in the dataframe, but not in the graph.</p> <ol> <li>I'm looking to display the values of one field in a dataframe while graphing another. For example, below, I'm graphing 'tip', but I would like to place the value ...
<h2>New in matplotlib 3.4.0</h2> <p>There is now a built-in <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.bar_label.html" rel="noreferrer"><code>Axes.bar_label</code></a> to automatically label bar containers:</p> <ul> <li><p>For <strong>single-group</strong> bar plots, pass the single bar con...
python|pandas|matplotlib|seaborn|bar-chart
117
1,213
72,154,060
Breast cancer Dataset high loss function and low accuracy
<p>i am new to the ml topic and tried some training today. I ran into several problems until i reached the position where i am now. Can anyone explane to me why the accurcy is not changing and why the loss function is so high? I used the wisconsin breast cancer data set.</p> <p>Here is my code:</p> <pre><code>import pa...
<p>Looking at the Kaggle dataset you provide in the question comments, I run the model again. I faced the same problem you were describing:</p> <pre><code>Epoch 500/500 16/16 [==============================] - 0s 3ms/step - loss: 0.6577 - accuracy: 0.6328 </code></pre> <p>The reason is that in the dataset is present th...
python|pandas|tensorflow|keras
1
1,214
50,310,389
Extracting data from web page to CSV file, only last row saved
<p>I'm faced with the following challenge: I want to get all financial data about companies and I wrote a code that does it and let's say that the result is like below:</p> <pre>Unnamed: 0 I Q 2017 II Q 2017 \ 0 Przychody netto ze sprzedaży (tys. zł) 137 134 1 Zysk (strata) z działal. op...
<p>You've almost got it. You're just overwriting your CSV each time. Replace</p> <pre><code>df2.to_csv('output.csv', index=False, header=None) </code></pre> <p>with </p> <pre><code>with open('output.csv', 'a') as f: df2.to_csv(f, header=False) </code></pre> <p>in order to append to the CSV instead of overwri...
python-3.x|pandas|web-scraping|beautifulsoup
1
1,215
50,255,849
Merging DataFrames that don't have unique indexes with Python and Pandas
<p>I'm presented with two dataframes. One contains school food ratings for types of foods at different campuses. The first df is student ratings, the second is teacher ratings. The order of the results and the length of the df cannot be guaranteed. Thats said, I need to join the two together.</p> <pre><code>import pan...
<p>Seems like you need an outer merge:</p> <pre><code>res = pd.merge(student_ratings, teacher_ratings, how='outer') print(res) campus food student_rating teacher_rating 0 37 chinese 97.0 86 1 37 mexican 90.0 79 2 37 american 83....
python|pandas
2
1,216
50,493,478
How array size affects numpy matrix operation execution time and CPU usage
<p>My question is about the following code:</p> <pre><code>%%time import numpy as np n_elems = 95 n_repeats = 100000 for i in range(n_repeats): X = np.random.rand(n_elems, n_elems) y = np.random.rand(n_elems) _ = X.dot(y) </code></pre> <p>I run this in iPython (version <code>6.2.1</code>) with Python <cod...
<p>It seems that some numpy operations (e.g. <code>numpy.dot</code>) use BLAS which can execute in parallel.</p> <p>Other numpy operations (e.g. <code>numpy.einsum</code>) are implemented directly in C and execute serially.</p> <p>See <a href="https://stackoverflow.com/questions/16617973/why-isnt-numpy-mean-multithre...
python|numpy
0
1,217
50,366,921
Regex Replace Expected Strings Or Byte Like Objects
<p>I have <a href="https://i.stack.imgur.com/NYg2T.png" rel="nofollow noreferrer">the following code</a> , I have imported a dataset via Pandas, and am trying to substitute numbers with a comma out of it (for example, <code>"12,000"</code>) but I seem to always hit the error of <code>"TypeError: expected string or byte...
<p>You may use <code>replace</code> directly without using <code>re</code> explicitly:</p> <pre><code>df2['Description'] = df2['Description'].str.replace(r'(?&lt;=\d)[.,]', '') </code></pre> <p>Here,</p> <ul> <li><code>(?&lt;=\d)</code> - a positive lookbehind that matches a position immediately preceded with a dig...
python|regex|pandas
0
1,218
45,615,439
Regex for Transformations (without using multiple statements)
<p>What is the best way to use Regex to extract and transform one statement to another?</p> <p>Specifically, I have implemented the below to find and extract a sudent number from a block of text and transform it as follows: <em>AB123CD</em> to <em>AB-123-CD</em></p> <p>Right now, this is implemented as 3 statements a...
<p>You could get list of segments using regexp and then join them this way:</p> <pre><code>'-'.join(re.search(r'(\d{2})(\w{3})(\d{2})', string).groups()) </code></pre> <p>You could get <code>AttributeError</code> if <code>string</code> doesn't contain needed pattern (<code>re.search()</code> returns <code>None</code>...
python|regex|pandas
2
1,219
62,505,181
Heatmap on only a part of the dataframe?
<p>I'm trying to make a heatmap plot but would like to omit the first row from it. So that I have a table where the first row wouldn't have any background colour. Somewhat like this <a href="https://i.stack.imgur.com/8LJ7c.png" rel="noreferrer">paint example</a></p> <p>But I'm not even sure if that is possible. I've tr...
<p>The masking idea of Stupid Wolf is great, but if you are looking for simpler ways you can simply incorporate the first row in the column names and plot the heatmap as usual.</p> <pre><code>import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns SO = pd.DataFrame(np.random.randin...
python|pandas|seaborn|heatmap
2
1,220
62,548,136
pandas column didn't change permanently
<p>This is my code having trouble. In double for loop, I created a temporary data frame which will be added into the original data frame. Before I add, I changed columns. But the column didn't change when I checked final data frame.</p> <pre><code>df['sd'] = labelencoder.fit_transform(df['sd']) copy_columns_of_x = ['c...
<p>You have to add <code>inplace=True</code> in your code <code>df = pd.concat([df, tmp_df], axis=1)</code></p>
pandas
0
1,221
62,509,730
group by rank continuous date by pandas
<p>I refer this <a href="https://stackoverflow.com/questions/53265362/pandas-groupby-rank-date-time">post</a> . But My goal is something different.</p> <p><strong>Example</strong></p> <pre><code>ID TIME 01 2018-07-11 01 2018-07-12 01 2018-07-13 01 2018-07-15 01 2018-07-16 01 2018-07-17 02 2019-0...
<p>First we check the difference between the dates, which are <code>&gt; 1 day</code>. Then we groupby on <code>ID</code> and the <code>cumsum</code> of these differences and <code>cumulative count</code> each group`</p> <pre><code># df['TIME'] = pd.to_datetime(df['TIME']) s = df['TIME'].diff().fillna(pd.Timedelta(days...
pandas
2
1,222
62,494,412
TypeError: Expected float32 passed to parameter 'y' of op 'Equal', got 'auto' of type 'str' instead
<p>I am making a neural network to predict audio data (to learn more about how neural networks function and how to use tensorflow), and everything is going pretty smoothly so far, with one exception. I've looked around quite a bit to solve this issue and haven't been able to find anything specific enough to help me. I ...
<p>Try changing</p> <pre><code>model.compile(optimizer='adam', loss=tf.keras.losses.MeanSquaredError) </code></pre> <p>to</p> <pre><code>model.compile(optimizer='adam', loss=tf.keras.losses.MeanSquaredError()) </code></pre>
python|tensorflow|machine-learning|keras|recurrent-neural-network
59
1,223
62,474,816
Create a Pandas Dataframe from nested dict
<p>I have a nested dict with following structure: course_id, nested dict with: 2 recommended courses and number of purchases for every course. For example entries of this dict look smth like this: </p> <pre><code> {490: {566: 253, 551: 247}, 357: {571: 112, 356: 100}, 507: {570: 172, 752: 150}} </code></pre> <p>I ...
<p>I would recommend you just re-shape your dictionary then re-create your dataframe, however you're not far off from getting your target output from your current dataframe.</p> <p>we can <code>groupby</code> and use <code>cumcount</code> to create our unique column then <code>unstack</code> and assign our column from...
python|pandas|dataframe
1
1,224
62,758,621
Matching lists to dataframes
<p>I have a dataframe of people with Age as a column. I would like to match this age to a group, i.e. Baby=0-2 years old, Child=3-12 years old, Young=13-18 years old, Young Adult=19-30 years old, Adult=31-50 years old, Senior Adult=51-65 years old.</p> <p>I created the lists that define these year groups, e.g. <code>Ad...
<p>Here's a way to do that using <code>pd.cut</code>:</p> <pre><code>df = pd.DataFrame({&quot;person_id&quot;: range(25), &quot;age&quot;: np.random.randint(0, 100, 25)}) print(df.head(10)) ==&gt; person_id age 0 0 30 1 1 42 2 2 78 3 3 2 4 4 44 5 5 ...
python|pandas|matching
1
1,225
62,817,483
'Wrong number of items passed 2, placement implies 1' error with pandas dataframe by operating two columns
<p>I have dataframe - for the purpose of sample data every day has only 10 minutes:</p> <pre><code> Date Close 0 2019-06-20 07:00:00 2927.25 1 2019-06-20 07:05:00 2927.00 2 2019-06-20 07:10:00 2926.75 183 2019-06-21 07:00:00 2932.25 184 2019-06-21 07:05:00 2932.25 185 2019-06-21 07:10:00 2931.00...
<p>Since you applied multiple <code>agg</code> functions, <code>pandas</code> automatically applied a <code>MultiIndex</code> to your grouped frame. See more details: <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/u...
python|pandas|dataframe
1
1,226
54,477,866
Efficiently aggregate a resampled collection of datetimes in pandas
<p>Given the following dataset as a pandas dataframe df:</p> <pre><code>index(as DateTime object) | Name | Amount | IncomeOutcome --------------------------------------------------------------- 2019-01-28 | Customer1 | 200.0 | Income 2019-01-31 | Customer1 | 200....
<p>Perhaps we can optimise your solution by having the resampling done only on a single column ("Amount", the column of interest).</p> <pre><code>(df.groupby(["Name", "IncomeOutcome"])['Amount'] .resample("M") .agg(['sum','size']) .rename({'sum':'Amount', 'size': 'MonthlyCount'}, axis=1) .reset_index(level...
python|pandas|performance|numpy
6
1,227
54,544,513
How to check the highest score among specific columns and compute the average in pandas?
<p>Help with homework problem: "Let us define the "data science experience" of a given person as the person's largest score among Regression, Classification, and Clustering. Compute the average data science experience among all MSIS students."</p> <p>Beginner to coding. I am trying to figure out how to check amongst c...
<p>If you want to get the highest score of column 'hw1' you can get it with:<br> <code>pd['hw1'].max()</code>. <br>this gives you a series of all the values in that column and max returns the maximum. for average use mean:<br></p> <p><code>pd['hw1'].mean()</code><br></p> <p><br> if you want to find the maximum of mul...
pandas|dataframe
0
1,228
73,578,333
How to iterate through a dataframe to format values?
<p>I have a dataframe where every column has numeric values like <code>5,12; 3,14; 12,01...</code> in object dtype. I want to iterate through the table to convert the dtype to float. Therefore, I made a list of all column names to replace the ',' with '.' of every value and then convert it into the right type.</p> <p>M...
<p>You need to iterate over each of the columns, converting each column to strings (with <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.html" rel="nofollow noreferrer"><code>Series.str</code></a>) to allow replacement and then converting those values to floats. To convert empty cells to <code>N...
python|pandas|for-loop
1
1,229
73,616,449
Pandas.read_csv stops at 50 characters
<p>i've got some finance data stored in a csv. The problem comes when loading my bids and asks, which are lists of lists, stored in a csv. My goal now is to load the csv into normal lists i can zip and map to whatever i need. Currently have found a way using .to_string() to create a string representation of my list of ...
<p>thanks everyone! with your help my solution wound up being simpler, using .at[] .at[] returns a string instead of any kind of object which i can use with literal_eval to convert it to list!</p> <pre><code>df = pandas.read_csv('C:/Users/Ethan/Desktop/csv/test.csv', names=['E','ID','Bids','Asks']) df2 = df.at[0,'Bids'...
python|pandas|csv
2
1,230
73,550,004
cross join pandas dataframe
<div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>A</th> <th>B</th> <th>C</th> </tr> </thead> <tbody> <tr> <td>aaa</td> <td>01-03-2022 12:40:00</td> <td>orange</td> </tr> <tr> <td>aaa</td> <td>01-03-2022 12:40:10</td> <td>apple</td> </tr> <tr> <td>aaa</td> <td>01-03-2022 12:40:00</td> <td>kiwi</t...
<pre><code># Import Your Data df = pd.DataFrame({'A':['aaa','aaa','aaa','aaa','bbb','bbb','bbb','bbb'], 'B':['01-03-2022 12:40:00','01-03-2022 12:40:10','01-03-2022 12:40:00','01-03-2022 12:40:08','15-03-2022 13:10:10','15-03-2022 13:10:18','15-03-2022 13:10:40','15-03-2022 13:10:15'], 'C':['orange','apple','kiwi','app...
python|pandas|dataframe
2
1,231
71,418,817
is there any way to include a counter(a variable that count something) in a loss function in pytorch?
<p>These are some lines from my loss function. <code>output</code> is the output of a multiclass classification network.</p> <pre class="lang-py prettyprint-override"><code>bin_count=torch.bincount(torch.where(output&gt;.1)[0], minlength=output.shape[0]) dr_output = (bin_count == 1) &amp; (torch.argmax(output, dim=1)=...
<p>If I got it correctly:</p> <pre class="lang-py prettyprint-override"><code>bin_count=torch.bincount(torch.where(output&gt;.1)[0], minlength=output.shape[0]) </code></pre> <p>computes how many elements are greater than <code>.1</code>, for each row.</p> <p>Instead:</p> <pre class="lang-py prettyprint-override"><code>...
pytorch|gradient|backpropagation
0
1,232
52,388,933
Pandas: Mark values between flags from another column
<p>The workflow is as below:</p> <ol> <li>Groupby LineNum then</li> <li>Mark values in LWS column greater than 50 as 'start'</li> <li>Mark values in Text column containing ':'(colon) as 'end'</li> <li>Mark values between start and end as 1 in 'ExpectedFlag'</li> </ol> <p><strong>I have finished upto step 3 i.e upto c...
<p>Regarding filling values between <code>start</code> and <code>end</code>, this can be done as follows, based on <a href="https://stackoverflow.com/questions/45118710/fill-in-values-between-given-indices-of-2d-numpy-array">this answer</a>:</p> <p>Data:</p> <p><code>df = pd.DataFrame([[0,0],[0,0],[0,0],[1,0],[0,0],[...
python|pandas|data-science
1
1,233
52,035,184
Pandas plot line graph with both error bars and markers
<p>I'm trying to use <code>pandas.plot</code> to plot a line chart that should contain both markers and error bars. But for some reason markers are not shown if I specify <code>yerr</code> values. </p> <p>These are data frames:</p> <pre><code>df = pd.DataFrame({ 'Time': [0, 5, 10, 15, 20, 25], 'Capomulin': [45.0, 44....
<p>Well, I can confirm that this happens also in Ubuntu 18.04, pandas 0.23.4, matplotlib 2.2.3 with TkAgg backend. I am not sure, if this is a bug or a feature, but you can emulate the expected behavior:</p> <pre><code>from matplotlib import pyplot as plt import pandas as pd #create your sample data df = pd.DataFrame...
python|pandas|matplotlib
3
1,234
60,444,575
How to use mongodb query operation on a very large database (have 3 shards of around 260-300 million in each)
<p>I have to find data in between different date ranges column in a sharded database having total of around 800 million documents. I am using this query:</p> <pre><code>cursordata=event.aggregate([{"$match":{}},{"$unwind":},{"$project":{}}]) </code></pre> <p>However, when I change it to a pandas dataframe</p> <pre><...
<p>Could we have a sample of documents? I think you should look for an index matching the fields you're querying.</p> <p>As a reminder, try to keep in mind the <a href="https://www.mongodb.com/blog/post/performance-best-practices-indexing" rel="nofollow noreferrer">Equality, Sort, Range</a> rule in MongoDB indexing.<b...
python|pandas|mongodb|mongodb-query|sharding
0
1,235
60,580,626
Resampling data monthly R or Python
<p>I have data recorded in the format as below,</p> <p><strong>Input</strong></p> <pre><code>name year value Afghanistan 1800 68 Albania 1800 23 Algeria 1800 54 Afghanistan 1801 59 Albania 1801 38 Alge...
<p>Here's a <code>tidyverse</code> approach that also requires the <code>zoo</code> package for the interpolation part.</p> <pre><code>library(dplyr) library(tidyr) library(zoo) df &lt;- data.frame(country = rep(c("Afghanistan", "Algeria"), each = 3), year = rep(seq(1800,1802), times = 2), ...
python|r|pandas|data.table
2
1,236
59,646,219
Test set accuracy of 1. How to debug
<p>I am trying to create a simple neural network using tensorflow as a learning exercise. These are the details of the NN I created.. </p> <pre><code>def multilayer_perceptron(x, weights, biases, keep_prob): layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1']) layer_1 = tf.nn.relu(layer_1) layer_1 =...
<p>There can be multiple reasons for it, first, let's look at the hyperparameter you are defining. </p> <p><strong>Learning rate:</strong></p> <p>There are multiple ways to select a good starting point for the learning rate. A naive approach is to try a few different values and see which one gives you the best loss w...
python|tensorflow|machine-learning|deep-learning|neural-network
0
1,237
32,343,743
Replace data frame values matching given condition
<p>I have the following data in a tab-separated file <code>test.tsv</code>.</p> <pre><code>Class Length Frag I 100 True I 200 True P 300 False I 400 False P 500 True P 600 True N 700 True </code></pre> <p>I have loaded the data into a <code>pandas.DataFrame</code> object, and anywhere that Class = I ...
<p>In your line</p> <pre><code>data.loc[(data.Class == 'I') &amp; (data.Frag is True), 'Class'] = 'F' </code></pre> <p>you shouldn't use <code>is</code>. <code>is</code> tests identity, not equality. So when you're asking if <code>data.Frag is True</code>, it's comparing the Series object <code>data.Frag</code> and...
python|pandas
3
1,238
40,666,316
How to get Tensorflow tensor dimensions (shape) as int values?
<p>Suppose I have a Tensorflow tensor. How do I get the dimensions (shape) of the tensor as integer values? I know there are two methods, <code>tensor.get_shape()</code> and <code>tf.shape(tensor)</code>, but I can't get the shape values as integer <code>int32</code> values.</p> <p>For example, below I've created a 2-...
<p>To get the shape as a list of ints, do <code>tensor.get_shape().as_list()</code>.</p> <p>To complete your <code>tf.shape()</code> call, try <code>tensor2 = tf.reshape(tensor, tf.TensorShape([num_rows*num_cols, 1]))</code>. Or you can directly do <code>tensor2 = tf.reshape(tensor, tf.TensorShape([-1, 1]))</code> whe...
python|tensorflow|machine-learning|artificial-intelligence
141
1,239
40,531,543
In distributed tensorflow, how to write to summary from workers as well
<p>I am using google cloud ml distributed sample for training a model on a cluster of computers. Input and output (ie rfrecords, checkpoints, tfevents) are all on gs:// (google storage)</p> <p>Similarly to the distributed sample, I use an evaluation step that is called at the end, and the result is written as a summar...
<p>My guess is you'd create a separate summary writer on each worker yourself, and write out summaries directly rather.</p> <p>I suspect you wouldn't use a supervisor for the eval processing either. Just load a session on each worker for doing eval with the latest checkpoint, and writing out independent summaries.</p>
tensorflow|google-cloud-ml
2
1,240
18,346,673
Preserving the distinctions between bools and floats when adding NaN to a pandas Series?
<p>I am adding data to a pandas <code>Series</code> via the <code>Series#append</code> method. Unfortunately, when <code>nan</code> is added to a <code>bool</code> Series, it is automatically converted to a <code>float</code> Series. Is there any way to avoid this conversion, or at least coerce it to <code>object</code...
<p>As @Jeff said, the best way is going to be to append a <code>Series</code> with <code>object</code> <code>dtype</code></p> <p>Here's an example using <code>Series</code></p> <pre><code>s = Series([True]) s.append(Series([nan], index=[1], dtype=object)) </code></pre> <p>yielding</p> <pre><code>0 True 1 NaN...
python|numpy|pandas
1
1,241
61,653,333
I cannot understand why "in" doesn't work correctly
<p>sp01 is dataframe which contains S&amp;P 500 index. And I have a dataframe,interest, which contains daily interest rate. The two data started from same date, but their size were not same. It's error. </p> <p>I want to get exact same date, so tried to check every date using "in" function. But "in" function doesn't w...
<p>I solved it! the problem is that "in" function does not work for pandas series data. Those two data are pandas series, so I have to change one of them to list</p>
pandas
1
1,242
61,688,550
CNN having high overfitting despite having dropout layers?
<p>For some background, my dataset is roughly 75000+ images, 200x200 greyscale, with 26 classes (the letters of the alphabet). My model is:</p> <pre><code>model = Sequential() model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(200, 200, 1))) model.add(MaxPooling2D((2, 2))) model.add(Dropout(0.2)) model.add(...
<p>The only way you would get all the predictions on a held-out test set incorrect while simultaneously getting almost 100% on validation accuracy is if you have a data leak. i.e. Your training data must contain the same images as your validation data (or they are VERY similar to the point of being identical). </p> <p...
python|tensorflow|deep-learning|conv-neural-network|dropout
1
1,243
61,875,790
speed up a Pandas fillna by subcatagory mean (how to replace a for loop)
<p>My data contains several sub categories coded in the column "RID", I'm filling by the mean of each sub category. The code I've been using is very slow. Looking for a better method that gets rid of the for loop.</p> <pre><code>filled = mergedf.copy() for c,v in enumerate(mergedf.RID.unique()): filled.loc[filled....
<p>Let's try the following, using <code>groupby</code> with <code>transform</code>:</p> <pre><code>filled['FDG'].fillna(filled.groupby('RID')['FDG'].transform('mean')) </code></pre> <p>or </p> <pre><code>fill4 = filled.fillna(filled.groupby('RID').transform('mean')) </code></pre>
pandas|dataframe|pandas-groupby|fillna
0
1,244
58,061,111
Java TFLITE error when allocating memory for runForMultipleInputsOutputs
<p>I'm getting an Error when preparing outputs for TFLITE interpreter for Android Java. The model has 1 input and 4 outputs. </p> <pre><code>interpreter.runForMultipleInputsOutputs(input, map_of_indices_to_outputs); E/Run multiple: Internal error: Unexpected failure when preparing tensor allocations: tensorflow/lite/...
<p>I got the solution of the issue:</p> <p>In the same way outputs require a List, so do Inputs:</p> <pre><code>Object[] outputs = {output0,output1,output2,output3}; Object[] inputs = {input}; interpreter.runForMultipleInputsOutputs(inputs, map_of_indices_to_outputs); </code></pre>
java|android|tensorflow-lite
0
1,245
57,854,204
Why model.predict computes different values in this sample?
<p><strong>Context</strong></p> <p>Given the following sample, I'm using Jupyter Notebook :</p> <pre><code>import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense import numpy as np x_input = np.array([[1,2,3,4,5]]) y_input = np.array([[10]]) model = Sequenti...
<p>Well, the inputs are no the same, the first is <code>[1,2,3,4,5]</code> and the second is <code>[1,2,5,4,5]</code>. The third element of both arrays are not the same.</p>
python|numpy|tensorflow|keras
1
1,246
58,155,138
Pandas Error: sequence item 0: expected str instance, NoneType found
<p>I have a dataframe as below: </p> <pre><code>Car_Modal Color Number_Passenger Proton Black 5 Proton Black 7 Perudua White 5 Perudua White 7 Perudua Red 7 Honda 5 </code></pre> <p>Due to the Honda row have Null value at Color column, is show m...
<p>try filtering data that are not null</p> <pre class="lang-py prettyprint-override"><code>df["Join"]=df[~df["Color"].isnull()].groupby("Car_Modal")["Color"] \ .transform(lambda x :'&lt;br&gt;'.join(x.unique())) </code></pre>
python|pandas|pandas-groupby
2
1,247
57,826,841
Calculate the maximum number of items allowed based on a fixed given value
<p>I have a set of items in this dataframe:</p> <pre><code>Items Calories Beer 320 Hotdog 200 Popcorn 100 Coca-Cola 75 </code></pre> <p>I need to calculate the fewest number of items I can have from the list to achieve <code>400</code> calories. Any suggestions?</p> <p>I have calculated the total value ...
<p>If you cannot pick a single item multiple times.</p> <ol> <li>Sort by calories</li> </ol> <pre class="lang-py prettyprint-override"><code>df = df.sort_values(by=['Calories'], ascending=False).reset_index() </code></pre> <p>Output</p> <pre><code> index Items Calories 0 0 Beer 320 1 1 H...
python|pandas
0
1,248
36,988,677
How to create matrices with different names inside a for loop
<p>I want to create the matrices 1x5: <code>matriz1</code>, <code>matriz2</code> and <code>matriz3</code>, with the values <code>i + j</code>, but my code doesn't work. Can someone help me?</p> <pre><code>import numpy as np for i in range(3): name= 'matriz%d'%i name= np.zeros((1,5)) for i in range(3): na...
<p>In Python, these 2 lines just assign two different objects to the variable <code>name</code>.</p> <pre><code>name= 'matriz%d'%i # assign a string name= np.zeros((1,5)) # assign an array </code></pre> <p>Some other languages have a mechanism that lets you use the string as variable name, e.g. <code>$name...
python|numpy|matrix
1
1,249
54,943,923
Dataframe with conflicting float formatting
<p>I have the below dataframe:</p> <pre><code>pd.DataFrame({'Full Dataset': m1_baseline.params, 'Train Set': m1_train.params}) </code></pre> <p>Which produces the below table:</p> <pre><code> Full Dataset Train Set Intercept 6.078966e+01 62.479667 DISTANCE 4....
<p>You can try <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html" rel="nofollow noreferrer">df.style:</a></p> <pre><code>df.style.format('{:.2f}') </code></pre> <p>This fill have numbers upto 2 decimal places and you can change the number to change it how many ever decimal places you want</p...
python|pandas|scientific-notation
1
1,250
54,733,971
How to sum column values into a new df
<p>I'm pretty new to pandas/python and coding overall. Thus I got a question about coding sums of columns with pandas.</p> <p>I have a 306x7 dataframe about past soccer results. Now I want to sum both the home goals and away goals for each club and put it into a new dataframe (18 rows for 18 clubs and 2 columns for h...
<p>The easiest way to think through this (no groupby) is to just create a unique list of teams and a df with home and away goals, then to add the sum of home and away goals for each team.</p> <pre><code># list of unique teams (assuming home and away teams are identical) teams = liga2['HomeTeam'].unique() # create the...
pandas
0
1,251
49,420,301
Numpy salt and pepper image on color region?
<p>I have tons of images that look like the following:</p> <p><a href="https://i.stack.imgur.com/issKU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/issKU.png" alt="enter image description here"></a></p> <p>I want to add random black and white pixels (salt and pepper) to those images, but only wi...
<p>The simplest way - generate random coordinates in given rectangle and check whether pixel at this position is not black. If not, change its color to random choice of black and white. Pseudocode:</p> <pre><code>while saltcount &lt; limit: rx = random(width) ry = random(height) c = pixel[ry][rx] if (c != ...
numpy|image-processing|machine-learning|dataset
5
1,252
49,540,703
How to use dictionary to replace the items in the inner list of a list?
<p>How to use dictionary to replace the items in the inner list of a list?</p> <p>This works fine</p> <pre><code>import numpy as np ss_dict = { 1 : np.array([1,0,0,0,0,0]), 2 : np.array([0,1,0,0,0,0]), 3 : np.array([0,0,1,0,0,0]), 4 : np.array([0,0,0,1,0,0]), 5 : np.array([0,0,...
<p>This should help. You just need to create a list comprehension within the list comprehension.</p> <pre><code>res = np.array([[ss_dict[j] for j in i] for i in l]) </code></pre> <p>Result:</p> <pre><code>[[[1 0 0 0 0 0] [0 1 0 0 0 0] [0 0 1 0 0 0]] [[0 0 0 1 0 0] [0 0 0 0 1 0] [0 0 0 0 0 1]]] </code></pre...
python|python-3.x|list|numpy|dictionary
1
1,253
28,058,563
Write to StringIO object using Pandas Excelwriter?
<p>I can pass a StringIO object to pd.to_csv() just fine:</p> <pre><code>io = StringIO.StringIO() pd.DataFrame().to_csv(io) </code></pre> <p>But when using the excel writer, I am having a lot more trouble. </p> <pre><code>io = StringIO.StringIO() writer = pd.ExcelWriter(io) pd.DataFrame().to_excel(writer,"sheet name...
<p>Pandas expects a filename path to the ExcelWriter constructors although each of the writer engines support <code>StringIO</code>. Perhaps that should be raised as a bug/feature request in Pandas.</p> <p>In the meantime here is a workaround example using the Pandas <code>xlsxwriter</code> engine:</p> <pre><code>imp...
python|excel|pandas|stringio|xlsxwriter
42
1,254
73,324,267
Group by and create new column in python
<p>I have a large dataset and I would like to create a new column that shows the State base off the many zip codes from the Postal code column.</p> <pre><code>data = {'Name':['Tom', 'nick', 'krish', 'jack', 'Petter'], 'Age':[20, 21, 19, 18, 52], 'Postal Code': [12345, 56789,12345, 96385, 56789]} </code></pre> <p>this i...
<p>You can try</p> <pre class="lang-py prettyprint-override"><code># create a dictionary that maps postcode to state d = { 12345: 'Utah', 96385: 'Utah', } df = pd.DataFrame(data) df['State'] = df['Postal Code'].map(d) # or df = (pd.DataFrame(data) .pipe(lambda df: df.assign(State=df['Postal Code'].map(d...
python|python-3.x|pandas|group-by
2
1,255
73,352,619
How can I build an advanced formula from a dict of functions without using eval()?
<p>I have two dicts of functions that I want to use to build a larger function. The goal is to be able to substitute different functions in their place based on the dict keys. I know using eval() is not the best way in terms of security and speed, but I cannot come up with another way.</p> <pre><code>def formula(x): ...
<p><code>eval()</code> can be a security issue when you're evaluating input from an user, since in most cases you can't predict what they're going to input. But it seems safe to use in this scenario.</p> <p>Anyway, here's a solution using lambda functions:</p> <pre><code>def formula(x): p1 = 10 p2 = 20 p3 =...
python|numpy
0
1,256
73,250,207
How to use pre-trained models for text classification?Comparing a fine-tuned model with a pre-trained model without fine-tuning
<p>I want to know how much the fine-tuned model improves compared to the model without fine-tuning.I want to compare the performance of the pre-trained model(BERT) and the model(fine-tuned BERT) obtained by fine-tuning the pre-trained model on text classification.I know how to fine-tune BERT for text classification, bu...
<p>What you are trying to do does not make sense. The naive BERT model was retrained using a combination of masked language modelling objective and next sentence prediction. So, all it can do is predicting masked tokens, predicting if a pair of given sentence can be next to each other in a text. Most importantly, it ca...
python|pytorch|huggingface-transformers
0
1,257
73,281,327
Is there a more efficient way to create a data frame (Pandas) from semi structured data?
<p><strong>What i want to achieve:</strong></p> <p>I want to create a (Pandas) data frame from a text file with variable-width formatted lines. For example the text file looks like</p> <pre class="lang-none prettyprint-override"><code>Time_stamp:0.0, Column_0:1.0, Column_1:2.0 Time_stamp:1.0, Column_2:3.0, Column_3:4.0...
<p>From the looks of it, you can split on whitespace into one massive row of data, then stack it, split it again on the <code>:</code> to separate the key/value pairs.</p> <p>Then you can flag each group incrementally by checking if the value is <code>Time_stamp</code>. From this point it's a pivot.</p> <pre><code>imp...
python|pandas|dataframe
0
1,258
73,224,555
Converting dataframes created by groupby with multiple conditions to nested dict
<p>I have a dataframe with 10 columns that it follows:</p> <pre><code>df: | x | y | z | t | a | b | c | .... 1: | x1 | y1 | z1 | t1 | [a1, a2] | {b1: 1, b2: 2} | 0 | .... 2: | x2 | y2 | z2 | t2 | [a3, a4] | {b1: 3, b2: 4} | 2 | .... 3: | x1 | y3 | z2 | t1 | [a1, a4] | ...
<p>With the dataframe you provided:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame( { &quot;x&quot;: [&quot;x1&quot;, &quot;x2&quot;, &quot;x1&quot;, &quot;x3&quot;], &quot;y&quot;: [&quot;y1&quot;, &quot;y2&quot;, &quot;y3&quot;, &quot;y1&quot;], ...
python|pandas|dataframe|data-processing
0
1,259
73,433,082
Find max/mean in range defined by values from another column
<p><a href="https://i.stack.imgur.com/L6cQL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L6cQL.jpg" alt="example pic" /></a>I have a df as follows:</p> <pre><code>import pandas as pd import numpy as np np.random.seed(5) df = pd.DataFrame(np.random.randint(10, size = (20, 1)),columns=['A']) s = [0,...
<p>You can achieve that with <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.agg.html" rel="nofollow noreferrer"><code>agg</code></a> and <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>merge</code></a>.</p> <p>Setup:</p> <pre cla...
python|pandas|dataframe
3
1,260
73,496,777
How to convert n*1 array into n*m array where m is unique values in the array?
<p>I have an array of array( [1,2,3, 4, 1,2 ,3 ,3,3,3]) having shape (10,)</p> <pre><code>a = np.array([1,2,3, 4, 1,2 ,3 ,3,3,3]) print(a) print(a.shape) </code></pre> <p>which has unique values 1,2,3,4 ie m = 4, unique values. Actual data i quite large nad has nuniuqe of ~300 How to pivot it to get an array of shape (...
<pre><code>np.eye(a.max(),dtype=int)[a - 1] array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0]]) </code></pre>
python|arrays|numpy
4
1,261
73,225,508
Finding the minimum euclidian distance from all points of class 0 to all points of class 1
<p><strong>The Problem</strong></p> <p>I have a dataset with 4 columns and ~90k rows. Columns 1, 2, 3 are the features and column 4 is the target class (binary classification, either 0 or 1).</p> <p>I want to add a 5th column to my dataset that will contain the closest Euclidian distance from row[i] to another point of...
<p>Thanks to <strong>Quang Hoang</strong> from the comments and his reference to the spatial distance matrix from the Scipy module I managed to solve my problem. I decided to post it as the answer to this question in case somebody has a similar problem.</p> <pre><code>import pandas as pd from scipy.spatial import dista...
python|pandas|dataframe|data-analysis
0
1,262
35,068,722
Pandas assign value of one column based on another
<p>Given the following data frame:</p> <pre><code>import pandas as pd df = pd.DataFrame( {'A':[10,20,30,40,50,60], 'B':[1,2,1,4,5,4] }) df A B 0 10 1 1 20 2 2 30 1 3 40 4 4 50 5 5 60 4 </code></pre> <p>I would like a new column 'C' to have values be equal to those in ...
<p>Use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="noreferrer"><code>np.where</code></a>:</p> <pre><code>df['C'] = np.where(df['B'] &lt; 3, df['A'], 0) &gt;&gt;&gt; df A B C 0 10 1 10 1 20 2 20 2 30 1 30 3 40 4 0 4 50 5 0 5 60 4 0 </code></pre...
python-3.x|pandas
5
1,263
67,361,002
How to train and save multi class artificial neural network model using tensorflow?
<p>I'm trying to train a multi class classification neural network model using tensorflow. So I have 24 feature vectors that's in the form of numpy array that looks like this when I print it:</p> <pre><code>[[1 0 0 ... 0 1 1] [1 0 0 ... 0 1 1] [1 0 0 ... 0 1 1] ... [1 0 0 ... 2 0 0] [1 0 0 ... 2 0 0] [1 0 0 ... 2...
<p>You have to provide <code>input_shape</code> parameter</p> <pre class="lang-py prettyprint-override"><code> #Normalize the data x_train = x_train/x_train.max() #Convert the y_train to be one-hot encoded because they're not a regression problem, to do categorical analysis by Keras. from keras.utils import to_categor...
python|tensorflow|deep-learning|neural-network
0
1,264
67,541,172
Python - Pandas - Reading excel file from o365
<p>I'm trying to read an o365 excel file into a pandas dataframe for analysis. I'm able to connect and authenticate, however am getting the error: &quot;Unsupported format, or corrupt file: Expected BOF record; found b'\r\n&lt;!DOCT' &quot;</p> <p>Some googling of the error showed that this can be an encoding issue, or...
<p>This worked for me. Don't fill spaces with special characters for your folder names.</p> <pre><code>from shareplum import Site from shareplum import Office365 from shareplum.site import Version authcookie = Office365('https://&lt;organization&gt;.sharepoint.com/', username='&lt;your username&gt;', password='&lt;you...
python|python-3.x|pandas
1
1,265
34,857,708
How to group pandas DF entries and progress column values?
<p>I have groupby my Dataframe by customer, year and month:</p> <pre><code>my_list = ['Customer','Year','Month'] g = df.groupby(my_list)['COST'].sum() Customer Year Month COST 1000061 2013 12 122.77 2014 1 450.40 2 249.61 3 533.58 ...
<p>IIUC you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.shift.html" rel="nofollow"><code>shift</code></a> and <a href="http://pandas.pydata.org/pandas-d...
python|pandas
1
1,266
59,909,041
Python - How to convert from object to float
<p>I had an XLSX file with 2 columns namely <code>months</code> and <code>revenue</code> and saved it as a CSV file. By using pandas to read my csv file, the <code>revenue</code> column has now turned into object. How can I change this column to float?</p> <pre><code>data = pd.DataFrame dat['revenue'] 7980.79 Nan 1...
<p>Now using nucsit026's answer to create a slightly different dataFrame with strings </p> <pre><code>dic = {'revenue':['7980.79',np.nan,'1000.25','17800.85','None','2457.85','6789.33']} print(df) print(df['revenue'].dtypes </code></pre> <p>Output:</p> <pre><code> revenue 0 7980.79 1 NaN 2 1000.25 3 17800...
python|pandas
2
1,267
60,048,624
Pandas: Compare rows from two columns with several RegEx and copy right ones into a own column
<p>I'd like to ask for help for my problem. So, I have this dataframe with two columns and have a huge dataset of about 9500~ rows with 2 columns. Sometimes I have to take a subset from column A, sometimes from B - depending on the RegEx. But I have more than two of them (RegEx) but they are kinda unique. The result sh...
<p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.select.html" rel="nofollow noreferrer">np.select</a> and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.match.html" rel="nofollow noreferrer">str.match</a> as below to get your desired output.</p> <pre><co...
python|pandas|dataframe|data-science
2
1,268
59,906,550
How to get output of middel layers in LSTM autoencoder in keras
<p>I have a multi-layer LSTM autoencoder with the following characteristics.</p> <pre><code>model = Sequential() model.add(LSTM(250, dropout_U = 0.2, dropout_W = 0.2)) #L1 model.add(LSTM(150, dropout_U = 0.2, dropout_W = 0.2)) #L2 model.add(LSTM(100, dropout_U = 0.2, dropout_W = 0.2)) #L3 model.add(LSTM(150, dropout_U...
<p>Thanks to @mahsa-monavari and @frogatto for your answers</p> <pre><code>from keras import backend as K # with a Sequential model get_3rd_layer_output = K.function([model.layers[0].input], [model.layers[3].output]) layer_output = get_3rd_layer_output([x])[0] </code></pre>
python|tensorflow|keras|lstm
0
1,269
60,240,925
How to find the variance between two groups in python pandas?
<p>I have a dataframe like this,</p> <pre><code>ID total_sec is_weekday 1 300 1 1 200 0 2 280 1 2 260 0 3 190 1 4 290 0 5 500 1 5 520 0 </code></pre> <p>I want to find the ID with the largest va...
<p>You can do:</p> <pre class="lang-py prettyprint-override"><code>df.pivot(index="ID", columns="is_weekday", values="total_sec").diff(axis=1)[1].fillna(0) </code></pre> <p>Outputs:</p> <pre class="lang-py prettyprint-override"><code>ID 1 100.0 2 20.0 3 0.0 4 0.0 5 -20.0 Name: 1, dtype: float64 <...
python|pandas|numpy|dataframe
4
1,270
65,107,263
Error while trying to load dictionary data into a Data Frame
<pre><code>import pandas as pd data={'Company':['GOOG','GOOG','MSFT','MSFT','FB','FB'],'Person':['Sam','charlie','Amy','vanessa','Sarah'],'Sales':[200,120,340,124,243,350]} df = pd.DataFrame(data) </code></pre> <p>And here is the error:</p> <hr /> <pre><code>ValueError Traceback (most r...
<p>I suggest you this code:</p> <pre><code>import pandas as pd data={'Company':['GOOG','GOOG','MSFT','MSFT','FB','FB'],'Person': ['Sam','charlie','Amy','vanessa','Sarah'],'Sales':[200,120,340,124,243,350]} df = pd.DataFrame.from_dict(data, orient='index') df = df.transpose() print(df) </code></pre> <p>output is:</p> ...
python|pandas|dataframe
0
1,271
65,255,061
Split pandas column into multiple columns based on 'key=value' items
<p>I have a dataframe where one column contains several information in a 'key=value' format. There are almost a hundred different 'key=value' that can appear in that column but for simplicity sake I'll use this example with only 4 (<code>_browser, _status, _city, tag</code>)</p> <pre><code>id name properties 0 A ...
<p>Let's use <code>str.findall</code> with regex capture groups to extract key-value pairs from the <code>properties</code> column:</p> <pre><code>df.join(pd.DataFrame( [dict(l) for l in df.pop('properties').str.findall(r'(\w+)=([^,\}]+)')])) </code></pre> <p>Result:</p> <pre><code> id name _browser _status _city...
python|pandas|dataframe
5
1,272
49,808,042
TensorFlow DLL load failed: A dynamic link library (DLL) initialization routine failed
<p>I installed and ran TensorFlow on my PC. When i ran it on this error appeared in jupyter notebook. I tried to reinstall Anaconda with Python 3.6 many times but I always get the same error. I tried to install a new operating system and install Visual C++ Redistributable for Visual Studio 2015 but there was no improv...
<p>These might be possible scenarios:</p> <pre><code>1.You need to install the MSVC 2019 redistributable 2.Your CPU does not support AVX2 instructions 3.Your CPU/Python is on 32 bits 4.There is a library that is in a different location/not installed on your system that cannot be loaded. </code></pre>
python-3.x|tensorflow
-1
1,273
50,206,222
Tensorflow How can I make a classifier from a CSV file using TensorFlow?
<p>I need to create a classifier to identify some aphids.</p> <p>My project has two parts, one with a computer vision (OpenCV), which I already conclude. The second part is with Machine Learning using TensorFlow. But I have no idea how to do it.</p> <p>I have these data below that have been removed starting from the ...
<p>You can start with this tutorial, and try it first without changing anything; I strongly suggest this unless you are already familiar with Tensorflow so that you gain some familiarity with it.</p> <p>Now you can modify the input layer of this network to match the dimensions of the HuMoments. Next, you can give a nu...
python|csv|tensorflow
0
1,274
49,937,365
replace values in series according to threshold
<p>I have a pandas series and I would like to replace the values with 0 if the value &lt; 3 and with 1 if the value >=3</p> <pre><code>se = pandas.Series([1,2,3,4,5,6]) se[se&lt;3]=0 se[se&gt;=3]=1 </code></pre> <p>Is there a better/pythonic way to do so?</p>
<p>In my opinion here is best/fast cast boolean mask to <code>integer</code>s:</p> <pre><code>se = (se &gt;= 3).astype(int) </code></pre> <p>Or use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a>, but <code>Series</code> constructo...
python|pandas|series
1
1,275
49,968,105
Does the TensorFlow backend of Keras rely on the eager execution?
<p>Does the TensorFlow backend of Keras rely on the eager execution?</p> <p>If it isn't the case, can I build a TensorFlow graph based on Keras and TensorFlow operations, then train the whole model using Keras high-level API?</p>
<blockquote> <p>It is for a research purpose which I can't present here.</p> </blockquote> <p>That makes it really difficult to answer your question. It would be better if you could find a toy example -- unrelated with your research -- of what you want and we try to build something from there.</p> <blockquote> <p...
python|tensorflow|keras
5
1,276
50,064,833
Fine tuned VGG-16 gives the exact same prediction for all test images
<p>I have fine-tuned a VGG-16 network to predict the presence of disease on medical images. I've then tested the model by using <code>model.predict()</code> but what I'm seeing is that the network predicts the exact same <strong><em>22.310%</em></strong> and <strong><em>77.690%</em></strong> for the presence and absenc...
<p>Ok so this is not really an answer but a step towards debugging. Please change the prediction loop to the code below and post the output.</p> <pre><code>for x in list[ :3 ]: # let's do the first 3 only img_path=Path0+'\\'+ x print() # leave an empty line before each image print( image_path ) # let's se...
python-3.x|image-processing|tensorflow|deep-learning|keras
0
1,277
64,053,537
Appending elements of arrays as a line to a file
<p>I want to append the array as a line to a flie ,</p> <pre><code>import numpy as np data1 = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) data2 = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) g = open(f'data.csv', 'w') for data in [data1,data2]: g.write(data) g.close() </code></pre> <p>I got</p> <pre><code>Traceback (most...
<p>Try:</p> <pre><code>np.savetxt('data.csv', data, fmt='%i ', newline='') </code></pre> <p>Example for more arrays:</p> <pre><code>data1 = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) data2 = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) data = np.array([data1, data2]) np.savetxt('data.csv', data, fmt='%i ', newline='\n') </c...
python|numpy
3
1,278
64,103,683
PyTorch LSTM not learning in training
<p>I have the following simple LSTM network:</p> <pre><code>class LSTMModel(nn.Module): def __init__(self, input_dim, hidden_dim, layer_dim, output_dim): super().__init__() self.hidden_dim = hidden_dim self.layer_dim = layer_dim self.rnn = nn.LSTM(input_dim, hidden_dim, layer_dim, ba...
<p>So normally 6 layers in your LSTM are way to much. The input dimension is 28 (are you training MNIST, or are the inputs letters?) so 10 as hidden dimension is acutally way to small. Try the following parameters:</p> <pre><code>hidden_dim = 128 to 512 layer_dim = 2 to max. 4 </code></pre> <p>I see your output-shape i...
python|pytorch
2
1,279
46,872,336
Mean each row of nonzero values and avoid RuntimeWarning and NaN as some rows are all zero
<p>I already checked <a href="https://stackoverflow.com/questions/38542548/numpy-mean-of-nonzero-values">Numpy mean of nonzero values</a> and it worked nicely. However, some rows of my matrix are all zero element. What is a good way to avoid <code>RuntimeWarning: invalid value encountered in true_divide</code> in this ...
<p>With <code>a</code> as the input array, you could use <code>masking</code> -</p> <pre><code>invalid_val = np.nan # specifies mean value to be assigned for all zeros rows out = np.full(a.shape[0],invalid_val) count = (a!=0).sum(1) valid_mask = count!=0 out[valid_mask] = a[valid_mask].sum(1)/count[valid_mask] </code>...
python-2.7|numpy|mean
2
1,280
33,058,590
Pandas Dataframe: Replacing NaN with row average
<p>I am trying to learn pandas but I have been puzzled with the following. I want to replace NaNs in a DataFrame with the row average. Hence something like <code>df.fillna(df.mean(axis=1))</code> should work but for some reason it fails for me. Am I missing anything, is there something wrong with what I'm doing? Is it...
<p>As commented the axis argument to fillna is <a href="https://github.com/pydata/pandas/issues/4514" rel="nofollow noreferrer">NotImplemented</a>.</p> <pre><code>df.fillna(df.mean(axis=1), axis=1) </code></pre> <p><em>Note: this would be critical here as you don't want to fill in your nth columns with the nth row aver...
python|pandas|dataframe|missing-data
42
1,281
38,931,631
ValueError: Invalid parameter solver for estimator LogisticRegression
<p>I am trying to run a gridsearch for Logistic regression and I am getting this very weird error. I run the same thing on my machine and it works fine but when I try to run it on my remote machine, it fails.</p> <p>The only visible difference is in the version of python, on my local machine it is 2.7.10 and on the re...
<p>I hope you have resolved this issue.</p> <p>If you use <code>estimator.get_params()</code>(in your case estimator is LogisticRegression), you can see that possible are:</p> <pre><code>{'bootstrap': True, 'class_weight': None, 'criterion': 'gini', 'max_depth': None, 'max_features': 'auto', 'max_leaf_nodes': None, '...
python|numpy|scikit-learn|logistic-regression|grid-search
2
1,282
62,927,710
How to get the output I want?
<p>I have started using Tensorflow of Machine learning. I am a beginner to don't understand much like the functions and their purpose. I started with a simple Hello world program. The I used is this:</p> <pre><code>import tensorflow as tf hello = tf.constant('hello Tensorflow!') sess = tf.Session() print(sess.run(he...
<p><code>hello Tensorflow!</code> gets converted into bytes. Ex: <code>type('Hello')</code> is <code>str</code> and <code>type(b'Hello')</code> is <code>bytes</code>. There's no way you can fix this. You <strong>can</strong> edit the code of <code>tensorflow</code>, but if you try this code on another device, it will a...
python|tensorflow
0
1,283
62,972,802
Python package with sample datasets but deferred download?
<p>I have a data analysis tool that I made a Python package for and I'd like to include some sample datasets, but I don't want to include all the datasets directly in the Python package because it will bloat the size and slow down install for people who don't use them.</p> <p>The behavior I want is when a sample datase...
<p>I ended up making a folder under AppData using the <code>appdirs</code> package</p> <hr /> <p><code>datasets.py</code></p> <pre><code>import os import pandas as pd from pandasgui.utility import get_logger from appdirs import user_data_dir from tqdm import tqdm logger = get_logger(__name__) __all__ = [&quot;all_dat...
python|pandas|pip|dataset
0
1,284
63,095,126
Python3 numpy array size compare to list
<p>I always thought numpy array is more compact and takes less memory size compare to list, however, for a 3-D float64 np array,</p> <pre><code>print (sys.getsizeof(result2)/1024./1024./1024.) print (sys.getsizeof(result2.astype('float16'))/1024./1024./1024.) print (sys.getsizeof(list(result2))/1024./1024./1024.) print...
<p>You show that each of your <code>list</code> elements consumes 8 bytes.</p> <p>But each element is just a pointer to a 24-byte float object.</p> <p>Additionally, when you start with a 3-D array, you'll be looking at lists within lists. You could recurse through the data structures yourself to accurately add up the a...
python-3.x|numpy
1
1,285
67,707,669
Pyarrow: How to specify the dtype of partition keys in partitioned parquet datasets?
<p>I would like to create a partitioned pyarrow dataset with strings as partition keys:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import pyarrow as pa from pyarrow import parquet as pq data = {'key': ['001', '001', '002', '002'], 'value_1': [10, 20, 100, 200], 'value_2': [...
<p>With this file structure, there is no explicit metadata (or schema information) about the partition keys stored anywhere. So <code>pq.read_table</code> tries to guess the type. In your case (even with the trailing zeros) it can't guess it is a string and think key is an integer.</p> <p>You can use the <code>dataset<...
python|pandas|parquet|pyarrow
2
1,286
67,699,830
Pass every excel file in python from assigning a specific name
<p>I have the following excel files in a directory:</p> <p>excel_sheet_01</p> <p>excel_sheet_02</p> <p>. . .</p> <p>excel_sheet_nm</p> <p>How can I do using pandas, that every excel sheet gets stored in a dataframe variable whose name corresponds to the two last digits. i.e. I would get in python the following variabl...
<p>If you do not want to type out every single variable (and especially if you have unknown number of files) you could think of storing the DataFrames in a List (or Dict). something like:</p> <pre><code>import os import pandas as pd excel_sheets = [f.name for f in os.scandir(path) if not f.is_dir() and 'excel_sheet' in...
python|pandas
3
1,287
67,790,590
How to flatten list of dictionaries in multiple columns of pandas dataframe
<p>I have a dataframe and each record stores a list of dictionaries like this:</p> <pre><code>row prodect_id recommend_info 0 XQ002 [{&quot;recommend_key&quot;:&quot;XXX567&quot;,&quot;recommend_point&quot;:50}, {&quot;recommend_key&quot;:&quot;XXX236&quot;,&quot;recommend_point&quot;:20}, ...
<p>Try:</p> <pre><code>pd.concat([df.explode('recommend_info').drop(['recommend_info'], axis=1), df.explode('recommend_info')['recommend_info'].apply(pd.Series)], axis=1) </code></pre> <p>You can do the same thing over and over again with every column</p> <p>Here is an example:</p> <pre><code>&gt;&...
python|pandas|dataframe|dictionary|flatten
2
1,288
32,126,758
Fastest way to create a numpy array from text file
<p>I have 60mb file with lots of lines.</p> <p>Each line has the following format:</p> <pre><code>(x,y) </code></pre> <p>Each line will be parsed as a numpy vector at shape (1,2).</p> <p>At the end it should be concatenated into a big numpy array at shpae (N,2) where N is the number of lines.</p> <p>What is the fa...
<p>One thing that would improve speed is to imitate <code>genfromtxt</code> and accumulate each line in a list of lists (or tuples). Then do one <code>np.array</code> at the end.</p> <p>for example (roughly):</p> <pre><code>points = [] for line in file: x,y = eval(line) points.append((x,y)) result = np.array...
python|arrays|performance|numpy
2
1,289
41,668,786
How do you create a dynamic_rnn with dynamic "zero_state" (Fails with Inference)
<p>I have been working with the "dynamic_rnn" to create a model.</p> <p>The model is based upon a 80 time period signal, and I want to zero the "initial_state" before each run so I have setup the following code fragment to accomplish this:</p> <pre><code>state = cell_L1.zero_state(self.BatchSize,Xinputs.dtype) output...
<p>The solution to the problem was how to obtain the "batch_size" such that the variable is not hard coded.</p> <p>This was the correct approach from the given example:</p> <pre><code>Xinputs = tf.placeholder(tf.int32, (None, self.sequence_size, self.num_params), name="input") state = cell_L1.zero_state(Xinputs.get_s...
tensorflow|tensorflow-serving
3
1,290
41,382,719
Sum of next n rows in python
<p>I have a dataframe which is grouped at product store day_id level Say it looks like the below and I need to create a column with rolling sum </p> <pre><code>prod store day_id visits 111 123 1 2 111 123 2 3 111 123 3 1 111 123 4 0 111 123 5 1 111 123 6...
<p>The formation of rolling sums can be done with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.rolling.html#pandas.Series.rolling" rel="nofollow noreferrer"><code>rolling</code></a> method, using boxcar window:</p> <pre><code>df['rolling_4_sum'] = df.visits.rolling(4, win_type='boxcar',...
python-3.x|pandas
4
1,291
27,488,622
How to get a value from every column in a Numpy matrix
<p>I'd like to get the index of a value for every column in a matrix <code>M</code>. For example:</p> <pre><code>M = matrix([[0, 1, 0], [4, 2, 4], [3, 4, 1], [1, 3, 2], [2, 0, 3]]) </code></pre> <p>In pseudocode, I'd like to do something like this:</p> <pre><code>for c...
<p>The tuple of matrices is a collection of items suited for indexing. The output will have the shape of the indexing matrices (or arrays), and each item in the output will be selected from the original array using the first array as the index of the first dimension, the second as the index of the second dimension, and...
python|numpy|matrix
3
1,292
27,888,835
IPython with and Without Notebook Differences
<p>One of the most important improvisations of Python that are my favorites are IPython and IPython Notebook.</p> <p>I was watching and repeating what's shown in this <a href="https://www.youtube.com/watch?v=3Fp1zn5ao2M" rel="nofollow">video</a> and found some issues. </p> <p>As specified in the video, I use <code>ip...
<p>This is what the <code>pylab</code> flag does:</p> <pre><code>import numpy import matplotlib from matplotlib import pylab, mlab, pyplot np = numpy plt = pyplot from IPython.core.pylabtools import figsize, getfigs from pylab import * from numpy import * </code></pre> <p>That said, it is recommended that you launc...
python|numpy|matplotlib|ipython|ipython-notebook
2
1,293
27,574,563
Correcting cumulatives in Pandas
<p>I have a DataFrame that has the following columns:</p> <blockquote> <p><strong>DeviceId</strong> | <strong>Timestamp</strong> | <strong>Total_Data</strong><br> 001 08/12/2014 500<br> 001 08/13/2014 600<br> 001 08/14/2014 750<br> 001 08/15/2014 150 (d...
<ol> <li>First divide your Dataframe according to your reset</li> <li>Make cumulative sum in each part</li> <li>Add extra value from previous part</li> </ol> <p>Code is given below:</p> <pre><code>grouped = df.groupby((df.TotalData.diff() &lt;= 0).cumsum()) parts = [g.reset_index(drop=True) for k, g in grouped] for...
python|pandas
0
1,294
61,462,597
Reading numbers into grid
<p>I have a numbers grid, that looks like this and goes on for a while further.</p> <pre><code>08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56...
<p>Some notes:</p> <ol> <li>Make sure you are using <code>open()</code> with the keyword <code>with</code>. Reference <a href="https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files" rel="nofollow noreferrer">here</a>.</li> </ol> <blockquote> <p>It is good practice to use the with keyword whe...
python|numpy
1
1,295
61,384,421
LSTM, Exploding gradients or wrong approach?
<p>Having a dataset of monthly activity of users, segment to country and browser. each row is 1 day of user activity summed up and a score for that daily activity. For example: number of sessions per day is one feature. The score is a floating point number calculated from that daily features.</p> <p>My goal is to try ...
<p>You are solving a regression task, using accuracy is not meaningful here.</p> <p>Use <code>mean_absollute_error</code> to check if your error is decreasing over time or not.</p> <p>Instead of blindly predicting the score, you can make the score bounded to <code>(0, 1)</code>.</p> <p>Just use a min max normalizati...
python|tensorflow|keras
1
1,296
61,427,432
Linear regression with multiple features - How to make a prediction after training a neural network using an array
<p>I designed an artificial neural networks model following the tutorial in here: <a href="https://www.tensorflow.org/tutorials/keras/regression" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/keras/regression</a></p> <p>Afterwards, I saved the model using model.save(), and I tried loading it into a di...
<p>The error you describe in your comment arises because your model expects an input of size (9, n), where 'n' is the number of data points you are feeding in - that's why it says <code>(9,)</code> is expected. But when you're feeding in while attempting to predict is actually a vector of size 9, which in two-dimension...
python|tensorflow|neural-network|linear-regression
0
1,297
68,726,799
How should I implement a tf.keras.Metric that computes on the whole prediction?
<p>The <code>tf.keras.Metric</code> interface provides a useful tool for implementing additive metrics such as loss/accuracy. The interface is designed to update on a batch when <code>update_state(self, y_pred, y_true)</code> is called and the result should be returned at <code>result(self)</code>. However when impleme...
<p>As I understand you question;</p> <pre><code>class BinaryTruePositives(tf.keras.metrics.Metric): def __init__(self, name='binary_true_positives', **kwargs): super(BinaryTruePositives, self).__init__(name=name, **kwargs) self.true_positives = self.add_weight(name='tp', initializer='zeros') def update_st...
python|tensorflow|keras
0
1,298
68,597,540
Problem with iterations and dataframes to store variables in dict
<p>I received a code I'm trying to reduce and make more flexible.</p> <p>The code is for obtaining climatical values from a .csv with many entries (+1M).</p> <p>Since I don't want to overextend the code, I've made so that variables are selected by the user, and therefore, when the user selects this variables via termin...
<p>As you see in the documentation here:</p> <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.mean.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.mean.html</a></p> <p>the <code>.mean()</code> method returns a series or d...
python|pandas
0
1,299
68,603,426
Fitting numerical data in Python
<p>I have more than 100,000 numbers to analyze in Python. Part of it is given in this sample: 84.49, 60.885, 33.6, 0, 6.4, 89.361, 0, 0, 5.6, 0, 39.828.</p> <p>The sum of this sample is 320.164 and I want to scale so that the new figures add up to 500 and plot these values.</p> <p>I previously divided my desired sum (5...
<p>You can do it this way:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt numbers = [84.49, 60.885, 33.6, 0, 6.4, 89.361, 0, 0, 5.6, 0, 39.828] current_sum = np.sum(numbers) desired_sum = 500 new_numbers = [desired_sum/current_sum * x for x in numbers] plt.hist(new_numbers) </code></pre>
python|pandas|numpy|seaborn|libraries
0