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
366,200
45,236,331
matplotlib scatter with c=date
<p>How to plot a pandas dataframe like the one below with x on the x-axis, the values on the y-axis (one line per row) and the lines colored by <strong>date</strong></p> <pre><code>values = [[0.2, 3.1, 17.4, 28.9, 57.7, 76.9, 82.8, 87.6, 92.4, 98.9, 100.0], [0.2, 2.1, 15.5, 26.0, 54.2, 75.6, 82.1, 87.4, 92.4...
<pre><code>import random import numpy as np import pandas as pd import matplotlib.pyplot as plt # create test data with a structure similar to the real data x_values = np.linspace(1, 10, 8) dat = np.random.randn(100, 8) df = pd.DataFrame(data=np.abs(dat), columns=x_values) df = df.cumsum(axis=1) df = df.divide(df.max(...
pandas|matplotlib
0
366,201
44,978,269
Python matrix inner product
<p>I am trying to solve the below question:</p> <pre><code>''' Take in two matrices as numpy arrays, X and Y. Determine whether they have an inner product. If they do not, return False. If they do, return the resultant matrix as a numpy array. ''' </code></pre> <p>with the following code:</p> ...
<p>One can calculate the <em>inner product</em> given that <strong>the last dimension of both matrices are the same</strong>. So you should not check whether <code>X.shape</code> is equal to <code>Y.shape</code>, but only the last dimension:</p> <pre><code>def mat_inner_product(X,Y): if X.shape<b>[-1]</b> != Y.sha...
python|python-2.7|numpy|inner-product
4
366,202
44,931,784
How to extract work hours from two datatimes
<p>I have a pandas data frame with employee start time and end time. I want to know how many hours an employee has worked in a given shift (Shift1: 8:00am-2:00pm; shift2: 2pm-10pm, and shift3: 10pm-8am). Your help is appreciated.</p> <pre><code> Start End 0 2015-01-01 18:44:00 2015-01-02 07:31:00 1 2015...
<p>Note that my answer is not quite polish yet. First, I create example dataset as in question.</p> <pre><code>import pandas as pd df = pd.DataFrame([ ['2015-01-01 18:44:00', '2015-01-02 07:31:00'], ['2015-01-01 06:38:00', '2015-01-01 19:57:00'], ['2015-01-01 06:34:00', '2015-01-01 19:13:00'], ['2015...
python|pandas
0
366,203
45,088,124
Understanding ndarray shapes
<p>I'm new to numpy and am having trouble understanding how shapes of arrays are decided. An array of the form </p> <pre><code>[[[5, 10, 15], [20, 25, 30], [35, 40, 45]], [1,2,4,3]] </code></pre> <p>has a shape of (2,) while one of the form </p> <pre><code>[[[5, 10, 15], [20, 25, 30], [35, 40, 45]], [1,2,4]] </co...
<p>The underlying idea is that <code>np.array</code> tries to create as high a dimensional array as it can. When the sublists have matching numbers of elements the result is easy to see. When they mix lists of differing lengths the result can be confusing.</p> <p>In your first case you have 2 sublists, one of length...
python|arrays|numpy|shapes
3
366,204
45,132,744
Binary output with tflearn
<p>I am begginer with tflearn/tensorflow. I'm making a DNN to classify heartbeat in <strong>Normal</strong> <strong>(0)</strong> or <strong>Arrhytmia</strong> <strong>(1)</strong>. My dataset is <a href="https://www.physionet.org/physiobank/database/mitdb/" rel="nofollow noreferrer">ECG by MIT Arrhytmia Dataset </a>.....
<p>One way to do it is changing your activation function to 'softmax' and rounding the predictions. You can do it by;</p> <pre><code>net = tflearn.fully_connected(net, 1, activation='sigmoid ') </code></pre> <p>and predict with:</p> <pre><code>pred = model.predict(test_data) print([ np.where(r==1)[0][0] for r i...
python|tensorflow|neural-network|deep-learning|tflearn
0
366,205
45,105,224
pandas - How to get 7 day sum for groups when some groups do not have entries on all days
<p>I have some data like this:</p> <pre><code>date, group_name, value ------------------- 2017-07-01, A, 10 2017-07-05, A, 4 2017-07-05, B, 21 </code></pre> <p>I want to compute the rolling 7 day sum of each group but the data only for each group only has records when the value is > 0 for that day.</p> <p>I want the...
<p>Use <a href="https://docs.python.org/2/library/datetime.html" rel="nofollow noreferrer">timedeltas</a>:</p> <pre><code>import pandas as pd from datetime import datetime, timedelta testdata = pd.DataFrame({'date': ['2017-07-01', '2017-07-05', '2017-07-05'], 'group_name': ['A', 'A', 'B'], 'value': [10, 4, 21]}) test...
python|pandas
0
366,206
45,151,561
Creating an Python np vstack of different sized hstacks
<p>I'm converting the following MATLAB code into Python:</p> <pre><code>function segments = segmentSlidingWindow(data, wSize, sSize) len = size(data,1); wCurr = 1; segments = []; % todo: init to make faster while (wCurr&lt;len-wSize) segments = [segments; wCurr wCurr+wSize]; % start stop ...
<p>I have a feeling that most likely you would like to replace your <code>while</code> loop with something like this:</p> <pre><code>s = np.arange(0, length - window_size, step_size) segments = np.vstack([s, s + window_size]).T </code></pre> <p>For <code>length = 15; step_size = 3; window_size = 6;</code> segments wi...
python|matlab|numpy
0
366,207
45,244,238
ImportError: No module named 'xlrd'
<p>I am currently using PyCharm with Python version 3.4.3 for this particular project.</p> <p>This PyCharm previously had Python2.7, and I upgraded to 3.4.3.</p> <p>I am trying to fetch data from an Excel file using Pandas.</p> <p>Here is my code:</p> <pre><code>import pandas as pd df = pd.read_excel("File.xls", "...
<p>I had the same problem. I went to the terminal (Using Linux), and typed </p> <pre><code>sudo pip3 install xlrd </code></pre> <p>Then I imported xlrd in python and used the same code:</p> <pre><code>df = pd.read_excel("File.xlsx", "Sheet1") print (df) </code></pre> <p>It worked for me!! </p>
python|python-3.x|pandas|ubuntu|pycharm
46
366,208
45,114,237
Keep leading and trailing islands of True in a boolean array - NumPy
<p>Given i have this 1d-numpy array.</p> <pre><code>a = np.array([True True True False False False False True True False True False False False False False False True True]) </code></pre> <p>Expeceted result:</p> <pre><code>b = np.array([True True True False False False False False False False False False False Fals...
<p><strong>Approach #1</strong> </p> <p>Here's one approach making use of <a href="https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#basic-slicing-and-indexing" rel="nofollow noreferrer"><code>slicing</code></a> and <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.accumulate.html...
python|numpy
3
366,209
56,909,399
np.where overwriting th values
<p>I am trying to create a derived column from two other columns in a pandas dataframe using np.where. </p> <pre><code>df['END_TIME'] = np.where(((df['TYPE'] == 'BOLUS') &amp; (df['DESCRIPTION'] == 'rocuronium')), df['START_TIME'] + dt.timedelta(minutes=30), None) df['END_TIME'] = np.where(((df['TYPE'] == 'BOLUS') &a...
<p>Use <code>np.select</code> for multiple conditions. This will generalize well for many conditions. The <code>pd.to_datetime</code> is because things get coerced to an int. </p> <pre><code>import numpy as np import pandas as pd cond_lst = [df['TYPE'].eq('BOLUS') &amp; df['DESCRIPTION'].eq('rocuronium'), ...
python|pandas|numpy|dataframe
2
366,210
57,148,149
Update specific number of rows based on condition
<p>If I want to updated only a specific number of records based on a filter in a Pandas data frame what should I do?</p> <p>In this case I am filtering all 'Tickets' series equals to 10 and I want to increment in one the first 5. Here's my attempt:</p> <pre><code>df.loc[df['Tickets'] == 10, 'Tickets'].iloc[:5] += 1 <...
<p>Chain of <code>.loc</code> and <code>.iloc</code> may cause the unsung error , so you may can check </p> <pre><code>df.update(df.loc[df['Tickets'] == 10, ['Tickets']].iloc[:5]+1) </code></pre>
python-3.x|pandas
3
366,211
56,884,289
Installation api object detection
<p>I install api object detection, it's take a lot of space, please tell me which files to save for just detect objects on images, Thanks you.</p>
<p>You need <code>utils</code>, <code>protoc</code>, and <code>ipynb script</code></p> <pre><code>import numpy as np import os import six.moves.urllib as urllib import sys import tarfile import tensorflow as tf import zipfile from distutils.version import StrictVersion from collections import defaultdict from io impo...
tensorflow|object-detection
0
366,212
57,185,793
Python pandas: how to do operations within a group?
<p>I have the following dataframe:</p> <pre><code>df = pd.DataFrame( { "group": [1,1,1,2,2], "type": ["initial", "update", "update", "initial", "update"], "update time": ["2019-01-01 12:00:00", "2019-01-03 12:00:00", "2019-01-05 12:00:00", "2019-01-02 12:00:00", "2019-01-04 12:00:00"], "finish time...
<p>Use <code>transform('first')</code> to broadcast to the same shape all first values of <code>update time</code>. Then, simple subtraction</p> <pre><code>df['finish time'] - df.groupby('group')['update time'].transform('first') </code></pre>
python|pandas|dataframe|pandas-groupby
5
366,213
56,988,419
Getting AttributeError: __exit__ when working with Tensorflow and MNIST data
<p>I'm a beginner with Tensorflow and working with MNIST data. When trying to run a Tensorflow session as below, I'm getting Attribute error. </p> <p>Could someone look into it? </p> <p>The code snippet where I'm getting the error is below. </p> <pre><code> with tf.Session as sess: sess.run(init) ...
<p>You are missing <code>()</code> in order to create a new <code>Session</code> object/instance:</p> <p><code>with tf.Session() as sess:</code></p> <p><code>tf.Session</code> just refers to the <code>Session</code> class.</p>
python|tensorflow|mnist
0
366,214
56,990,460
Pandas - How to sum sentences in a column based on conditions in other columns, and store resulting documents in a list
<p>I want to create a documents list. Each document is combined sentences from the "text" column, when "company" and "date" are the same. </p> <p>For illustration, I have a dataframe:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame(np.array([['28/02/2017', 'Apple', "A"], ['28/02/2017', 'Apple', ...
<p>You can <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> both columns and aggregate with <a href="https://docs.python.org/3/tutorial/datastructures.html" rel="nofollow noreferrer"><code>join</code></a>:</p> <pre><co...
python|pandas|dataframe
1
366,215
57,079,203
How to add a column to the left of a datafra,e
<p>I am trying to add a column to the left of the dataframe. By default it seems to add to the right. Is there a way to add the columns to the left?</p> <p>Here is my code:</p> <pre><code>import pandas as pd import numpy as np df = pd.read_csv("/home/Sample Text Files/sample5.csv", delimiter = "\t") df=pd.DataFrame(d...
<p>you can add a line of code to rearrange the columns as follows:</p> <pre><code>df = df[['Creation_DT', 'ID', 'Name', 'Age']] </code></pre> <p>another option is to insert the column during conversion:</p> <pre><code>df.insert(loc=0, column='Creation_DT', value=pd.to_datetime('today')) </code></pre>
python-3.x|pandas|numpy|dataframe
2
366,216
57,257,033
How to add a new column to a pandas df that returns the smallest value that is greater in the same group from another dataframe
<p>Hi I have the following two pandas dataframes: df1 and df2.</p> <p>I want to create a new dataframe, df3 such that it is the same as df1 but with one extra column called "new price".</p> <p>The way I want new price to be populated is to return the first price with the same code from df2 that is greater than or equ...
<p>You can do a cross join and then <code>query</code> , finally <code>groupby().first()</code>:</p> <pre><code>m=(df1.assign(key=1).merge(df2.assign(key=1),on='key',suffixes=('','_y')).drop('key', 1) .query("(Code==Code_y)&amp;(Price&lt;=Price_y)")) m.groupby(['Code','Price...
python|python-3.x|pandas|dataframe
1
366,217
57,049,727
IndexError: too many indices for array. Numpy + Pandas DataFrame
<p>I expect the DataFrame to output in an 'Excel' type of fashion, but instead, get the index error:</p> <blockquote> <p>'IndexError: too many indices for array'</p> </blockquote> <pre><code>import numpy as np import pandas as pd from numpy.random import randn rowi = ['A', 'B', 'C', 'D', 'E'] coli = ['W', 'X', 'Y'...
<p>Is this what you want:</p> <pre><code>df = pd.DataFrame(randn(5, 4), rowi, coli) Out[583]: W X Y Z A -0.630006 -0.033165 -1.005409 -0.827504 B 0.044278 0.526636 1.082062 -1.664397 C 0.523847 -0.688798 -0.626712 0.149128 D 0.541975 -1.448316 -0.961484 -0.526547 E 0.066888 0...
python|pandas|numpy|atom-editor
0
366,218
57,277,753
Is there a way to merge a DataFrame on the first non null variable similar to a coalesce?
<p>I am trying to left merge two DataFrames but I want to left_on the first non null variable. Similar to a coalesce in SQL. Is there a way to do that? </p> <p>In my example below I am left merging on a variable called 'clean_email' but I need to do something like coalesce(clean_email,email) </p> <pre><code>df = df.m...
<p>use <code>pandas.Series.combine_first¶</code></p> <p>Combine Series values, choosing the calling Series’s values first.</p> <pre><code>import pandas as pd import numpy as np s1 = pd.Series([1, np.nan]) s2 = pd.Series([3, 4]) s1.combine_first(s2) </code></pre>
python|pandas
0
366,219
57,275,540
Remove extra spaces from all cells in dataframe
<p>I have this function:</p> <pre><code>def Remove_Space(string): return string.rstrip().lstrip() </code></pre> <p>And I would like to run this on each cell in a dataframe so that if a value has spaces before or after the letters of the string they are dropped. What is a good way to iterate through the columns l...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.applymap.html" rel="nofollow noreferrer">applymap</a>:</p> <pre><code>df = df.applymap(lambda x: x.strip()) </code></pre> <p>If there are integers or floats and you want to convert the ints/flaots to string, then use t...
python|pandas|dataframe|dictionary|multiple-columns
3
366,220
56,897,988
Pandas interval multiindex
<p>I need to create a data stucture allowing indexing via a tuple of floats. Each dimension of the tuple represents one parameter. Each parameter spans a continuous range and to be able to perform my work, I binned the range to categories.</p> <p>Then, I want to create a dataframe with a MultiIndex, each dimension of ...
<p>I think select by tuple is not implemented yet, possible solution is get position for each level separately with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.get_level_values.html" rel="nofollow noreferrer"><code>Index.get_level_values</code></a>, get intersection by <a href="https...
python|pandas|multi-index
1
366,221
57,211,727
How to generate a Sine wave tone on python 3
<p>I am wanting to generate a sinusoidal tone using python 3 of 1kHz frequency. I found an old question on stackoverflow <a href="https://stackoverflow.com/questions/8299303/generating-sine-wave-sound-in-python">(old question)</a> about it but that was using the <code>pyaudio</code> which is for python 2. </p> <p>Is t...
<p>The <a href="https://pypi.org/project/tonescale/" rel="nofollow noreferrer">tonescale installation instructions</a> suggest using the python3 version of pyaudio: python3-pyaudio.</p> <p>There is also <a href="https://www.pygame.org/docs/ref/sndarray.html" rel="nofollow noreferrer">pygame</a>.</p> <p>The <a href="h...
python|python-3.x|numpy|audio
0
366,222
57,281,094
Dictionary values to array according to np.where or similar
<p>I have a dictionary of integer keys and values:</p> <pre><code>dict1 = {100:1, 101:3, 103:2} </code></pre> <p>I have a numpy array:</p> <pre><code>arr1 = np.array([101, 103, 101, 101, 100, 103]) </code></pre> <p>I would like an array of the same length as <code>arr1</code> that has the values from the dict that ...
<pre><code>arr2 = np.vectorize(dict1.get)(arr1) </code></pre>
python|numpy
2
366,223
56,981,563
OpenCV: Extracting the colour channels from an RGB image
<p>I am trying to segment a colour image using Mean-Shift clustering using sklearn. I have read the image into a numpy array, however I want to extract each colour channel (R,G,B) so that I can use each as a variable for classification.</p> <p>I have found the following code online, which extracts the RGB colour chan...
<p>A normal picture you will have 3 layer, Red Green and Blue. </p> <p>When you read an picture by a tool (example is open-cv), it will return for you a numpy array with shape (width_image x length_image x channels). </p> <p>The arrange of channels depend on what you used, if you read by open-cv it will be Blue is fi...
python|numpy|opencv|scikit-learn|computer-vision
2
366,224
57,211,796
Pandas - Use groupby and filter on multiple conditions
<p>I am trying to group a dataset by IDs, then by time. Then, I want to select records based on the criteria of one column and based on time by ID.</p> <p>I have been researching and playing around for hours now, but I have no luck.</p> <pre><code>df = pd.DataFrame({'a': ['A1', 'A1', 'A1', 'A2', 'A2','A3','A3', 'A4',...
<p>We need <code>groupby</code> + <code>shift</code> , </p> <pre><code>df.loc[(df.groupby(["a"]).value2.shift()+df.value2).eq('OrangeApple'),'a'] Out[287]: 2 A1 6 A3 9 A2 Name: a, dtype: object df.loc[(df.groupby(["a"]).value2.shift()+df.value2).eq('OrangeApple'),'a'].nunique() Out[288]: 3 </code></pre>
python|pandas
0
366,225
57,152,574
Finding anomalies or deviation in a dataframe. Comparing mean and stand deviations via plotting
<p>I have collected data by crawling web pages and collected script hashes and depth of them. I have converted the data into a pandas dataframe. </p> <p><strong>Goal</strong> As part of my research, I would like to do some statistical measures and find how the depth behaves in each group of hashes.</p> <p>2) I had ca...
<p>Does the following work for what you need?</p> <pre><code>import matplotlib as plt import pandas as pd import numpy as np # your data df = pd.DataFrame({'FileHash': ['A', 'A', 'C', 'B', 'C', 'A', 'C', 'A'], 'Depth': [1,2,1,1,3,5,2,0]}) mean_dev = df.Depth - df.groupby('FileHash').Depth.transform('mean') df.assig...
python|python-3.x|pandas|statistics
1
366,226
56,910,950
Keras predict loop memory leak using tf.data.Dataset but not with a numpy array
<p>I encounter a memory leak and decreasing performance when looping over a Keras model <code>predict</code> function when using a <code>tf.data.Dataset</code> to feed the model, but not when feeding it with a numpy array.</p> <p>Does anyone understand what is causing this and/or how to resolve the issue?</p> <p><str...
<p>The root of the problem appears to be that Keras is creating dataset operations each <code>predict</code> loop. Notice at <code>training_utils.py:1314</code> a dataset iterator is created in each predict loop. </p> <p>The problem can be reduced in severity by passing in an iterator, and is solved entirely by passin...
python|tensorflow|keras
2
366,227
57,115,360
Optimizing checking each element of numpy array against a given condition
<p>I have a simulation that looks through a numpy array arbitrarily many times in a given loop to check if any of the elements have exceeded some threshold value. If an element has exceeded the threshold, I need to keep track of which element it was that did so, so I can operate on that particular element. I have a fun...
<p>What you comoute in the function is actually a list of indices in a flattened array, which as 1D view on mulidimentional array. Just compute a mask of value where s_array is greater or equal to t_array. Next implicitly flatten the mask on non-false indices using np.flatnonzero(). There one more issue. Values L*j+i i...
python|numpy|optimization|simulation
0
366,228
56,883,432
Flatten Dataframe in Pandas
<p><a href="https://i.stack.imgur.com/V8NFJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V8NFJ.png" alt="This is my dataframe"></a></p> <p>I have a dataframe which has two column 'Year' and 'Month' and date of month 1 to 31. Now, i need a dataframe which has four columns 'Year', 'Month', 'Day' an...
<p>You want <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.melt.html" rel="nofollow noreferrer"><code>melt</code></a>, setting <code>Year</code> and <code>Month</code> as <code>id_vars</code>:</p> <pre><code>df.melt(id_vars=['Year', 'Month'], var_name='Day') </code></pre>
python|pandas|dataframe
4
366,229
57,080,453
Neural network with 2D array input and 1D array output
<p>I have got some problems writing my simple neural network. I was learning about neural networks in python by "Neural network in 11 lines" guide (<a href="https://www.kdnuggets.com/2015/10/neural-network-python-tutorial.html" rel="nofollow noreferrer">https://www.kdnuggets.com/2015/10/neural-network-python-tutorial.h...
<blockquote> <p>After that n6 size is 1000x44. And how can I get 1D array, not 2D array?</p> </blockquote> <p>The reason you're getting an output array with dimensions <code>1000x44</code> is because <code>n6</code> has 44 output nodes, and your input data has 1000 examples (meaning, you're training the network on a...
python|numpy|machine-learning|neural-network
1
366,230
57,186,663
Seaborn barplot color_palette not working
<p>I'm seeing a weird behavior with a Seaborn barplot. I am using a script that I verified that it works with one data frame. When I concatenate multiple data frames and use <code>groupby</code>, the barplot is coming out white, i.e., the <code>color_palette</code> is no longer working.</p> <pre class="lang-py prettyp...
<p>According to @mwaskom, the issue is because I'm trying to fit too many bars in a short space.</p>
python|pandas|matplotlib|seaborn
0
366,231
56,973,530
Extracting the integers from a column of strings
<p>I have 2 dataframes: longdf, and shortdf. Longdf is the ‘master’ list and I need to basically match values from shortdf to longdf, those that match, replace values in other columns. Both longdf and shortdf need extensive data cleaning.</p> <p>The goal is to reach the df ‘goal.’ I was trying to use a for loop where ...
<p>If I understand correctly, you want to take a series of strings that contain integers and remove all the characters that aren't integers. You don't need a for-loop for this. Instead, you can solve it with a simple regular expression.</p> <pre><code>b.replace('\D+', '', regex=True).astype(int) </code></pre> <p>Re...
python|pandas|for-loop
3
366,232
57,252,559
Copy values only to a new empty dataframe with column names - Pandas
<p>I have two dataframes. </p> <pre><code>df1= pd.DataFrame({'person_id':[1,2,3],'gender': ['Male','Female','Not disclosed'],'ethnicity': ['Chinese','Indian','European']}) df2 = pd.DataFrame(columns=['pid','gen','ethn']) </code></pre> <p>As you can see, the second dataframe (<code>df2</code>) is empty. But may also c...
<p>Do:</p> <pre><code>df1.columns = df2.columns.tolist() df2 = df2.append(df1) ## OR df2 = pd.concat([df1, df2]) </code></pre> <p>Output:</p> <pre><code> pid gen ethn 0 1 Male Chinese 1 2 Female Indian 2 3 Not disclosed European </code></pre> <p><hr> Edit based on ...
python|python-3.x|pandas|python-2.7|dataframe
3
366,233
57,283,513
Read multiple csv files (size mxm) and load as an n dimensional array (size nxmxm) (not concatenate)
<p>I'm working on a program that requires loading of a large number of csv files (thousands of them) into an array. </p> <p>The csv files are of dimension 45x100, and I want to create a 3-d array with dimension nx45x100. For now, I am using pd.read_csv() to load each csv file and then convert each into an array using ...
<p>First you need to convert the <code>dataframes</code> in to mxm array. Refer to the code below</p> <pre><code>from glob import glob import numpy as np strain = glob("strain*.csv") df = [pd.read_csv(f).values for f in strain] df_ = np.asarray(df) </code></pre>
python|pandas|csv|numpy
1
366,234
56,934,495
python - Machine Learning 2D Regression with confidence bands
<p>I have measures of a variable versus time.<br> I want to obtain a regression with confidence bands so that the plot sounds like this:<br> <img src="https://i.stack.imgur.com/dqTq0.png" alt="image"></p> <p>Given an arbitrary <code>x</code>, I "predicted" the <code>y</code> and its confidence by evaluating mean and s...
<p>You can achieve something like that with Gaussian Processes. For regression problems, you can use <a href="https://scikit-learn.org/stable/modules/generated/sklearn.gaussian_process.GaussianProcessRegressor.html#sklearn.gaussian_process.GaussianProcessRegressor" rel="nofollow noreferrer"><code>GaussianProcessRegress...
python|machine-learning|scikit-learn|regression|pytorch
1
366,235
57,246,683
How to search for multiple multi-word phrases in pandas?
<p>I have some JSON data converted into a Pandas DataFrame. I am looking to find all columns whose string content matches a list of multi word phrases. </p> <p>I am working with a massive amount of Twitter JSON data <a href="https://archive.org/details/twitterstream" rel="nofollow noreferrer">already downloaded for pu...
<p>Make a list with keywords or phrases you want to match, i have put on logic for perfect match, you can change it by changing regex. Also it will capture by which keywords was the text caught. Here is the code -</p> <pre><code>for i in range(len(mustkeywords)): for index in range(len(text)): result = re....
python|pandas
0
366,236
56,874,980
TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed. when writing a custom metric function in keras
<p>Keras version: <code>2.2.4</code></p> <p>Tensorflow version: <code>1.14.0</code></p> <p>TypeError: Using a <code>tf.Tensor</code> as a Python <code>bool</code> is not allowed. Use <code>if t is not None:</code> instead of <code>if t:</code> to test if a tensor is defined, and use TensorFlow ops such as tf.cond to ...
<p>Using <code>tf.py_func</code> solved the issue for me. Given below are the code blocks with the necesarry changes to the above mentioned code blocks in the question. </p> <pre><code>def IOU(y_true, y_pred): intersections = 0 unions = 0 gt = y_true pred = y_pred # Compute...
python|tensorflow|keras
0
366,237
57,260,608
How to fix flatlined accuracy and NaN loss in tensorflow image classification
<p>I am currently experimenting with TensorFlow and machine learning, and as a challenge, I decided to try and code a machine learning software, on the Kaggle website, that can analyze brain MRI scans and predict if a tumour exists or not. I did so with the code below and began training the model. However, the text tha...
<p>I managed to solve the problem. I looked at my code again and realized that my output layer only had one node. However, it needed to output the probabilities for two different categories ('yes' or 'no' for whether it is a tumour or not). Once I changed it to 2 nodes, the network began working properly and reached 95...
tensorflow|machine-learning|artificial-intelligence
1
366,238
56,987,143
How do I use pickle in this code snippet?
<p>I have a simple code snippet to train a model but, when I use pickle to save the model for future use, it gives me an error message:</p> <pre><code>cannot pickle thread.LOCK objects </code></pre> <p>I used the pickle in more than one format yet it gives me the same error.</p> <pre><code>import pickle model = ker...
<p>Which version of keras are you using? I am almost sure that old versions do not support pickle.</p> <p>Alternatively, It is recommended to use <code>model.save()</code> to save your models in keras. As it is stated in page FAQ for keras:</p> <blockquote> <p>You can use model.save(filepath) to save a Keras model ...
python|tensorflow|machine-learning|pickle|data-science
0
366,239
56,878,718
Why numpy.sum does not give me the right result?
<p>The sum of a standard python list say x=list(range(100000)) does not coincide with a sum of the same sequence x_array=np.array(x). In the first case I obtain sum(x)=4999950000, which is the correct result. Using numpy sum I obtain np.sum(x_array))=704982704. This troubles me because i am a beginner with this langu...
<p>Your NumPy defaults to standard 32-bit integers; Python will switch to indefinitely long integers as needed.</p> <p>You got bitten by overflow/wraparound.</p> <pre><code>4999950000 % (2**32) ==&gt; 704982704 </code></pre>
python|list|numpy|sum
2
366,240
57,156,606
train an ai on laptop using tensorflow and execute on raspberry pi
<p>i`m doing a school project and decided to use tensorflow to train an object detection. my question is, is it possible to train the ai on a laptop and once the training is done and deploy it on a raspberry pi?</p>
<p>yes, you can, however, the best way is to train on a cloud! because training takes too much time and your machine suffers</p>
python|tensorflow|neural-network|raspberry-pi3
1
366,241
57,290,281
Is there any way to change columns datatype that should be int became a float while using read_sql from table
<p>I am using <code>read_sql</code> function to pull data from a <code>postgresql</code> table. As I store that data in a dataframe, I could find that some integer <code>dtype</code> column is automatically getting converted to <code>float</code>, is there any way to prevent that while using <code>read_sql</code> funct...
<p>Since your column contains <code>NaN</code> values, which are floating point numbers, I don't think you can avoid this 'issue' loading from the Database without changing the query. </p> <p>If you wish to change the query, you can insert a <code>WHERE</code> clause that would exclude <code>None</code> values, or che...
python|pandas
0
366,242
57,233,539
TypeError: can't pickle _thread.RLock objects
<p>After checking all the existing answers on Stackoverflow here: <a href="https://stackoverflow.com/questions/47066635/checkpointing-keras-model-typeerror-cant-pickle-thread-lock-objects/55229794#55229794">Checkpointing keras model: TypeError: can&#39;t pickle _thread.lock objects</a> and here: <a href="https://stacko...
<p>I think TFer2 got it right. The issue is that TensorFlow models are not natively serializable by pickling. <em>Somewhere</em> (I think it's in your callback) <code>deepcopy</code> is being called on a Model. To confirm this, you can try to apply <a href="https://github.com/tensorflow/tensorflow/issues/34697#issuecom...
python|tensorflow|keras|conv-neural-network|pickle
1
366,243
57,116,956
How to iterate over dataframe to unpack dictionaries into a new dataframe
<p>I want to unpack a dataframe that contains variable amount of 'productIDs' nested in dictionaries in each column. Example table:</p> <pre><code>awardedProducts 0 [] 1 [{'productID': 14306}] 2 [] 3 [] 4 [] 5 [] 6 [] 7 [{'productID': 60974}, {'productID': 72961}] 8 [{'productID': 78818}, {'productID...
<p>Since <a href="https://github.com/pandas-dev/pandas/issues/8517" rel="nofollow noreferrer">there is no flatmap operation in Pandas</a>, you may do something like this:</p> <pre><code>import pandas as pd data = pd.Series([[], [{'productID': 14306}], [], [], [], [], [], [{'productID': 60974}, {'pro...
python|pandas
1
366,244
57,034,171
Python : Problem reading filename with brackets/long path name
<p>I am trying to read excel file with pandas.</p> <pre><code>df=pd.read_excel('abcd (xyz-9) Interim Report 01-03-18.xlsx') </code></pre> <p>which gives me file not found error. If I remove brackets and rename file to <code>'abcd Interim Report 01-03-18.xlsx'</code>, then it works fine. </p> <p>I tried renaming with...
<p>The <code>os.stat</code> test shows that accessing the path with brackets fails with <code>ERROR_PATH_NOT_FOUND</code> (3), which is either from a missing path component or a path that's too long. We know it's not a problem with finding the final path component, since in this case we expect the error to be <code>ERR...
python|windows|pandas|spyder|shutil
5
366,245
45,986,578
Cloud ML Engine distributed training default type for custom tf.estimator
<p>This <a href="https://cloud.google.com/ml-engine/docs/tutorials/distributed-tensorflow-mnist-cloud-datalab" rel="nofollow noreferrer">article</a> suggests there are three options for distributed training </p> <ol> <li>Data-parallel training with synchronous updates.</li> <li>Data-parallel training with asynchronous...
<p>The short answer is that <code>tf.estimator</code> is currently mostly built around Data-parallel training (2).</p> <p>You get Model-parallel training simply by using <code>with tf.device()</code> statements in your code.</p> <p>You could try to use <a href="https://github.com/tensorflow/tensorflow/blob/master/ten...
tensorflow|google-cloud-platform|google-cloud-ml|google-cloud-ml-engine
1
366,246
46,131,962
Count records in different time ranges in pandas
<p>I have a pandas Dataframe consisting of 3 columns like this:</p> <pre><code> no id timestamp 0 4 ab729f70-f3f3-4c57-94e5-e8408b2b0a80 2017-09-09 12:51:56.642810 1 3 ab729f70-f3f3-4c57-94e5-e8408b2b0a80 2017-09-09 12:35:57.412720 2 2 ab729f70-f3f3-4c57-...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#dateoffset-objects" rel="nofollow noreferrer">DateOffset</a> for previous datetime, then get boolen mask by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.between.html" rel="nofollow noreferrer"><code>between</code...
python|pandas|group-by|timestamp
1
366,247
46,160,584
Tensorflow - Nodedef difference between keys DTYPE and T
<p>I would like to know what is the difference in the protobuf file of the graph between the attribute with keys "T" and "dtype"</p> <p>For example for the add operator we have a key "T" with the type as value:</p> <pre><code>name: "conv1/truncated_normal" op: "Add" input: "conv1/truncated_normal/mul" input: "conv1/t...
<p>Note that for TruncatedNormal both T and dtype are "type" attributes. <code>shape</code> input argument takes its type from "T" and <code>output</code> takes its type from "dtype". Names "T" and "dtype" are arbitrary, an op creator could've called them "T1" and "T2" instead, which would be more natural.</p>
python|tensorflow
2
366,248
45,971,477
import file and convert too pandas
<p>Using python and pandas i want to achieve the following:</p> <p>i have about 600 json files with the following file format:</p> <pre><code>User Name: ǝuuǝıɹpɐ\nAll Tags: Delightful Followers\t|\tlibtards\t........|\tExpressionEngine\t|\t\nYour Tag: </code></pre> <p>i want to create a pandas DataFrame for all the ...
<p>1) Iterate over files, for instance by using <code>os.listdir()</code> on the input directory: <a href="https://docs.python.org/2/library/os.html" rel="nofollow noreferrer">docs</a></p> <p>2) for each file, <code>open</code> (exact procedure depends on your Py version) and convert the file into a Python dictionary ...
python|json|pandas|dataframe
1
366,249
45,879,908
LabelEncoder with sklearn , transform and inverse single relationship between values?
<p>Hello and thank you in advance for any tip or advice.</p> <p>I am working in Python 3.6 with sklearn and DecisionTree Classifier. I use label encoder as my Pandas Dataframe has 4 columns and some are strings.</p> <pre><code> Origin Duration Origin Octave Origin Pitch Next Pitch 0 quarter ...
<p>I guess you can store your original labeling, for instance in a dictionary, and use it for further labeling.</p> <p>Here is an example referring to the unlabeled df as ´df_orig´ and to the labeled df as ´df_label´. Once you have labelled your dataframe you can build the dictionary. </p> <pre><code>map_dict = dict(...
python|pandas|encoding|scikit-learn|decision-tree
0
366,250
46,121,804
Fast selection of a percentage of elements between ranges
<p>Given pre-defined ranges, a list of percentages, and some data, I need to randomly select a <em>percentage</em> of IDs from those elements that are located between each range.</p> <p>The code below shows how I do it, and the <code>for</code> block is currently the bottleneck. I'm sure this could be made faster prob...
<p>We could reduce the workload inside the loop by computing <code>idxs</code> by simple slicing of the sorted indices of <code>c_indx</code> that we could compute before going into the loop.</p> <p>Hence, one solution would be -</p> <pre><code>sidx = c_indx.argsort() sc = c_indx[sidx] idx = np.flatnonzero(sc[1:] != ...
python|arrays|numpy|random
1
366,251
45,945,407
Fastest method of finding data from another row in Pandas DataFrame based upon column data calculation?
<p>Without resorting to looping thru each individual row of the dataframe, which can be very slow for large datasets, how do I used the calculated result of two columns in a row, <code>2*A - B</code>, to find a value in column <code>B</code> and from that new row pull data from column <code>C</code> and place into col...
<p>If you can guarantee unique combinations, then...</p> <pre><code>mapping = dict(df[['B', 'C']].values) df['D'] = (2 * df.A - df.B).replace(mapping) df A B C D 0 3 1 3 5 1 3 3 4 4 2 3 5 5 3 </code></pre> <p>Create a mapping of <code>B</code> values to <code>C</code> values. Perform the operati...
python|pandas|dataframe|mapping
3
366,252
46,141,696
tensorflow Estimator cannot initialize global variables
<p>I am using tensorflow slim resnet_v2 to extract image features. the resnet_v2_152.ckpt is from :<a href="http://download.tensorflow.org/models/resnet_v2_152_2017_04_14.tar.gz" rel="nofollow noreferrer">resnet_v2_152.ckpt</a> This is my code.</p> <pre><code>import tensorflow as tf import tensorflow.contrib.slim.pyt...
<p>I think, you are expecting to load pre-trained weights but not just initialize variables in resnet. You should consider using <a href="https://www.tensorflow.org/api_docs/python/tf/train/Scaffold" rel="nofollow noreferrer">tf.train.Scaffold</a> object. </p> <p>Model routine should look like this</p> <pre><code>def...
tensorflow
1
366,253
46,143,492
Faster RCNN tensorflow object detection API : dealing with big images
<p>I have images of a big size (6000x4000). I want to train FasterRCNN to detect quite small object (tipycally between 50 150 pixels). So for memory purpose I crop the images to 1000x1000. The training is ok. When I test the model on the 1000x1000 the results are really good. When I test the model on images of 6000x400...
<p>You need to keep training images and images to test on of roughly same dimension. If you are using random resizing as data augmentation, you can vary the test images by roughly that factor.</p> <p>Best way to deal with this problem is to crop large image into images of same dimension as used in training and then us...
python|tensorflow|size|object-detection|region
3
366,254
45,874,620
tensorflow sess.run returns List instead of float32 causing TypeError: unsupported operand type(s) for +=: 'float' and 'list'
<p>New to coding. Ran into a strange problem. Could not find any good answer on Stackoverflow or internet which explains or provides a way to avoid the error. Tensorflow sess.run returns a list when the original variable was of the <code>float32</code> type. These are the controlling lines:</p> <pre><code>accuracy = t...
<p><code>sess.run</code> accepts a list of the graph elements and returns a list of their values. In your case the list of the graph elements is <code>[accuracy]</code>, so <code>sess.run</code> returns a list with a single element.</p> <p>For convenience you can write</p> <pre><code>(accuracy_batch, ) = sess.run([ac...
python|tensorflow
4
366,255
45,823,212
How can you implement a C callable from Numba for efficient integration with nquad?
<p>I need to do a numerical integration in 6D in python. Because the scipy.integrate.nquad function is slow I am currently trying to speed things up by defining the integrand as a scipy.LowLevelCallable with Numba.</p> <p>I was able to do this in 1D with the scipy.integrate.quad by replicating the example given <a hre...
<p>Wrapping the function in a <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.LowLevelCallable.html" rel="nofollow noreferrer"><code>scipy.LowLevelCallable</code></a> makes <code>nquad</code> happy:</p> <pre><code>si.nquad(sp.LowLevelCallable(nb_func.ctypes), [[0,1],[0,1]], full_output=True) # (-2....
python|numpy|scipy|numba
4
366,256
45,991,998
More efficient way of calculating data from pandas dataframe (stock)
<p>I was wondering if there is a more efficient/cleaner way of doing the following. Say I have a dataframe that contains 2 columns, the percentage, (base on previous price) and the action, play/buy (1) or not play/sell (-1). Its basically about stocks.</p> <p>For simplicity, consider the example df:</p> <pre><code>...
<p>You could try this:</p> <pre><code># decide whether to play based on action df['Playing'] = df.Action.shift().eq(1) # replace Percent for not playing row with 1 and then calculate the cumulative product df['Money'] = '$' + df.Percent.where(df.Playing, 1).cumprod().mul(100).astype(str) df #Percent Action Playing...
python|pandas|numpy|dataframe
2
366,257
46,083,804
Python Pandas Aggregate Series Data Within a DataFrame
<p>Within a dataframe, I am trying split-apply-combine to a column which contains series data element-wise. (I've searched SO but haven't found anything pertaining to series within data frames.)</p> <p>The data frame:</p> <pre><code>import pandas as pd from pandas import Series, DataFrame import numpy as np ex = {'...
<pre><code>&gt;&gt;&gt; df.groupby(['account', 'account_type']).apply( lambda group: tuple(group['data'].apply(pd.Series).sum())) account account_type 1 A (5, 7, 9) B (7, 8, 9) 2 A (1, 3, 5) B (2, 4, 6) dtype: object </code...
python|pandas|split-apply-combine
2
366,258
45,809,201
Merge two dataframes based on a column
<p>I want to compare name column in two dataframes df1 and df2 , output the matching rows from dataframe df1 and store the result in new dataframe df3. How do i do this in Pandas ? </p> <p>df1</p> <pre><code>place name qty unit NY Tom 2 10 TK Ron 3 15 Lon Don 5 90 Hk Sam 4 49 </code></pre> <p>...
<p>You want something called an inner join.</p> <pre><code>df1.merge(df2,on = 'name') place_x name qty unit place_y price NY Tom 2 10 PH 7 TK Ron 3 15 TK 5 </code></pre> <p>The <code>_x</code>and <code>_y</code> happens when you have a column in both data frames being merge...
python|pandas|dataframe|merge
0
366,259
46,015,489
Using Numpy's PyArray_IsScalar in Cython
<p>TLDR: How can I define the <code>is_float_object</code> function below in pure cython?</p> <p>I'm trying to understand a few functions in <code>pandas._libs</code> that are defined in <a href="https://github.com/pandas-dev/pandas/blob/master/pandas/_libs/src/numpy_helper.h" rel="nofollow noreferrer">pandas/_libs/sr...
<p><code>##</code> is a C preprocessor concatenation. <code>Floating</code> isn't in any namespace but is just used in a string concatenation by the C preprocessor. The section <code>PyArray_IsScalar(obj, Floating)</code> is translated by the C preprocessor to be:</p> <pre><code>(PyObject_TypeCheck(obj, &amp;PyFloatin...
numpy|cython
3
366,260
45,804,879
Tensorflow - stop restoring network parameters
<p>I'm attempting to make multiple sequential predictions from a tensorflow network, but performance seems very poor (~500ms per prediction for a 2-layer 8x8 convolutional network) even for a CPU. I suspect that part of the problem is that it appears to be reloading the network parameters every time. Each call to <co...
<p>The <a href="https://www.tensorflow.org/extend/estimators" rel="nofollow noreferrer">Estimator API</a> is a high-level API.</p> <blockquote> <p>The tf.estimator framework makes it easy to construct and train machine learning models via its high-level Estimator API. Estimator offers classes you can instantiate...
python|machine-learning|tensorflow
0
366,261
46,009,303
How to extract a value from a tensor as int in tensorflow?
<p>This question is with respect to accessing individual elements in a tensor, say [1,2,3]. I need to access the inner element [1]. Since I am calling another api library which is not from tensorflow. This api needs an int value as an argument.I am having problems putting [1] into that api as [1] is shown as a tensor, ...
<p>You need to start a session, load/initialize variables then run the session.</p> <pre><code># build graph target_tensor = bigger_tensor[1, 2] # whichever index you want with tf.Session() as sess: sess.run(tf.global_variables_initializer()) # or load from file target_value = sess.run(target_tensor) #may n...
tensorflow
0
366,262
46,081,444
Pivoting Column has N/A in DataFrame which Python is filtering
<p>I am trying to pivot columns in CSV. I am first pulling them into a dataframe and pivoting them. This is my code:</p> <pre><code>import pandas as pd import csv df1=pd.read_csv("C:\\testfolder\\testdemofinal1.csv",sep=',') df=pd.DataFrame(df1) a=df.pivot_table(index='Parameter1_Calculation',columns='Measure Names...
<p>Apply <code>na_filter =False</code> while using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer">pandas.read_csv</a> . This should help you to get away with the problem.</p> <blockquote> <p>na_filter : boolean, default True Detect missing value mar...
python|pandas|csv|dataframe|pivot
0
366,263
45,748,061
Delete all elements in an array corresponding to Boolean mask
<p>I have a Boolean mask that exists as 2-D numpy array (Boolean Array)</p> <pre><code>array([[ True, True, True, True, True, True, True], [ True, True, True, True, True, True, True], [ True, True, True, True, True, True, True], [ True, True, True, True, True, True, True], ...
<p>For most purposes you could simply create a <a href="https://docs.scipy.org/doc/numpy/reference/maskedarray.generic.html" rel="nofollow noreferrer"><code>MaskedArray</code></a> which behaves as if these were "removed", that also allows to "remove" single elements from a column/row while keeping the dimensionality th...
python|arrays|numpy|multidimensional-array|slice
4
366,264
45,961,224
SyntaxNet - Reduce time for parsing sentence
<p>I am successfully able to parse a sentence using Syntaxnet using following command. </p> <blockquote> <p><code>echo 'Bob brought the pizza to Alice.' | syntaxnet/demo.sh</code></p> </blockquote> <p>On an average Syntaxnet takes about 4 seconds to parse. I presume the model loads everything each time it is called...
<pre><code>$ cat test.txt| syntaxnet/demo.sh </code></pre> <p>In the test.txt, I write two setences:</p> <pre><code>how are you doing today i am doing great </code></pre> <p>The result is as follows:</p> <pre><code>Input: how are you doing today Parse: doing VBG ROOT +-- how WRB advmod +-- are VBP aux +-- you PR...
parsing|tensorflow|syntaxnet
0
366,265
45,773,613
How to deconve a None shape tf.placeholder?
<p>Here is the problem.:</p> <p>I want to deconve a Tensor with uncertain shape(depend on the input). So I use</p> <pre><code> tf.placeholder(dtype = tf.float32,shape=None) </code></pre> <p>as the tensor and to deconv.</p> <pre><code>tf.nn.conv2d_transpose() </code></pre> <p>But tf.nn.conv2d_transpose() requires...
<p>I think i figured out a solution. I have used tensor.get_shape().as_list() to get the input shape and caculate the deconvolution output shape. But it seems tensor.get_shape() is a static method to get shape and cannot handle a tf.placeholder or tensors derived from a tf.placeholder and then cannot build the Graph. S...
tensorflow
-1
366,266
45,852,928
How can I find minimum and maximum value of date for ID 1 and 5 using python pandas?
<p>Here, as shown in image I want to find minimum and maximum value of date for ID 1 and 5. it is like for ID 1 minimum date is 2016-01-27 17:13:19 and maximum is 2016-03-28 00:56:43. Same for ID 5.</p> <p><a href="https://i.stack.imgur.com/x9FBH.png" rel="nofollow noreferrer">Please Click to see Image</a></p>
<p>You can use aggregate,</p> <p>Consider this df</p> <pre><code> Date ID 0 2016-3-28 00:56:43 1 1 2017-3-28 00:56:43 1 2 2005-3-28 00:56:43 1 3 2010-3-28 00:56:43 1 4 2002-3-28 00:56:43 1 5 2017-3-29 00:56:43 1 6 2004-3-28 00:56:43 5 7 2002-3-21 00:56:43 5 8 2015-3-28 00:56:43 5 9 ...
excel|python-3.x|pandas|duplicates
0
366,267
45,966,500
Use sklearn GridSearchCV on custom class whose fit method takes 3 arguments
<p>I'm working on a project that involves implementing some algorithms as python classes and testing their performance. I decided to write them up as sklearn estimators so that I could use <a href="http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html" rel="nofollow noreferrer"><cod...
<p>So after getting some inspiration from a friend on this (<a href="https://stackexchange.com/users/2660392/matthew-drury?tab=accounts">@Matthew Drury</a>) I constructed a much more elegant solution.</p> <p>Again the problem is framed as such:</p> <p>I have a matrix completion method that takes <code>X</code>, <code...
python|numpy|machine-learning|scikit-learn|grid-search
2
366,268
45,900,653
TensorFlow: How to predict from a SavedModel?
<p>I have exported a <code>SavedModel</code> and now I with to load it back in and make a prediction. It was trained with the following features and labels:</p> <pre><code>F1 : FLOAT32 F2 : FLOAT32 F3 : FLOAT32 L1 : FLOAT32 </code></pre> <p>So say I want to feed in the values <code>20.9, 1.8, 0.9</code> get a single ...
<p>Assuming you want predictions in Python, <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/predictor/saved_model_predictor.py" rel="noreferrer">SavedModelPredictor</a> is probably the easiest way to load a SavedModel and get predictions. Suppose you save your model like so:</p> <pre><...
python|machine-learning|tensorflow|tensorflow-serving
15
366,269
46,007,158
Alternative Loss Functions for Multi Label Classification
<p>I am currently using the following loss function:</p> <pre><code>loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits, labels)) </code></pre> <p>However, my loss quickly approaches zero since there are ~1000 classes and only a handful of ones for any example (see attached image) and the algorithm i...
<p>Did you try to project one multi-label target vector into multiple one-hot vectors?</p> <p>Bear with me for a moment. For brevity I will build the loss function in numpy.</p> <p>Apply sigmoids on your model outputs. Let's call it <em>y</em>. This will be the probabilities for each class. Here for simplicity I will...
python|machine-learning|tensorflow|neural-network
0
366,270
45,885,183
Python tkinter - numpy - Listbox doesn't load values
<p>I'm building a python tkinter software with a listbox, but the listbox doesn't load values from a list (that is inside a dictionary) through for loop.</p> <p>The dictionary is stored in a .npy file with numpy and has this structure: <code>m={"subject":["subjectname"], ...}</code>. But I don't think the problem is c...
<p>Found the problem: Numpy loads the dictionary but the variable m will be lost forever if I don't add <code>global m</code>before. So I rechecked the code and added some more controls. Here it is the fully functional code:</p> <pre><code>import os.path import numpy as np global m m={} global fn_sub global path # fil...
python|numpy|tkinter|listbox|ttk
1
366,271
45,941,886
How to group data and create bins?
<p>I have the following DataFrame df (a small extract is given):</p> <pre><code>time_diff avg_qty_per_day 1.450000 1.0 1.483333 1.0 1.500000 1.0 2.516667 1.0 2.533333 1.0 2.533333 1.5 3.633333 1.8 3.644567 5.0 </code></pre> <p>How can I group it into bins in order to get the following result...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow noreferrer"><code>cut</code></a>:</p> <pre><code>bins = [-np.inf, 2, 3, np.inf] labels=[1,2,3] df = df['avg_qty_per_day'].groupby(pd.cut(df['time_diff'], bins=bins, labels=labels)).sum() print (df) time_di...
python|python-2.7|pandas
2
366,272
45,865,608
Executing an SQL query over a pandas dataset
<p>I have a pandas data set, called 'df'.</p> <p>How can I do something like below;</p> <pre><code>df.query("select * from df") </code></pre> <p>Thank you.</p> <p>For those who know R, there is a library called sqldf where you can execute SQL code in R, my question is basically, is there some library like sqldf in ...
<p>This is not what <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html" rel="noreferrer"><code>pandas.query</code></a> is supposed to do. You can look at package <code>pandasql</code> (same like <code>sqldf</code> in R )</p> <pre><code>import pandas as pd import pandasql as ps ...
python|sqlite|pandas
124
366,273
45,865,260
Cannot get decent accuracy on validation on Convolutional NN project
<p>I am trying to design a convolution neural network for detecting a small red football ball. I have captured aproxx 4000 pictures of a scene in different configurations (adding chairs, bottles,etc…) without the ball inside and 4000 pictures of the scene in also different configurations but with the ball inside somewh...
<p>Your results and accuracy curve seem quite normal to me, so the model is learning fine. Few suggestions:</p> <ul> <li>As already pointed out in the comments, you probably need a bigger data set. Compare your data set to <a href="https://www.cs.toronto.edu/~kriz/cifar.html" rel="nofollow noreferrer">CIFAR-10</a>, wh...
python|machine-learning|tensorflow|neural-network
0
366,274
45,724,806
Matrix isn't being appended to correctly
<p>My code is for the user to create a custom matrix which is applied to the starting state. Because I want it to be able to generate any square matrix the user wishes, I have to do some funky things. My basic approach was to have the user input the different elements, which are all put in one list. Based on the positi...
<p>Given the input that you specified above (size 2 and elements of 0, 1, 1, 0), the error is coming from the fact that you are trying to append a row of 2 elements to an empty matrix. Your (empty) matrix has shape (1, 0) while the current_row has shape (2, ) if turned into an np.array.</p> <p>As DYZ mentioned above, ...
python|python-3.x|numpy|matrix
3
366,275
45,864,550
TypeError: src is not a numpy array, neither a scalar
<pre><code> gray_image = cv2.cvtColor(contrast, cv2.COLOR_BGR2GRAY) TypeError: src is not a numpy array, neither a scalar </code></pre> <p>I am currently working to solve this, any help would be appreciated. As mentioned in the comments, the PIL image needs to be converted to CV2 accepted format, can anyone provid...
<p>PIL is almost completely object oriented, so most functions return objects.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; image = Image.open('img6.png') &gt;&gt;&gt; type(image) &lt;class 'PIL.PngImagePlugin.PngImageFile'&gt; </code></pre> <p>The PIL <code>Image</code> is a class (hence the capital) so it retur...
python|python-2.7|opencv|numpy|image-processing
12
366,276
46,096,801
Create flag based on cumsum and timediff
<p>Consider the following data frame,</p> <pre><code>import pandas as pd import numpy as np np.random.seed(666) dd=pd.DataFrame({'v1': np.random.choice(range(30), 20), 'v2': np.random.choice(pd.date_range( '5/3/2016', periods=365, freq='D'), 20, replace=Fal...
<p>Setup:</p> <pre><code>dd['days'] = dd['v2'].diff().dt.days.fillna(0).astype(int) dd = dd[['v1', 'v2', 'days']] # the order of the columns matters </code></pre> <p>Initialize:</p> <pre><code>increment = pd.Series(False, index=dd.index) v1_cum = 0 days_cum = 0 </code></pre> <p>Loop:</p> <pre><code>for row in dd....
python|pandas|numpy
3
366,277
23,322,025
Julia Dataframes vs Python pandas
<p>I am currently using python <code>pandas</code> and want to know if there is a way to output the data from pandas into julia <code>Dataframes</code> and vice versa. (I think you can call python from Julia with <code>Pycall</code> but I am not sure if it works with dataframes) Is there a way to call Julia from python...
<p>So there is a library developed for this</p> <p><code>PyJulia</code> is a library used to interface with Julia using Python 2 and 3</p> <p><a href="https://github.com/JuliaLang/pyjulia" rel="nofollow noreferrer">https://github.com/JuliaLang/pyjulia</a></p> <p>It is experimental but somewhat works</p> <p>Secondly...
python|pandas|dataframe|julia
6
366,278
23,244,443
Plot normal distribution in Python from a .csv file
<p>The following script draws the Normal Distribution of a sort of data given.</p> <pre><code>import numpy as np import scipy.stats as stats import pylab as pl h = sorted ([0.9, 0.6, 0.5, 0.73788,...]) #Data that I would like to change fit = stats.norm.pdf(h, np.mean(h), np.std(h)) pl.plot(h,fit,'-o') pl.show() ...
<p>It seems very roundabout to write the data back out to a file, presumably to read it back in again later. Why not create a list of the data?</p> <pre><code>def import_data(filename): """Import data in the second column of the supplied filename as floats.""" with open(filename, 'rb') as inf: return [...
python|python-2.7|csv|numpy|matplotlib
4
366,279
22,998,318
From (n,) to (n,1) numpy arrays and viceversa?
<p>I understand that Numpy treats arrays with shapes <code>(n,1)</code> differently from those with <code>(n,)</code> shapes, although they can hold the same data. </p> <p>How can I convert between them?</p>
<p>Hopefully the following should illustrate the difference, with <code>(n,)</code> you have a flat array, with <code>(n,1)</code> you have a nested array (array of <code>n</code> one-element arrays):</p> <pre><code>&gt;&gt;&gt; np.ones(10).reshape((10,)) array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]) &gt;&...
python|numpy
6
366,280
23,257,079
How to extract array from the first element of triples in 2d array of triples using numpy
<p>I have an array with shape <code>(480, 640, 3)</code> and I want to create an array made up of all the first elements from the triples using numpy. I tried </p> <p><code>newArray = array[np.arange(array.shape[0]),np.arange(array.shape[1]),0]</code> </p> <p>but that returns this:</p> <p><code>cannot be broadcast t...
<p>Sounds like you want to take a slice along the depth axis:</p> <pre><code>In [8]: a = np.ones((480,640,3)) In [9]: a[:,:,0] Out[9]: array([[ 1., 1., 1., ..., 1., 1., 1.], [ 1., 1., 1., ..., 1., 1., 1.], [ 1., 1., 1., ..., 1., 1., 1.], ..., [ 1., 1., 1., ..., 1., 1.,...
python|arrays|numpy
3
366,281
23,397,629
Finding the position of a subsequence in a sequence
<p>If T1 is this:</p> <pre><code>T1 = pd.DataFrame(data = {'val':['B','D','E','A','D','B','A','E','A','D','B']}) </code></pre> <p>and P is this: </p> <pre><code>P = pd.DataFrame(data = {'val': ['E','A','D','B']}) </code></pre> <p>how do I get the positions of P within T1 ?</p> <p>In terms of min and max I would li...
<p>well, you can always do a workaround like this:</p> <pre><code>t1 = ''.join(T1.val) p = ''.join(P.val) start, res = 0, [] while True: try: res.append(t1.index(p, start)) start = res[-1] + 1 except: break </code></pre> <p>to get the starting indices and then figure out the ending ind...
python|pandas
0
366,282
23,033,416
How to optimize math operations on matrix in python
<p>I am trying to reduce the time of a function that performs a serie of calculations with two matrix. Searching for this, I've heard of numpy, but I really do not know how apply it to my problem. Also, I Think one of the things is making my function slow is having many dots operators (I heard of that in this <a href="...
<p>In the simple example you've given, with <code>for k in xrange(4):</code> the loop body only executes twice (if <code>r==s</code>), or three times (if <code>r!=s</code>) and an initial numpy implementation, below, is slower by a large factor. Numpy is optimized for performing calculations over long vectors and if th...
python|numpy|matrix|heuristics
6
366,283
35,582,531
pandas subplot title size in ipython notebook
<p>I plotted two plots side by side in an ipython notebook cell. But, I am having trouble changing the size of the title. I can change the size of the labels by adding the argument <code>fontsize = 20</code>. How do I change the title for <code>df</code> and <code>df2</code>.</p> <pre><code>fig, axes = plt.subplots(nc...
<p>You can change the size of an existing title on the Axes using <code>title.set_size()</code></p> <pre><code>axes[0].title.set_size(40) </code></pre>
python|pandas|matplotlib
23
366,284
35,723,759
Pandas Efficient Count Unique Values in column then find max of that count
<p>The dataframe (df) looks like:</p> <pre><code> Date Caller Called 0 2011-01-01 00:00:00 Sarah Claire 1 2011-01-01 00:00:00 Sarah Ryan 2 2011-01-01 00:00:00 Sarah Alex 3 2011-01-02 00:00:00 Sarah Max 4 2011-01-02 00:00:00 Sarah Phoebe number_date = df.groupby(['Caller',pd.Da...
<p>You can try <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.SeriesGroupBy.nunique.html" rel="nofollow"><code>nunique</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.SeriesGroupBy.nlargest.html" rel="nofollow"><code>nlargest</code></...
python|pandas
1
366,285
35,509,857
ImportError: cannot import name '__check_build'
<p>I can't seem to get from sklearn.cluster import KMean to work in Python I did the whole pip install scipy/numpy and they are installed in python but I can't get the KMeans into it at the moment I have found a load of ones that are similar to my problem but I can't seem to get it working with mine. </p> <p>When I do...
<p>Try this:</p> <pre><code>sudo pip install scipy </code></pre> <p>Then in Python:</p> <pre><code>import scipy </code></pre>
python|numpy|scipy|k-means
0
366,286
35,654,187
Numpy Choose Elements from 2 arrays
<p>I need to choose n items from 2 arrays such that the indices are the same. So, for instance, I need to choose two items from x randomly, and pick elements from y such that y's chosen indices are the same as x's:</p> <pre><code>x = np.asarray([0.1123,0.223,0.8873]) y = np.asarray([1,1,2]) x_chosen = np.random.choi...
<p>Use <code>np.random.randint()</code> to find your indices:</p> <pre><code>x = np.asarray([0.1123,0.223,0.8873]) y = np.asarray([1,1,2]) indices = np.random.randint(0, x.size, 2) &gt;&gt;&gt; x[indices] array([ 0.1123, 0.223 ]) &gt;&gt;&gt; y[indices] array([1, 1]) </code></pre> <p><strong>EDIT</strong></p> <p>A...
python|numpy|numpy-random
2
366,287
35,685,717
Indexes of min/max elements in 4D array
<p>I need to change min/max values of a 4D array along specific axis. The coordinates of min/max along a particular axis are retuned by <code>armax</code>, so for 4D array a have a 3D array.</p> <p>Now from this 3D array I need to recover the full index of min/max values. I understand the most efficient way to do it i...
<p>Try indexing with:</p> <pre><code>Array[:, np.argmin(Array, axis=1), :, :] = .... </code></pre> <p>I think you are trying to set all the values of one 'plane' to a minimum value. <code>:</code> is a <code>slice</code>, specifying all indexes along that axis.</p> <p>I haven't actually tried to run your example, b...
python|numpy|multidimensional-array|max|min
0
366,288
35,610,275
Transforming and creating colums in a data frame using python
<p>I'm working on building a python script that computes a d' statistic, using data from a CSV file, but the data in the CSV need to be manipulated so that the d' can be computed. <strong> My question: What code do I need to employ to transform the data in a data frame created from the csv. </strong></p> <h1><strong>D...
<p>You can try <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow"><code>loc</code></a> for identifying values in columns <code>Stim</code> and <code>Detect</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="n...
python|csv|pandas
0
366,289
35,721,404
Control xaxis tick mark size on all subplots
<p>I have the below code, which works to a point. However, it only changes the size of the xticks for one of the subplots. How can I change it to change the size for all of them?</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import numpy as np input_file = 'CSP.csv' output_file = 'sub_plots.png' ...
<p><code>plt.xticks</code> only acts on the final subplot axes created. You want to set it on all the subplots. You have two options: </p> <p>1) You can set the tick label size for each axes using the <a href="http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.tick_params" rel="noreferrer"><code>tick_params<...
python|pandas|matplotlib
5
366,290
35,548,193
Create a new column and assign value for each group starting using groupby
<p>I want to create a new column as 'fold' and assign new values to it depending on group of quote_id.Let's say if 3 quote_id is same then it should assign 1 and next 4 quote_id is same then it should assign 2.</p> <p>In short it should assign a number to a particular group of quote_id. I have been trying from long t...
<p>call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.rank.html" rel="nofollow"><code>rank</code></a> with <code>method='dense'</code>:</p> <pre><code>In [10]: df['fold'] = df['quote_id'].rank(method='dense') df Out[10]: quote_id fold 0 1300079-DE 1 1 1300079-DE 1 2 ...
python|pandas
1
366,291
11,799,511
writing large netCDF4 file with python?
<p>I am trying to use the netCDF4 package with python. I am ingesting close to 20mil records of data, 28 bytes each, and then I need to write the data to a netCDF4 file. Yesterday, I tried doing it all at once, and after an hour or so of execution, python stopped running the code with the very helpful error message:<...
<p>It's hard to tell what you are doing without seeing code, but you could try using the <code>sync</code> command to flush the data in memory to disk after some amount of data has been written to the file:</p> <p><a href="http://netcdf4-python.googlecode.com/svn/trunk/docs/netCDF4.Dataset-class.html" rel="nofollow">h...
python|numpy|netcdf
1
366,292
11,760,490
How to generate a clean x and y axis for a numpy matrix?
<p>I am creating a distance matrix in numpy, with an out put as such:</p> <pre><code> ['H', 'B', 'D', 'A', 'I', 'C', 'F'] [[ 0. 2.4 6.1 3.2 5.2 3.9 7.1] [ 2.4 0. 4.1 1.2 3.2 1.9 5.1] [ 6.1 4.1 0. 3.1 6.9 2.8 5.2] [ 3.2 1.2 3.1 0. 4. 0.9 4.1] [ 5.2 3.2 6.9 4. 0. 4.7 7.9] [ 3.9...
<p>It is not so pretty, but this pretty table prints works:</p> <pre><code>import numpy as np names=np.array(['H', 'B', 'D', 'A', 'I', 'C', 'F']) a=np.array([[ 0., 2.4, 6.1, 3.2, 5.2, 3.9, 7.1], [2.4, 0., 4.1, 1.2, 3.2, 1.9, 5.1], [6.1, 4.1, 0., 3.1, 6.9, 2.8, 5.2], [3.2, 1.2, 3.1, 0., 4....
python|arrays|numpy|matrix
2
366,293
11,903,083
Find the set difference between two large arrays (matrices) in Python
<p>I have two large 2-d arrays and I'd like to find their set difference taking their rows as elements. In Matlab, the code for this would be <code>setdiff(A,B,'rows')</code>. The arrays are large enough that the obvious looping methods I could think of take too long.</p>
<p>This <strong>should</strong> work, but is currently broken in 1.6.1 due to an unavailable mergesort for the view being created. It works in the pre-release 1.7.0 version. This should be the fastest way possible, since the views don't have to copy any memory:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&g...
python|numpy|set-difference
16
366,294
28,507,383
Count the individual values within the arrays stored in a pandas Series
<p>Here's a simple example to set the stage:</p> <pre><code>import pandas as pd import numpy as np example_series = pd.Series([np.arange(5), np.arange(15), np.arange(12), np.arange(7), np.arange(3)]) pr...
<p>Flatten the list then use value_counts()</p> <pre><code>pd.Series([item for sublist in example_series for item in sublist]).value_counts() 2 5 1 5 0 5 4 4 3 4 6 3 5 3 11 2 10 2 9 2 8 2 7 2 14 1 13 1 12 1 </code></pre>
python|pandas
2
366,295
28,654,481
Using string methods on dataframes in Python Pandas?
<p>I have a dataframe with the following string format.</p> <pre><code>data.description[4000]=['Conduit, PVC Utility Type DB 60 TC-6, 1-1/2" LF .050 $.86 $1.90 $2.76'] </code></pre> <p>the string varies in size but I would like be broken up splitting the string at the ' LF '...
<p>You can use the string method <code>split</code> directly on the column with the text:</p> <pre><code>df['text'].str.split('(CLF|LF|EA)') </code></pre> <p>You can use capturing parentheses to keep the delimiter</p> <p>Example:</p> <pre><code>units ='(CLF|LF|EA)' df =pd.DataFrame({'text':['aaaaaaa LF bbbbbbbb','1...
python|regex|string|pandas
1
366,296
28,407,265
Aggregating numpy masked arrays
<p>I'm working with <a href="http://docs.scipy.org/doc/numpy/reference/maskedarray.html" rel="nofollow">numpy masked arrays</a> and there is a trivial operation I cannot figure out how to do it in a simple way. If I have two masked arrays, how can I get them aggregated into another array that contains only the unmasked...
<p>Stack the masks and the arrays using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.dstack.html" rel="nofollow"><code>numpy.dstack</code></a> and create a new masked array and then you can get the required output using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.prod.html" ...
python|numpy
1
366,297
28,754,658
What's the fastest way to pickle a pandas DataFrame?
<p>Which is better, using Pandas built-in method or <code>pickle.dump</code>?</p> <p>The standard pickle method looks like this:</p> <pre><code>pickle.dump(my_dataframe, open('test_pickle.p', 'wb')) </code></pre> <p>The Pandas built-in method looks like this: </p> <pre><code>my_dataframe.to_pickle('test_pickle.p') ...
<p>Thanks to @qwwqwwq I discovered that pandas has a built-in <code>to_pickle</code> method for dataframes. I did a quick time test:</p> <pre><code>In [1]: %timeit pickle.dump(df, open('test_pickle.p', 'wb')) 10 loops, best of 3: 91.8 ms per loop In [2]: %timeit df.to_pickle('testpickle.p') 10 loops, best of 3: 88 ms...
python|pandas|pickle
18
366,298
50,980,810
How to create a discrete RGB colourmap with N colours using numpy
<p>I am trying to create a really simple colourmap using RGB triples. That has a discrete number of colours.</p> <p>Here is the shape that I am trying to make it follow:</p> <p><a href="https://i.stack.imgur.com/5aWDC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5aWDC.png" alt="enter image description he...
<p>Here is one reasonably convenient method using <code>np.clip</code>:</p> <pre><code>def spec(N): t = np.linspace(-510, 510, N) return np.round(np.clip(np.stack([-t, 510-np.abs(t), t], axis=1), 0, 255)).astype(np.uint8...
python|numpy|colormap
6
366,299
50,736,908
Making Prediction with tensorflow's estimator.DNNRegressor
<p>I am quite new to tensorflow and in order to learn to use it I am currently trying to implement a very simple DNNRegressor that predicts the movement of an object in 2D but I can't seem to the the predict function to work.</p> <p>for this purpose I have some Input data - x and y coordinates of the object in a numbe...
<p>The <code>input_fn</code> to <code>regressor.predict</code> should be a function. See the <a href="https://www.tensorflow.org/api_docs/python/tf/estimator/DNNRegressor#predict" rel="nofollow noreferrer">definition</a>:</p> <blockquote> <p>input_fn: A function that constructs the features.</p> </blockquote> <p>Yo...
python|tensorflow|tensorflow-estimator
1