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
367,100
47,897,199
Bug when using TensorFlow-GPU + Python multiprocessing?
<p>I have noticed a strange behavior when I use TensorFlow-GPU + Python multiprocessing.</p> <p>I have implemented a <a href="https://arxiv.org/abs/1511.06434" rel="nofollow noreferrer">DCGAN</a> with some customizations and my own dataset. Since I am conditioning the DCGAN to certain features, I have training data an...
<p>I am coming with the same error when trying to use tensorflow and multiprocessing</p> <pre><code>E tensorflow/stream_executor/cuda/cuda_blas.cc:366] failed to create cublas handle: CUBLAS_STATUS_NOT_INITIALIZED </code></pre> <p>but in different environment tf1.4 + cuda 8.0 + cudnn 6.0. matrixMulCUBLAS in sample co...
python|multithreading|tensorflow|multiprocessing
1
367,101
47,716,384
Adding MANY variables in Tensorflow
<p>If <code>tf.add</code> only takes 2 to 3 positional arguments how do I add half a dozen or more values together (hoping you won't say do lots of sub-totals first!). I'd like to specify something like:</p> <pre><code>tf.AddTheseTogether(value1,value2,value3,value4,value5) etc. </code></pre> <p>Tried <code>tf.add_n...
<p><a href="https://www.tensorflow.org/api_docs/python/tf/add_n" rel="nofollow noreferrer"><code>tf.add_n</code></a> takes a list of inputs, like this (note the <code>[]</code>):</p> <pre><code>tf.add_n([value1,value2,value3,value4,value5]) </code></pre>
python|math|tensorflow
1
367,102
47,732,186
TensorFlow - TF Record too large to be loaded into an np array at once
<p>I am trying to train an AlexNet CNN model by following the steps <a href="https://www.tensorflow.org/tutorials/layers" rel="nofollow noreferrer">in the tutorial from the TensorFlow guide site</a> .However, the tutorial makes use of the below code to load in the training data</p> <pre><code>mnist = tf.contrib.learn....
<p>If you can access your data as a <code>tf.data.Dataset</code>, there is no need to convert it to a NumPy array before passing it to an <code>Estimator</code>. You can simply build the <code>Dataset</code> directly in your input function, with something like the following:</p> <pre><code>def train_input_fn(): data...
tensorflow|tensorflow-datasets|tfrecord
3
367,103
47,787,085
Bug code OpenAI weigh normalization get_variable tf1.4
<p>I'm trying to use the source code of OpenAI which implements weight normalization (Saliman's paper). <a href="https://github.com/openai/weightnorm/tree/master/tensorflow" rel="nofollow noreferrer">https://github.com/openai/weightnorm/tree/master/tensorflow</a></p> <p>The code works very well on tf 1.1. But I can't ...
<p>You may try add a line:</p> <pre><code>inp = tf.map_fn(tf.identity, inp) </code></pre> <p>This works for my case, but I still dont know why it works. </p>
python|tensorflow|initialization|normalization
0
367,104
47,890,602
Interpolate polar/circular data with Pandas
<p>I have a sparse data set, <code>f44</code>, made up of bearings in degrees and ssi (dbm) values:</p> <pre><code> ssi deg 4.0 -69 59.0 -73 162.0 -73 267.0 -61 319.0 -75 </code></pre> <p>I reindexed <code>f44</code> to include all the missing indices from 0-359:</p> <pre><code>f44i = f44.reinde...
<p>I have an alternative approach to this problem using <code>scipy</code> to interpolate onto a closed curve. First, I converted your data from (deg, ssi) to <em>psuedo</em> cartesian coordinates (x,y) assuming <code>deg</code> is the polar angle and <code>ssi</code> is the (negative) of the radial distance. Then you ...
python|pandas|scipy
1
367,105
47,615,041
Tensorflow Saver.Save(), FailedPreconditionError, Failed to rename: ... The process cannot access the file because it is being used by another process
<p> Tried to use Saver to save a session. And encountered an error:</p> <pre><code>FailedPreconditionError (see above for traceback): Failed to rename: ./Language_model_lab3-0.data-00000-of-00001.tempstate15754770084434331914 to: ./Language_model_lab3-0.data-00000-of-00001 : The process cannot access the file because ...
<p>I searched this site, the only answer is related to dropbox and I don't have dropbox running. Turned of Symantic anti-virus, Mircosoft Onedrive and Google Backup/Sync. Not helping.</p> <p>I tried to use " Process Explore" to search which process has the file / folder locked and can't find any.</p> <p>So I tried t...
python|tensorflow
1
367,106
47,576,025
Pandas, how to reindex a dataframe that is generated from appending multiple dataframe.
<p>I have a dataframe that is generated from appending multiple dataframe together into a long list. As shown in figure, the default index is a loop between 0 ~ 7 because each original df has this index. The total row number is 240. So how can reindex the new df into 0~239 instead of 30 x 0~7. </p> <p>I tried <code>df...
<p>It seems you forget assign output, because by default <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow noreferrer"><code>reset_index</code></a> does not work <code>inplace</code>:</p> <pre><code>df = df.reset_index(drop=True) </code></pre> <p>Or:</p> ...
python|pandas|dataframe
5
367,107
47,650,132
Shuffling input files with tensorflow Datasets
<p>With the old input-pipeline API I can do:</p> <pre><code>filename_queue = tf.train.string_input_producer(filenames, shuffle=True) </code></pre> <p>and then pass the filenames to other queue, for example:</p> <pre><code>reader = tf.TFRecordReader() _, serialized_example = reader.read_up_to(filename_queue, n) </cod...
<p>Start reading them in order, <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset#shuffle" rel="noreferrer">shuffle</a> right after:</p> <pre><code>BUFFER_SIZE = 1000 # arbitrary number # define filenames somewhere, e.g. via glob dataset = tf.data.TFRecordDataset(filenames).shuffle(BUFFER_SIZE) </cod...
python|tensorflow|dataset
8
367,108
47,670,072
numpy boolean indexing selecting and setting
<p>I'm not very familiar with python. I reading the book 'Python for Data Analysis' recently, and I'm a bit confused about the numpy boolean indexing and setting. The book said:</p> <blockquote> <p>Selecting data from an array by boolean indexing always creates a copy of the data, even if the returned array is unchange...
<p>While <code>data[data &lt; 0] = 0</code> sorta looks like a view being set to <code>0</code>, that's not what's actually happening. In reality, an <code>ndarray</code> followed by <code>=</code> calls <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ndarray.__setitem__.html" rel="noreferre...
python|numpy
5
367,109
47,585,843
Telling python to ignore undefined data frames while iterating over a list of data frames?
<p>Consider this dataframe and iteration:</p> <pre><code>pdata= {'col1': [1, 2], 'col2': [3, 4]} pdata= pd.DataFrame(data=pdata) for i in [pdata, vdata, odata]: i.index = i.iloc[:, 0] </code></pre> <p>if any of pdata, vdata, or odata is not defined, Python throws the error: </p> <pre><code>NameError: name 'vd...
<p>Just skip over the errors with a <code>try-except</code> clause:</p> <pre><code>try: for i in [pdata, vdata, odata]: i.index = pd.DatetimeIndex(i.date) except: # You can do whatever you want here; pass does nothing pass </code></pre>
python|pandas
0
367,110
47,847,461
How to enforce rules like move legality in chess at the output of a neural network?
<p>How do I apply rules, like chess rules, to a neural network, so the network doesn't predict/train invalid moves?</p>
<p>In the example of AlphaZero Chess, the network's output shape allows for all possible moves for any pieces starting on any square.</p> <p>From the paper <a href="https://arxiv.org/abs/1712.01815" rel="noreferrer">Mastering Chess and Shogi by Self-Play with a General Reinforcement Learning Algorithm</a>:</p> <block...
machine-learning|tensorflow|neural-network|keras|lstm
7
367,111
47,763,862
Error in using np.NaN is vectorize functions
<p>I am using Python 3 on 64bit Win1o. I had issues with the following simple function:</p> <pre><code>def skudiscounT(t): s = t.find("ITEMADJ") if s &gt;= 0: t = t[s + 8:] if t.find("-") == 2: return t else: return np.nan # if change to "" it will work fine! </code></pr...
<p>Without <code>otypes</code> the dtype of the return array is determined by the first trial result:</p> <pre><code>In [232]: f = np.vectorize(skudiscounT) In [234]: f(['abc']) Out[234]: array([ nan]) In [235]: _.dtype Out[235]: dtype('float64') </code></pre> <p>I'm trying to find an argument that returns a string. ...
pandas|numpy|vectorization
1
367,112
47,838,306
Getting No loop matching the specified signature and casting error
<p>I'm a beginner to python and machine learning . I get below error when i try to fit data into statsmodels.formula.api OLS.fit()</p> <p>Traceback (most recent call last):</p> <blockquote> <p>File "", line 47, in regressor_OLS = sm.OLS(y , X_opt).fit()</p> <p>File "E:\Anaconda\lib\site-packages\stats...
<p>try specifiying the </p> <blockquote> <p>dtype = 'float'</p> </blockquote> <p>When the matrix is created. Example:</p> <pre><code>a=np.matrix([[1,2],[3,4]], dtype='float') </code></pre> <p>Hope this works!</p>
python|numpy|machine-learning|scikit-learn
62
367,113
47,542,073
Total Number of Missing Attributes
<p>Using python and panda: For a given data set how does one find the total number of missing attributes? I have found the number for each column, but I need to sum the columns using python to find the total. Below is the code I have currently used. </p> <pre><code>def num_missing(x): return sum(x.isnull()) print(...
<p>Consider <code>df</code> -</p> <pre><code>df A B C 0 1.0 4 NaN 1 2.0 5 1.0 2 NaN 6 6.0 3 NaN 7 3.0 </code></pre> <hr> <ol> <li><p>Column-wise NaN count -</p> <pre><code>df.isnull().sum(0) A 2 B 0 C 1 dtype: int64 </code></pre></li> <li><p>Row-wise NaN count - </p> <pre><code>df.i...
python|pandas
2
367,114
47,939,921
tabula-py ImportError: cannot import name 'read_pdf'
<p>Im trying to use tabula-py to transfer a table from pdf to excel.</p> <p>When im trying to </p> <pre><code>from tabula import read_pdf </code></pre> <p>it says</p> <p>ImportError: cannot import name 'read_pdf'</p> <p>All solutions i found say that i have to</p> <pre><code>pip uninstall tabula pip3 install tabu...
<p>Maybe this is because of the version of tabula you installed.</p> <p>If you installed tabula by running:</p> <pre><code>pip install tabula </code></pre> <p>You get an old version of tabula (1.0.5) that has the problem with the module .read_pdf(). To fix the problem and get a newer version of tabula, first:</p> <...
python|excel|pandas|pdf|tabula
10
367,115
47,677,957
Group b Time and return Boolean value if group contain
<p>I have df as below.</p> <pre><code>Index Receiver 1970-01-01 00:00:00.000000000 R1 1970-01-01 00:00:00.800000000 R1 1970-01-01 00:00:01.000287000 R2 1970-01-01 00:00:01.600896000 R2 1970-01-01 00:00:02.001388...
<p>We can use pivot_table with aggfunc <code>size</code> and then convert <code>notnull()</code> values to int i.e </p> <pre><code>df.pivot_table(index = pd.Grouper(key='Index',freq='s'),columns='Receiver',aggfunc='size').notnull().astype(int) Receiver R1 R2 Index 1970-01-01 00:...
pandas|dataframe
3
367,116
47,848,525
How to get data from np.array to std::vector in c++ using <numpy/arrayobject.h>?
<p>This is my first question on this site.</p> <p>First of all, I need to make a module with one function for python in C++, which must work with numpy, using <code>&lt;numpy/arrayobject.h&gt;</code>. This function takes one numpy array and returns two numpy arrays. All arrays are one-dimensional.</p> <p>The first qu...
<p>NumPy includes <a href="https://docs.scipy.org/doc/numpy/reference/c-api.array.html" rel="nofollow noreferrer">lots of functions and macros</a> that make it pretty easy to access the data of an <code>ndarray</code> object within a C or C++ extension. Given a 1D <code>ndarray</code> called <code>v</code>, one can acc...
python|c++|arrays|python-3.x|numpy
4
367,117
47,707,210
splitting a data frame by date and computing median for all rows with each date
<p>I am attempting to roughly estimate that amount of work than could have been done by staff for a given month.</p> <p>I've got a csv that looks roughly like this (although it's a lot bigger): </p> <pre><code>+--------+-------+---------------+ | Date | Name | Units of Work | +--------+-------+---------------+ | 1...
<p>I hope the following steps get you closer to your desired CSV output.</p> <p>First, here's a clean rendition of the input DataFrame for anyone else looking to copy-paste into <code>pd.read_clipboard()</code>:</p> <pre><code> Date Name Units of Work 0 Jan-17 Bob 450.0 1 Feb-17 Al...
python|pandas|csv|date|median
0
367,118
47,557,601
How can I restructure a dataframe to create new column labels based on Column[se] values and then populate those new columns with Column[value] Values
<p>Original Dataframe</p> <pre> index Date Device Element Sub_Element Value 179593 2017-11-28 16:39:00 x y eth_txload 9 179594 2017-11-28 16:39:00 x y eth_rxload 30 179595 2017-11-28 16:39:00 x y eth_ip_addr x.x.x.x 179596 2017-11-28 16:39:...
<p>IIUC, given:</p> <pre><code>print(df) index Date Device Element Sub_Element Value 0 179593 2017-11-28 16:39:00 x y eth_txload 9 1 179594 2017-11-28 16:39:00 x y eth_rxload 30 2 179595 2017-11-28 16:39:00 x y eth_ip_addr x.x.x.x 3 17...
python|pandas
2
367,119
47,934,073
pandas adding mean and variance coulm
<p>I would like to add a weighted mean column and a weight std dev to my df: </p> <pre><code>[Existing df....] [New columns to add in existing df i.e df[Mean] &amp; df[StdDev]] Name 1 2 3 4 Mean StdDev x 2 2 2 2 m1=(2*1+2*2+2*3+2*4)/(2+2+2+2) sqrt[(2*(1-m1)^2+2*(2-m1)...
<p>By using <code>numpy</code></p> <pre><code>df=df.set_index('Name') df.columns=df.columns.astype(int) Mean=np.sum(df.values*df.columns.values,1)/np.sum(df.values) Std=np.sum(np.power(df.columns.values-Mean[:,None],2)*df.values,1)/df.values.sum(1) df.assign(Mean=Mean,Std=np.sqrt(Std.astype(float))) Out[523]: ...
python|pandas|mean|standard-deviation
1
367,120
47,647,894
How to do dimension reduction in Bag of Words for a Classification Model using Random Forest
<p>I am using Text data Features along with other numerical features for classification model. </p> <p>How can I group similar bag of words together in a supervised classification Model. How I can group similar words after countvectorizing , I want reduce the dimension of bag of words .</p> <p>My code</p> <pre><cod...
<p>If you want to reduce the diemension of your bag of words, you can use <code>SelectPercentile</code> from sklearn. Here is an exemple on Iris data :</p> <pre><code>from sklearn.feature_selection import SelectPercentile from sklearn.feature_selection import chi2 import numpy iris = load_iris() X, y = iris.data, iris...
pandas|scikit-learn|nltk|random-forest|supervised-learning
2
367,121
47,865,690
How to get number of Frames(or Samples) per sec or ms in a audio (.wav or .mp3) file?
<p>I've been observing an audio file under <code>scipy.io.wavfile</code> </p> <p>which has a framerate of <code>44100 per sec or hz</code> and total frames are <code>9745238</code> and the duration of the audio is <code>220 secs</code> by the file properties but it should be <code>220.9804535147392</code> and has <cod...
<p>So, I wanted number of bits per second and after doing some research i found that i needed the rate of each bit i.e. <strong>bit rate</strong> , and certainly <strong>bit depth</strong> is the number of bits per sample (which is constant).</p> <p>to understand this if we use the <code>wave</code> module to print t...
python|numpy|audio
0
367,122
47,714,653
Acces Cell Data from Paraview Programmable Filter
<p>I need to create a programmable filter using Paraview. The idea is to create a vector called Speed equal to the speed in the non-rotating part equal to the speed+rotational speed in the rotational one.</p> <p>The problem is that I can't accept the value of the speed in each single cell.</p> <pre><code>input0 = inp...
<p>The correct syntax is </p> <pre><code>X[i] </code></pre> <p>The documentation can be found <a href="https://blog.kitware.com/improved-vtk-numpy-integration-part-5/" rel="nofollow noreferrer">here</a></p>
python|numpy|paraview
0
367,123
47,722,693
DataFrame dynamic columns from embedded lists in dataFrame
<p> Ok so I am a relative noob to Python. I have a need for a transformation of the following dataframe </p> <p><strong>bd, date</strong></p> <pre><code>[[None]], 2017-11-01 09:00:00 [[Sulphur], [Green Tea]], 2017-11-02 09:00:00 [[Green Tea], [Jasmine]], 2017-11-03 09:00:00 </code></pre> <p>.....</p> <p>to ...
<p>I am sure there are more elegant, functional, pythonic ways to do this... and I would love to know what they are.</p> <pre><code>import numpy as np import pandas as pd # define dataframe df = pd.DataFrame(columns = ['bd', 'date']) df.loc[0, 'bd'] = [[None]] df.loc[0, 'date'] = '2017-11-01 09:00:00' df.loc[1, 'bd']...
python|list|pandas|dataframe
0
367,124
49,102,009
Split pandas dataframe conditionally to plot with different colors
<p>I have pandas dataframe with pair of values and like to color code it conditionally such as</p> <p><code>df.plot(kind='scatter', ax=ax1, x='a', y='b', c=np.where(['a']&gt;0.5, 'r', 'g']))</code></p> <p>But not getting anywhere. Applying same condition on both <code>a</code> and <code>b</code> is ultimate objective...
<p>Demo:</p> <pre><code>In [50]: df = pd.DataFrame(np.random.rand(100, 2), columns=['x','y']) In [51]: df.head() Out[51]: x y 0 0.376715 0.209387 1 0.633065 0.212350 2 0.538783 0.883493 3 0.753707 0.983746 4 0.135703 0.840134 In [52]: df.plot.scatter(x='x', y='y', s=20, c=np.where(df[...
python|pandas|numpy|matplotlib
4
367,125
48,959,884
Pivot a DataFrameGroupBy panadas object
<p>I have a DataFrameGroupBy object called 'grouped' that looks like this:</p> <pre><code>for key, item in grouped: print('key: {0}, value: {1}'.format(key, grouped.get_group(key))) key: 9909, value: date quantity 0 2018-01-28 00:00:00+00:00 2.3 1 2018-01-29 00:00:00+00:00 3.0 ke...
<p>It is possible by apply:</p> <pre><code>def f(x): return (x.pivot('id','date','quantity')) grouped = df.groupby('id', group_keys=False).apply(f) print (grouped) date 2018-01-22 2018-01-23 2018-01-24 2018-01-25 2018-01-26 id 543 32.0 ...
python|pandas|pandas-groupby
1
367,126
49,287,830
replacing a positioned value in dataframe
<p>I have the following df:</p> <pre><code> A B C 0 s d f 1 3 5 3 2 4 4 5 3 6 6 6 </code></pre> <p>I would like to replace the value at <code>df.iloc[[0],[0]]</code> from <code>s</code> to <code>j</code> . How can I do so?</p>
<p>Pass positional indexers to <code>iat</code>:</p> <pre><code>df.iat[0, 0] = 'j' </code></pre> <p>Or, pass labels to <code>at</code>:</p> <pre><code>df.at[0, 'A'] = 'j' </code></pre> <p></p> <pre><code>df A B C 0 j d f 1 3 5 3 2 4 4 5 3 6 6 6 </code></pre>
python|pandas
1
367,127
49,298,187
error: command 'gcc' failed with exit status 1; Unable to make after clone
<p>Im trying to run the eval.py to evaluate my training session. To do that I need to install the cocodataset (see the error message below). This is where the error occurs. </p> <p>I've tried </p> <ul> <li>sudo apt-get update &amp;&amp; sudo apt-get upgrade</li> <li>uninstalling and re-installing cython, gcc, numpy</...
<p>Do you finished install gcc? I think you should check it, I have some error when make coco lib, and I just realized that something wrong with the hosts contains some gcc packages. Try:</p> <pre><code>sudo apt-get update </code></pre> <p>then</p> <pre><code>sudo apt-get gcc </code></pre> <p>And make sure that yo...
python-2.7|amazon-web-services|tensorflow|ubuntu-16.04
1
367,128
49,115,416
How to use a tensorflow tensor value in a formula?
<p>I have a quick question. I am developing a model in tensorflow, and need to use the iteration number in a formula during the construction phase. I know how to use global_step, but I am not using an already existing optimizer. I am calculating my own gradients with</p> <pre><code>grad_W, grad_b = tf.gradients(xs=[W...
<p>You can define <code>epoch</code> as a non-trainable <code>tf.Variable</code> in your graph and increment it at the end of each epoch. You can define an operation with <a href="https://www.tensorflow.org/api_docs/python/tf/assign_add" rel="nofollow noreferrer"><code>tf.assign_add</code></a> to do the incrementation ...
python|tensorflow|machine-learning
1
367,129
48,925,651
It is possible to numpy calculate below without loop?
<p>I have 10x10x4 array, and let say its dimension is a, b, c.</p> <p>For each element c with respect to (a, b) , How can I calculate the multiplication of c.T × c ?</p> <p>c: 1×4 matrix</p> <p>c.T × c: 4×4 matrix</p> <p>So the result has the array in the form of 10×10×(4×4) shape.</p> <p>Is it possible without fo...
<p>Sure, you can use <code>np.einsum</code> for that:</p> <pre><code>np.einsum('...i,...j-&gt;...ij', arr, arr, optimize = True) </code></pre> <p>You can also use brodcasted multiplication in this case:</p> <pre><code>arr[:,:, None, :] * arr[:,:,:, None] </code></pre>
arrays|numpy
1
367,130
49,255,222
If Condition combined with OR
<p>I have the following example:</p> <pre><code>data = {'model': ['Lisa', 'Lisa 2', 'Macintosh 128K', 'Macintosh 512K'], 'launched': [1983,1984,1984,1984], 'discontinued': [1986, 1985, 1984, 1986]} df = pd.DataFrame(data, columns = ['model', 'launched', 'discontinued']) def set_row(row): if ((row...
<p>Here is best dont use <code>apply</code>, because loop under the hood. Better is <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a>:</p> <pre><code>mask = (df["model"] == "Lisa") | df["model"].str.contains("Mac") df['new Column'] ...
python|python-2.7|pandas|if-statement
2
367,131
49,127,961
Python pandas: "can not merge DataFrame with instance of type <class 'str'>"
<p>I have two df: <code>df_jan_2001</code> and <code>df_feb_2001</code>. I would like to do a full outer join by using this syntax:</p> <pre><code>new_df = pd.merge('df_jan2001', 'df_feb2001', how='outer', left_on= ['designation', 'name'], right_on=['designation', 'name']) </code></pre> <p><code>designation</code> an...
<p>YOU can try like this.</p> <pre><code>new_df = pd.merge(df_jan2001, df_feb2001, how='outer', left_on=['designation', 'name'], right_on=['designation', 'name']) </code></pre>
python|pandas
2
367,132
49,099,515
TensorFlow Docker Images
<p>When using the general TensorFlow docker images, they won't be optimized for the exact target architecture.</p> <p>a) Are there studies for the performance penalty for using these general docker images vs. compiling for the specific architecture?</p> <p>b) When using a orchestration system such as KubeFlow/Mesos a...
<p>For the performance, you can have a look at <a href="http://www.brendangregg.com/blog/2017-05-15/container-performance-analysis-dockercon-2017.html" rel="nofollow noreferrer">breandangregg container performance analysis</a> It's quite good, due to dockerizing is more similar to doing chroot than virtualization, beca...
docker|tensorflow
0
367,133
49,080,513
Change values in pandas dataframe based on values in certain columns
<p>How can I convert this first dataframe to the one below it? Based on different scenarios of the first three columns matching, I want to change the values in the rest of the columns. </p> <pre><code>import pandas as pd df = pd.DataFrame([['foo', 'foo', 'bar', 'a', 'b', 'c', 'd'], ['bar', 'foo', 'bar', 'a', 'b', 'c'...
<p>You can use:</p> <pre><code>import pandas as pd df = pd.DataFrame([['foo', 'foo', 'bar', 'a', 'b', 'c', 'd'], ['bar', 'foo', 'bar', 'a', 'b', 'c', 'd'], ['spa', 'foo', 'bar', 'a', 'b', 'c', 'd']], columns=['col1', 'col2', 'col3', 's1', 's2', 's3', 's4']) counter = 0 # df[df.col1 == df.col2] = df[df...
python-3.x|pandas|dataframe
0
367,134
49,293,393
Extract indices of sublists found within a list
<p>Given list_a and list_b. I want to run list_b through a function that gives all possible sublist of list_b (this part of the code works). I then want to take every sublist of list_b, and see if that sublist is also a sublist of list_a. If it is I should get a list of all the indexes, or splices where that sublist ap...
<p>Using tools from <a href="https://stackoverflow.com/questions/48988038/find-boolean-mask-by-pattern/49002944">Find boolean mask by pattern</a></p> <pre><code>def rolling_window(a, window): #https://stackoverflow.com/q/7100242/2901002 shape = a.shape[:-1] + (a.shape[-1] - window + 1, window) strides = a.str...
python|arrays|python-3.x|list|numpy
2
367,135
49,306,467
Vectorized way of checking dataframe values (as key, value tuple) against a dictionary?
<p>I'd like to create a column in my dataframe that checks whether the values in one column are the dictionary values of <em>another</em> column which comprises the dictionary keys, like so: </p> <pre><code>In [3]: df = pd.DataFrame({'Model': ['Corolla', 'Civic', 'Accord', 'F-150'], 'Make': ['Toyota...
<p>You can using <code>map</code> </p> <pre><code>df.assign(match=df.Model.map(dic).eq(df.Make)) Out[129]: Make Model match 0 Toyota Corolla True 1 Honda Civic True 2 Toyota Accord False 3 Ford F-150 True </code></pre>
python|pandas|dictionary|dataframe|boolean
5
367,136
49,330,708
Count zero rows in 2D numpy array
<p>How do you count the amount of zero rows of a numpy array? </p> <pre><code>array = np.asarray([[1,1],[0,0],[1,1],[0,0],[0,0]]) </code></pre> <p>-> has three rows with all zero's, hence should give 3</p> <p>Took me sometime to figure out this one and also couldn't find an answer on SO</p>
<p>You could also leverage the "truthiness" of non-zero values in an array. </p> <pre><code>np.sum(~array.any(1)) </code></pre> <p>i.e., sum the rows where none of the values in said row are truthy (and hence are all zero)</p>
python|numpy
8
367,137
49,040,715
Tensorflow serving
<p>Does anybody know how to create a C# client for tensorflow serving? </p> <p><strong>My tensorflow serving installation:</strong></p> <p>I installed tensorflow serving using the tensorflow serving dockerfile, then inside the container I did the following:</p> <pre><code>pip install tensorflow pip install tensorfl...
<p>As far as I understand, you need the proto files to generate a tensorflow serving client in C# for the grpc services. </p> <p><a href="https://github.com/Wertugo/TensorFlowServingCSharpClient" rel="nofollow noreferrer">https://github.com/Wertugo/TensorFlowServingCSharpClient</a> This is one example I am following. ...
c#|python|client|grpc|tensorflow-serving
3
367,138
49,258,949
How to sort a pandas dataframe by date
<p>I am importing data into a pandas dataframe from Google BigQuery and I'd like to sort the results by date. My code is as follows:</p> <pre><code>import sys, getopt import pandas as pd from datetime import datetime # set your BigQuery service account private private key pkey ='#REMOVED#' destination_table = 'test.t...
<p>I managed to solve this by transforming my date field into a datetime object, I assumed this would be done automatically by <code>parse_date=True</code> but it seems that will only parse a <em>existing</em> datetime object.</p> <p>I added the following after my query to create a new datetime column from my date str...
python|pandas
2
367,139
48,966,166
How to run .bat files on windows 2016 server on EC2, after python has been configured?
<p>I need to kick off a python script on 2016 windows server EC2 instance on AWS. </p> <p>When I set the task up in 'task scheduler' the script does not run. I have tried setting up a batch file with the following code: </p> <pre><code>@echo off python C:\Users\Administrator\Desktop\script.py %* pause </code></pre> ...
<p>The solution was too restart anaconda, after adjusting the path variables. </p>
python-3.x|pandas|amazon-ec2
0
367,140
49,012,912
Error when calling global_variables_initializer in TensorFlow
<p>I have the following code in <code>TensorFlow</code>:</p> <pre><code>def func(a): b = tf.Variable(10) * a return a with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print(sess.run(func(tf.constant(4)))) </code></pre> <p>It works well. But when I substitute <code>a</code> with <...
<p>In your first piece of code you don't use the <code>tf.Variable(10)</code> so it doesn't matter if it hasn't been initialized, while in your second piece of code you do try to evaluate it, and so TensorFlow complains that it hasn't been initialized.</p> <p>In your code the <code>Variable</code> is defined (when the...
python|tensorflow
3
367,141
49,233,984
Group by and find sum for groups but return NaN as NaN, not 0
<p>I have a dataframe where each unique group has 4 rows. So I need to group by columns that makes them unique and does some aggregations such as max, min, sum and average. But the problem is that I have for some group all NaN values (in some column) and returns me a 0. Is it possible to return me a NaN? For example...
<p>Change parameter <code>min_count</code> to <code>1</code> - this working in <a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#arithmetic-operations" rel="noreferrer">last pandas version <code>0.22.0</code></a>:</p> <blockquote> <p><strong>min_count</strong> : int, default 0</p> <p>The required numbe...
python|pandas|numpy|dataframe|nan
10
367,142
48,979,223
Numpy Array creation causing "ValueError: invalid literal for int() with base 10: 'n'"
<p>I'm trying to run a predictive RNN from this repo <a href="https://github.com/jgpavez/LSTM---Stock-prediction" rel="nofollow noreferrer">https://github.com/jgpavez/LSTM---Stock-prediction</a>. "python lstm_forex.py"<br> It seems to be having trouble creating an empty Numpy array</p> <p>The function giving me proble...
<p>You're trying to int() the string 'n' in your assertion. To get the same error:</p> <pre><code>int('n') ValueError Traceback (most recent call last) &lt;ipython-input-18-35fea8808c96&gt; in &lt;module&gt;() ----&gt; 1 int('n') ValueError: invalid literal for int() with base 10: 'n'...
python|numpy|valueerror
1
367,143
48,963,258
Run multiple groupby operations and different transform functions on a data set
<p>I have the below data set which is a reading of values every 5 seconds. I need to do two operations on the data set.</p> <ol> <li>Calculate average value for every minute from the data set</li> <li>Using the above minute average values, calculate hourly variation (i.e difference every minute values and sum total)</...
<p>0) To get a datetime index from a <code>.csv</code> file, you can do something like this:</p> <pre><code>df = pd.read_csv('water_data.txt', parse_dates=[0], index_col=0) </code></pre> <p><code>parse_dates=[0]</code> will parse dates for column in position <code>0</code> and <code>index_col=0</code> will make colum...
python|pandas|time-series
0
367,144
49,318,170
Value error when plotting Dataframe from index
<p>I have a dataframe which is of the following structure:</p> <pre><code>A B Location1 1 Location2 2 1 3 2 4 </code></pre> <p>In the above example column A is the index. I am attempting to produce a scatter plot using the index and column B. This data frame is made by resampling and aver...
<p>You may have to transponse the DataFrame, so that you have the index(Column A) as columnnames and then calculate the mean of the columns and plot them. </p>
python|pandas|dataframe
0
367,145
49,117,632
Creating array of arrays in numpy with different dimensions
<p>I'm trying to create an array of numpy arrays, each one with a different dimension. So far, it seems to be fine. For example, if I run:</p> <pre><code>np.array([np.zeros((10,3)), np.zeros((11,8))]) </code></pre> <p>the result is:</p> <pre><code>array([ array([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., ...
<p>This has been hashed out before (<a href="https://stackoverflow.com/questions/26885508/why-do-i-get-error-trying-to-cast-np-arraysome-list-valueerror-could-not-broa">Why do I get error trying to cast np.array(some_list) ValueError: could not broadcast input array</a>; <a href="https://stackoverflow.com/questions/4...
arrays|numpy|dimensions|valueerror
4
367,146
49,134,926
How to do FFT on signal of different period
<p>I need to perform FFT on gait signals that are not strictly periodic. Below is the code I created for double and single sided. However, I do not know if it is right as the signal is not strictly periodic -- people walk differently every step. If I sample the same number of samples each period, then I do not know wha...
<p>d = should be one over the sampling frequency. This will allow your results to show you the frequencies of the gait, and those variations will help you see the differences in the gait patterns.</p>
python|numpy|signal-processing|fft|fftpack
0
367,147
49,104,677
Python: how do I add markers to lines in a figure at a particular y-value (y=1)?
<p>I'm working on some code to produce a figure showing the evolution of the universe. <a href="https://i.stack.imgur.com/u1QLC.png" rel="nofollow noreferrer">This</a> is the plot I have. I would like it to have points on each line at the value scale factor a=1 (y=1). The code I have used is:</p> <pre><code>import num...
<p>First find the corresponding t value:</p> <pre><code>from scipy.optimize import fmin def testfunc(t): return abs(1.0-odeint(Friedmann, a_0, t)) tmin=fmin(testfunc,t_0) </code></pre> <p>Then plot a marker at that place:</p> <pre><code>plt.plot(tmin,odeint(Friedmann,a_0,tmin),'ro') </code></pre>
python|numpy|matplotlib|plot|scipy
1
367,148
49,287,934
Dask DataFrame - Prediction of Keras Model
<p>I am working for the first time with dask and trying to run predict() from a trained keras model.</p> <p>If I dont use dask, the function works fine (i.e. pd.DataFrame() versus dd.DataFrame () ). With Dask the error is below. Is this not a common use case (aside from scoring a groupby perhaps)</p> <pre class="la...
<p>I found the answer. It is an issue with keras or tensorflow: <a href="https://github.com/keras-team/keras/issues/2397" rel="noreferrer">https://github.com/keras-team/keras/issues/2397</a></p> <p>Below code worked and using dask shaved 50% from the time versus standard pandas groupby.</p> <pre><code>#dask model=ker...
tensorflow|keras|dask
5
367,149
49,259,210
Filtering list in python based on condition
<p>I have following implementation where CSV file is converted into one row numpy array:</p> <pre><code>results = [] with open(file2) as csvfile: reader = csv.reader(csvfile, quoting=csv.QUOTE_NONNUMERIC) # change contents to floats for row in reader: # each row is a list results.append(row) p...
<p>Sometimes people think to complex... keep it simple and select earlier in the process...</p> <p>Row = string.</p> <pre><code># arbitrary taken selector values and char. key = 100 position = 4 splitter = '.' for row in reader: # row as a string. # preprocess input string_row = str(row) row_data ...
python|arrays|numpy|boolean
0
367,150
49,105,096
Python error: I install it correctly but still doesn't work
<p>I tried to import the following code in python, but an error message occurred. I am using Python 3.6.4, Windows</p> <pre><code>from keras.models import Sequential </code></pre> <p>Error message:</p> <pre><code>Using TensorFlow backend. Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;modu...
<p>Keras has a default backend of Tensorflow. So first install the tensorflow with the command, <br> <code>pip install tensorflow</code> <br> You can do this in your current stage too. It should work fine.</p>
python-3.x|tensorflow|keras
0
367,151
49,095,860
No matching distribution found for tensorflow==1.4.1
<p>I'm trying to install Rasa Core so I installed </p> <pre><code>pip install rasa_core </code></pre> <p>...and then I tried to install the development dependencies:</p> <pre><code>pip install -r dev-requirements.txt pip install -e </code></pre> <p>...but I get this error:</p> <pre><code>(base) C:\Users\\\rasa_co...
<p>Duplicate of <a href="https://stackoverflow.com/questions/38896424/tensorflow-not-found-using-pip">this question</a></p> <p>Quick answer - Requires Python 64 bit</p> <p>Credit - <a href="https://stackoverflow.com/a/41084963/3882482">@rocket1037's answer</a></p>
python|r|python-2.7|tensorflow|rasa-nlu
1
367,152
49,131,510
How to iterate over all columns using pandas and save output to file
<p>I want to iterate over all of the columns in my dataset and discover if a column contains a one or a zero. </p> <p>My dataset is a matrix of 68x300000.</p> <p>I am reading the file using pandas:</p> <pre><code>df= pd.read_csv("filepath", header=None) </code></pre> <p>From this output I want to create a new matri...
<p>I think need:</p> <pre><code>df = pd.DataFrame({0:list('abcdef'), 1:[4,1,4,5,5,4], 2:[7,0,9,4,2,3], 3:[1,0,1,0,1,0], 4:[5,3,6,0,2,4], 5:list('aaabbb')}) print (df) 0 1 2 3 4 5 0 a 4 7 1 5 a 1 b 1 0 0 3...
python|pandas|matrix
0
367,153
59,004,873
Convert each element in col of df from string to a list
<p>Input :</p> <p>If this was one of the values in the col of a df </p> <p>'dog went to the kennel and drank his water'</p> <p>Output: I want this as the converted value ( str to list ) ['dog went to the kennel and drank his water']</p>
<p>Try this:</p> <pre><code>df['col1'].apply(lambda x: [str(x)]) </code></pre> <p>I applied it to the following data to show the conversion:</p> <pre><code>df ...
python|string|pandas|list
0
367,154
58,710,157
pandas DataFrame : extract data in a 2 columns dataframe
<p>I have a 2 columns df with a redundant but irregular structure ('name', 'code' and 'w' associated with a'code') I would like to extract. Here the DF :</p> <pre><code> import pandas as pd pd.DataFrame([('name','john'), ('date','NaN'), ('curr','NaN'), ('cod...
<p>Use:</p> <pre><code>#filter rows by name df[3] = df.loc[df[0] == 'name', 1] #forward filling missing values df[3] = df[3].ffill() #filter out rows by 0 column and change order of columns [3,0,1] df = df.loc[~df[0].isin(['name','date', 'curr', 'code']), [3, 0, 1]] #set columns names df.columns= ['name','code','w'] ...
pandas
0
367,155
58,636,774
Generate a column based on incolumn constraints
<p>I have a dataframe having 2 columns : </p> <pre><code>F_Date Count 01/09/2019 1421 01/09/2019 1421 01/09/2019 1421 01/09/2019 1421 01/09/2019 1421 01/09/2019 1421 01/09/2019 1421 01/09/2019 1421 01/09/2019 1421 01/09/2019 1421 01/09/2019 1421 01/09/2019 1421 01/09/2019 1421 01/09/2019 1421 01/09/2...
<p>If I understand you correctly:</p> <pre><code>import pandas as pd import numpy as np old_df = pd.DataFrame({'F_Date': ["01/09/2019" for _ in range(1421)], "Count": [1421 for _ in range(1421)]}) def split_dates(old): df = old.copy() df["Date_2"] = np.where((df.index//(df["Count"]//5)).as...
python|pandas|numpy
1
367,156
58,810,310
Count of unique rows based on preceding row - Pandas
<p>I want to return unique rows from multiple columns in a <code>df</code>. The issue is I want to include the same set of values if they don't appear in the previous row. This is a little hard to explain so I'll display it;</p> <pre><code>df = pd.DataFrame({ 'Time' : ['2019-08-02 09:50:10.1','2019-08-02 09...
<p>First we use <code>iloc</code> to select the correct columns, then we use <code>shift</code>to check if current row is not equal to the next one. Finally we use <code>any</code> over <code>axis=1 (columns)</code>. Because <code>A B C</code> and <code>B A C</code> are different, but have <code>C</code> in common:</p>...
python|pandas|pandas-groupby
1
367,157
58,654,704
Pandas dataframe groupby more than one string from a column
<p>some example dataset is as follows</p> <pre><code> Name Year Item sales_Amount1 A1 1.2019 Badam 2 A1.pre 1.2019 Badam 10 A1.post 1.2019 carrot 8 N1 1.2019 carrot 10 A2 1.2019 Badam 10 G 1.2019 Badam...
<p>You can write a custom function to apply the mapping of Name->Group</p> <pre class="lang-py prettyprint-override"><code>def map_group(name): if name in ("A1", "A1.pre", "A1.post", "N1"): return "G1" if name in ("A2", "G"): return "G2" if name in ("A3", "P"): return "G3" sum_sale...
python-3.x|dataframe|sum|pandas-groupby
1
367,158
58,849,146
Changing Pandas .loc output format
<p>I have a very quick/simple question. I have created a list from a data table, and used .loc to extract values from my data table into my list. However, I want to change the format into something else. </p> <p>Here is my current code:</p> <pre><code>import re import os import pandas as pd os.chdir('C:/Users/Sams P...
<p>Try</p> <pre><code>data.append(list(data3.values)) </code></pre> <p>Update <code>data.append(list(data3))</code> works only when it is a Series i.e you are selecting a single row</p>
python|pandas
0
367,159
58,829,713
How to filter a data frame from each first non NaN value until next and sum values from corresponding column?
<p>I am struggling with the following data frame:</p> <pre><code>Activity Duration (mins) BREAK/REST 120 AVAILABILITY 57 WORK 13 DRIVING 10 WORK 31 DRIVING 100 DRIVING 81 DRIVING 106 BREAK/REST 89 BREAK/REST 4 </code></pre> <p>I am trying ...
<p>IIUC we need <code>shift</code> + <code>cumsum</code> create the group key </p> <pre><code>s=df.groupby(df.Activity.ne(df.Activity.shift()).cumsum()).\ agg({'Activity':'first','Duration(mins)':'sum'}) s Out[185]: Activity Duration(mins) Activity 1 BREAK/RE...
python-3.x|pandas
1
367,160
58,692,792
Numerical integration of a numpy array in incremental time steps
<p>I have two arrays. The first one is time in terms of Age (yrs) and the second one is a parameter that needs to be integrated with respect to time.</p> <pre class="lang-py prettyprint-override"><code>age = [5.00000e+08, 5.60322e+08, 6.27922e+08, 7.03678e+08, 7.88572e+08, 8.83709e+08, 9.90324e+08, 1.10980e+09,...
<p>The exact form of your desired result is not so clear. So, here are 2 posibilities:</p> <pre><code>age = [5.00000e+08, 5.60322e+08, 6.27922e+08, 7.03678e+08, 7.88572e+08, 8.83709e+08, 9.90324e+08, 1.10980e+09, 1.24369e+09, 1.39374e+09, 1.56188e+09, 1.75032e+09, 1.96148e+09, 2.19813e+09, 2.46332e+09, ...
python-3.x|numpy|scipy
0
367,161
58,891,966
Errors saving stacked NumPy array to text
<p>I am combining column data from three different input arrays into a new csv. To do so I am using the NumPy stack function. Right now I have a [12,3] stacked NumPy array that I am trying to export to a csv. </p> <pre><code>VI_Samples_v4 = numpy.stack((samplename,sample_start_date,sample_type_code), axis =1) </code...
<p>The problem is the square brackets you've placed around your array in the call to <code>numpy.savetxt</code>. By passing a list containing your 2D array, you're causing <code>numpy.savetxt</code> to read it as a 3D array. Just pass the array without the square brackets like so:</p> <pre><code>numpy.savetxt('array.c...
python|arrays|numpy|csv
1
367,162
59,027,545
Vectorize angle calculation of all combinations from matrix in python
<p><em>See edits below</em></p> <p>I have a rather big matrix <code>x</code> (3xn, n >> 1000) with limited information about the relation of each column. From this matrix <code>x</code>, I need to find the biggest angle and the corresponding indices of two columns. Currently I'm using two <code>for</code>-loops, which...
<p>Turns out, what I was looking for is actually called <a href="https://en.wikipedia.org/wiki/Gramian_matrix" rel="nofollow noreferrer">[Gramian Matrix]</a>, a matrix whose elements are all possible combinations of inner products. In my case, that translate to the following code:</p> <pre class="lang-py prettyprint-o...
python|numpy|matrix|optimization|vectorization
1
367,163
58,759,077
pandas selecting max and min simultaneously
<p>Give a dataframe like this:</p> <pre class="lang-py prettyprint-override"><code> count date location type 0 100 2018-01-01 site1 high 1 10 2018-01-01 site2 low 2 11 2018-01-01 site3 low 3 101 2018-01-03 site2 high 4 103 2018-01-03 site2 high 5 15 2018-01-03...
<p>What you want to do is complicated by the fact that you have already assigned highs and lows. Do you need to account for these? (Is one day's max labelled as a <code>low</code>?) If not, you can go with something as simple as this:</p> <pre class="lang-py prettyprint-override"><code>df.groupby(['month-day']).agg({ ...
python|pandas
1
367,164
58,842,636
verbose logging in tensorflow serving via docker
<p>Is there a way to set log level in tf serving via docker? I see these params but do not see anything about logging there </p> <pre><code> --port=8500 int32 Port to listen on for gRPC API --grpc_socket_path="" string If non-empty, listen to a UNIX socket for gRPC API...
<p>I'm not sure this is going to give you exactly what you want, but I have had luck getting more verbose logging out of TensorFlow Serving by setting the environment variable <code>TF_CPP_MIN_VLOG_LEVEL</code>, where the bigger the value, the more verbose the logging.</p> <p>E.g., <code>TF_CPP_MIN_VLOG_LEVEL=4</code>...
tensorflow|logging|tensorflow-serving
6
367,165
59,003,351
tensorflow affine transform fill value
<p>But I'm trying to replicate:</p> <pre><code>img_tr = cv2.warpAffine(img, m, (IMAGE_SIZE, IMAGE_SIZE), borderMode=cv2.BORDER_CONSTANT, borderValue=(FILL_VALUE,FILL_VALUE,FILL_VALUE), flags=cv2.INTER_LINEAR) </code></pre> <p>I'm using </p> <pre><code> img_tr = tf.c...
<p>When we trace the source, we can find the low level implementation is in the file <a href="https://github.com/tensorflow/tensorflow/blob/r1.15/tensorflow/contrib/image/kernels/image_ops.h" rel="nofollow noreferrer">image_ops.h</a>. The fill_vaule is set to zero in (line 65, 74, 86), so the only way to change it is t...
image|opencv|tensorflow|affinetransform
0
367,166
58,820,338
Pandas: combine columns with different time frequencies
<p>I have two dataframes: <code>df_p</code> and <code>df_d</code>.</p> <p><code>df_p</code> contains 8760 entries, it represents 1 year of records with 1 hour resolution. <code>date</code> is a datetime column, <code>hy</code> is the number of the hour (of the year), <code>profile</code> is a value</p> <pre><code> ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html" rel="nofollow noreferrer"><code>merge_asof</code></a>:</p> <pre><code>#if necessary convert to datetimes df_d['date'] = pd.to_datetime(df_d['date']) df_p.index = pd.to_datetime(df_p.index) df = pd.merge_asof(df_p, df_d, ...
python|pandas
3
367,167
58,966,346
How to insert data from conditional SQL Query to Hbase in Python and Pandas(Data Frame)?
<p>Supposed I have some sample data in <code>table_name_a</code> as below:</p> <pre><code> code val_a val_b remark date ------------------------------------------ 1 00001 500 0.1 111 20191108 2 00001 1000 0.2 222 20191109 3 00002 200 0.1 111 20191110...
<p>Well, here is my solution, I hope it will help someone else. I love Python, I love SQL and I also love myself. Finally, I can solve it by myself, hahaha. ☕️</p> <pre><code>from db_conn import impala, hbasecon import numpy as np import pandas as pd def main(): conn_impa = impala().getcon() sql = """ S...
python|pandas|dataframe|hbase|impala
0
367,168
58,637,436
Color Bar Chart based on values in Dataframe
<p>I have plotted a stacked bar chart (see here: <a href="https://imgur.com/a/ESJeHuF" rel="nofollow noreferrer">https://imgur.com/a/ESJeHuF</a>), formed out of the dataframe below. </p> <pre><code> condition1 condition2 condition3 timestamp ...
<p>I don't know how important to you is the choice of colors. I've just found a solution that seems to fix your problem, the only "but" is that is the development is easier if you accept one of the color schema's available. Othewrise, if you will have to make a colormap by hand, you can find examples with LinearSegment...
python|pandas|dataframe|matplotlib|bar-chart
0
367,169
58,786,354
Can not load image segmentation model partially in pytorch
<p>I'm trying to load a model partially (i.e., instead of loading all the layers at once, I'm just trying to load the first couple layers of the network). Here is my code:</p> <pre><code>import torch unet = my_unet(in_ch=5, out_ch=1).cuda() enc = torch.nn.Sequential(*list(unet.children())[:10]) del unet # Comment thi...
<p>You didn't say where the <code>CUDA out of memory</code> is thrown. Anyway, I wouldn't move the model to the GPU until you have the final one. Do something like this:</p> <pre class="lang-py prettyprint-override"><code>unet = my_unet(in_ch=5, out_ch=1) # removed .cuda() enc = torch.nn.S...
python-3.x|deep-learning|pytorch
0
367,170
58,789,511
Calculate average and standard deviation per 5 rows in a pandas dataframe
<p>I have a dataframe such as:</p> <pre><code>A 27.00 18.00 15.00 7.50 5.00 4.00 3.00 1.50 1.00 </code></pre> <p>now I want to calculate average and standard deviation per 5 rows from bottom to top and set it at a above row as an additional column such as:</p> <pre><code>A B(avg) C(standard deviation) 27.0...
<p>Use rolling and shift a result 5 row up</p> <pre><code>df[['B','С']] = df.rolling(5)['A'].agg(('mean','std')).shift(-5) </code></pre>
pandas|dataframe|average
1
367,171
58,778,191
Average and dummy value in pandas
<p>Iam beginner in python I have a <code>dataframe</code>:</p> <pre><code>df Road_Section RoadType Speed Landuse Zone1 Local 1.33 Shops Zone1 National 0.37 Field Zone1 Collector 0.52 Park Zone1 National 1.17 Resident Zone1 Local ...
<p>Create index first <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>DataFrame.set_index</code></a> with <code>Road_Section</code>. Then create <code>mean</code> per first column, and join another DataFrame created by <a href="http://p...
python|pandas
1
367,172
58,692,801
Is there a way to map a numpy array to a certain dataframe?
<p>I have a DataFrame, let's say:</p> <pre class="lang-py prettyprint-override"><code>#d = {'col1': [1, 2, 3], 'col2': [3, 4, 5]} // that's what the data might look like df = pd.DataFrame(data=d) </code></pre> <p>and I have a np array with <code>[0, 2]</code>.</p> <p>Now I want to add a column to the DataFrame, wher...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.isin.html" rel="nofollow noreferrer"><code>Index.isin</code></a> with cast mask to integers:</p> <pre><code>d = {'col1': [1, 2, 3], 'col2': [3, 4, 5]} df = pd.DataFrame(data=d) a = np.array([0, 2]) df['new'] = df.index.isin(a).as...
python|python-3.x|pandas|numpy
3
367,173
58,811,035
Keras code not working in Jupyter: "The kernel appears to have died. It will restart automatically."
<p>I am writing code in Keras for a simple deep learning based 30x30 cat image classifier. When I get to the portion of my code that is supposed to train the model, Jupyter stops running and gives the error message "The kernel appears to have died. It will restart automatically." I do not know what is causing this to h...
<p><code>target_size: tuple of integers (height, width), default: (256, 256). The dimensions to which all images found will be resized.</code> Your image are 30x30 but the target size of your images are being resized to 150x150. taking a chunk of additional memory. You can tell that your data exceed the available memor...
python|tensorflow|keras|deep-learning|jupyter-notebook
0
367,174
58,793,110
Vectorizing multiplication of matrices with different shapes in numpy/tensorflow
<p>I have a 4x4 input matrix and I want to multiply every 2x2 slice with a weight stored in a 3x3 weight matrix. Please see the attached image for an example:</p> <p><a href="https://i.stack.imgur.com/dGbqh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dGbqh.png" alt="enter image description here"...
<p>Alright, I think I have a solution but this involves using both numpy operations (e.g. <code>np.repeat</code>) and TensorFlow 2.0 operations (i.e. <code>tf.segment_sum</code>). And to warn you this is not the most clear elegant solution in the world, but it was the most elegant I could come up with. So here goes.</p...
numpy|tensorflow|math|matrix|vectorization
2
367,175
58,724,956
Adding additional random parameter as an argument in pool.map function in python 3.4.7
<p>I want to use multiprocessing on a large dataset to find the product of two columns and filter the data set with a given parameter in the argument. I constructed a test set, but I have been unable to get multiprocessing to work on this set.</p> <p>Firstly, I am trying to divide the data set in parallelize_dataframe...
<p>From the official docs of <a href="https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool.map" rel="nofollow noreferrer">multiprocessing.Pool.map</a>, it "supports supports only one <em>iterable</em> argument". Hence you need to change the interface of <code>subset_col</code> to take a sing...
python|pandas|numpy|python-multiprocessing|multiprocess
1
367,176
58,755,970
How to load a model with tf.saved_model and call the predict function [TENSORFLOW 2.0 API]
<p>I'm very new to tensorflow and especially the 2.0 since there's not enough examples about that API but it seems much handy than the 1.x So far I managed to train a linear model using the tf.estimator api, and then managed to save it using the tf.estimator.exporter.</p> <p>After that I wanted to load this model usin...
<p>The <code>saved_model.load(...)</code> <a href="https://www.tensorflow.org/api_docs/python/tf/saved_model/load" rel="nofollow noreferrer">documentation</a> demonstrates the basic mechanism like this:</p> <pre class="lang-py prettyprint-override"><code>imported = tf.saved_model.load(path) f = imported.signatures["se...
tensorflow|model|save|load|predict
2
367,177
59,021,997
Editing CSV files with Pandas
<p>My CSV file contains <code>""</code> which ruins the file, when I import using Pandas, it considers that all columns as one value.</p> <p>what I want to make is to change the following value in the column </p> <p><code>4.7,3.2,1.3,.2,"Setosa"</code></p> <p>to </p> <p><code>4.7,3.2,1.3,.2,'Setosa'</code></p>
<p>Can't you use something like below?</p> <pre><code>string.replace('"', "'") </code></pre>
python-3.x|pandas
0
367,178
58,740,091
Iterate a script over multiple folders in master folder
<p>I have written a script that extracts columns from multiple csv files (staying in a folder named SIM1) and saves them in a txt file. Now, I need to iterate this script over multiple folders (SIM2, SIM3, SIM4,...). All of these SIM folders are in one master folder. I will really appreciate if I can get help on iterat...
<p>Try this</p> <pre><code>import os import pandas as pd import numpy as np import csv master_path = '&lt;master dir path&gt;' subfolders = list(filter(lambda x: os.path.isdir(os.path.join(master_path, x)), os.listdir(master_path))) for folder in subfolders: ppt = pd.read_csv(f"{master_path}/{folder}/ppt.csv") ...
python|python-3.x|pandas|numpy|csv
1
367,179
58,778,300
Is there any way to create column based on relation between previous column in Pandas DataFrame?
<p><strong><em>Given:</em></strong> I have <strong>Pandas Dataframe</strong> as shown below</p> <pre><code>| Employee_ID | Manager_ID | |:-----------:|:----------:| | E068 | E067 | | E071 | E067 | | E229 | E069 | | E248 | E144 | | E226 | E223 | | E236 ...
<p>We can use <a href="https://pandas.pydata.org/pandas-docs/version/0.25/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a>,The loop is executed while there is no column full of NaN Values. Checking with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas...
python|python-3.x|pandas
0
367,180
58,895,526
Sampling while keeping the ratio
<p>I am trying to get the sample from dataset due to memory issue (dataset size is 2.5GB my memory cannot take it). <code>df_12</code> is original dataframe and <code>df_12val</code> is Series which contains the abbrebiation of states and values are the number of appearances(occurences) of each state in the dataframe. ...
<p>Yes so the problem with test_train_split is that it would take 30% of the entire dataset without regard to the state column you are interested to, I think for you to accomplish what you want, you need first to subdivide your dataset per state, the resample, I'll include here only the subdivision of the dataset.</p> ...
python|pandas|dataframe|sampling
0
367,181
58,627,520
How to convert a column in a pandas dataframe to datatime?
<p>I have a csv document, an example below:</p> <pre><code>oci,citing,cited,creation,timespan,journal_sc,author_sc 0200100000236252421370109080537010700020300040001-020010000073609070863016304060103630305070563074902,"10.1002/pol.1985.170230401","10.1007/978-1-4613-3575-7_2",1985-04,P2Y,no,no </code></pre> <p>There a...
<p>There are a couple of issues to address in your code.</p> <p>First, notice that in your <code>.csv</code> file the first column is:</p> <pre><code>oci,citing,cited,creation,timespan,journal_sc,author_sc </code></pre> <p>So when you're building a database with <code>pd.read_csv</code> the first row of your datafra...
python|python-3.x|pandas|datetime
1
367,182
58,741,673
Input 0 is incompatible with layer lstm_16: expected ndim=3, found ndim=2?
<p>I got the error <code>Input 0 is incompatible with layer lstm_16: expected ndim=3, found ndim=2</code> with the following code:</p> <pre><code>#Step 6: Initialize the RNN regressor = Sequential() #Step 7: Adding the LSTM layers and some Dropout regularization #Dropout regularization: drops out unnecessary data, s...
<p>Here you are passing two values in <code>input_shape</code> of first LSTM layer.</p> <p>Keras <code>LSTM</code> takes and input with shape of <code>(samples, time_steps, nfeatures)</code> and your layers input has to have this shape.</p>
python|tensorflow|keras|lstm|recurrent-neural-network
0
367,183
58,901,953
Problem with Tensorflow-Gpu and Cuda drivers in Anaconda
<p>I have the following problem with Tensorflow-GPU. While trying to setup the gpus (in Jupyter) for a deep learning task, I get the following error:</p> <pre><code>InternalError Traceback (most recent call last) &lt;ipython-input-3-a08c39e19f9e&gt; in &lt;module&gt; 20 for gpu in ...
<p>The reason for this error is the mismatch of your installed CUDA Toolkit version and the version of the python package CUDA toolkit, which is usually installed as dependency of Tensorflow GPU</p> <p>Running a CUDA application requires the system with at least one CUDA capable GPU and a driver that is compatible wit...
python|tensorflow|intel|nvidia
1
367,184
58,952,107
How to standardize values in a Pandas dataframe based on index position?
<p>I have a number of pandas dataframes that each have a column 'speaker', and one of two labels. Typically, this is 0-1, however in some cases it is 1-2, 1-3, or 0-2. I am trying to find a way to iterate through all of my dataframes and standardize them so that they share the same labels (0-1). </p> <p>The one consis...
<h3>Method 1</h3> <p>We can use <code>iat</code> + <code>np.where</code> here for conditional creation of your column:</p> <pre><code># import numpy as np first_val = df['speaker'].iat[0] # same as df['speaker'].iloc[0] df['speaker'] = np.where(df['speaker'].eq(first_val), 0, 1) </code></pre> <pre><code> speake...
python|pandas
2
367,185
58,937,197
Converting pandas dataframe to dict and vice versa
<p>I have a <code>pandas.DataFrame</code> called <code>df</code> (this is just an example)</p> <pre><code>col1 col2 col3 A1 B1 C1 NaN B2 NaN NaN B3 NaN A2 B4 C2 Nan B5 C3 A3 B6 C4 NaN NaN C5 </code></pre> <p>The dataframe is sorted, and each <code>NaN</code> is <code...
<p>We can explode each column separately using a <code>cumcount</code> to align during the concatenate. <code>col1</code> then needs to be masked where it was duplicated. </p> <pre><code>import pandas as pd df = pd.DataFrame.from_dict(data, orient='index') df.index.name='col1' l = [] for col in ['col2', 'col3']: ...
python|pandas
1
367,186
59,034,513
pandas how to get result of groupby and compare them?
<p>I have pets dataFrame.</p> <p>I can do:</p> <pre><code>df=pets['PetID'].groupby([pets['Kind'], pets['Gender']]).count() </code></pre> <p>The result of dataframe(the variable df) is:</p> <pre><code>Kind Gender Cat female 12 male 19 Dog female 22 male 35 Parrot female ...
<p>In your case we can use <code>mode</code> </p> <pre><code>pets['Gender'].groupby(pets['Kind']).apply(lambda x : x.mode().iloc[0]) </code></pre> <p>To fix your output <code>df</code> </p> <pre><code>df.sort_values().groupby(level=0).tail(1).reset_index() </code></pre>
python|pandas|pandas-groupby
0
367,187
58,685,759
matplotlib numpy -- TypeError: Cannot read property 'props' of undefined -- Graph not showing up?
<p>This code works on one machine, but not the other. I can't seem to isolate the issue with the dependencies.</p> <p>Sample code from: <a href="https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/simple_plot.html" rel="nofollow noreferrer">https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/simple_plo...
<p>Can you tell us on which line it fails specifically? Which function call causes the issue? You could comment everything and then uncomment every line until an error occurs on execution. Maybe there's a github page of this issue.</p> <p>My suspicion is, that it's the ax.set() call. Haven't seen that before and never...
python|numpy|matplotlib|plot|pytorch
0
367,188
58,834,740
Using list of URLs to extract the data
<p>I am struggling using list of urls to extract the data. I tried to use this code to fetch data from one url: </p> <pre><code>r = requests.get('https://www.horizont.net/marketing/nachrichten/anzeige.-digitalisierung-wie-software-die-kreativitaet-steigert-178413') c = r.content soup = BeautifulSoup(c, 'html.parser') ...
<p>After struggling. I able to find the solution. </p> <pre><code> for url in url_list: r = requests.get(url) c = r.content soup = BeautifulSoup(c, 'html.parser') all = soup.select('.PageArticle') for item in all: t = item.find_all('h1')[i].text title.appen...
python|pandas|beautifulsoup|request
0
367,189
58,725,738
How to give multiple arguments in tensorflow Model call function?
<p>I'm trying to build a model in tensorflow by extending the 'Model' class in tensorflow.keras. I need to pass two arguments in the 'call' function of this class, input images x (224,224,3) and output label y. But I get the following error while building the model:</p> <blockquote> <p>ValueError: Currently, you can...
<p>Inputs parameter of call method can be an <code>input tensor</code> or <code>list/tuple of input tensors</code>.</p> <p>You can pass two arguments like this:</p> <pre class="lang-py prettyprint-override"><code>def call(self, inputs): x = inputs[0] y = inputs[1] x = self.conv_1(x) x = self.flatten(x) ...
python-3.x|tensorflow|keras
3
367,190
58,687,931
Pandas read_csv parse_dates format "%m/%d/%Y %H:%M:%S" in column only parse date, missing time
<p>I have a statistic in csv files, some are huge file with thousands of lines. the structure is:</p> <pre><code>"Result : Stat01" "Save Time: 09/23/2019 19:01:27" "User Name:admin" "Total 1,365 Records" "Start Time","Period","Messages Received","Messages Sent" 09/23/2019 01:30:00,5,114,57 09/23/2019 01:30:00...
<p>The presentation for index was reduce to <code>%m-%d-%Y</code> however it has also time does not displayed. thanks guys</p> <p><a href="https://i.stack.imgur.com/XypOC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XypOC.png" alt="parse_date"></a></p>
python|pandas|date|datetime
1
367,191
58,867,875
Converting JSON to pandas DataFrame- Python
<p>I have read data from particular <strong>API</strong> using the following Python lines </p> <pre><code>import requests import json # read all Measurement from one sensor for several days. r = requests.get('https://wastemanagement.post-iot.lu/measurement/measurements?source=83512 pageSize=1000000000&amp;dateFrom=20...
<p>You can try this, it works well</p> <pre><code>// importing required libraries import pandas as pd import json import requests // hosted your json response as a url response URL = 'https://my-json-server.typicode.com/abhikumar22/JsonServer/data' // getting requests from the server req = requests.get(URL ) text_d...
python|json|pandas
3
367,192
58,924,055
Drop duplicates where some rows contain lists and others ints/strings
<p>I have a dataframe where I want to drop rows that have duplicate IDs. For the most part, the IDs are ints and strings. Some of the ID entries, however, are lists of multiple IDs. I cannot split up these lists, but when trying to drop duplicates I get an error. For reference, I used <code>df = df['ID'].astype(str)</c...
<p>unhashable type: 'list' error means Pandas trying to use list as an hash argument.</p> <p><a href="https://docs.python.org/3.1/glossary.html" rel="nofollow noreferrer">All of Python's immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are.</a></p> <p>Try to convert...
python|python-3.x|pandas|dataframe
0
367,193
58,752,286
Python data type type codes comprehensive table or resource
<p>Today, and on several other occasions, I received an error like this:</p> <p><code>{TypeError}ufunc subtract cannot use operands with types dtype('&lt;M8[us]') and dtype('O').</code></p> <p>On other days, I'd want to do some printf type command and be at a loss for which character stood for some obtuse data type (...
<p>General notes: </p> <ul> <li>Make sure you are reading the doc for the right version of python, numpy, etc. </li> <li>The codes used depend on the use case (i.e. numpy array-protocol type strings are different than those used to define the types in general python arrays)</li> <li>Even worse, some of the same charac...
python|numpy|types|printf
0
367,194
58,632,517
How to properly reshape an array of large dimensions into two separate assignments?
<p>I am trying to reshape an array of shape (1, 400) to (20, 20) with numpy arrays and am struggling to find the proper syntax.</p> <p>Consider the following:</p> <pre><code>import numpy as np d_array = np.ones((1 + 10 * (20 + 1), 1 + 10 * (20 + 1))) # tA and tB have shape (20,) tA = np.array([1, 1, 1, 1, 1, 1, 1, ...
<p>You can use:</p> <pre class="lang-py prettyprint-override"><code>d_array[tA.reshape(-1, 1), tB] = np.reshape(xA, (20, 20)) </code></pre> <p>I think <a href="https://stackoverflow.com/questions/22927181/selecting-specific-rows-and-columns-from-numpy-array/22931212">this question</a> is also related to your case.</p...
python|arrays|numpy|multidimensional-array|neural-network
0
367,195
58,904,112
Pandas Filter date
<p>I have a dataframe like the following,</p> <pre><code>+-----------+-------+----------+--+--+ | Date | OPP | Result | | | +-----------+-------+----------+--+--+ | Sat 11/16 | @DAL | L110-102 | | | +-----------+-------+----------+--+--+ | Wed 11/13 | @POR | W114-106 | | | +-----------+-------+-------...
<p>First you need to convert your date into proper <code>datetime</code> object, providing proper input format (which I assumed is <code>&lt;weekday&gt; &lt;month&gt;/&lt;day&gt;</code> - you can tweak it as per <code>datetime</code> documentation: <a href="https://docs.python.org/2/library/datetime.html#strftime-and-s...
python|pandas
1
367,196
58,644,408
How to access size column in groupby
<p>Consider the following code.</p> <pre><code>d=pd.DataFrame([[1,'a'],[1,'b'],[2,'c'],[2,'a'],[3,'c'],[4,'a'],[4,'c']],columns=['A','B']) k=d.groupby(d.A).size().to_frame('size') </code></pre> <p>It returns</p> <pre><code> size A 1 2 2 2 3 1 4 2 </code></pre> <p>Also,</p> <pre><code>k.shape (4,...
<p>Actually, 'size' column is the only column you can access, the one on the left is simply an index.</p> <p>If you want to have that index as a column as well you could do the following:</p> <pre><code>d=pd.DataFrame([[1,'a'],[1,'b'],[2,'c'],[2,'a'],[3,'c'],[4,'a'],[4,'c']],columns=['A','B']) k=d.groupby(d.A).size()...
pandas
1
367,197
58,688,255
How to optimize a simulation metric with deep learning without target values?
<p>I am trying to use an RNN model that outputs bus routes and its input is the demand matrix. The bus routes are then used in a simulation which spits out a metric of how the routes performed. The question is, since there is no target value of bus routes, how do I back propagate the simulation result?</p> <p>To expla...
<p>How does the model output represent the bus routes? Maybe you could try a reinforced learning approach. Take a look at Deep-Q Learning, It basically takes and input vector (the state of the system) and outputs an action (usually represented by an index in your output layer), then it computes the reward of that actio...
optimization|deep-learning|pytorch|recurrent-neural-network
1
367,198
70,215,290
How to find row and column of an item in a Dataframe
<p>I have a DataFrame like this:</p> <pre><code> A B C 0 True True False 1 True True True 2 False True True </code></pre> <p>I want to look for the instances of <code>False</code> and get its row and column.</p> <p>Expected result: <code>[(0, 'C'), (2, 'A')]</code>. not exactly on this data structure for...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>DataFrame.stack</code></a> for <code>MultiIndex Series</code> and then filter indices by inverted values by <code>~</code> for match <code>False</code>s:</p> <pre><code>s = df.stack() L...
python|pandas
2
367,199
70,367,071
How can I convert 8 bit array to 16 bit array in Python?
<p>I'm transferring 16 bit numbers from a STM32 (from an ADC) over SPI to raspberry pi 4. On the pi side, I have a script that runs in a loop, waits for a GPIO pin to go high to act as a &quot;detect&quot; for my system to then enable the raspberry pi to initiate the SPI transfer. Unfortunately the raspberry pi hardwar...
<p>Use numpy:</p> <pre><code>In [9]: data = (255, 3, 19, 0, 38, 0, 47, 0, 51, 0, 52, 0, 53, 0, 59, 0, 76, 0, 91, 0, 99, 0, 119, 0, 172, 0, 174, 0, 179, 0, 205, 0, 215, 0, 218, 0, 225, 0, 235, 0, 242, 0, 8, 1, 28, 1, 52, 1, 60, 1, 78, 1, 148, 1, 175, 1, 178, 1, ...: 186, 1, 186, 1, 201, 1, 212, 1, 223, 1, 234, 1, 24...
python|numpy
2