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
3,700
33,804,410
Using IBM_DB with Pandas
<p>I am trying to use the data analysis tool Pandas in Python Language. I am trying to read data from a IBM DB, using <strong>ibm_db</strong> package. According to the documentation in Pandas website we need to provide at least 2 arguments, one would be the sql that would be executed and other would be the connection o...
<p>On doing further studying the package, i found that I need to wrap the IBM_DB connection object in a ibm_db_dbi connection object, which is part of the <a href="https://pypi.org/project/ibm-db/" rel="noreferrer">https://pypi.org/project/ibm-db/</a> package.</p> <p>So</p> <pre><code>conn = ibm_db_dbi.Connection(con) ...
python|pandas|db2
19
3,701
33,760,643
Finding squared distances beteen n points to m points in numpy
<p>I have 2 numpy arrays (say <code>X</code> and <code>Y</code>) which each row represents a point vector.<br> I would like to find the squared euclidean distances (will call this 'dist') between each point in X to each point in Y.<br> I would like the output to be a matrix D where <code>D(i,j)</code> is <code>dist(X(i...
<p>Scipy has the <a href="http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.spatial.distance.cdist.html#scipy.spatial.distance.cdist" rel="nofollow"><code>cdist</code></a> function that does exactly what you want:</p> <pre><code>from scipy.spatial import distance distance.cdist(X, Y, 'sqeuclidean') </co...
python|performance|numpy|euclidean-distance
8
3,702
23,892,443
Show all the nan in pandas?
<p>I want to find all the rows which have a specific field as <code>NaN</code> using pandas.</p> <p>I have seem some code on the internet that it says to fillnan with something and find that something. Isn't there any easier way?</p>
<p>You can use <code>isnull</code>:</p> <pre><code>In [302]: df = pd.DataFrame({"A": [1,np.nan,np.nan, 2], "B": range(4)}) In [303]: df Out[303]: A B 0 1 0 1 NaN 1 2 NaN 2 3 2 3 [4 rows x 2 columns] In [304]: df["A"].isnull() Out[304]: 0 False 1 True 2 True 3 False Name: A, dtype: bool ...
python|pandas|nan
5
3,703
15,262,527
How to pull a date index out of a pandas dataframe to use as x-axis in matplotlib
<p>I am trying to plot data in a pandas dataframe, using the index, which is a date and time, as the x-axis, and the rest of the data in the dataframe as the actual data. Here's what I am trying now:</p> <pre><code>from matplotlib.finance import candlestick2 bars[['open','high','low','close']].head() tickdatetime ...
<p>As Chang She noted, <code>bars.index</code> is what you want, not <code>bars.ix</code>. <code>bars.index</code> returns an Index object that's essentially a Series with your indexes. This is what you want. bars.ix returns an _NDFrameIndexer, something that seems very poorly documented, but is some sort of view of th...
matplotlib|pandas
5
3,704
62,406,673
Convert dataset of points with each x and y separate to list of points
<p>So I have a dataset that looks like this:</p> <pre><code> x0 y0 x1 y1 x2 y2 0 0 5 1 5 1 4 1 1 5 1 4 2 4 2 1 4 2 4 2 3 3 2 4 2 3 3 3 4 2 3 3 3 3 2 </code></pre> <p>This I gathered reading a csv that looks like this:</p> <pre><code> x...
<pre><code>df.to_numpy().reshape(-1,3,2).tolist() </code></pre> <p>Result:</p> <pre><code>[[[0, 5], [1, 5], [1, 4]], [[1, 5], [1, 4], [2, 4]], [[1, 4], [2, 4], [2, 3]], [[2, 4], [2, 3], [3, 3]], [[2, 3], [3, 3], [3, 2]]] </code></pre>
python|pandas
1
3,705
62,164,489
1d array from columns of an ndarray
<p>This is the array I have at hand:</p> <pre><code>[array([[[ 4, 9, 1, -3], [-2, 0, 8, 6], [ 1, 3, 7, 9 ], [ 2, 5, 0, -7], [-1, -6, -5, -8]]]), array([[[ 0, 2, -1, 6 ], [9, 8, 0, 3], [ -1, 2, 5, -4], [0, 5, 9, 6], [ 6, 2, 9, 4]]]), arr...
<p>You can do this with a single <a href="https://numpy.org/doc/1.18/reference/generated/numpy.hstack.html" rel="nofollow noreferrer"><code>hstack()</code></a> and use <a href="https://numpy.org/doc/stable/reference/generated/numpy.squeeze.html" rel="nofollow noreferrer"><code>squeeze()</code></a> to remove the extra d...
python|arrays|numpy|multidimensional-array
1
3,706
62,349,883
loss not reducing in tensorflow classification attempt
<p>I wanted to simulate classifying whether a student will pass or fail a course depending on training data with a single input, namely a student's exam score.</p> <p>I start by creating data set of test scores for 1000 students, normally distributed with a mean of 80. I then created a classification "1" (passing) fo...
<p>The main issue here: Use <code>softmax</code> activation in the last layer, not separetely outside the model. Change the final layer to:</p> <pre><code>tf.keras.layers.Dense(2, activation="softmax") </code></pre> <p>Secondly, for two hidden layers with relu, 0.1 may be too high a learning rate. Try with a lower ra...
python|tensorflow|machine-learning|keras
0
3,707
62,169,144
Installing Python packages into a virtualenv is not supported on Windows | Tensorflow & Keras for Windows 10
<p>I'm trying to set up for the first time R environment with Keras and Tensorflow installed for Windows 10. This error shows in the RStudio but I tried also to do it from the Anaconda prompt in some other way and even if there's no error I'm not able to import Tensorflow properly. In RStudio:</p> <pre><code>&gt; libr...
<p>I also had a lot of problems trying to install keras and tensorflow in R but somehow, I managed to do it after 5 days of trial-and-error.</p> <p>I had to install them in a notebook with Windows 7 Professional. The notebook was shared with other people so, I was not allowed to install Windows 10.</p> <ol> <li><p>Beca...
python|r|tensorflow|keras|anaconda
6
3,708
62,236,335
Iterating through columns in pandas while applying different functions to each column
<p>Lets say I want to iterate though each column of a certain data frame, while at the same time applying different functions to each column. If every function is different for each column, is there a way to automate the code and not write N lines of code, where N is the total number of columns?</p>
<p>Use <code>agg</code>, as in :</p> <pre><code>df = pd.DataFrame({"a": range(3), "b": range(3,6)}) df.agg({"a": sum, "b": np.mean}) </code></pre>
python|pandas|dataframe
1
3,709
51,541,302
How to wrap a CFFI function in Numba taking Pointers
<p>It should be a easy task, but I can't find a way how to pass a pointer of a scalar value to a CFFI function within a Numba function. Passing a pointer to an array works without problems using <code>ffi.from_buffer</code>.</p> <p><strong>Example function</strong></p> <pre><code>import cffi ffi = cffi.FFI() defs="v...
<h2>Pass scalar values by reference using Numba</h2> <p>To get useful timings I have modified the wrapped function a bit. The function simply adds a scalar (passed by value) to a scalar b (passed by reference).</p> <p><strong>Pros and cons of the approach using intrinsics</strong></p> <ul> <li>Only working in nopython ...
python|performance|numpy|numba|python-cffi
3
3,710
51,214,329
Get rows in numpy array where column contains string
<p>I have a numpy array with 4 columns. The first column is text.</p> <p>I want to retrieve every row in the array where the first column contains a substring.</p> <p>Example: if the string I'm searching for is "table", find and return all rows in the numpy array whose first column contains "table."</p> <p>I've tri...
<p>Given a pandas DataFrame <code>df</code>, this will return all rows where <code>searchString</code> is a substring of the value in the column <code>column</code>:</p> <pre><code>searchString = "table" df.loc[df['column'].str.contains(searchString, regex=False)] </code></pre>
python|numpy
1
3,711
48,304,756
Optimization for making a null class in a one-hot pixel-wise label
<p>I'm preparing data for an image segmentation model. I have 5 classes per pixel that do not cumulatively cover the entire image so I want to create a 'null' class as the 6th class. Right now I have a one-hot encoded ndarray and a solution that makes a bunch of Python calls that I am looking to optimize. My sketch co...
<p>I believe you can do this with a combination of <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a> and <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.all.html" rel="nofollow noreferrer"><code>numpy....
python|numpy|optimization|computer-vision|array-broadcasting
1
3,712
48,266,912
Writing a conditional statement that modifies the original object, setting boundaries on a risk score
<p>I am currently trying to take a risk score that is between ~(-0.5) and ~1.5 and put boundaries on it so that if it is below 0 it will be set to zero and if it is above 1 it will be set to 1. I have yet to find an example where the initial object is the one that is changed, as I do not wish to just create a flag or s...
<p>You need the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.clip.html" rel="nofollow noreferrer">clip</a> method (works in <code>pandas</code> 21 and higher): </p> <pre><code>df["Risk score"].clip(lower=0, uppper=1, inplace=True) </code></pre> <p>In older versions of <code>pandas</co...
python|pandas|if-statement
0
3,713
48,737,810
alternating, conditional rolling count in pandas df column
<p>In a Technical Trading book by Larry Connors, I came across a simple indicator that for a financial asset time-series, it measures the number of consecutive closes in the same direction. Individual days are given a score of -1, 0, or +1 depending whether the close is lower, equal or higher than the previous close. <...
<p>You are 99% of the way there:</p> <pre><code>df['sign'] = np.sign(np.log(df['close']/df['close'].shift(1))).map(str) df['streak'] = df.groupby((df['sign'] !=df['sign'].shift(1)).cumsum()).cumcount()+1 df['final_streak'] = df['sign'].astype(float)*df['streak'] </code></pre> <p>Should give you what you want (not sur...
python|pandas|numpy|time-series
1
3,714
48,449,444
unidecode a text column from postgres in python
<p>I am new to Python and I want to take a column "user_name" from a postgresql database and remove all the accents from the names. Postgres earlier had a function called unaccent but it doesn't seem to work now. So, I resorted to Python.</p> <p>So far I have:</p> <pre><code>from sqlalchemy import create_engine from ...
<p>You have 2 slight problems, "unidecode" in your code is a module, you want the unidecode function out of this module, second you need to apply to each element not series/column so:</p> <pre><code>df.applymap(unidecode.unidecode) </code></pre>
python|postgresql|pandas|unidecoder
0
3,715
48,480,020
what does it mean having a negative cost for my training set?
<p>I'm trying to train my model and my cost output decreases each epoch till it reaches a values close to zero then goes to negative values I'm wondering what is <strong>the meaning of having negative cost output</strong>?</p> <pre><code>Cost after epoch 0: 3499.608553 Cost after epoch 1: 2859.823284 Cost after epoch...
<p>It means the labels are not in the format in which the cost function expects them to be.</p> <p>Each label that is passed to <code>sigmoid_cross_entropy_with_logits</code> should be 0 or 1 (for binary classifcation) or a vector containing 0's and 1's (for more than 2 classes). Otherwise, it won't work as expected....
python-3.x|tensorflow|neural-network|deep-learning
1
3,716
71,068,253
convert various source data_types schema to synapse data types schema mapping framework
<p>In order to convert various source data_types to Azure synapse data types to generate ddl so that data can be injected through a PySpark framework. For that I have to use the datatypes dictionary which contains distinct source data types mapped to synapse data types shown below as 'distinct_data_types_source2synaps...
<pre><code> data_type_mapping = { 'DATE': 'DATE', 'PERIODTIME': 'DATETIME', 'NUMERIC': 'INT', 'UROWID': 'VARCHAR', 'DATETIME2': 'DATETIME2', 'INTERVAL DAY TO MINUTE': '', 'PERIOD TIMESTAMP': '', 'BINARY': 'VARBINARY', 'DECFLOAT': 'FLOAT', 'DATETIME': 'DATETIME', 'VARCHAR': 'VARCHAR' } l = ['[profile_id] VARCHAR NOT NU...
python|pandas|pyspark|azure-synapse
0
3,717
51,984,239
Pandas fill missing values of a column based on the datetime values of another column
<p>Python newbie here, this is my first question. I tried to find a solution on similar SO questions, like <a href="https://stackoverflow.com/questions/51636583/set-column-value-based-on-indexed-datetime-filter">this one</a>, <a href="https://stackoverflow.com/questions/49161120/pandas-python-set-value-of-one-column-b...
<p>Your intuition seems fine by me, but you can't apply it this way since your dataframe <code>foo</code> doens't have the same size as your <code>groupby</code> dataframe. What you could do is map the values like this:</p> <pre><code>foo['last'] = foo.sess_id.map(foo.groupby('sess_id').DATE.max()) foo['first'] = foo....
pandas|datetime|missing-data
0
3,718
51,643,158
Create tf.constant given indices and values
<p>I want to improve my current code in order to improve the execution performance on my GPU so I am replacing the operations that it does not support to avoid delegating them to the CPU.</p> <p>One of this operations is tf.sparse_to_dense. So, is there some way to create a Tensor (constant) from its indices and value...
<p><a href="https://www.tensorflow.org/api_docs/python/tf/constant" rel="nofollow noreferrer"><code>tf.constant</code></a> currently does not support instantiation in coordinate format (indices and values) so the numpy/scipy workaround is actually not a bad one:</p> <pre><code>import scipy.sparse as sps A = sps.coo_m...
python|tensorflow
0
3,719
51,686,658
Pandas out of memory error when applying regex function
<p>I want to apply a regex function to clean text in a dataframe column.</p> <p>ie:</p> <pre><code>re1 = re.compile(r' +') def fixup(x): x = x.replace('#39;', "'").replace('amp;', '&amp;').replace('#146;', "'").replace( 'nbsp;', ' ').replace('#36;', '$').replace('\\n', "\n").replace('quot;', "'").replac...
<p>Break the <code>replace</code> chain into individual <code>replace</code> operations. Not only that will make your code more readable and maintainable, but the intermediate results will be discarded immediately after use, instead of being kept until all modifications are done:</p> <pre><code>replacements = ('#39;',...
python|regex|pandas|memory
1
3,720
64,302,733
Plotting low-pressure centers over time using xarray and CORDEX data
<p>I want to plot low-pressure centers over time as a way of 'tracking' extreme storms across NW Europe. I can do this by plotting the contours of low pressure like so:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import xarray ds = xarray.open_mfdataset('D:\Data\CORDEX\Historical\*.nc') ds </cod...
<p>you can use <a href="https://github.com/ecjoliver/stormTracking" rel="nofollow noreferrer">Open Source storm tracking software</a> or you have to build your own solution.</p> <p>If you are interested to develope your own solution I recommend to use an algorthim to find local minima (and maxima)</p> <p>E.g. scipy and...
python|pandas|python-xarray
2
3,721
64,462,395
Pandas: Collapse many rows into a single row by removing NaN's in a multiindex dataframe
<p>Below is my pivoted df:</p> <pre><code>Out[1446]: D A abc C G2 G3 G4 G1 G5 B uniq x 1 100.0 NaN NaN NaN NaN 2 NaN 200.0 NaN NaN NaN 3 NaN ...
<p>If there is always one non missing value per groups use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.first.html" rel="nofollow noreferrer"><code>GroupBy.first</code></a> for return first non NaN value per first level of <code>MultiIndex</code>:</p> <pre><code>df = df...
python|python-3.x|pandas|dataframe
1
3,722
64,516,655
How to change the auto rounding of floats in a numpy array after the array has been divided by a constant?
<p>Using Python 2.7, and numpy 1.16.5</p> <p>I want to convert array elements from inch to foot</p> <pre><code>FootToInch = 12.0 a = [.5, 1, 1.5, 2] a = np.array(a) new_a = a/FootToInch </code></pre> <p>I get:</p> <pre><code>[0.04166667 0.08333333 0.125 0.16666667] </code></pre> <p>I don't want the first element r...
<p>It's really a display rounding issue, though there is an underlying dependence on the float precision:</p> <pre><code>In [189]: .5/12 Out[189]: 0.041666666666666664 In [190]: np.float64(.5)/np.float64(12) Out[190]: 0.041666666666666664 In [191]: np.float32(.5)/np.float32(12) Out[191]: 0.041666668 In [192]: np.float1...
numpy|rounding
0
3,723
64,194,286
Create a list of years with pandas
<p>I have a dataframe with a column of dates of the form</p> <pre><code>2004-01-01 2005-01-01 2006-01-01 2007-01-01 2008-01-01 2009-01-01 2010-01-01 2011-01-01 2012-01-01 2013-01-01 2014-01-01 2015-01-01 2016-01-01 2017-01-01 2018-01-01 2019-01-01 </code></pre> <p>Given an integer number k, let's say k=5, I would like ...
<p>Let's use <code>pd.to_datetime</code> + <code>max</code> to compute the largest date in the column <code>date</code> then use <code>pd.date_range</code> to generate the dates based on the offset frequency one year and having the number of periods equals to <code>k=5</code>:</p> <pre><code>strt, offs = pd.to_datetime...
python|pandas|datetime
4
3,724
64,278,985
How to Install Tensorflow in firebase cloud function
<p>I've installed Tensorflow but it does not work. I've installed Tensorflow by using Dockerfile. Adding the commend</p> <pre><code>RUN pip install tensorflow==2.3. </code></pre> <p>When I import tensorflow from main.py, It shows <strong>Service Unavailable</strong>.</p> <pre><code>import tensorflow as tf </code></pre>...
<p>I think you can find the answer here: (<a href="https://stackoverflow.com/questions/52521190/error-installing-tensorflow-in-docker-image">Error installing Tensorflow in docker image</a>) &quot;RUN python3 -m pip install --upgrade <a href="https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-0.12.0-py3-none-a...
python|tensorflow|google-cloud-functions
2
3,725
64,571,083
Drop Duplicates in a DataFrame where a column are identical and have near timestamps
<p>Currently i have the following dataframe :</p> <pre><code> index timestamp | id_a | id_b | id_pair -------------------------------------------------------- 0 2020-01-01 00:00:00 | 1 | A | 1A 1 2020-01-01 00:01:30 | 1 | A | 1A 2 2020-01-01 00:02:30 |...
<p>First convert column to <code>datetime</code>s and then for expected output remove <code>| mask1.shift(-1)</code>:</p> <pre><code>df['timestamp'] = pd.to_datetime(df['timestamp']) mask1 = df.groupby('id_pair').timestamp.apply(lambda x: x.diff().dt.seconds &lt; 300) mask2 = df.id_pair.duplicated(keep=False) &amp; mas...
python|python-3.x|pandas|dataframe|timestamp
1
3,726
47,610,531
Pandas appending to series
<p>I am trying to write some code to scrape a website for a list of links which I will then do something else with after. I found some code <a href="https://github.com/jabbalaci/Bash-Utils/blob/master/get_links.py" rel="nofollow noreferrer">here</a> that I am trying to adapt so that instead of printing the list it adds...
<p><a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.append.html" rel="nofollow noreferrer"><code>.append()</code> method of a <code>Series</code> object</a> expects an another <code>Series</code> object as an argument. In other words, it is used to concatenate <code>Series</code> together.<...
python|pandas|beautifulsoup
2
3,727
49,133,681
to_csv() and read_csv() for dataframe containing serialized objects
<p>I have proved that the storing and retrieving of a serialized object from the cell of a pandas dataframe is failing after it is stored and loaded again from csv:</p> <pre><code>a = df['cookie'].iloc[0] print (type(a)) &gt;&gt; &lt;class 'requests.cookies.RequestsCookieJar'&gt; </code></pre> <p>then</p> <pre><code...
<p>I don't think you can store cookies or other non trivial objects as text in normal text files / csv. However, <code>pickle</code> will work for you.</p> <pre><code>import pickle # dump dataframe to a serialized pickle, df.pkl will be its filename with open('df.pkl', 'wb') as output: pickle.dump(df, output) # ...
python|python-3.x|pandas|file-io
1
3,728
58,732,316
Combining data from different rows based on the cell content and creating new columns based on the cell values with pandas and python
<p>I have data in csv file where in every row there's a name, a fruit and amount related to the fruit. What i want is to combine the data from different rows to a single row where all amounts for fruits related to a certain name is under one row. </p> <p>I have trouble finding a proper way of reading all the data from...
<p>Try to use pivot table when you want to reshape a dataframe.</p> <pre><code>df.pivot(index='name', columns='fruit', values='amount') </code></pre>
python|pandas|pandas-groupby
1
3,729
58,737,712
Is there some way of load a .pb file created in tf v1 on tensorflow v2?
<p>I'm trying to load a .pb file that was created in tf v1 on a tfv2 dist, my question is, the version 2 does have compatibility with older pb?</p> <p>I already tried a few things, but none of them worked. Trying to load the pb file directly with:</p> <pre class="lang-py prettyprint-override"><code>with tf.compat.v1....
<p>Convert it to a <code>tf.saved_model</code> with the code from here <a href="https://stackoverflow.com/questions/44329185/convert-a-graph-proto-pb-pbtxt-to-a-savedmodel-for-use-in-tensorflow-serving-o">Convert a graph proto (pb/pbtxt) to a SavedModel for use in TensorFlow Serving or Cloud ML Engine</a></p> <p>I jus...
python-3.x|tensorflow|tensorflow2.0
2
3,730
58,657,765
How to develop a neural network to predict joint angles form joint positions and orientation
<p>I am all new to neural network. I have a dataset of 3d joint positions (6400*23*3) and orientations in quaternions (6400*23*4) and I want to predict the joint angles for all 22 joints and 3 motion planes (6400*22*3). I have tried to make a model however it will not run as the input data don't match the output shape...
<p>Here are some suggestions that might get you further down the road:<br> (1) You might want to insert a "Flatten()" layer just before the final Dense. This will basically collapse the output from the previous layers into a single dimension.<br> (2) You might want to make the final Dense layer have 22*3=66 units as o...
python|numpy|tensorflow|keras|neural-network
2
3,731
58,764,541
Pandas iterate over each row of a column and change its value
<p>I have a pandas dataframe which looks like this:</p> <pre><code> Name Age 0 tom 10 1 nick 15 2 juli 14 </code></pre> <p>I am trying to iterate over each name --> connect to a mysql database --> match the name with a column in the database --> fetch the id for the name --> and replace the id in the pla...
<p>Slight rewrite of your code, if you want to do a transformation in general on a dataframe this is a better way to go about it</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import MySQLdb from sqlalchemy import create_engine engine = create_engine("mysql+mysqldb://root:Abc@123def@localhost/...
python|pandas
2
3,732
70,214,018
Segmenting order data into new rows based on max quantity pandas Dataframe
<p>I'm trying to generate a new dataframe that takes a certain <strong>total</strong> order and splitting it into actually shippable orders. Max eligibility shows what the maximum number of pallets can be put on an order. So in the below example, a total pallet order of 50, with a max eligibility 24, then I'd like the ...
<p>Apply a function f to construct the data of a new dataframe:</p> <pre><code>def f(x): q = x.pallets // x.max_eligability r = x.pallets % x.max_eligability l = [x.max_eligability] * q + [r] * (1 if r else 0) l = [(x.date, x.shipper_id, v, x.max_eligability) for v in l] return l df_output = pd.Dat...
python|pandas|dataframe
2
3,733
70,205,007
pytorch derivative returns none on .grad
<pre><code>i1 = tr.tensor(0.0, requires_grad=True) i2 = tr.tensor(0.0, requires_grad=True) x = tr.tensor(2*(math.cos(i1)*math.cos(i2) - math.sin(i1)*math.sin(i2)) + 3*math.cos(i1),requires_grad=True) y = tr.tensor(2*(math.sin(i1)*math.cos(i2) + math.cos(i1)*math.sin(i2)) + 3*math.sin(i1),requires_grad=True) z = ...
<p>Use:</p> <pre><code>i1 = tr.tensor(0.0, requires_grad=True) i2 = tr.tensor(0.0, requires_grad=True) x = 2*(torch.cos(i1)*torch.cos(i2) - torch.sin(i1)*torch.sin(i2)) + 3*torch.cos(i1) y = 2*(torch.sin(i1)*torch.cos(i2) + torch.cos(i1)*torch.sin(i2)) + 3*torch.sin(i1) z = (x - (-2))**2 + (y - 3)**2 z.backward() dz_...
python|pytorch|torch
1
3,734
70,054,095
Explanation of parameters of Tflite.runModelOnImage
<p>Can someone explain each line of this code? Like what is the purpose of <code>imageMean</code>, <code>imageStd</code>, <code>threshold</code>.</p> <p>I can't really find the documentation of this</p> <pre><code>Tflite.runModelOnImage( imageMean: 0.0, imageStd: 255.0, numResults: 2, thres...
<p>When performing an image classification task, it's often useful to normalize image pixel values based on the dataset mean and standard deviation. More reasons on why we need to do can be found in this question: <a href="https://stats.stackexchange.com/q/185853">Why do we need to normalize the images before we put th...
tensorflow|tensorflow-lite
3
3,735
70,236,139
Pandas Groupby Select Groups that Have More Than One Unique Values in a Column
<p>I have a dataframe of some information about some artists, their albums, and their tracks.</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'Artist': ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'C', 'C', 'D', 'E'], 'AlbumId': [201, 201, 451, 390, 390, 272, 272, 698, 698, 235, 312], 'TrackId': [1022, 34...
<p>Grouping should be <strong>solely</strong> by <em>Artist</em>.</p> <p>Then, for each group, check how many (different) albums it contains and take only groups having more than 1 album.</p> <p>So the proper solution is:</p> <pre><code>data.groupby('Artist').filter(lambda grp: grp.AlbumId.nunique() &gt; 1) </code></pr...
python|pandas|dataframe|pandas-groupby
3
3,736
64,629,933
How to format a JSON object as Pandas Dataframe?
<p>I'm loading up a json, and accessing a nested object, <em>plotArray</em>:</p> <pre><code>with open(testArray, &quot;r&quot;) as rf: arr = json.load(rf) plotArray = arr['data']['plotArray'] </code></pre> <p>plotArray has the following structure:</p> <pre><code>{'headers': ['p_id', 'e_id', 'l_id', 'o_id'], 'da...
<p>The following should work:</p> <pre><code>df=pd.DataFrame(plotArray['data'], columns=plotArray['headers']) </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt;print(df) p_id e_id l_id o_id 0 1 3 5 9 </code></pre>
python|json|pandas
2
3,737
64,652,951
How can I create irregularly shaped networks in Tensorflow and Keras?
<p>I'm making a neural network with tensorflow 2 and keras, but unlike all the tutorials I have found, my net is sort of irregularly shaped:</p> <p><a href="https://i.stack.imgur.com/eTff2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eTff2.png" alt="enter image description here" /></a></p> <p>It c...
<p>Instead of using standard slicing, use <code>tf.split</code>. It's much cleaner.</p> <pre><code>input = tf.keras.Input(shape=(1594,)) inp1, inp2 = tf.keras.layers.Lambda(lambda x: tf.split(x, 2, axis=1))(input) model_a = tf.keras.Sequential( [tf.keras.layers.Dense(600, activation=&quot;sigmoid&quot;), tf....
tensorflow|keras
1
3,738
65,001,763
How to generate same random arrays while using np.random.normal()
<pre><code>X_p=np.random.normal(0,0.05,size=(100,2)) X_n=np.random.normal(0.13,0.02,size=(50,2)) plt.scatter(X_p[:,0],X_p[:,1]) plt.scatter(X_n[:,0],X_n[:,1],color='red') plt.show() </code></pre> <p>this code generates different plot everytime we run it. Can someone tell me is there a way to generate same data always w...
<p>After some digging, I found a way</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import random rng = np.random.RandomState(0) X_p=rng.normal(0,0.05,size=(100,2)) X_n=rng.normal(0.13,0.02,size=(50,2)) plt.scatter(X_p[:,0],X_p[:,1]) plt.scatter(X_n[:,0],X_n[:,1],color='red') plt.show() </code></pre>...
python|numpy|random
0
3,739
44,025,664
drop all rows in 2 columns if value in one column is beyond a certain value
<p>I have two columns "sentiment" and "tweets". Sentiment contains numbers, tweets strings. I have a dataframe df with these two columns. And now I would like to drop all rows in which tweet length is beyond 150 letters.</p> <p>I am able to drop the values in X via:</p> <pre><code> X = df["x"] X =[x for x in X...
<p>You could zip the two lists together into a third list, so it'd be a list of two-tuples.</p> <pre><code>&gt;&gt;&gt;x = [1, 2, 3, 4] &gt;&gt;&gt;y = [9, 8, 7, 6] &gt;&gt;&gt;z = zip(x, y) &gt;&gt;&gt;z [(1, 9), (2, 8), (3, 7), (4, 6)] </code></pre> <p>With the zipped list, you could do a similar list comprehension...
python|python-3.x|pandas|twitter
0
3,740
44,319,849
recoding categorical variables in pandas
<p>I have a dataframe of categorical data that I would like to recode. Below is toy example of the code I have thus far</p> <pre><code>import pandas as pd ser = pd.DataFrame({'a':[1,3,3,1], 'b':[2,2,4,5]}) print(ser) a_dict = {1:11, 3:33} b_dict = {2:22, 4:44, 5:55} ser.a = ser.a.map(a_dict) ser.b = ser.b.map(b_dict) ...
<p><code>replace</code> can take a tiered dictionary where the first tier's keys are the names of columns and the values are the dictionaries to use for the replacement in the respective columns.</p> <pre><code>ser.replace(dict(a=a_dict, b=b_dict)) a b 0 11 22 1 33 22 2 33 44 3 11 55 </code></pre>
python|pandas|categorical-data
6
3,741
44,035,247
Determining if there is a gap in dates using pandas
<p>I have to determine if there are gaps between date sets (determined by start and end date). I have two example dataframes:</p> <pre><code>import pandas as pd a = pd.DataFrame({'start_date' : ['01-01-2014', '01-01-2015', '05-01-2016'], 'end_date' : ['01-01-2015', '01-01-2016', '05-01-2017']}) order = ...
<p>This is the idea...</p> <ul> <li>Assign a <code>+1</code> for start dates and a <code>-1</code> for end dates.</li> <li>Take a cumulative sum where I order by all dates as one flat array.</li> <li>When cumulative sum is zero... we hit a gap.</li> <li>Date values are the first priority, followed by being a start_dat...
python|date|pandas
1
3,742
44,260,217
Hyperparameter optimization for Pytorch model
<p>What is the best way to perform hyperparameter optimization for a Pytorch model? Implement e.g. Random Search myself? Use Skicit Learn? Or is there anything else I am not aware of?</p>
<p>Many researchers use <a href="http://ray.readthedocs.io/en/latest/tune.html" rel="noreferrer">RayTune</a>. It's a scalable hyperparameter tuning framework, specifically for deep learning. You can easily use it with any deep learning framework (2 lines of code below), and it provides most state-of-the-art algorithms,...
python|machine-learning|deep-learning|pytorch|hyperparameters
29
3,743
69,359,623
Plotting step function with empirical data cumulative x-axis
<p>I have a dummy dataset, <strong>df</strong>:</p> <pre><code> Demand WTP 0 13.0 111.3 1 443.9 152.9 2 419.6 98.2 3 295.9 625.5 4 150.2 210.4 </code></pre> <p>I would like to plot this data as a step function in which the &quot;WTP&quot; are y-values and &quot;Demand&quot; are x-values.</p> <p>The...
<p>You can try:</p> <pre><code>import matplotlib.pyplot as plt import pandas as pd df=pd.DataFrame({&quot;Demand&quot;:[13, 443.9, 419.6, 295.9, 150.2],&quot;WTP&quot;:[111.3, 152.9, 98.2, 625.5, 210.4]}) df=df.sort_values(by=[&quot;Demand&quot;]) plt.step(df.Demand,df.WTP) </code></pre> <p>But I am not really sure a...
python|pandas|matplotlib|plot
1
3,744
41,010,850
Fill NAN values of a column in dataframe from other dataframe pandas
<p>i have a table in pandas df</p> <pre><code> main_id p_id_y score 1 1 123 0.617523 0 2 456 0.617523 0 3 789 NaN 0 4 987 NaN 1 5 654 NaN </code></pre> <p>also i have another datafr...
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.combine_first.html" rel="nofollow noreferrer"><code>combine_first</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.html" rel="nofollow noreferrer"><code>fillna</code></a>,...
python|pandas
3
3,745
41,078,003
Convert categorical variables from String to int representation
<p>I have a numpy array of classification of text in the form of String array, i.e. <code>y_train = ['A', 'B', 'A', 'C',...]</code>. I am trying to apply SKlearn multinomial NB algorithm to predict classes for entire dataset. </p> <p>I want to convert the String classes into integers to be able to input into the algo...
<p>Try <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.factorize.html" rel="noreferrer">factorize</a> method:</p> <pre><code>In [264]: y_train = pd.Series(['A', 'B', 'A', 'C']) In [265]: y_train Out[265]: 0 A 1 B 2 A 3 C dtype: object In [266]: pd.factorize(y_train) Out[266]: (array...
pandas|numpy|scikit-learn
16
3,746
41,220,475
Tensorflow + LSF. Distributed tensorflow on LSF cluster
<p>How to setup tensorflow to work with LSF job scheduler? I have almost no experience with LSF. tf.train.ClusterSpec needs ip addresses of workers and parameter servers. Is it possible to obtain them from the LSF environment? Are there any success stories of making them work together?</p> <p><strong>EDIT:</strong></p...
<p>There's a blog post and sample launch script for TensorFlow on LSF <a href="https://developer.ibm.com/storage/2017/01/31/ibm-spectrum-lsf-support-for-deep-learning-distributed-frameworks/" rel="nofollow noreferrer">here</a>.</p>
tensorflow|distributed-computing|lsf
1
3,747
41,226,744
Normalize data in pandas dataframe
<p>I would like to normalise this value in the range of 0 to 100. I have these values in a pandas dataframe. </p> <pre><code> Latitude Longitude 25.436596 -100.887300 25.436596 -100.887700 25.436493 -100.887421 25.436570 -100.887344 25.436596 -100.887321 </code></pre> <p>I am able ...
<p>Change it to:</p> <pre><code>100 * (df - df.min()) / (df.max() - df.min()) </code></pre> <p>The <code>(df - df.min()) / (df.max() - df.min())</code> part is min-max normalization where the new scale is [0, 1]. If you multiply that with 100, you get your desired range.</p>
python|pandas|normalization
4
3,748
54,085,278
How to paste (like R) and groupby in Python
<p>I am having trouble converting an R code example to my script and was wondering how to achieve the same. </p> <pre><code>product_df &lt;- example_df[,paste(name, collapse="_"),by=product_id] </code></pre> <p>I found this code snippet on the a previous SO question but it was just concatenating everything together a...
<p>You may check with <code>groupby</code> </p> <pre><code>example_df.groupby('product_id').name.apply('_'.join).reset_index() product_id name 0 100_1244 apple_apple_apple_apple 1 200_1244 orange_orange_orange_orange </code></pre>
python|pandas|pandas-groupby
1
3,749
54,110,984
Convert Tensorflow model into Tensorflow Lite
<p>I have a problem with the conversion of the tensorflow model to tflite. I have a learned model based on <a href="https://github.com/tensorflow/models/tree/master/research/object_detection" rel="nofollow noreferrer">Tensorflow Object Detection</a> I would like to use the conversion code from <a href="https://www.ten...
<p>We have <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/export_tflite_ssd_graph.py" rel="nofollow noreferrer">a script</a> in the Object Detection API to get the Flatbuffer.</p>
python|tensorflow|tensorflow-lite
0
3,750
54,132,072
Change sign of column based on condition
<p>input DF:</p> <pre><code>value1, value2 123L, 20 222S, 10 222L, 18 </code></pre> <p>I want to make values in volumn <code>value2</code> where in <code>value1</code> is <code>L</code> letter negative, so I am trying to multiply them by -1</p> <p>expexted result:</p> <pre><code>value1, value2 123L, -20 22...
<p>You can use Boolean indexing with <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>loc</code></a>:</p> <pre><code>df.loc[df['value1'].str[-1] == 'L', 'value2'] *= -1 </code></pre> <p>Alternatively, using <a href="https://pandas.pydata.org/pa...
python|pandas|dataframe
3
3,751
53,875,880
convert a pandas dataframe of RGB colors to Hex
<p>I've attempting to convert a long list of RGB values in a dataframe into Hex to allow some chart building, I've managed to locate the right code to do the conversion, it is just applying it that is killing me.</p> <pre><code>df = pd.DataFrame({'R':[152,186,86], 'G':[112,191,121], 'B':[85,222,180] }) def rgb_to_hex...
<p>The <code>%</code> operator can't work with sequences the way you'd want it to. Instead, you should use the <code>.apply</code> method of the dataframe to pass each row individually to your function:</p> <pre><code>df['hex'] = df.apply(lambda r: rgb_to_hex(*r), axis=1) R G B hex 0 152 112 85 #...
python|pandas|hex|rgb
4
3,752
52,843,144
Numpy array and matrix multiplication
<p>I am trying to get rid of the for loop and instead do an array-matrix multiplication to decrease the processing time when the <code>weights</code> array is very large: </p> <pre><code>import numpy as np sequence = [np.random.random(10), np.random.random(10), np.random.random(10)] weights = np.array([[0.1,0.3,0.6],...
<p>The same can be achieved by working with the weights as a matrix and then looking at the diagonal elements of the result. Namely:</p> <pre><code>np.diag(weights.dot(Cov_matrix).dot(weights.transpose())) </code></pre> <p>which gives:</p> <pre><code>array([0.03553664, 0.02394509, 0.03765553]) </code></pre> <p>Thi...
python|arrays|numpy|matrix|multiplication
1
3,753
52,554,765
Python Pandas groupby and join
<p>I am fairly new to python pandas and cannot find the answer to my problem in any older posts.</p> <p>I have a simple dataframe that looks something like that:</p> <pre><code>dfA ={'stop':[1,2,3,4,5,1610,1611,1612,1613,1614,2915,...] 'seq':[B, B, D, A, C, C, A, B, A, C, A,...] } </code></pre> <p>Now I want t...
<p>I think you need create helper <code>Series</code> for grouping:</p> <pre><code>g = dfA['stop'].diff().ne(1).cumsum() dfC = dfA.groupby(g)['seq'].apply(''.join).reset_index() print (dfC) stop seq 0 1 BBDAC 1 2 CABAC 2 3 A </code></pre> <p><strong>Details</strong>:</p> <p>First get differe...
pandas|pandas-groupby|difference
0
3,754
52,803,972
This issue about keras model and how to compile the model
<p>I'm trying to create a CNN in pycharm. When I run my code, the console outputs<br> <code>RuntimeError: You must compile your model before using it.</code><br></p> <p>I write down compile. This is my code: </p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*-o from keras.models import Sequential from keras...
<p>You seem to overwrite Keras <code>model()</code> function with your function. Try this instead:</p> <pre><code>def get_model(): model = Sequential() ... &lt; *rest of your function code here* &gt; ... return model nn = get_model() </code></pre>
python|tensorflow|keras
1
3,755
46,365,194
Find the latest file for each calendar month in a folder
<p>The code below works as I need it to, but I feel like there must be a better way. I have a folder with daily(ish) files inside of it. All of them have the same prefix and the date they were sent as the file name. On certain days, no file was sent at all though. My task it to read the last file of each month (most of...
<p>So the file names would be <code>prefix_&lt;date&gt;</code> and the date is in format <code>%Y-%m-%d</code>.</p> <pre><code>import os from datetime import datetime as dt from collections import defaultdict from pathlib import Path group_by_month = defaultdict(list) files = [] # Assuming the folder is the data fol...
python|pandas
1
3,756
58,388,726
Sum a seprate colum based on the range of the dataframe between values in other columns after groupby
<p>I have a dataframe as below</p> <pre><code>id Supply days days_180 1 30 0 180 1 100 183 363 1 80 250 430 2 5 0 180 2 5 10 190 3 5 0 180 3 30 100 280 3 30 150 330 3 30 200 380 3 30 280 460 3 ...
<p>Use list comprehension for loop each <code>days_180</code> values per groups, filter with <code>sum</code> and create new column:</p> <pre><code>def f(x): a = [x.loc[(x['days'] &lt;= d) &amp; (x['days_180'] &gt;= d),'Supply'].sum() for d in x['days_180']] x['use'] = a return x </code></pre> <p>Or solut...
python|pandas|dataframe|pandas-groupby
2
3,757
58,382,192
Object detection in 1080p with SSD Mobilenet (Tensorflow API)
<p>Hello everybody,</p> <p>My objective is to detect people and cars (day and night) on images of the size of 1920x1080, for this I use the tensorflow API, I use a SSD mobilenet model, I annotated 1000 images (900 for training, 100 for evaluation) from 7 different cameras. I launch the training with an image size of 9...
<p>What do you mean by "not converge"? Are you referring to the train/validation loss?<br> In this case, the first thing that comes to my mind is to reduce the learning rate (I had a similar problem). You can do it by modifying you configuration file, in the "<em>train_config</em>" section you'll find the value "<em>in...
python|tensorflow|deep-learning|object-detection|object-detection-api
0
3,758
58,566,054
create dataframe from unequal sized list objects with different non integer indicies
<p>I have a list of numpy arrays - for example:</p> <h1>Lets call this LIST_A:</h1> <pre><code>[array([ 0. , -11.35190205, 11.35190205, 0. ]), array([ 0. , 36.58012599, -36.58012599, 0. ]), array([ 0. , -41.94408202, 41.94408202, 0. ])] </code></pre> <p>I have ...
<p>Not quite different from your approach, but this should be quite faster:</p> <pre><code>df = pd.DataFrame(dict(zip(list_b[i], list_a[i])) for i in range(len(list_a))).T </code></pre> <p>Output:</p> <pre><code> 0 1 2 A_A 0.000000 0.000000 NaN A_B -11.351902 ...
python|arrays|pandas|numpy|dataframe
1
3,759
58,211,856
How to "Iterate" on Computer Vision machine learning model?
<p>I've created a model using google clouds vision api. I spent countless hours labeling data, and trained a model. At the end of almost 20 hours of "training" the model, it's still hit and miss.</p> <p>How can I iterate on this model? I don't want to lose the "learning" it's done so far.. It works about 3/5 times. </...
<p>I'm by no means an expert, but here's what I'd suggest in order of most to least important:</p> <p>1) Add more data if possible. More data is always a good thing, and helps develop robustness with your network's predictions.</p> <p>2) <a href="https://stackoverflow.com/questions/40879504/how-to-apply-drop-out-in-t...
opencv|tensorflow|google-cloud-platform|google-vision|vision-api
1
3,760
68,930,708
How to fix ValueError: too many values to unpack (expected 2)?
<p>Recently faced with such a problem: ValueError: too many values to unpack (expected 2).</p> <pre><code>import os import natsort from PIL import Image import torchvision import torch import torch.optim as optim from torchvision import transforms, models from torch.utils.data import DataLoader, Dataset import torch.nn...
<p>Batch doesn't contain both the inputs and the targets. Your problem is just that <strong>getitem</strong> returns only tensor_image (which is presumably the inputs) and not whatever targets should be.</p>
python|pytorch
1
3,761
68,978,583
How to get unique values of a column in pyspark dataframe and store as new column
<p>Basically I want to know how much a brand that certain customer buy in other dataset and rename it as change brand, here's what I did in Pandas</p> <pre><code>firstvalue=firstvalue.merge((pd.DataFrame(profile.groupby('msisdn') .handset_brand.nunique() ...
<p>The same thing can be done in Pyspark as below -</p> <p><code>nunique</code> equivalent - <a href="https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.sql.functions.countDistinct.html" rel="nofollow noreferrer">countDistinct</a> , <code>merge</code> equivalent - <a href="https://spark.apache.org/do...
python|pandas|pyspark
2
3,762
44,758,596
Split a list of tuples in a column of dataframe to columns of a dataframe
<p>I've a dataframe which contains a list of tuples in one of its columns. I need to split the list tuples into corresponding columns. My dataframe df looks like as given below:- </p> <pre><code> A B [('Apple',50),('Orange',30),('banana',10)] Winter [('Orange'...
<p>This should work:</p> <pre><code>fruits = [] rates = [] seasons = [] def create_lists(row): tuples = row['A'] season = row['B'] for t in tuples: fruits.append(t[0]) rates.append(t[1]) seasons.append(season) df.apply(create_lists, axis=1) new_df = pd.DataFrame({"Fruit" :fruits,...
python|pandas|dataframe
1
3,763
71,566,471
How to detect and convert monthly data to NaN if there is n consecutive NaN values?
<p>I have this df:</p> <pre><code> CODE DATE TMAX 0 000130 1963-09-01 NaN 1 000130 1963-09-02 29.4 2 000130 1963-09-03 27.8 3 000130 1963-09-04 25.0 4 000130 1963-09-05 27.8 ... ... ... 7393858 158328 2020-12-27 12.2 7393859 158328 2020-12-28...
<p>You had the right logic but the code could be simplified. You don't need to compute twice the <code>isnull</code>/<code>notnull</code>, nor to convert booleans to integers.</p> <p>I am also testing a <code>cumcount</code> rather than <code>sum</code> here.</p> <p>Can you try this potential improvement?</p> <pre><cod...
python|pandas
1
3,764
42,192,332
iterating through a list with a function that relates list objects
<p>Let's say I have a list: </p> <pre><code>stuff = ['Dogs[1]','Jerry','Harry','Paul','Cats[1]', 'Toby','Meow','Felix'] </code></pre> <p>Is it possible to iterate through the list and assign the animal name to the animal in a dataframe format like:</p> <pre><code>Animal Name Dog Jerry Dog Harry Dog ...
<p>I think you can use first <code>DataFrame</code> constructor:</p> <pre><code>df = pd.DataFrame({'Name':stuff}) print (df) Name 0 Dogs[1] 1 Jerry 2 Harry 3 Paul 4 Cats[1] 5 Toby 6 Meow 7 Felix </code></pre> <p>Then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Da...
python|list|pandas|iteration
2
3,765
42,234,039
Getting the row with max value in Pandas
<p>Have a df like that:</p> <p><a href="https://i.stack.imgur.com/B6hDS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/B6hDS.png" alt="enter image description here"></a></p> <p>I'd like to have a dataframe with only row with max date in it. How can it be performed?</p> <p>Thanks!</p>
<p>Find the most recent date:</p> <pre><code>recent_date = df['date'].max() </code></pre> <p>And then get the dataframe with the recent date:</p> <pre><code>df[df['date'] == recent_date] </code></pre> <p>To get the row with Top n dates (say top 2 dates),</p> <pre><code>top_2 = df['date'].nlargest(2) df[df['date'].isin(...
python|pandas
12
3,766
69,766,469
How to concatenate lists in Dataframe after grouping
<p>After grouping a dataframe the result is that I have a list in each row of the dataframe.</p> <pre><code> Id 0 [GSTE00057] 1 [LOKH18675] 2 [LWWSD61, PTZW6, VCVCD064, AFER53423] 3 [KJHZ64534] 4 [GDHSGD88888] 5 [FSDAE00003] 6 [IHUGZF051, ZGGTHZ0052, PRRDSE0...
<p>Use itertools.chain:</p> <pre><code>import pandas as pd from itertools import chain # toy data data = [[&quot;GSTE00057&quot;], [&quot;LOKH18675&quot;], [&quot;LWWSD61&quot;, &quot;PTZW6&quot;, &quot;VCVCD064&quot;, &quot;AFER53423&quot;], [&quot;KJHZ64534&quot;], [&quot;GDHSGD88888&...
python|pandas
2
3,767
69,830,006
Get the integer value inside a tensor tensorflow
<p>I have a list of tensors, but i need to use the integer value that is saved inside each one. Is there a way to retrieve it without need to change eager mode?</p> <p>Example test:</p> <pre><code>import tensorflow as tf tf.compat.v1.disable_eager_execution() if __name__ == '__main__': test = tf.constant([1,4,5]) ...
<p>You can use <code>Tensor.numpy()</code> method to convert <code>tensorflow.Tensor</code> to <code>numpy</code> array or if you don't want to work with <code>numpy</code> representation <code>Tensor.numpy().tolist()</code> converts your variable to python list.</p> <pre class="lang-py prettyprint-override"><code>test...
python|tensorflow
1
3,768
72,235,626
How can I group elements in pandas series based on how many times they repeat?
<p>I have this example_series:</p> <pre><code>0 False 1 False 2 False 3 False 4 False 5 False 6 False 7 False 8 False 9 False 10 False 11 False 12 False 13 True 14 True 15 True 16 True 17 True 18 True 19 True 20 True 21 False 22 Fals...
<p>Not sure if there's a one-liner, but this may work if IIUC. It builds on <code>cumsum</code> to apply the counts to each row. If the row count is less than 5, in your example, those rows should stay with preceding group number. The <code>bfill</code> and <code>ffill</code> are needed depending on where the counts ar...
python|pandas|series
0
3,769
50,246,911
How to find mode of every n (50) rows in python?
<p>I have a dataframe with 8 columns and ~0.8 million rows. I want to find the mode of every 50 rows of a specific column (e.g. Column 5) in a separate dataframe. My approach looks like this. </p> <pre><code>for i in range(1, len(data['Column5'])-1) : splitdata = (data['Column5'][i:(i+49)]) mode_pressure[j] = sp...
<p>I think need <code>groupby</code> by numpy arange for more general solution, e.g. working nice with <code>DatetimeIndex</code> with floor division:</p> <pre><code>df = df.groupby(np.arange(len(df)) // 50)['Col5'].apply(lambda x: x.mode()) </code></pre> <hr> <p>There is possible multiple values, so possible soluti...
python|pandas|dataframe|mode
5
3,770
45,308,382
Python / Pandas - Filtering according to other dataframe's index
<p>I have this two dataframes:</p> <pre><code>df1: Value dude_id 123 x 543 y 984 z df2: Value id 123 R 498 S 543 D 984 X 009 Z </code></pre> <p>I want to filter <code>df2</code> in a way that it o...
<p>Use <code>loc</code></p> <pre><code>In [952]: df2.loc[df1.index] Out[952]: Value dude_id 123 R 543 D 984 X </code></pre> <p>And, you can rename the index name</p> <pre><code>In [956]: df2.loc[df1.index].rename_axis('id') Out[956]: Value id 123 R 543 D 984 X </code><...
python|pandas
4
3,771
62,874,098
Python how to create new dataset from an existing one based on condition
<p>For example: I have this code:</p> <pre><code>import pandas df = pandas.read_csv('covid_19_data.csv') </code></pre> <p>this dataset has a column called <code>countryterritoryCode</code> which is the country code of the country.<a href="https://i.stack.imgur.com/5hlCC.png" rel="nofollow noreferrer">sample data from t...
<pre><code>import pandas df = pandas.read_csv('covid_19_data.csv') new_df = df[df[&quot;country&quot;] == &quot;USA&quot;] or new_df = df[df.country == &quot;USA&quot;] </code></pre>
python|pandas
3
3,772
62,873,633
pytorch training loop ends with ''int' object has no attribute 'size' exception
<p>The code I am posting below is just a small part of the application:</p> <pre><code>def train(self, training_reviews, training_labels): # make sure out we have a matching number of reviews and labels assert(len(training_reviews) == len(training_labels)) # Keep track of corre...
<p>Target should be a <code>torch.Tensor</code> variable. Use <code>torch.tensor([target])</code>.</p> <p>Additionally, you may want to use batches (so there are <code>N</code> samples and shape of <code>torch.tensor</code> is <code>(N,)</code>, same for <code>target</code>).</p> <p>Also see <a href="https://pytorch.or...
python|pytorch
1
3,773
62,594,877
Pyspark using Window function with my own function
<p>I have a Pandas's code that calcul me the R2 of a linear regression over a window of size x. See my code :</p> <pre><code>def lr_r2_Sklearn(data): data = np.array(data) X = pd.Series(list(range(0,len(data),1))).values.reshape(-1,1) Y = data.reshape(-1,1) regressor = LinearRegression() regresso...
<p>You need a udf with pandas udf with a bounded condition. This is not possible until spark3.0 and is in development. Refer answer here : <a href="https://stackoverflow.com/questions/48160252/user-defined-function-to-be-applied-to-window-in-pyspark">User defined function to be applied to Window in PySpark?</a> However...
python|pandas|pyspark|window
1
3,774
54,258,674
Get first column value in Pandas DataFrame where row matches condition
<p>Say I have a pandas dataframe that looks like this:</p> <pre><code> color number 0 red 3 1 blue 4 2 green 2 3 blue 2 </code></pre> <p>I want to get the first value from the number column where the color column has the value <code>'blue'</code> which in this case would return <cod...
<p>Use <code>head</code>—this will return the first row if the color exists, and an empty <code>Series</code> otherwise.</p> <pre><code>col = 'blue' df.query('color == @col').head(1).loc[:, 'number'] 1 4 Name: number, dtype: int64 </code></pre> <p>Alternatively, to get a single item, use <code>obj.is_empty</code>...
python|pandas|performance|dataframe|optimization
2
3,775
54,392,563
From a one-hot representation to the labels
<p>My predictions are under a tensor <code>pred</code>, and <code>pred.shape</code> is <code>(4254, 10, 3)</code>. So we have <code>4254</code> matrices of dimension <code>(10, 3)</code>. Let's take a look on one of those matrices.</p> <pre><code>W = array([[0.04592975, 0.09632163, 0.85774857], [0.03408821,...
<p>I am not sure it is the optimal way to deal with that, but here's an answer.</p> <pre><code>import numpy as np threshold_array = np.array([0.6, 0.65, 0.70, 0.75, 0.80, 0.80, 0.80, 0.80, 0.80, 0.80]) def get_labels(W, threshold_array): labels = [] for i, vect in enumerate(W): neutral_position =...
python|numpy|tensor|threshold
0
3,776
54,305,910
Error calculating the mean due to a list which doesn't exist
<p>I am attempting to calculate the average hourly fraction from a column of integers called <code>hour</code> in a pandas DataFrame df called <code>train</code>.</p> <p>The code used to calculate is as follows:</p> <p><code>hourly_frac = train.groupby(['hour']).mean()/np.sum(train.groupby(['hour'].mean()))</code> </...
<p>It looks like you misplaced a parenthesis. Near the end of your line, the snippet:</p> <pre><code>['hour'].mean() </code></pre> <p>is trying to take the <code>mean</code> of <code>['hour']</code>, a <code>list</code> with a single element of type <code>str</code>. And so, as is proper, you're getting an <code>Attr...
python|pandas|numpy
1
3,777
54,654,148
Random boolean mask sampled according to custom PDF in Tensorflow
<p>I am trying to generate a random boolean mask sampled according to a predefined probability distribution. The probability distribution is stored in a tensor of the same shape as the resulting mask. Each entry contains the probability that the mask will be true at that particular location.</p> <p>In short I am looki...
<p>I must have been sleeping, here is how I solved it:</p> <pre><code>def sample_mask(pdf, s, n, replace): """Initialize the model. Args: pdf: A 3D Tensor of shape (batch_size, hight, width, channels=1) to use as a PDF s: The number of samples per mask. This value should be l...
tensorflow|mask|probability-distribution
1
3,778
54,527,134
Counting column values based on values in other columns for Pandas dataframes
<p>I'm trying to count the number of each category of storm for each unique <code>x</code> and <code>y</code> combination. For example. My dataframe looks like:</p> <pre><code>x y year Category 1 1 1988 3 2 1 1977 1 2 1 1999 2 3 2 1990 4 </code></pre> <p>I want to create a dataframe th...
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot_table.html" rel="nofollow noreferrer"><code>pivot_table</code></a> sounds like what you want. A bit of a hack is to add a column of <code>1</code>'s to use to count. This allows <code>pivot_table</code> to add <code>1</code> for each oc...
python|pandas|dataframe
2
3,779
73,821,746
How to use OR in a regex?
<p>I am trying to select only columns from a dataframe that start with a p or that contain an s. I am using the following:</p> <pre><code>df2 = (df.filter(regex ='(^p)' or '(s)')) df2 </code></pre> <p>But that only selects columns that start with a p. It ignores the second part and doesn't select columns that have an s...
<p>Use the pipe character <code>|</code> which is equivalent to <code>OR</code> in <code>regex</code>.</p> <pre><code>df2 = (df.filter(regex ='^p|s')) </code></pre>
pandas
1
3,780
73,539,357
too many dates on x-axis (matplotlib graph)
<p>So, I have a dataset of stock prices, let's call it <code>sp.csv</code>.</p> <p><a href="https://i.stack.imgur.com/e1QCt.png" rel="nofollow noreferrer">It has a date column that looks like this</a></p> <p><a href="https://i.stack.imgur.com/6R2oh.png" rel="nofollow noreferrer">A price column that looks like this</a><...
<p>When you convert the date using <code>strptime()</code>, that will convert it to datetime. Do not use <code>strftime()</code>, which will convert it back to string. Check by using <code>df.info()</code> and make sure you see that the column you are plotting is datetime. Only then will you be able to use the dateform...
pandas|dataframe|date|matplotlib|graph
0
3,781
73,794,984
How to merge multiple rows in pandas DataFrame within a column to numpy array
<p>I have a pandas DataFrame <code>df</code> that looks like:</p> <pre><code>df = sample col1 data_value time_stamp A 1 15 0.5 A 1 45 0.5 A 1 32 0.5 A 2 3 1 A 2 57 1 A 2 89 ...
<p>If the number of values in each group is identical, you can use:</p> <pre><code>import numpy as np a = np.vstack(df.groupby(['sample','col1'])['data_value'].agg(list)) </code></pre> <p>Or:</p> <pre><code>a = (df .assign(col=lambda d: d.groupby(['sample', 'col1']).cumcount()) .pivot(['sample', 'col1'], 'col', 'data...
python|pandas|dataframe|numpy-ndarray
2
3,782
71,333,443
Differential Privacy in Tensorflow Federated
<p>I try to run mnist_dpsgd_tutorial.py in Tensorflow Privacy, and check number of dimensions of the gradient. I think gradient is calculated by dp_optimizer. Is there a way to check and operate the gradient?</p>
<p>It is optimizer, for loss optimizer there are basics methods as this below, you can adjust to your method.</p> <pre><code>optimizer = tf.keras.optimizers.Adam( learning_rate=learning_rate, beta_1=0.9, beta_2=0.999, epsilon=1e-07, amsgrad=False, name='Adam' ) var1 = tf.Variable(10.0) var2 = tf.Variable(10.0...
python|tensorflow
0
3,783
71,362,022
Flattening the input to nn.MSELoss()
<p>Here's the screenshot of a YouTube video implementing the <strong>Loss</strong> function from the <em>YOLOv1</em> original research paper. <a href="https://i.stack.imgur.com/FINfx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FINfx.png" alt="enter image description here" /></a></p> <p>What I don...
<p>It helps to go back to the definitions. What is MSE? What is it computing?</p> <p>MSE = mean squared error.</p> <p>This will be rough pythonic pseudo code to illustrate.</p> <pre><code>total = 0 for (x,y) in (data,labels): total += (x-y)**2 return total / len(labels) # the average squared difference </code></pr...
pytorch|object-detection|yolo|flatten|mse
0
3,784
52,257,890
Convert ordered dataFrame into a dictionary with the elements start for the bottom
<p>I have data Frame with elements ordered by the Value column:</p> <pre><code>ID Value 04 1 06 2 01 3 02 4 03 5 </code></pre> <p>I need obtain the Dictionary with points as key and the list of points as values order in circle(first bottom, after top). </p> <pre><code>Dictionary: { 0...
<p>Here's one solution using <code>collections.deque</code>:</p> <pre><code>from collections import deque dq = deque(df['ID']) res = {} for i in list(dq): res[i] = list(dq)[1:] dq.rotate(-1) </code></pre> <p>Result:</p> <pre><code>{'04': ['06', '01', '02', '03'], '06': ['01', '02', '03', '04'], '01': ['0...
python|pandas|dictionary
2
3,785
52,152,922
Unpacking Dictionaries within a Data Frame
<p>I have a Pandas Data Frame that contains a series of dictionaries, as follows:</p> <pre><code>df.head() Index params score 0 {'n_neighbors': 1, 'weights': 'uniform'} 0.550 1 {'n_neighbors': 1, 'weights': 'distance'} 0.550 2 {'n_neighbors': 2, 'weights': 'un...
<p>Construct a new dataframe from <code>df['params']</code> and join it to your original dataframe. As a convenience, <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pop.html" rel="nofollow noreferrer"><code>pd.DataFrame.pop</code></a> simultaneously returns a series and drops it from y...
python|pandas|numpy|dictionary|dataframe
1
3,786
60,468,407
Pytorch tensor data is disturbed when I convert data loader tensor to numpy array
<p>I am using a simple train loop for a regression task. To make sure that regression ground-truth values are the same as what I expect in the training loop, I decided to plot each batch of data. However, I see that when I convert the data loader’s tensor to numpy array and plot it, it is disturbed. I am using myTensor...
<p>I think it is because I set shuffle = True in data loader. If I set it to false, it is fine. However, How can I shuffle training batches after each epoch if I set shuffle = False in data loader then?</p>
python|numpy|pytorch|dataloader
0
3,787
60,420,492
Up to date Bokeh grouped bar chart example?
<p>I am new to both Bokeh and Pandas and I am trying to generate a grouped bar chart from some query results.</p> <p>My data looks something like this</p> <pre><code>Day Fruit Count ----------- -------- ------- 2020-01-01 Apple 19 2020-01-01 Orange 8 2020-01-01 Banana 7 ... 2020-02-23 Apple 1...
<p>What you're looking for is a method called <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer"><code>pivot</code></a>.</p> <p>But you don't really need it in this case - the Bokeh example you linked already deals with the pivoted data and that's...
python|bokeh|pandas-bokeh
1
3,788
60,377,552
Pandas: apply list of functions on columns, one function per column
<p>Setting: for a dataframe with 10 columns I have a list of 10 functions which I wish to apply in a <code>function1(column1), function2(column2), ..., function10(column10)</code> fashion. I have looked into <code>pandas.DataFrame.apply</code> and <code>pandas.DataFrame.transform</code> but they seem to broadcast and a...
<p>IIUC, with <code>zip</code> and a <code>for</code> loop:</p> <h3>Example</h3> <pre><code>def function1(x): return x + 1 def function2(x): return x * 2 def function3(x): return x**2 df = pd.DataFrame({'A': [1, 2, 3], 'B': [1, 2, 3], 'C': [1, 2, 3]}) functions = [function1, function2, function3] prin...
python-3.x|pandas
2
3,789
60,622,685
Keras: .predict returns percentages instead of classes
<p>I am building a model with 3 classes: <code>[0,1,2]</code> After training, the <code>.predict</code> function returns a list of percentages instead. I was checking the keras documentation but could not figure out, what I did wrong. <code>.predict_classes</code> is not working anymore, and I did not have this proble...
<p>You did not do anything wrong, <code>predict</code> has always returned the output of the model, for a classifier this has always been probabilities per class.</p> <p><code>predict_classes</code> is only available for <code>Sequential</code> models, not for Functional ones.</p> <p>But there is an easy solution, yo...
python|tensorflow|keras
3
3,790
72,635,676
How to Convert Online Txt file padas Dataframe
<p>Im using requests and beautiful soup to navigate and download data from the Census Webpage. Im able to get the data into a result object, and if i want a soup object, but can not seem to convert it into a dataframe so that it can be appended with each of the other files. It is stored online as a .txt file.</p> <pre>...
<p>Off the bat, you import <code>pandas</code> as <code>pd</code> so you need use that when calling the <code>DataFrame()</code> method. Secondly, pandas is not parsing the text into a csv table. It would require a tad more manipulation to read in that text. Pandas can actually just read in the csv from a url though, s...
python|pandas|dataframe|beautifulsoup
0
3,791
72,818,097
Tensorflow Federated Learning on ResNet failse
<p>I do some some experiments with the tensorflow federated learning API. Actualy I try to train a simple ResNet on 10 Clients. Based on the data and metrics, the training seems to be successful. But the evaluation as well as local and federated fails.</p> <p>Does anyone have an advice?</p> <p>The model:</p> <pre><cod...
<p>The Problem was the BatchNormalization Layer. During execution of the next() function in the tensorflow federated framework only the trainable weights will processed. The value of the BatchNormalization Layer are non-trainable. But every client will have their own mean and standard deviation. For this layer the trai...
python|tensorflow|machine-learning|tensorflow-federated|federated-learning
0
3,792
72,790,292
Good way to represent a data form in Python
<p>I wanted some general advice on how to represent a certain data form in image format. I have two arrays <code>A</code> and <code>B</code>.</p> <p><code>A[0]=array([0, 1]), A[1]=array([0, 3])</code> represents connection from 0 to 1 and 0 to 3 respectively. In general, <code>[i,j]</code> elements in <code>A</code> re...
<p>It looks like what you're trying to do is to set up a directed graph with labeled edges. For that, I believe networkx (<a href="https://networkx.org/documentation/stable/index.html" rel="nofollow noreferrer">https://networkx.org/documentation/stable/index.html</a>) should have what you need. See also <a href="https:...
python|numpy
1
3,793
72,802,464
Tensorflow - Received a label value of 99 which is outside the valid range of [0, 10)
<p>I was trying to make a cifar100 model. When I was beginning to train the model, I got this error</p> <blockquote> <p>Node: 'sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits' Received a label value of 99 which is outside the valid range of [0, 10). Label values:...
<p>Your dataset is made up of 100 different classes and not 10, hence the 100 in &quot;cifar100&quot;. So just change this line in your code:</p> <pre><code> tf.keras.layers.Dense(100, activation= 'softmax') </code></pre> <p>and it will work.</p>
python|tensorflow|machine-learning|keras|artificial-intelligence
2
3,794
72,658,313
How to cut float value to 2 decimal points
<p>I have a Pandas Dataframe with a float column. The values in that column have many decimal points but I only need 2 decimal points. I don't want to round, but truncate the value after the second digit.</p> <p>this is what I have so far, however with this operation i always get NaN's:</p> <pre><code>t['latitude']=[18...
<p>The simpliest way to truncate:</p> <pre class="lang-py prettyprint-override"><code>t = pd.DataFrame() t['latitude']=[18.398, 18.4439, 18.346, 37.5079, 38.11, 38.2927] t['latitude'] = (t['latitude'] * 100).astype(int) / 100 print(t) &gt;&gt; latitude 0 18.39 1 18.44 2 18.34 3 37.50 4 38.11 5 3...
python|pandas
1
3,795
72,590,936
Error saving keras model: "RuntimeError: Mismatching ReplicaContext.", "ValueError: Error when tracing gradients for SavedModel."
<p>I've made a keras model. It works and trains well. But when I try to save that model, I get an error. For some reason it saves successfully before training, but when I try to save it after training, it does not work.</p> <p>Platform: Arch Linux. Tensorflow is installed from official arch repos, package &quot;python-...
<p>I installed python through <code>conda</code> and tensorflow through <code>pip</code>. Now it works.</p> <p>Full instructions:</p> <ol> <li>Install <code>cuda</code> and <code>cudnn</code>: <code>$ sudo pacman -S cuda cudnn</code></li> <li>Install <code>miniconda3</code> package from <code>AUR</code>. I use <code>pa...
python|tensorflow|keras
0
3,796
59,797,830
Unable to write function for df.columns to factorize()
<p>I have a dataframe df:</p> <pre><code>age 45211 non-null int64 job 45211 non-null object marital 45211 non-null object default 45211 non-null object balance 45211 non-null int64 housing 45211 non-null object loan 45211 non-null object contact 45211 non-null...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.select_dtypes.html" rel="nofollow noreferrer"><code>DataFrame.select_dtypes</code></a> first:</p> <pre><code>object_df = df.select_dtypes(object) int_df = df.select_dtypes(np.number) </code></pre> <p>And then create lambda func...
python-3.x|pandas|dataframe
0
3,797
59,534,288
How to correctly deal with one-hot-encoding and multi-dimensional data in tensorflow RNN
<p>I'm creating a binary classifier that classifiers letter sequences e.g 'BA'.</p> <p>Each sequence is made up of 2 letters encoded as one-hot vectors. For example, the sequence 'BA' is <code>[[0, 1, 0, 0], [1, 0, 0, 0]]</code>. </p> <p>(The sequences are longer in my original code but I want to keep my question sim...
<p>This line is the culprit. LSTM expects 3 dimensional input. In your case you are trying to pass a 4 dimensional input (remember that Keras add an additional batch dimension to the input shape). So, getting rid of the first <code>2</code> will solve your issue.</p> <pre><code>model.add(LSTM(128, i...
python|tensorflow|machine-learning|recurrent-neural-network|one-hot-encoding
2
3,798
59,493,282
Tensorflow GPU Device "Failed to get device properties"
<p>When I run <code>session.run()</code> with my deep learning model in Python Tensorflow, for some reason, I get the following error:</p> <pre><code>E tensorflow/core/grappler/clusters/utils.cc:87] Failed to get device properties, error code: 30 Failed to initialize GPU device #0: unknown error \tensorflow/core/ker...
<p>I actually was able to resolve it by updating my NVIDIA GPU graphics driver. Now it's working!</p>
tensorflow|gpu
-2
3,799
59,565,271
Save Pandas Dataframe Object inside Dictionary
<p>I have a pandas dataset and I was wondering if I can include it into a dictionary to export it as pickle together with other stuff.</p> <p>i.e.</p> <pre><code>import pandas as pd import pickle raw_data = {'first_name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'], 'last_name': ['Miller', 'Jacobson', 'Ali', '...
<p>You can save the dict with</p> <pre><code>with open('shared.pkl', 'wb') as f: pickle.dump(dict, f) </code></pre> <p>and then open it with</p> <pre><code>with open('shared.pkl', 'rb') as f: dict_ = pickle.load(f) </code></pre>
python|pandas|dictionary
1