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
363,900
52,841,791
Reduce image dimension with mapping
<p>I have a .png image with four colors in it. If I convert the image to a numpy array I get an array with the following dimensions: <code>[length X height X 3]</code>, with <code>length == height</code>. How can I reduce the dimension with mapping the colors? </p> <p>This is the current structure: </p> <pre><code>ar...
<p>You can use <code>numpy.unique</code> for this. For example, here's a 3x5 image that has just three colors:</p> <pre><code>In [105]: img Out[105]: array([[[10, 20, 30], [ 5, 5, 0], [ 5, 5, 0], [ 5, 5, 0], [ 0, 0, 0]], [[ 5, 5, 0], [ 5, 5, 0], [ 0...
python|arrays|numpy
1
363,901
52,768,562
Python Xarray: how to convert a 3-d DataArray to a 2-d stacked Pandas dataframe
<p>I have a 3d <code>xarray</code> <code>DataArray</code> volume of data of time series data for multiple runs of a model. So the rows are indexed by the simulation timestep, the columns are just a variety of variables captured about the model, and then the depth coordinate represents the individual simulation run, sin...
<p>You can use <code>.to_dataframe</code> and then <code>unstack</code>, you just need to pass a name to attach to the dataset (which becomes a column containing that value):</p> <pre><code>In [41]: simulation_matrix.to_dataframe("results").unstack() Out[41]: results simdata val1 val2 val3...
python|pandas|python-xarray
2
363,902
52,518,048
PandasError:KeyError: "['Brain'] not in index"
<p>Here's the code :</p> <pre><code>data=pd.read_csv("/home/crpsm/Pycharm/DataSet/headbrain.csv") print(data.describe()) y=data[["Brain"]] x=data[["Head"]] </code></pre> <p>when I run this code I got this error:</p> <pre><code>"['Brain'] not in index" </code></pre> <p>Is there any way to fix this error? Thanks in...
<p>There are spaces in end of columns names, need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.rstrip.html" rel="nofollow noreferrer"><code>str.rstrip</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.strip.html" rel="nofollow noreferrer">...
python|pandas|csv
1
363,903
46,413,817
Get dictionary element in Tensorflow
<p>I have a dictionary and I need to get the element from the dictionary by key. However, the key needs to be set as tf.placeholder and get the value after. For example, I want</p> <pre><code>dict={'a':10,'b':20} key=tf.placeholder(tf.float32, shape=[1]). result=dict[key] sess=tf.InteractiveSession() sess.run(result...
<p>This is a common confusion with TF. While everything looks like python code, what is actually happening is that TF is building a graph of operations and then executes it outside of the python interpreter context. This means that you cannot access python objects from inside the graph. And as far as I know TensorFlow ...
python|tensorflow|deep-learning
1
363,904
46,602,613
Iterate through large csv using pandas (without using chunks)
<p>I wrote a small simple script to read and process a huge CSV file (~150GB), which reads 5e6 rows per loop, converts it to a Pandas DataFrame, do something with it, and then keeps reading the next 5e6 rows.</p> <p>Albeit it does the job, at every iteration it takes longer to find the next chunk of rows to read, as i...
<p>Using your approach Pandas will have to start reading this huge CSV file from the very beginning again and again in order to skip rows... </p> <p>I think you do want to use <code>chunksize</code> parameter:</p> <pre><code>reader = pd.read_csv(inputfile, sep=',', header=None, chunksize=5*10**6) for df in reader: ...
python|pandas
4
363,905
46,426,235
Pandas: reindex with dates in groupby, filling/maintaining values as appropriate
<p>I have the following DataFrame. </p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame(data={'date': ['2010-05-01', '2010-07-01', '2010-06-01', '2010-10-01'], 'id': [1,1,2,2], 'val': [50,60,70,80], 'other': ['uno', 'uno', 'dos', 'dos']}) &gt;&gt;&gt; df['date'] = df['date'].apply(lambda d: pd.to_datetime(d)) &gt;&gt;&gt; d...
<p>You can use <code>groupby</code> by custom function with <code>reindex</code> and filling <code>NaN</code>s - in <code>other</code> by <code>ffill</code> and <code>bfill</code> (forward and back filling) and in <code>val</code> by <code>fillna</code> by constant:</p> <pre><code>def f(x): x = x.reindex(pd.date_r...
python|pandas|pandas-groupby
5
363,906
46,591,000
pandas groupby and boolean selection
<p>I often end up doing things like this in <code>pandas</code>:</p> <pre><code>s2 = s1.groupby(level=1).sum() s2 = s2[s2&gt;25] </code></pre> <p>In words, I do some <code>groupby</code> operation and then want to keep only results that meet some condition for the result.</p> <p>Is there a way to do with in one line...
<p><strong>Assuming <code>s1</code> is a <code>pandas.Series</code></strong> </p> <ol> <li>You can pass <code>level</code> to <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sum.html" rel="noreferrer"><strong><code>pd.Series.sum</code></strong></a></li> <li><a href="https://pandas.pydata...
python|pandas|group-by|pandas-groupby
9
363,907
46,420,430
Reshaping a column into rows group-wise using Pandas
<p>i have a df</p> <pre><code>id name value 1 abc 10 1 qwe 23 1 zxc 12 2 sdf 10 2 wed 23 2 abc 12 2 mnb 11 </code></pre> <p>i want to reshape this dataframe into:</p> <pre><code>id n1 n2 n3 n4 1 abc qwe zxc 0 2 sdf wed ...
<p><strong>Possibly Overkill</strong> </p> <pre><code>f, u = pd.factorize(df.id.values) b = np.bincount(f) n, m = u.size, b.max() c = np.arange(f.size) - np.arange(n).repeat(b) * (m - 1) v = np.zeros((n, m), dtype=object) v[f, c] = df.name.values pd.DataFrame( v, pd.Index(u, name='id'), ['n{}'.format(i) for...
python|pandas|dataframe|group-by|pandas-groupby
2
363,908
46,460,594
Sum set of values from pandas dataframe within certain time frame
<p>I have a fairly complicated question. I need to select rows from a data frame within a certain set of start and end dates, and then sum those values and put them in a new dataframe. </p> <p>So I start off with with data frame, <code>df</code>:</p> <pre><code>import random dates = pd.date_range('20150101 020000',pe...
<p>You can use</p> <pre><code>def get_dates(x): # Select the df values between start and ending datetime. n = df[(df['time_stamp']&gt;x['start'])&amp;(df['time_stamp']&lt;x['end'])] # Return first id and sum of values return n['id'].values[0],n['value'].sum() dates = pd.date_range('20150101 020000',p...
python|pandas|datetime|dataframe|group-by
2
363,909
46,414,026
How do I access elements of a 2d array based on two where clauses?
<p>I have the following ndarray:</p> <pre><code>[[ 3 271] [ 4 271] [375 271] [ 3 216] [375 216] [ 0 0] [ 0 546] [378 546] [378 0] [ 1 182] [ 2 181] [376 181] [377 182] [377 544] [376 545]] </code></pre> <p>Essentially a bunch of X,Y coordinates/points. I'd like to be able to select X,Y coordi...
<p>With <code>a</code> as the array in your example.</p> <pre><code>target = np.array([3, 271]) </code></pre> <p>Subtract the target</p> <pre><code>diff = a - target </code></pre> <p><em>y</em> (column one) must be the same as the target - this results in a boolean array of shape a.shape[0]:</p> <pre><code>y_rows ...
python|numpy|multidimensional-array
1
363,910
46,478,697
Tensorflow - trying to run BasicLSTMCell once
<p> I would like to run <code>BasicLSTMCell</code> once, get result and see if I can reproduce results manually. However, I am stuck at executing <code>BasicLSTMCell</code> once. Here is my code:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf BATCH_SIZE = 7 SEQUENCE_LENGTH = 5 VECTOR_SIZE...
<p><em>cell</em> is an object of BasicLSTMCell, which is a part of the graph to populate output and a new state.</p> <p>Thanks for python Readability</p> <pre><code>cell(rnn_inputs[0], (init_state, init_state)) </code></pre> <p>is actually:</p> <pre><code>cell.__call__(rnn_inputs[0], (init_state, init_state)) </cod...
tensorflow|initialization
3
363,911
46,223,195
Comparing a column from two dataframes and deleting rows in df2 that are within +/-0.03 of values in df1
<p>I have two dataframes:</p> <pre><code> A B df1&lt;- 45.5219 5.3179 0.9670 4.2212 A B df2&lt;- 1.0000 5.3178 0.1922 4.7881 0.0395 4.5975 0.0813 ...
<p>Well I know <a href="https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html" rel="nofollow noreferrer"><code>NumPy broadcasting</code></a>, so here's one <em>ab</em>using it -</p> <pre><code>a = df1.values b = df2.values df2_out = df2[~(np.abs(a[:,None,:] - b[None]) &lt;= 0.03).any(0).any(1)] </code>...
python-3.x|pandas|numpy
4
363,912
46,439,573
How to sort a two-dimensional array in descending order for a column?
<pre><code>array([[ 0. , 0.04], [ 0. , 0.1 ], [ 0. , 0.2 ], [ 0. , 0.4 ], [ 0.27, 1. ], [ 0.3 , 1. ]]) </code></pre> <p>How to sort the array by the second column in descend order in an simple way ? The result's shape is also (6,2).</p>
<p>Get <code>argsort</code> indices for the second column, flip them and index into rows -</p> <pre><code>a[a[:,1].argsort()[::-1]] </code></pre> <p>Alternatively, get <code>argsort</code> indices on negated version and index into rows -</p> <pre><code>a[(-a[:,1]).argsort()] </code></pre>
numpy
5
363,913
46,506,646
ValueError: No gradients provided for any variable, check your graph for ops that do not support gradients, between variables
<p>I am training the "Show and tell" model using tensorflow in which the model automatically generates the captions of the images. How ever I am getting this error.</p> <p>This is the traceback:</p> <blockquote> <pre><code>------------------------------------------------------------------------ --- ValueError ...
<p>Branching in the loss building routine is invalid.</p> <pre><code>with tf.variable_scope("RNN"): for i in range(self.n_lstm_steps): if i &gt; 0: [...] else: [...] if i &gt; 0: [...] if i &gt; 0: ...
tensorflow|deep-learning|gradient|conv-neural-network|recurrent-neural-network
0
363,914
46,630,986
In tensorflow source code, what is node class (merge, enter, exit ...)?
<p>I'm looking for code of tensorflow v1.3 for using this framework more precise. </p> <p>However there are lots of complicate things.</p> <p>Specifically, I'm watching the process of running the graph. </p> <p>When one node's numerical computation is done, the output of that node will be added to ready queue. </p> ...
<p>Merge/Switch are concepts taken from data flow processing concepts from the 70s <a href="https://i.stack.imgur.com/qa5kn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qa5kn.png" alt="enter image description here"></a></p> <p>(from Advances in Computers, 1992)</p> <p>See section 4.4 of <a href=...
c++|tensorflow
2
363,915
46,601,853
How to filter all data that is not divisible by n in pandas dataframe
<p>In this case n=100</p> <p>Here's my dataset</p> <pre><code>id amount 1 1000 2 2000 3 2300.7632 4 4560 </code></pre> <p>What I want is </p> <pre><code>id amount 3 2300.7632 4 4560 </code></pre>
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with modulo <code>%</code>:</p> <pre><code>df = df[df['amount'] % 100 != 0] print (df) id amount 2 3 2300.7632 3 4 4560.0000 </code></pre> <p>Same as:</p...
python|pandas|numpy|dataframe|filter
4
363,916
46,471,468
Train High Definition images with Tensorflow and inception V3 pre trained model
<p>I'm looking to do some image classification on PDF documents that I convert to images. I'm using tensorflow <a href="http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz" rel="nofollow noreferrer">inception v3 pre trained model</a> and trying to retrain the last layer with my own categories ...
<p>If you want to use a different image resolution than the pre-trained model uses , you should use only the convolution blocks and have a set of fully connected blocks with respect to the new size. Using a higher level library like Keras will make it a lot easier. Below is an example on how to do that in Keras.</p> <...
machine-learning|tensorflow|deep-learning|image-recognition
3
363,917
46,455,374
Keras: TypeError: run() got an unexpected keyword argument 'kernel_regularizer'
<p>I am using <code>tensorflow==1.2.1</code> and <code>Keras==2.0.6</code> to build a model:</p> <pre><code>input_num = X_norm_keras[:,2:].shape[1] model_keras = Sequential() model_keras.add(Dense(10, input_dim=input_num, activation='relu')) model_keras.add(Dense(1, activation='linear')) kernel_regularizer=regularizer...
<p>The regularizer <code>kernel_regularizer=regularizers.l2(0.2)</code> should be an argument of <code>Dense()</code>, not <code>model.compile()</code>.</p> <p>From the documentation of <code>model.compile()</code>:</p> <blockquote> <p>**kwargs: When using the Theano/CNTK backends, these arguments are passed into K...
python-3.x|tensorflow|deep-learning|keras
4
363,918
46,453,599
I tf.gfile.DeleteRecursively the wrong directory, is there a way to restore it ?
<p>I was running the <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/mnist/mnist_with_summaries.py" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/mnist/mnist_with_summaries.py</a> example .</p> <p>And I set my lo...
<p>No. A reminder to <em>always</em> have a backup. </p>
python|tensorflow|delete-directory
0
363,919
46,627,470
How to understand the target of tf.Session?
<p>The <code>tf.Session</code> has parameter <code>target</code>, it can be <code>''</code>, <code>grpc://ip:port</code>, or <code>tf.train.Server().target</code>, what is the difference between them? And when we create a <code>session</code>, does it mean we create a <code>client</code>, if we have <code>client</code>...
<p>It's the location of session master (the thing that can execute session.run calls).</p> <ul> <li><p>'' is local master (local runtime).</p></li> <li><p>tf.train.Server(...).target is local master (distributed runtime). It has the form grpc://localhost:port</p></li> <li>grpc://ip:port is the master listening on ip</...
python|c++|tensorflow|grpc
1
363,920
46,368,514
Unable to make predictions using TensorFlow Go API
<p>I have a MLP coded using Tensorflow Python API. The following is the code snippet:</p> <pre><code># tf Graph input x = tf.placeholder("float", [None, 11],name="x") y = tf.placeholder("float", [None]) # Store layers weight &amp; bias weights = { 'h1': tf.Variable(tf.random_normal([11, 32], 0, 0.1)), 'h2': t...
<p>The error is clear: <code>In[0] is not a matrix</code>.</p> <p>Your <code>In[0]</code> is: <code>df := []float32{9.5,0.0,7.5,0.0,0.0,2.0,0.0,0.0,0.0,0.0,1505292248.0}</code></p> <p>This is a 1-dimensional tensor, not a matrix.</p> <p>The <code>matmul</code> node requires both its arguments to be matrices, thus 2-...
go|tensorflow
0
363,921
46,458,372
Can you use pandas/python to concatenate a folder of .xlsx files based on row 2?
<p>I'm having trouble using pandas to concatenate a very large folder of .xlsx files. The issue is we have some text written in the first row of each document that can't be removed. </p> <p>My path to the folder is set and the concatenate works. The issue is after the first file, it's removing the ID #'s in the first ...
<p>I would echo piRSQUARED's answer. pd.read_excel has skiprows but remember to pass skip rows as an iterable.</p>
python|excel|python-2.7|pandas
0
363,922
46,383,300
Unpack a list of nested dictionaries and convert to CSV
<p>I am trying to write to CSV a JSON that produces a list of nested dictionnaries as follows:</p> <pre><code>[{'spam': 'xxxx', 'egg': 'yyyy', 'line_items': [{'description': 'hhh', 'amount': 'iii'}, {'description': 'jjj', 'amount': 'kkk'}], 'bacon': 'zzzz'}] <...
<blockquote> <p>Or perhaps there is another way to achieve my expected result?</p> </blockquote> <p>If you use <code>pandas</code>, there's a one-liner for this, using <code>json_normalize</code>:</p> <pre><code>import pandas as pd data = [{'spam': 'xxxx', 'egg': 'yyyy', 'line_items': [{'description': 'hhh', ...
python|json|pandas|csv
1
363,923
46,419,180
Pandas: normalize within the group
<p>Let's say we have the following dataset:</p> <pre><code>import pandas as pd data = [('apple', 'red', 155), ('apple', 'green', 102), ('apple', 'iphone', 48), ('tomato', 'red', 175), ('tomato', 'ketchup', 96), ('tomato', 'gun', 12)] df = pd.DataFrame(data) df.columns = ['word', 'rel_word', 'weight'] </code>...
<p>Use <code>transform</code> - faster than <code>apply</code> and lookup</p> <pre><code>In [3849]: df['weight'] / df.groupby('word')['weight'].transform('sum') Out[3849]: 0 0.508197 1 0.334426 2 0.157377 3 0.618375 4 0.339223 5 0.042403 Name: weight, dtype: float64 In [3850]: df['norm_w'] = df['wei...
python|pandas
10
363,924
46,514,923
How to replace grouped dataframe with dict pandas python
<p>I have a dataframe:</p> <pre><code>date | brand | red | blue | green --------------------------------- 2017 | BMW | 2 | 1 | 0 | GM | 0 | 1 | 0 2018 | BMW | 0 | 0 | 1 | GM | 1 | 2 | 0 </code></pre> <p>Which is result of following line:</p> <pre><code>pd.pivot_table(d...
<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rename.html" rel="nofollow noreferrer"><code>rename</code></a> for replace values of <code>MultiIndex</code> by <code>di</code>:</p> <pre><code>df = df.rename(di) #same as #df = df.rename(index=di) print (df) color blue ...
python|pandas|replace|pivot-table|pandas-groupby
1
363,925
46,556,580
Creating a dictionary in pandas by mapping column values to headers
<p>I have the following data frame: </p> <pre><code>F1: head drowsiness sweat head_P D_P sw_f head_S D-H sw_h head_F D_L sw_l </code></pre> <p>I need to create a dictionary by mapping all the values in columns to the header of the columns as follows:</p>...
<p><strong>Option 1</strong> </p> <pre><code>dict(zip(df.values.ravel(), df.columns.repeat(len(df)))) {'D-H': 'drowsiness', 'D_L': 'sweat', 'D_P': 'head', 'head_F': 'sweat', 'head_P': 'head', 'head_S': 'drowsiness', 'sw_f': 'head', 'sw_h': 'drowsiness', 'sw_l': 'sweat'} </code></pre> <hr> <p><strong>Option...
python|pandas|dictionary
3
363,926
46,577,203
Tensorflow Issues
<p>I am trying to learn tensorflow, and I have modified the linear regression code that tensorflow provides on its website tutorial to do quadratic regression. However, instead of reducing the loss as it does in the linear model, the loss explodes and I have no idea why it's doing that.</p> <p>Code, in python 2.7.12:<...
<p>This learning rate:</p> <pre><code>optimizer = tf.train.GradientDescentOptimizer(0.01) </code></pre> <p>Is too large.</p> <p>with:</p> <pre><code>optimizer = tf.train.GradientDescentOptimizer(0.001) </code></pre> <p>output is:</p> <pre><code>A: [ 0.99987358] B: [ 0.00042567] C: [-0.00021291] loss: 7.5869e-08 <...
python|tensorflow|regression
0
363,927
46,424,415
transforming a Series of lists into a structured DataFrame
<p>I have a pandas <code>Series</code>, where each entry is a <code>list</code>. I would like to transform it into a <code>DataFrame</code> in a particular way. Namely, I want the new <code>DataFrame</code> to have as many columns as there are elements in the longest <code>list</code> in the <code>Series</code>. This n...
<p>You had it correct, you just used <code>pd.Series</code> instead of <code>pd.DataFrame</code>:</p> <pre><code>df = pd.DataFrame([[1,2], [3,4,5], [6]]) </code></pre>
python|pandas|dataframe|vectorization|series
1
363,928
46,204,466
Saving and Restoring a model using tensorflow
<p>I saved parameters of my neural network using this:</p> <pre><code>parameters = { 'w_h1': w_h1, 'b_h1': b_h1, 'w_h2': w_h2, 'b_h2': b_h2, 'w_h3': w_h3, 'b_h3': b_h3, 'w_o': w_o, 'b_o': b_o } saver = tf.train.Saver(parameters) saver.save(sess, 'my-model', global_step=epoch) </co...
<p>names like <code>'Variable_21/Adam_3:0'</code> is your variable names and <code>"w_h1"</code> isn't, you should get this tensor with <code>w_h1 = tf.get_default_graph().get_tensor_by_name("Variable_21/Adam_3:0")</code></p>
tensorflow|python-2.x
1
363,929
46,220,285
Pyinstaller with Tensorflow takes incorrect path for _checkpoint_ops.so file
<p>I am trying to make an executable of my Python code which uses <code>Tensorflow</code> with <code>Pyinstaller</code>. The executable gets generated correctly but when I try to run it, I get the following error:</p> <pre><code>Traceback (most recent call last): File "detection_init.py", line 14, in &lt;module&gt; ...
<p>Add the following to your spec file (finds tensorflow binaries and adds them to your .app in the main binary/file directory):</p> <pre><code>import os tensorflow_location = '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tensorflow' tensorflow_binaries = [] for dir_name, sub_dir_li...
python|tensorflow|pyinstaller
2
363,930
46,411,836
pandas df remove items from df1 that are also in df2
<p>I have two very large csv files. They are both only one col with integers. I need to check for every integer in dfA if they are in dfB. If so, I need to remove item a from dfA.</p> <p>I would probably loop through dfA and check for every value if in dfB, but looping is wayyyy too slow.</p> <p>dfA :</p> <pre><code...
<p>There's no 'magic bullet' here, you'll have to loop through each list at least once</p> <p>You can iterate through just one of the lists as follows (though, i think under the hood, we iterate through both lists)</p> <pre><code>dfA = pd.read_csv(file1) dfB = pd.read_csv(file2) for n in dfB.values: dfA = dfA[df...
pandas
0
363,931
46,528,599
Pandas pivot produces "ValueError: Index contains duplicate entries, cannot reshape"
<p>I have a pandas table formatted as following:</p> <pre><code> anger_metric metric_name angle_value 0 71.0991 roll 14.6832 1 71.0991 yaw 0.7009 2 71.0991 pitch 22.5075 3 90.1341 roll 4.8566 4 90.1341 yaw 6.4458 5 90.1341 pitch -10.1930 </code></pre> <p>I need to create a view of this...
<p>Try <code>pivot_table</code>:</p> <pre><code>df anger_metric metric_name angle_value 0 71.0991 roll 14.6832 1 71.0991 yaw 0.7009 2 71.0991 pitch 22.5075 3 90.1341 roll 4.8566 4 90.1341 yaw 6.4458 5 90.1341 ...
python|pandas|dataframe|duplicates|pivot
31
363,932
46,542,632
Unable to install Tensorflow using pip
<p>I am trying to install Tensorflow but it gives the following error. I have python 3.5.4 on my system and using windows 10 as my operating system <a href="https://i.stack.imgur.com/7YHwO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7YHwO.png" alt="enter image description here"></a></p>
<p>What python do you have and is Python in your path?</p> <p>try </p> <pre><code>pip3 install --upgrade tensorflow </code></pre> <p>or also</p> <pre><code>python -m pip3 install --upgrade tensorflow </code></pre> <p>Worked for me on a PC with Python 3.</p>
python|tensorflow
0
363,933
46,581,160
How to modify a neural network with Keras during training?
<p>Let's say I have the following inside my network:</p> <pre class="lang-py prettyprint-override"><code>x = Conv2D( filters=256, kernel_size=5, strides=2, padding="same" )(x) x = Dropout(0.5)(x) x = BatchNormalization(momentum=0.8)(x) x = LeakyReLU(alpha=0.2)(...
<p>I have finally found out:</p> <pre class="lang-py prettyprint-override"><code>class MyModel(): def __init__(self, init_dropout, dropout_decay): self.init_dropout = init_dropout self.dropout_decay = dropout_decay input_layer = Input((64, 64, 1)) x = Conv2D( filter...
tensorflow|neural-network|deep-learning|keras|keras-layer
1
363,934
58,358,258
Making histogram of object attribute of a DataFrame
<p>I am making histogram from a dataset but observed that <code>hist()</code> works only for numerical data values. While I have some object type attributes in my dataframe, for example: Name, gender (possible values: male, female) etc.</p> <p>I want to plot histogram for gender attribute of my dataset. How is that po...
<p>Try </p> <pre><code>mydataFrame.gender.value_counts().plot(kind='bar'); </code></pre> <p><code>value_counts()</code> will make a series with the values of gender in the index, and the count as the values.</p>
python|pandas|dataframe|matplotlib|histogram
0
363,935
58,581,989
How to translate arabic rows of text from columns into english
<p>I have a jupyter dataframe with 10,000 rows in arabic that I want to translate to english in an adjacent column. There are actually 2 columns that I want to translate they would be "description" and "text". and next to each of those columns I want new columns with the translation that are called "Description_Transla...
<p>Do you have a preferred library for translation? A small example table would also be helpful in troubleshooting.</p> <pre><code>from googletrans import Translator translator = Translator() df['Description_Translated'] = df['description'].apply(lambda x: translator.translate(x)) df['Text_Translated'] = df['text'].ap...
python|pandas|translation
0
363,936
58,190,556
Offset function using If else statement
<p>I have a pd df and I want to create a third column"LCC_saving" based on the following conditions.</p> <pre><code>nvals=df['Offset_base'] for i, row in df.iterrows(): if nvals &lt;0: df.at[i,'LCC_savings']=df.loc[i+row['Offset_base']]['LCC']-row['LCC'] else: df.at[i,'LCC_savings'] = 0 df Offset_base ...
<p>Although this kind of problems can be solved with <code>iterrows</code> and <code>iat</code> or maybe even some operations implying shift, I think the easiest, fastest and most straightforward way is to do the calculation on the underlying numpy array and assign the result to the dataframe:</p> <pre><code>import pa...
pandas
1
363,937
58,350,518
Cannot run Python file as .exe file, getting error 'ModuleNotFoundError: No module named 'pandas' '
<p><strong>Original Question</strong></p> <p>After installing auto-py-to-exe (<a href="https://pypi.org/project/auto-py-to-exe/" rel="nofollow noreferrer">https://pypi.org/project/auto-py-to-exe/</a>) and trouble shooting my installation problems (<a href="https://stackoverflow.com/questions/58332990/how-to-convert-py...
<p>The following information relating to the <code>--hidden-import</code> flag may be important to the build process and may resolve your issue. This is from the <a href="https://nitratine.net/blog/post/issues-when-using-auto-py-to-exe/" rel="nofollow noreferrer">blog post</a> that appears in the link in your question:...
python|pandas|exe
3
363,938
58,246,060
Transforming Complex Flat File using Python
<p>I have a flat file which has format something like below,</p> <pre><code>Country{Year{Working_Days_Month1{Working_Days_Month2...{Working_Days_Month12 IND{2019{111110011111001111100111110011{111110011111001111100111110011....{111110011111001111100111110011 </code></pre> <p>I need to transform the above data to a ta...
<p>You can try to use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="nofollow noreferrer"><code>read_csv</code></a> from pandas.</p> <pre><code>import pandas as pd df = pd.read_csv("/path/to/file", sep="{") </code></pre> <p>You can use <code>names</code> keyword argume...
python|pandas|dataframe|data-science
1
363,939
58,349,025
Pandas: How to filter column list by value?
<p>I have a Pandas DataFrame that stores lists in one of its columns: </p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; d = [{'name': 'john', 'properties': ['a','b']}, ... {'name': 'mary', 'properties': ['a','c']}] &gt;&gt;&gt; df = pd.DataFrame(d) &gt;&gt;&gt; df name properties 0 john [a, b]...
<p>You can use <code>map</code>.</p> <pre><code>df[df.properties.map(lambda x: 'c' in x)] </code></pre>
python|pandas|dataframe
1
363,940
58,568,375
Different Standard Deviation in Pandas and Numpy
<p>I was trying to calculate <code>std</code> for an array, i've tried to use <code>numpy</code> and <code>pandas</code> in order to find <code>std</code>, but what i achieved is not logical, i have two different <code>std</code>'s for the same array !</p> <p>Why does this happens ?</p> <pre><code>&gt;&gt;&gt; import...
<p>Difference is in degree of freedom, default in numpy is <code>ddof=0</code>, in pandas is <code>ddof=1</code>:</p> <pre><code>print(a.std()) 2.8722813232690143 print(a.std(ddof=0)) 2.8722813232690143 print(a.std(ddof=1)) 3.0276503540974917 </code></pre> <hr> <pre><code>b = pd.DataFrame(a) print(b.std()) 0 3.0...
python|pandas|numpy
5
363,941
58,365,610
How to define a new optimization function for Keras
<p>I would like to implement for Keras a new optimization function that would not be based on the partial derivatives of the parameters, but also on the derivatives of these partial derivatives. How can I proceed?</p>
<p>You start by creating a custom optimizer by looking at the <a href="https://github.com/keras-team/keras/blob/master/keras/optimizers.py" rel="nofollow noreferrer">code for the current optimizers</a>.</p> <p>You can see that an optimizer can be defined by subclassing <code>keras.optimizers.Optimizer</code>:</p> <pr...
python|tensorflow|math|keras
0
363,942
58,447,956
Rearrange Numpy Matrix
<p>I have a matrix as shown below with shape (2, 2, 1).</p> <pre><code>[[[1] [3]] [[2] [4]]] </code></pre> <p>Is there an easy way/function to rearrange the elements such that it becomes:</p> <pre><code>[[[1] [2]] [[3] [4]]] </code></pre> <p>Thanks!</p>
<p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.swapaxes.html" rel="noreferrer"><code>swapaxes</code></a> to interchange the two first axes of the array:</p> <pre><code>a.swapaxes(0,1) array([[[1], [2]], [[3], [4]]]) </code></pre>
python|numpy
5
363,943
58,509,047
meshgrid changing max values
<p>If I have</p> <pre><code>min_E, max_E = (-1335000.0, -1190000.0) min_N, max_N = (2255000.0, 2405000.0) </code></pre> <p>And I want to make a meshgrid:</p> <pre><code>res = 1000 xx, yy = np.meshgrid(np.arange(min_E, max_E, res), np.arange(min_N, max_N, res)) </code></pre> <p>why is <code>yy.max() != max_N</cod...
<p><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html" rel="nofollow noreferrer"><code>numpy.arange</code></a> generates values in <code>[start, stop)</code>, i.e. <code>start &lt;= x &lt; end</code>, replicating the <code>range</code> builtin. that said, due to floating point precision ev...
python|numpy
1
363,944
58,596,379
how to write into excel file without dataframe using xlsxwriter
<p>If my dataframe is empty then I simply need to create empty excel file and write in it <code>"There is no data for selected timeframe "</code></p> <pre><code>folder_list = ['San Diego', 'Vista'] if not df.empty: # if daraframe is not empty then do this: for location, d in df.groupby('OfficeLocation'): ...
<p>You should be adding a new sheet instead:</p> <pre><code>for folder in folder_list: # this creates empty file with sheet name 'Sheet1' writer=pd.ExcelWriter(f'\\\\my\username\Documents\Python\Split DataFrame by Multiple dataframes\{folder}\{folder}.xlsx', engine='xlsxwriter') wb = writer.book ws = ...
python|python-3.x|pandas|xlsxwriter
2
363,945
58,223,422
How to use OpenMP parallelism effectively with tensorflow 1.14.0
<p>I'm currently trying to find an effective way of running a machine learning task over a set amount of cores using <code>tensorflow</code>. From the information I found there were two main approaches to doing this.</p> <p>The first of which was using the two tensorflow variables intra_op_parallelism_threads and inte...
<p>Answer to your first and last question.</p> <p>Yes I ran into a similar situation while using TensorFlow installed through pip. You can limit python to a specific number of cores by using thread affinity, numatcl or taskset on linux.</p> <p>Looking at the details provied by the following links, TensorFlow will alway...
python|tensorflow|openmp|python-3.6
0
363,946
58,514,359
Pandas boxplot plotting incorrectly
<p>I'm trying to create boxplots for all columns in a dataframe, but the resulting boxplot for the first column (Exon 8) has points that are not in my dataframe. It shows an outlier that shouldn't exist as well as a second boxplot on top of it. <img src="https://i.stack.imgur.com/z8qzT.png" alt="Resulting image can be...
<h2>Given your data:</h2> <ul> <li>There isn't an issue that can be reproduced with the information provided</li> <li>If Jupyter is being used, Restart Kernel and Clear All Outputs <ul> <li>Read the data back in</li> </ul></li> </ul> <pre class="lang-py prettyprint-override"><code>import pandas as pd import matplotl...
python-3.x|pandas|matplotlib
0
363,947
58,253,408
How to get value of a Keras tensor in TensorFlow 2?
<p>TF1 had <code>sess.run()</code> and <code>.eval()</code> to get values of tensors - and Keras had <code>K.get_value()</code>; now, neither work the same (former two at all).</p> <p><code>K.eager(K.get_value)(tensor)</code> appears to work inside Keras graph by exiting it, and <code>K.get_value(tensor)</code> outsid...
<p>I think you want <a href="https://keras.io/backend#eval" rel="noreferrer"><code>K.eval</code></a>:</p> <pre><code>&gt;&gt;&gt; v = K.ones(1) &gt;&gt;&gt; K.eval(v) array([1.], dtype=float32) &gt;&gt;&gt; K.eval(K.sqrt(v)) array([1.], dtype=float32) </code></pre> <p>Note that <a href="https://keras.io/backend/#get_...
python|tensorflow|keras|tensorflow2.0
7
363,948
58,470,824
Enable to use Tensorflow JS in the local computer
<p>Goal:<br> Enable to run the tensorflow.js toxicity classifier demo in the local computer.</p> <p>Problem:<br> Based on instruction "<a href="https://github.com/tensorflow/tfjs/issues/149" rel="nofollow noreferrer">https://github.com/tensorflow/tfjs/issues/149</a>" </p> <p>"You cannot call imports in a browser sin...
<p><a href="https://stackblitz.com/edit/typescript-tkmkho" rel="nofollow noreferrer">https://stackblitz.com/edit/typescript-tkmkho</a></p> <p>Apply the code as typescript in stackblitz.</p>
tensorflow.js
0
363,949
58,525,547
Pandas DataFrame: Groupby Column, Sort By DateTime, and Truncate Group by Condition
<p>I have a Pandas DataFrame that looks similar to:</p> <pre><code>import pandas as pd df = pd.DataFrame([['a', '2018-09-30 00:03:00', 'that is a glove'], ['b', '2018-09-30 00:04:00', 'this is a glove'], ['b', '2018-09-30 00:09:00', 'she has ball'], ['a', '2018...
<p>Here's my approach:</p> <pre><code># as the final expected output is sorted by id and time # we start by doing so to the whole data df = df.sort_values(['id','time']) # mark the rows containing the word `ball` has_ball = (df.equipment.str.contains(r'\bball\b') ) # cumulative number of rows with `ball` in the grou...
python|pandas|dataframe
0
363,950
58,507,877
Pairwise calculation on a 1D-Array with Matrix-like output
<p>Assume you have the following 1D-Array:</p> <p><code>array([1,2,3,4,5])</code></p> <p>I want to perform different (simple) calculations between each combination of numbers (such as addition, subtraction, etc.) resulting in a Matrix-type output (without duplication), i.e. for the above array, the output should be a...
<p>For anyone interested, I managed to find a solution using pairwise_distances from scikit-learn. This will by default just calculate the absolute distance between any pair, but it is possible to supply a custom function that takes two arguments, i.e. two numbers of a pair, for more elaborate calculations. It will req...
numpy|numpy-ndarray
2
363,951
58,405,215
Is input order affecting regression model result?
<p>I have X and y to train a model.</p> <p>X has input x1,x2,x3,x4.</p> <p>And I use this model to predict new data new_X.</p> <p>but input in new_X are x3,x2,x1,x4.</p> <p>X and X_new are dataframes witm many features.</p> <p>Will the order of columns affect model result?</p> <p>For example: model.predict_prob...
<p><strong>Short answer:</strong> YES</p> <hr> <p><strong>Long answer:</strong></p> <p>If the variables <code>x1,x2,x3,x4</code> in <code>X</code> represent the same things as variables <code>x3,x2,x1,x4</code> in <code>X-new</code>, <strong>then yes</strong>.</p> <p>The reason is simple. Think about the following....
python|scikit-learn|jupyter-notebook|logistic-regression|sklearn-pandas
0
363,952
58,480,225
Iterate through dataframe to obtain a desired result
<p>I have a dataframe which has 3 fields </p> <pre><code>date_1, date_2, num_Days </code></pre> <p><code>num_Days</code> is a derived column which is calculated by <code>date_2 - date_1</code></p> <p>I want to bring the <code>num_Days</code> in the range of 1-30. Currently it takes on more values than that. </p> <...
<p>When working with Pandas it's usually best to think of everything as vectorized operations. So let's start by generating a series of random deltas in the range of <code>delta_min</code> to <code>delta_max</code> inclusive, assuming your dataframe is called <code>df</code>:</p> <pre><code>rand_days = np.random.randi...
python|pandas|numpy
0
363,953
58,457,332
How to assign the values in a list to a column/row in a dataframe?
<p>How to assign the values in a list to a column/row in python dataframe? </p> <p>I could only do the vice versa with the command: <code>list_name = df.iloc[x, y]</code>. However, when I tried to command <code>df.iloc[x, y] = list_name</code>, I failed to convert the values in list_name to <code>df.iloc[x, y]</code>....
<p>Unfortunately, the <code>iloc</code> indexing isn't designed for setting in quite as versatile a way as it is for getting. There is, however, a bit of a workaround if you want to have your row <code>x</code> and column <code>y</code> to be dynamic like in your example.</p> <p>For the following, I've used the <a hre...
python|pandas|dataframe
1
363,954
58,360,469
Joining two data frames that appear to be same type gives error 'ValueError: You are trying to merge on object and int64 columns'
<p>I have two data frames, sessions1 and sessions2 that I would like to join on field 'ga:dimension1'.</p> <pre><code>sessions1.info() &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 15775 entries, 0 to 15774 Data columns (total 9 columns): ga:dimension1 15775 non-null object ga:date ...
<p>Use <code>merge</code></p> <pre><code>sessions_combined = sessions1.merge(sessions2, on = 'ga:dimension1', how = 'left') </code></pre>
python|pandas
0
363,955
58,594,879
How can I tell Pandas read_csv to use multiple whitespaces as separators but not single whitespaces?
<p>I want to read in a Pandas dataframe from csv, where there are single whitespaces inside column names and the separators are multiple whitespaces. How can I tell Pandas to use only more than one consecutive whitespace as separator but ignore single whitespaces?</p>
<p>With specific regex pattern for <code>sep=</code> option:</p> <pre><code>df = pd.read_csv(sep='\s{2,}') </code></pre> <ul> <li><code>\s{2,}</code> - quantifier, matches any whitespace character between <code>2</code> and unlimited times, as many times as possible</li> </ul>
python|regex|pandas
6
363,956
58,202,858
on a numpy 2D array - how to set last N array elements in each row to zero when N changes over rows
<p>Say, I have a 2D numpy array consists of 20 elements, for example:</p> <pre><code>arr = np.array([[1, 2, 15, 7],[9, 11, 17, 19],[5, 7, 5, 8],[19, 4, 1, 45],[10, 7, 14, 8]]) </code></pre> <p>and an additional array:</p> <pre><code>to_zero = np.array([0, 2, 1, 3, 2]) </code></pre> <p>now, for each row <code>i</cod...
<p>Use <code>broadcasted-comparison</code> to get a mask of those trailing ones and then mask the input -</p> <pre><code>In [63]: r = np.arange(arr.shape[1])[::-1] In [66]: mask = to_zero[:,None]&gt;r In [69]: mask # mask of trailing places to be reset in input Out[69]: array([[False, False, False, False], [...
python|numpy|vectorization
5
363,957
58,386,012
How can I group a list of strings by another list of strings using Python?
<p>I have two lists:</p> <p><strong>List 1</strong></p> <pre><code>filenames = ['K853.Z', 'K853.N', 'K853.E', 'K400.Z', 'K400.N', 'K400.E'] </code></pre> <p><strong>List 2</strong></p> <pre><code>l = ['K853', 'K400'] </code></pre> <p>I want to iterate through the <code>filenames</code> list and group the strings b...
<p>you could just use a list generator like this:</p> <pre><code>new = [[name for name in filenames if(name.startswith(prefix))] for prefix in l] </code></pre> <p>This would provide you with a list of list, where for each index of l you would get a list of files with its prefix at the same index in the new list.</p>
python-3.x|loops|pandas-groupby|python-3.7
1
363,958
58,545,224
how to plot two bar graphs
<p>Qs</p> <p>Use pandas to create a DataFrame that reports the number of graduates working at jobs that do require college degrees ('college_jobs'), and do not require college degrees ('non_college_jobs'). Assign this to a variable named df1.</p> <p>my code</p> <ul> <li>DataFrame of college and non-college job sums<...
<p>Probably you should reorganize your DataFrame in such a way that for each "other" classification (men, women, full time, part time and so on) it contains just <strong>two rows</strong>:</p> <ul> <li>first - for working at jobs requiring college education,</li> <li>second - for jobs which don't require it.</li> </ul...
python|pandas|matplotlib
0
363,959
58,509,444
Plain Pandas Dataframe Pivot
<p>I have a pandas dataframe that has six rows and nine columns. It is formatted like so:</p> <pre><code> 0 1 2 lat 33 33 32 long 66 88 78 input_string string string string status OK ok ok </code></pr...
<p>As what Quang Hong said, your question is not a pivot one but a transpose one - to invert rows and columns of a dataframe. df.T will give the transpose of df</p>
python|pandas|dataframe
0
363,960
58,544,809
pandas dictionary to list of dictionary key/values
<p>I am trying to perform list comprehension with nested list of dictionary from data-frame and I get this after some tryouts. Is there pandas functionality that I might be missing than using for loops?</p> <pre><code>file = ['a.txt','a.txt','b.txt','c.txt'] year = ['2016','2017','2016','2018'] paper = ['Biology','Bio...
<p>You almost had it correct above. You can use dfd.items() to iterate over both the keys and values at once of your dfd dict. Then you can ignore the key part of the tuple and just add the value to the list comprehension like this:</p> <pre><code>d = [v for k,v in dfd.items()] </code></pre> <p>Just tested that with ...
python-3.x|pandas|dictionary-comprehension
1
363,961
58,572,818
np.linalg.norm and how to deal with machine epsilon
<p>I have this fairly simple problem. I want to calculate Euclidean distance with numpy with this code:</p> <pre><code>a= np.array([1,2,3]) b= np.array([2,3,4]) print((np.linalg.norm(a-b))**2) </code></pre> <p>This yields <code>2.9999999999999996</code>, However, the answer should be <code>3</code>. How do I achieve...
<p>In general, you can use <a href="https://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.isclose.html" rel="nofollow noreferrer">np.isclose</a> to compare float values.</p>
python|numpy|euclidean-distance|epsilon
1
363,962
58,247,186
Sorting columns with pandas / xslxwriter after adding formulas
<p>I have my dataframe with few columns, that's actually irrelevant to this problem, but I wanted to sort my columns in specific order.</p> <p>Now, the issue is that I have a bunch of formulas that refer to excel tables (that I'm creating with xslxwriter worksheet.add_table), like for example:</p> <pre><code>planned_...
<p>It looks like there are two issues here: sorting and the table formula.</p> <p>Sorting is something that Excel does at runtime, in the Excel application and it isn't a property of, or something that can be triggered in, the file format. Since XlsxWriter only deals with the file format it cannot do any sorting. Howe...
python|pandas|xlsxwriter
1
363,963
58,389,183
ARM softfp vs hardfp performance
<p>I have an ARM based platform with a Linux OS. Even though its gcc-based toolchain supports both hardfp and softfp, the vendor recommends using softfp and the platform is shipped with a set of standard and platform-related libraries which have only softfp version.</p> <p>I'm making a computation-intensive (NEON) AI...
<p>Normally, all objects that are linked together need to have the same float ABI. So if you need to use this <code>softfp</code> only library, i'm afraid you have to compile your own software in <code>softfp</code> too.</p> <p>I had the same question about mixing ABIs. See <a href="https://stackoverflow.com/questions...
performance|gcc|arm|tensorflow-lite|eabi
0
363,964
58,286,170
How to cut the csv data into equal parts using python and panda
<p>I want to cut my CSV file equal parts and then plot the graph separately then one graph to overlap all the graph into one graph.</p>
<p>Something like this:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('filepath') n_splits = 4 dfs = [] for x in range(n_splits): dfs.append(df[x*int(len(df)/n_splits):(x+1)*int(len(df)/n_splits)]) fig = plt.figure() for frame in dfs: plt.plot(frame['col1'], frame['co...
pandas|csv|jupyter-notebook
0
363,965
58,427,004
Tensorflow neural network doesn't optimize properly
<p>I am a beginner to neural networks and TensorFlow, I have tried the following code for handwritten digit classification (single layer perceptron model)</p> <p>I have downloaded the dataset from kaggle which contains the first column as the digit and the next 784 columns the pixel values.</p> <pre><code> import ...
<p>Problem was caused, because pixel values was not normalized. Normalization is appropriate because optimization algorithms works better if inputs are from some appropriate range 0-1 for example. For pixel values is enough division by 255.</p>
python-3.x|tensorflow|neural-network|deep-learning|tensorflow-datasets
0
363,966
58,518,660
Expansion of dataset based on few constraints
<p><strong>EDIT :</strong> </p> <p>I have a dataframe with the following fields, </p> <pre><code>I_Code Date_1 Date_2 Count real_Count 4 01/09/2019 02/08/2019 112 1 4 01/09/2019 03/08/2019 178 3 1 01/09/2019 04/08/2019 174 6 4 01/09/2019 04/08/2019 174 6 1 01/09/2019 05/08/2019 194 8 4 01/09/...
<p>You can use <code>.max(axis=1)</code> over the results of <code>.nunique()</code> to get the maximum number of unique values (across all other columns) for every value of <strong>Date_2</strong>.</p> <p>Then give the resulting Series a name and join it back with the original dataframe.</p> <pre><code>df.join(df.gr...
python|r|pandas|numpy
0
363,967
58,605,279
Tensorflow - Value Error in model.fit - How to fix
<p>I am trying to train a Deep Neural Network using MNIST data set.</p> <pre><code>BATCH_SIZE = 100 train_data = train_data.batch(BATCH_SIZE) validation_data = validation_data.batch(num_validation_samples) test_data = scaled_test_data.batch(num_test_samples) validation_inputs, validation_targets = next(iter(validatio...
<p>The tf doc will give you more clues why you get the error. </p> <p><a href="https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit</a></p> <pre><code>validation_data: Data on which to evaluate the loss and any model met...
python-3.x|tensorflow|machine-learning|neural-network|mnist
2
363,968
58,237,216
Python PyInstaller 4.0 packaging TensorFlow 2.0 project not working ImportError: cannot import name 'pywrap_tensorflow'
<p>I am trying to bundle a python application using pyinstaller that uses tensorflow.</p> <p>I am now using Pyinstaller-4.0.dev0+2f4426f52, Tensorflow 2.0, Keras 2.3 and Python 3.7.3 all in a virtual environment.</p> <p>I have tried various older versions, but each older version had a different issue that I could not...
<p>Go to this path <code>/usr/local/lib/python3.7/dist-packages</code><br /> Copy the <code>tensorflow_core</code> folder, paste it to your Project Directory and rename it as:</p> <pre><code>tensorflow from tensorflow import keras </code></pre> <p>After <code>import tensorflow as tf</code>, it works for me. Please, che...
python|tensorflow|keras|pyinstaller
0
363,969
58,204,710
How can I train a sequential model in keras, giving a list as outputs and inputs?
<p>I am very new to Keras and to machine learning in general, but here is what I want. I have a list of inputs (1 value for every input node) and a list of targets (1 value for every output node).</p> <pre><code> input_list = [1, 0, 1, 0, 1, 0] # maybe longer wanted_output_list = [1, 0, 0, 0] # also maybe long...
<p>When defining your model, you specified a model that accepts an input with 6 features, and output a vector with 3 component. You training data, however, is not shaped correctly (nor your labels, by the way). You should shape your data the way you have defined your model. In this case, that means that each sample of ...
python|tensorflow|keras
2
363,970
58,506,208
Python Pandas Update Values According to Multiples of "x" Values
<p>My input dataframe:</p> <pre><code> Order Package 1 5 6 2 4 3 3 7 10 4 2 1 5 9 4 6 12 5 7 1 1 </code></pre> <blockquote> <p>If my "Order" values are lower than "Package" values it should be updated as "0(zero)".</p> <p...
<p>Another approach:</p> <pre><code>df['Order'] -= df['Order'] % df['Packages'] </code></pre> <p>Output:</p> <pre><code> Order Package 1 0 6 2 3 3 3 0 10 4 2 1 5 8 4 6 10 5 7 1 1 </code></pre>
python|pandas|dataframe
1
363,971
58,594,072
How to append K random values from DataFrame to list of lists with no duplicates?
<p>I have the following data frame of the form: </p> <pre><code>1 2 3 4 5 6 7 8 A C C T G A T C C A G T T A D N Y F V H Q A F D </code></pre> <p>I need to randomly select a column <em>k</em> times where <em>k</em> is the number of columns in the given sample. My program creates a list of empty lists of size <em>k</e...
<p>You can use <code>numpy.random.shuffle</code> to just shuffle the column indexes. Because from your question, this is what I assume you want to do.</p> <p>An example:</p> <pre><code>import numpy as np to_shuffle = np.array(df.columns) np.random.shuffle(to_shuffle) print(to_shuffle) </code></pre>
python|python-3.x|pandas|list|bioinformatics
1
363,972
58,424,046
How do I pull data from a specific column using Python and pandas in a Jupyter notebook?
<p>I'm pulling data from a previously established df called police_2013_by_date. Within that df, there are columns named: shift, disposition_desc and unit.</p> <p>I need to make a subset of data for all disposition_desc of "DISREGARD / SIGNAL 9" so that I can determine what percentage of all calls were for "DISREGARD ...
<p>Your question seems different from what you're really looking for. </p> <pre><code>police_2013_by_date.disposition_desc.value_counts(normalize=True) </code></pre> <p>will get you all proportion of disposition_desc, including "DISREGARD / SIGNAL 9".</p> <p>But if the question only for getting the specific value in...
python|pandas|jupyter
0
363,973
58,523,194
I have two dataframes DF1 and DF2, what is the best way to append rows that meet a conditional from DF2 to DF1 at specific indices?
<p>I am trying to append a row from dataframe2 to dataframe1 at the end of each group in dataframe1, but only those rows from dataframe2 that match the column value in dataframe 1 (in this case: that match on 'Name'). </p> <p>If I have the dataframe1 given by: </p> <pre><code>data = { 'Name':['Jill', 'Jill', 'Jil...
<p>This should work</p> <pre><code>compare = df1.Name.unique() df3 = df2[df2['Name'].isin(compare)] df4 = df1.append(df3) df5 = df4.sort_values(['Name','Age']) df5 = df5.reset_index(drop=True) print(df5) </code></pre> <p>Output:</p> <pre><code> Age Gender Name 0 24.0 NaN Jack 1 65.0 NaN Jac...
python|pandas
1
363,974
58,179,604
strings to column using python
<p>I have entire table as string like below: a= "id;date;type;status;description\r\n1;20-Jan-2019;cat1;active;customer is under\xe9e observation\r\n2;18-Feb-2019;cat2;active;customer is genuine\r\n"</p> <p>inside string we do have some ascii code like \xe9e so we have to convert the string to non-ascii</p> <p>My expe...
<p>Here is a bit of a hacky answer, but given that your question isn't really clear, this should hopefully be sufficient.</p> <pre><code> import pandas as pd import numpy as np import re a="id;date;type;status;description\r\n1;20-Jan-2019;cat1;active;customer is under\xe9e observation\r\n2;18-Feb-2019;cat2;active;...
python|string|pandas|python-2.7
0
363,975
68,939,141
Envelope or convex hull of set of geometries
<p>I have a problem which involves grouping geometries that I am trying to solve. The idea is to group a number of geometrical objects into &quot;sets&quot; or large polygons. Basically, it means either finding the convex hull or the envelope of the union of these polygons as a set (which ever is easiest). Note that th...
<p><code>geopandas.envelope(df)</code> will give you a bounding box of everything</p> <pre><code>df['new_col']=0 df=df.dissolve(by='new_col') </code></pre> <p>Will merge everything into a multigon, you can use another feature in 'by' to merge into len(unique(feature)) polygons.</p>
python|pandas|geopandas
1
363,976
69,277,384
Understanding the architecture of an LSTM for sequence classification
<p>I have this model in pytorch that I have been using for sequence classification.</p> <pre><code>class RoBERT_Model(nn.Module): def __init__(self, hidden_size = 100): self.hidden_size = hidden_size super(RoBERT_Model, self).__init__() self.lstm = nn.LSTM(768, hidden_size, num_layers=1, bi...
<p>Your code is a basic LSTM for classification, working with a single rnn layer.</p> <p>In your picture you have multiple LSTM layers, while, in reality, there is only one, <code>H_n^0</code> in the picture.</p> <ol> <li>Your input to LSTM is of shape <code>(B, L, D)</code> as correctly pointed out in the comment.</li...
pytorch|lstm|recurrent-neural-network
1
363,977
68,981,874
What is sharding in machine learning and how to do sharding in Tensorflow?
<p>What is sharding in the context of machine learning specifically ( a more generic antic question is asked [here][1] ) and how is it implemented in Tensorflow ?</p> <p>What is referred to as sharding, why do we need sharding altogether, when speaking about the data pipeline in machine learning ?</p>
<p>In Tensorflow - In <code>Dataset</code> the function <code>shard()</code> creates a Dataset that includes only 1/num_shards of this dataset. Shard is deterministic. The Dataset produced by A.shard(n, i) will contain all elements of A whose index mod n = i.</p> <pre><code>A = tf.data.Dataset.range(10) B = A.shard(num...
python|tensorflow|machine-learning|input|sharding
1
363,978
69,274,714
Grouping and pivoting dataframe
<p>I have a dataframe that looks like this:</p> <pre><code>Names Company Values Period HeadCount Google 1000 1 HoursWorked Google 500 1 HeadCount Microsoft 600 1 HoursWorked Microsoft 200 1 HeadCount Google 2000 2 HoursWorked Google 100 2 </co...
<p>Use <code>pivot_table</code>:</p> <pre><code>&gt;&gt;&gt; df.pivot_table(index=['Company', 'Period'], columns='Names', values='Values') \ .rename_axis(None, axis=1).reset_index() Company Period HeadCount HoursWorked 0 Google 1 1000 500 1 Google 2 2000 ...
python|pandas
2
363,979
69,052,804
groupby is not functioning when working with multiple columns in numpy.where
<p>I'm trying to add multiple columns to <code>numpy.where</code> <code>groupby</code> question <a href="https://stackoverflow.com/questions/60171017/using-pandas-groupby-and-numpy-where-together-in-python">here</a></p> <p>but got error when I add another column</p> <pre><code>import pandas as pd import numpy as np df ...
<p>Try:</p> <pre><code>m = df['Gender'].eq('M') df['new'] = df.assign(mask=m).groupby(['Occupation', 'Emp_Code'])['mask'] \ .transform('mean').mul(100) df.loc[~m, 'new'] = 0 </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; df Occupation Emp_Code Gender new 0 d a M 50.0 1 ...
python|pandas|dataframe|numpy
1
363,980
69,114,516
Merging dfs when values of columns are str that are identical at specific locations of the str's slice
<p>let's say I have two dfs as follows:</p> <pre><code>data1= {'Column': ['01A01', '03C12', '04F23']} df1=pd.DataFrame(data1) data2 = {'Plate': ['1A1', '3D14', '1B6']} df2=pd.DataFrame(data2) </code></pre> <p>I would like to find the values (str) from df1 that their second and third letter match the first and second l...
<p>Just merge on the sliced strings.</p> <p>Code below</p> <pre><code>df1.merge(df2, how='left', left_on=df1['Column'].str[1:3], right_on=df2['Plate'].str[0:2]) </code></pre>
python|pandas|compare
3
363,981
68,894,537
Extend multilevel dataframe using existing index name with reindex Pandas
<p>The objective is deepen existing multiindex <code>df</code>.</p> <p>Such that, given a <code>df</code> as below</p> <pre><code> col1 col2 mylevelA_caseA__VAR_A bar one -1.012046 0.808332 mylevelA_caseA__VAR_B bar two -0.558629 -0.358550 mylevelA_caseB__VAR_A baz one 1...
<p>Use a small list comprehension on the index and make a new multiindex:</p> <pre><code>import re from itertools import chain df.index = pd.MultiIndex.from_tuples([tuple(chain(re.split('__?', e[0], maxsplit=2), e[1:])) for e in df....
python|pandas|multi-index
2
363,982
69,089,504
Delete words with regex patterns in Python from a dataframe
<p>I'm playing around with regular expression in Python for the below data.</p> <pre><code> Random 0 helloooo 1 hahaha 2 kebab 3 shsh 4 title 5 miss 6 were 7 laptop 8 welcome 9 pencil </code></pre> <p>I would like to delete the words which have patterns of repeated letters (e.g. b...
<p>You can use <code>Series.str.contains</code> directly to create a mask and disable the user warning before and enable it after:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import warnings data = {'Random' : ['helloooo', 'hahaha', 'kebab', 'shsh', 'title', 'miss', 'were', 'laptop', 'welco...
python|regex|pandas|dataframe
4
363,983
69,011,005
How do I check if the dtype of an array-like (or scalar) object is a float
<p>This seems like it should be super simple, but the answer is eluding me. I Have done a bunch of google-searches for the answer but don't feel like any of the results really answered my question, perhaps I'm just searching for the wrong thing? please help:</p> <p>I am writing a function:</p> <pre><code>def cheese(arr...
<p>I think you want <code>np.issubdtype</code>:</p> <pre><code>In [871]: np.issubdtype(np.array([1.23,3]).dtype, np.float64) Out[871]: True In [872]: np.issubdtype(np.array([1.23,3]).dtype, np.floating) Out[872]: True In [873]: np.issubdtype(np.array([1.23,3]).dtype, np.inexact) Out[873]: True In [874]: np.issubdtype(n...
python|numpy|typechecking
2
363,984
69,084,932
select a range of specific rows with pandas
<p>I have an ascii file with two columns and 365 rows. A sample is given below. following</p> <pre><code>1 255.45833333333334 2 261.5833333333333 3 315.0416666666667 4 325.0833333333333 5 303.625 6 273.8333333333333 7 279.5416666666667 8 255.58333333333334 9 197.54166666666666 10 222.625 11 276.6666...
<p>Try something like:</p> <pre><code>df.iloc[[*range(1, 5), *range(10, 13)]] </code></pre>
python|pandas|rows
1
363,985
68,886,013
Calculating multi year 5-day running percentile
<p>I need to calculate 3-day running 90th percentile value for each calendar day from multi-year data. I have 30-year daily datasets looking like this,</p> <pre><code> year month day value DATE 01/01/1980 1980 1 1 12.3957 02/01/1980 1980 1 2 8.2678 03/01/19...
<p>I have managed to solve the problem. First, I dropped Feb 29. Therefore, I would have either a 365-day or 360-day dataset. Then, I changed the datetime index to string.</p> <pre><code>df.index = df.index.strftime('%m-%d') </code></pre> <p>I used enumerate on the unique index values to loop through all days. I used t...
python|pandas|datetime|indexing|percentile
0
363,986
68,912,016
how can I convert Regression data into Classification data?
<p>I have a data with columns</p> <pre><code> ['symboling', 'Company', 'fueltype', 'aspiration', 'doornumber', 'carbody', 'drivewheel', 'enginelocation', 'carlength', 'carwidth', 'curbweight', 'enginetype', 'cylindernumber', 'enginesize', 'fuelsystem', 'horsepower', 'price', 'total_mpg'] </code></pre> <p>whe...
<p>Let's suppose that we have a dataframe with 2 continuous columns, named <code>x1</code> and <code>x2</code>:</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns x1 = np.random.rand(100) x2 = np.random.rand(100) df = pd.DataFrame({&quot;x1&quot;:x1,&quot;x2&quo...
pandas|machine-learning|scikit-learn|regression|classification
1
363,987
68,984,120
Is there an advantage to using json.dumps vs pandas.to_json to convert a pyspark dataframe to a json string?
<p>I would like to convert a simple pyspark dataframe into a json string in python. It looks like I have a couple of options for this. For example, if I have a dataframe of People:</p> <pre><code>+----+----------+ |name| dob| +----+----------+ | Mia|1980-01-31| |Jose|1967-05-15| |Carl|1995-11-25| +----+----------...
<p>Why don't you simply use :</p> <pre class="lang-py prettyprint-override"><code>df.write.json() </code></pre> <p>In theory, you are not supposed to process your data with spark and then collect them in python ... of course, you can do it, nobody will stop you but the amount of data processed in parallele with spark s...
python|json|pandas|pyspark
0
363,988
68,874,807
How to do Normalization in CNN?
<p>I am new to CNN, and I am learning it with Food Classification. Here is my code. In the <strong>DATASET</strong> part, I change the train dataset and validation dataset from numpy to tensor. At that point, the shape of tensor is (<code>[9866, 128, 128, 3]</code>). Since the channel 3 need to be in the first index, s...
<p>If you wan to normalize the images, you can add transforms.Normalize in the train_transform and test_transform (in your 2nd code snippet). Something like this:</p> <pre><code>train_transform = transforms.Compose([ transforms.ToPILImage(), transforms.RandomHorizontalFlip(), transforms.RandomRotation(15),...
machine-learning|pytorch|conv-neural-network
0
363,989
69,103,528
How to make inference with Huggingface deep learning container from Lambda using Serverless framework
<p>This is a question from ML newbee :-)</p> <p>I am building AWS StepFunction with Serverless framework and one of the steps is intended to deploy a Sagemaker endpoint with HuggingFace deep learning container (DLC).</p> <p>The problem is that I could not make Lambda to work with SageMaker (to build estimator).</p> <p>...
<p>Answer found:</p> <ol> <li>API is deployed using Sagemaker studio like described <a href="https://github.com/C24IO/SageMaker-HuggingFace-Workshop/blob/main/inference/lab1_deploy_transformer_model_from_s3/1_deploy_transformer_model_from_s3.ipynb" rel="nofollow noreferrer">here</a></li> </ol> <ol start="2"> <li>The in...
python|aws-lambda|serverless-framework|amazon-sagemaker|huggingface-transformers
0
363,990
69,110,975
Plot the transformed (augmented) images in pytorch
<p>I want to use one of the image augmentation techniques (for example rotation or horizontal flip) and apply it to some images of the CIFAR-10 dataset and plot them in PyTorch.</p> <p>I know that we can use the following code to augmented images:</p> <pre><code>from torchvision import models, datasets, transforms from...
<blockquote> <p>when this code is used, all CIFAR10 datasets are transformed</p> </blockquote> <p><em>Actually, the transform pipeline will only be called when images in the dataset are fetched via the <code>__getitem__</code> function by the user or through a data loader. So at this point in time, <code>train_set</cod...
python|machine-learning|deep-learning|pytorch|image-augmentation
1
363,991
68,978,614
Poorer performance when change optimizer from Adam to Nesterov
<p>I am running an image segmentation code on Pytorch, based on the architecture of Linknet. The optimizer is initially set as:</p> <pre><code>self.optimizer = torch.optim.Adam(params=self.net.parameters(), lr=lr) </code></pre> <p>Then I change it to Nesterov to improve the performance, like:</p> <pre><code>self.optimi...
<p>Seems like your question relies on the assumption that SGD with Nesterov would definitely perform better than Adam. However, there is no learning algorithm that is better than another no matter what. You always have to check it given your model (layers, activation functions, loss, etc.) and dataset.</p> <p>Are you i...
optimization|deep-learning|pytorch
1
363,992
69,173,363
Creating a heatmap with uneven block sizes / stacked bar chart using Python
<p>I want to create a heatmap in Python that is similar to what is shown on the bottom of this screenshot from TomTom Move: <a href="https://d2altcye8lkl9f.cloudfront.net/2021/03/image-1.png" rel="nofollow noreferrer">https://d2altcye8lkl9f.cloudfront.net/2021/03/image-1.png</a> (source: <a href="https://support.move.t...
<p>Here is a simple example of a heatmap with different box sizes. Based on the example &quot;Heatmap with Unequal Block Sizes&quot; <a href="https://plotly.com/python/heatmaps/" rel="nofollow noreferrer">https://plotly.com/python/heatmaps/</a>. Just set the xe variable to all of the x-axis edges and z to the values ...
python|pandas|heatmap|stacked-chart|tomtom
0
363,993
69,074,602
How to fix an error code that removes whitespace separating columns in fwf file python pandas read_fwf
<p>I am reading in an fwf file (using python/pandas' read_fwf) that normally has 2-3 spaces between the columns. However, when a certain error is thrown, the error code produced in the second column takes up extra spaces, and therefore removes the whitespace between the first and second columns, so the computer reads i...
<p>Try defining a <code>colspecs</code> to <code>read_fwf</code>, <code>file.txt</code> copied from your sample:</p> <pre><code>import pandas as pd colspecs = [(0, 7), (7, 14), (14, 21), (21, 29), (29, 33)] df = pd.read_fwf(&quot;file.txt&quot;, colspecs=colspecs, header=None) print(df) </code></pre>
python|pandas|read-fwf
0
363,994
68,944,657
Trying to create multiple boxplots using df.plot(kind='box) and receiving "IndexError: index 0 is out of bounds for axis 0 with size 0"
<p>I am working through the exercises in Jason Brownlee's &quot;Machine Learning Mastery with Python&quot; and in Chapter 21, we use the <a href="https://archive.ics.uci.edu/ml/datasets/Connectionist+Bench+(Sonar,+Mines+vs.+Rocks)" rel="nofollow noreferrer">Sonar dataset found in the UCI repository</a>.</p> <p>I've rea...
<p>This box plot doesn't work if the column headers are unnamed. After you name each of the columns, the box plot should work.</p>
python|pandas|dataframe|matplotlib|boxplot
0
363,995
69,204,639
How to numerically solve difference equations in python
<p>I am trying to learn how to solve difference equations (also called recurrence relations) using python.</p> <p>The problem in question is the equation</p> <pre><code>$x_{n+2} - 4x_{n+1} - x_{n} = 0$ where x_0 = 1 and x_1 = 1 </code></pre> <p>Which outputs the sequence: n = 1, 1, 5, 21, 89, 377, ....</p> <p...
<p>Difference equations are just recursive relationships. The mathematics behinds them can be quite tricky... finding the basis of the companion matrix, ... but you need a solid background. For that stuffs I suggest you <code>sympy</code>which is a mathematics package for symbolic manipulation.</p> <pre><code>import fu...
python|numpy|math|numerical-methods|difference-equations
2
363,996
69,115,810
Division in pandas dataframe
<p>I am trying to divide my data frame with one of its columns:</p> <p>Here is my data frame:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">A</th> <th style="text-align: center;">B</th> <th style="text-align: center;">C</th> </tr> </thead> <tbody> <tr> <td styl...
<p>try this:</p> <pre><code>d = { 'A': [1,2,3], 'B': [10,20,15], 'C': [10,30,33] } df = pd.DataFrame(d) df['B'] = df['B']/df['A'] df['C'] = df['C']/df['A'] print(df) </code></pre> <p>Output:</p> <pre><code> A B C 0 1 10.0 10.0 1 2 10.0 15.0 2 3 5.0 11.0 </code></pre>
python|pandas|dataframe
2
363,997
69,006,674
How to sort numpy array by row sum and extract top N rows
<p>For example, given matrix</p> <pre><code>array([[ 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23], [ 0, 1, 2, 3, 4, 5], [24, 25, 26, 27, 28, 29]]) </code></pre> <p>and top_n=3, it should return</p> <pre><code>array([[24, 25, 26, 27, 28, 29], [18, 19,...
<p>You can use this simple 1-liner <code>a[np.argsort(a.sum(axis=1))[:-top_n-1:-1]]</code></p> <p><code>a.sum(axis=1)</code> sums along axis 1</p> <p><code>np.argsort(..., axis=0)</code> argsorts along axis 0 (<code>axis=0</code> is default option anyway so could be omitted)</p> <p><code>...[:-top_n-1:-1]</code> picks ...
python|arrays|numpy|indexing
5
363,998
69,229,397
Why can't torchtext find a symbol _ZN2at6detail10noopDeleteEPv?
<p>Why can't torchtext find this symbol?</p> <pre><code>(synthesis) miranda9~/ultimate-utils $ python ~/type-parametric-synthesis/src/main.py --reproduce_10K --serial --debug --num_workers 0 Traceback (most recent call last): File &quot;/home/miranda9/type-parametric-synthesis/src/main.py&quot;, line 32, in &lt;mo...
<p>Reinstall torchtext with the current version of pytorch:</p> <p>e.g.</p> <pre><code>conda install -y torchtext -c pytorch </code></pre> <p>or for older versions of pytorch <a href="https://stackoverflow.com/questions/65575871/torchtext-importerror-in-colab">torchtext ImportError in colab</a></p> <pre><code>conda ins...
pytorch
2
363,999
68,880,129
How to display a dataframe multiple times?
<p>Is there a way to display multiple times dataframe? Basically, I would like to see the df X time in a row. I've tried via for loop but didn't manage to do so.</p> <pre class="lang-py prettyprint-override"><code>data = {'Counter':list(range(1, 10)), 'Country':['USA','UK','UK','USA','UK','USA','UK','USA','UK']...
<p>This is a peculiar request, details on what you really want to achieve would be appreciated.</p> <p>Nevertheless, you can use the following loop (example for 3 times):</p> <pre><code>for i in range(3): print(df) </code></pre> <p>or concatenate your data n times:</p> <pre><code>print(pd.concat([df]*3)) </code></p...
python|pandas
0