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
373,800
59,272,234
AttributeError: module 'tensorflow' has no attribute 'app': error
<p>I am currently following this <a href="https://github.com/EdjeElectronics/TensorFlow-Object-Detection-API-Tutorial-Train-Multiple-Objects-Windows-10" rel="nofollow noreferrer">tutorial</a> at section 4. When I run the command to generate the TF Records it returns a trace-back error for the generate_tfrecord.py file....
<p>Or you can simpy add <code>import tensorflow.compat.v1 as tf tf.disable_v2_behavior()</code> instead of <code>import tensorflow as tf</code></p>
python|tensorflow|machine-learning|artificial-intelligence
1
373,801
59,305,940
@tf.function is slowing down training step
<p>I am using the following tf.function decorated training step:</p> <pre><code>@tf.function def train_step(inputs, labels): with tf.GradientTape(persistent=True) as tape: predictions = model([X, F], training=True) losses = [l_f(tf.expand_dims(labels[:,i], axis=-1), predictions[i]) for i, l_f in en...
<p>From what I read, <code>tf.function</code> should not include any assignment to the graph vars for it to run smoothly.</p> <p>In a training step, you are changing the weights of the model, thus violating this. </p> <p>I'm not sure this is the reason, but you can try to leave <code>tf.function</code> only in the lo...
python|tensorflow|keras
0
373,802
59,269,250
TensorFlow 2.0, error in keras.applications (as_list() is not defined on an unknown TensorShape)
<p>There are several questions on SO with this error:</p> <pre><code>ValueError: as_list() is not defined on an unknown TensorShape. </code></pre> <p>and a few relevant issues on git as well: <a href="https://github.com/tensorflow/tensorflow/issues/26305" rel="nofollow noreferrer">1</a>, <a href="https://github.com/t...
<p>I fixed this error by tf.cast(label, tf.float32) after importing the masks.</p>
tensorflow|keras|deep-learning|tensorflow2.0|tf.keras
0
373,803
59,242,835
CTC: blank must be in label range
<h1>summary</h1> <p>I'm adding alphabets to captcha recognition, but pytorch's CTC seems to not working properly when alphabets are added.</p> <h1>What I've tried</h1> <p>At first, I modified <code>BLANK_LABEL</code> to 62 since there are 62 labels(0-9, a-z, A-Z), but it gives me runtime error <code>blank must be in la...
<p>This error will occur when the index of blank is larger than the total number of classes, which equals <code>number of chars + blank</code>. What's more, the index starts from <code>0</code>, instead of <code>1</code>, so if you have <code>62</code> characters in total, their index should be <code>0-61</code> and th...
python|pytorch|ctc
1
373,804
59,111,486
Plot groupby of groupby pandas
<p>The data is a time series, with many member ids associated with many categories: </p> <pre><code>data_df = pd.DataFrame({'Date': ['2018-09-14 00:00:22', '2018-09-14 00:01:46', '2018-09-14 00:01:56', '2018-09-14 00:01:57', ...
<p>Creating your dataframe</p> <pre><code>import pandas as pd data_df = pd.DataFrame({'Date': ['2018-09-14 00:00:22', '2018-09-14 00:01:46', '2018-09-14 00:01:56', '2018-09-14 00:01:57', '2018-09-14 00:01:5...
python|pandas|for-loop|matplotlib|pandas-groupby
1
373,805
59,080,681
Forward Propagate RNN using Pytorch
<p>I am trying to create an RNN forward pass method that can take a variable input, hidden, and output size and create the rnn cells needed. To me, it seems like I am passing the correct variables to self.rnn_cell -- the input values of x and the previous hidden layer. However, the error I receive is included below. </...
<p>I am not an expert at RNNs but giving it a try.</p> <pre><code>class RNN(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(RNN, self).__init__() self.hidden_size = hidden_size self.rnn_cell = nn.RNN(input_size, hidden_size) self.fc = nn.Linear(hidden_size, output_size) d...
python|machine-learning|pytorch|recurrent-neural-network
1
373,806
59,222,218
Does the backend matter for savefig
<p>I have a script which plots some pandas data, and then either shows the plot interactively with <code>plt.show()</code>, or saves it to a file with <code>plt.savefig(args.out)</code>.</p> <pre><code>import matplotlib.pyplot as plt # set up the dataframe here ax = df.plot.line(x=0, title=args.title, figsize=(12,8)...
<p>When showing a figure, the backend obviously matters, because it provides two things: </p> <ul> <li>The renderer to draw the image</li> <li>The GUI within which the image is shown.</li> </ul> <p>When saving a figure, only the former matters. However, matplotlib provides a multitude of export formats. At the end, t...
python-3.x|pandas|matplotlib
2
373,807
59,201,907
Overfitting on image classification
<p>I'm working on image classification problem of sign language digits dataset with 10 categories (numbers from 0 to 10). My models are highly overfitting for some reason, even though I tried simple ones (like 1 Conv Layer), classical ResNet50 and even state-of-art NASNetMobile.</p> <p>Images are colored and 100x100 i...
<p>This is going to be a very interesting answer. There's so many things you need to pay attention to when looking at a problem. Fortunately, there's a methodology (might be vague, but still a methodology).</p> <p><strong>TLDR</strong>: Start your journey at the data, not the model.</p> <h2>Analysing the data</h2> <...
python|tensorflow|keras|deep-learning|computer-vision
8
373,808
59,156,753
how to extract features from the exist data based on time and date
<p>I am wondering how can i extract total transaction count per user, monthly total transaction count, weekly total transaction count of the user, daily total transaction counts, hourly total transaction count and ten mins total transaction counts as well as the average of the six above periods using the following form...
<p>You can use this:</p> <pre><code>df['date'] = pd.to_datetime(df['date']) asd = df.set_index('date').groupby('user').resample('1M') df_result = pd.DataFrame({'mean':asd.mean()['value'], 'max':asd.max()['value'], 'sum':asd.sum()['value']}) df_result mean max sum user date ...
python|pandas
0
373,809
59,334,422
Creating new column based on condition and extracting respective value from other column. Pandas Dataframe
<p>I am relatively new to this field and am working with a data set to find meaningful insights into customer behavior. My <code>dataset</code> looks like:</p> <p>customerId week first_trip_week rides 0 156 44 36 2 1 164 44 38 6 2 224 42 ...
<p>If I'm understanding you correctly, you want to create new columns in the same dataframe for weeks 44, 43, and 42 with the correct values for each customerId and NaN for those that don't have it. If your original dataframe has all the user data, I would first filter for dataframes that have the correct week number</...
pandas
0
373,810
59,262,364
Iterating / Slicing over a dataframe and performing mathematical calculations
<p><a href="https://i.stack.imgur.com/oi8XC.jpg" rel="nofollow noreferrer">Dataframe image</a></p> <p>the operation that I intend to perform is whenever there is a '2' in the column 3, we need to take that entry and take the column 1 value of that entry and subtract the column 1 value of the previous entry and then mu...
<p>Perhaps this <a href="https://stackoverflow.com/questions/23664877/pandas-equivalent-of-oracle-lead-lag-function">question</a> will help you</p> <p>I think in SQL way, so basically you will make new column that filled with the value from the row above it.</p> <pre><code>df['column1_lagged'] = df['column 1'].shift(...
python|pandas|dataframe
0
373,811
59,408,554
Applying lambda function in two data frames in the same time
<p>I have two data frames and I want to apply only one lambda function in both of them in the same time. They are string.</p> <pre><code>df1: A B C 0 1 1 2 1 2 0 0 2 1 2 2 3 1.5 1 3 df2: A B 0 3 1 1 4 5 2 2.7 2 3 3.1 4 </code></pre> <p>Some Thing like :</...
<p>I believe you need convert output to list of Dataframes with <code>astype</code> function:</p> <pre><code>dfs = list(map(lambda x: x.astype(float), [df1, df2])) </code></pre>
python|pandas
2
373,812
59,341,819
Sample every nth minute in a minute based datetime column in python
<p>How to select every 5th minute row in a dataframe? If 5th minute is missing then 4th or 3rd would do..</p> <p>I DO NOT WANT MEAN OR ANY AGGREGATE</p> <p>I have tried:</p> <pre><code>df.groupby(pd.TimeGrouper('5Min'))['AUDUSD'].mean() df.resample('5min', how=np.var).head() </code></pre> <p>both are not producing...
<p>This works for me, except i used first as i don't know what method your using:</p> <pre><code>df.set_index(pd.DatetimeIndex(df['DATETIME'])) df.set_index(pd.DatetimeIndex(df['DATETIME'])).resample("5T").agg('first') ...
python|pandas|pandas-groupby
4
373,813
59,117,360
How to reshape an array of arrays in Python using Numpy
<p>As you can see below I have created three arrays that contain different random numbers:</p> <pre><code>np.random.seed(200) Array1 = np.random.randn(300) Array2 = Array1 + np.random.randn(300) * 2 Array3 = Array1 + np.random.randn(300) * 2 data = np.array([Array1, Array2 , Array3]) #data.reshape(data, (Array3, Arr...
<p>You can use <code>.T</code> to transpose either the data <code>data = np.array([Array1, Array2 , Array3]).T</code> or the dataframe <code>mydf = pd.DataFrame(data).T</code>. </p> <p>Output:</p> <pre class="lang-py prettyprint-override"><code> 0 1 2 295 -0.126758 1.697413 0.399351 296 ...
python|pandas|numpy
6
373,814
59,339,005
elementwise comparison failed; returning scalar, but in the future will perform elementwise comparison
<pre><code>n1data = pcatrain_data[train_labels[0, :] == i, :] n2data = pcatrain_data[train_labels[0, :] == j, :] </code></pre> <p>the shape of pcatrain_data is (14395,40) and the shape of train_labels is (1,14395)</p> <p>it is my understanding that "train_labels[0, :] == i" will return a list of boolean of size 14395...
<p>you need to write</p> <pre><code>import warnings import numpy as np warnings.simplefilter(action='ignore', category=FutureWarning) </code></pre> <p>Then the warning can disapear</p>
python|python-3.x|numpy
-1
373,815
59,091,544
In python3: strange behaviour of list(iterables)
<p>I have a specific question regarding the behaviour of iterables in python. My iterable is a custom built Dataset class in pytorch:</p> <pre><code>import torch from torch.utils.data import Dataset class datasetTest(Dataset): def __init__(self, X): self.X = X def __len__(self): return len(sel...
<p>A bunch of useful links:</p> <ol> <li><a href="https://docs.python.org/3/reference/datamodel.html#emulating-container-types" rel="nofollow noreferrer">[Python 3.Docs]: Data model - Emulating container types</a></li> <li><a href="https://docs.python.org/3/library/stdtypes.html#iterator-types" rel="nofollow noreferre...
python|list|dictionary|pytorch|iterable
1
373,816
59,292,524
index 5 is out of bounds for axis 1 with size 5
<p>Hi I have the following function which produces an out of bounds error:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import pandas as pd dataset = pd.read_csv('50_Startups.csv') x = dataset.iloc[:,:-1].values y = dataset.iloc[:,4].values from sklearn.preprocessing import LabelEncoder , OneHot...
<p>Well an array with a size of 5 has it's last index as 4. </p> <p>An array always starts at index 0 and not 1.</p>
python|pandas|numpy
1
373,817
59,154,530
Why is matplotlib plotting so much slower than pd.DataFrame.plot()?
<p>Hello dear Community,</p> <p>I haven't found something similar during my search and hope I haven't overseen anything. I have the following issue:</p> <p>I have a big dataset whichs shape is 1352x121797 (1353 samples and 121797 time points). Now I have clustered these and would like to generate one plot for each cl...
<p>Posting as answer as it may help OP or someone else: I had the same problem and found out that it was because the data I was using as x-axis was an Object, while the y-axis data was float64. After explicitly setting the object to DateTime, plotting With Matplotlib went as fast as Pandas' df.plot(). I guess that Pand...
python|pandas|matplotlib|plot
2
373,818
59,426,684
How to append rows from one Dataframe to another having different column structure
<p>I have two excel files, the first one has 34 columns and the second one has 19 columns, the first one has all these 19 columns but if I add some empty column I can get the structure of the first file. I want to append rows from 2nd file to the first file</p> <p>I added empty columns to get the same structure as the...
<p>I don't know if it is efficient or not but this is what I did:</p> <pre><code>new_res = pd.DataFrame(data = resolved_planning.values, columns = merged.columns) new_merged=merged.append(new_res, ignore_index = True, sort = False) </code></pre> <p>I made a new data frame (new_res) with the first data frame's header ...
python|excel|pandas|numpy
0
373,819
59,075,406
Can't plot in jupyter notebook
<p>I have a jupyter notebook script and a part of it looks like that:</p> <pre><code>import pandas as pd import matplotlib import matplotlib.pyplot as plt import numpy as np %matplotlib inline matplotlib.style.use('ggplot') matplotlib.rc('text', usetex=True) import scipy.stats df = pd.read_csv("./titanic-train.csv...
<p>Okay so I found a solution on my problem.. </p> <p>First I uninstalled Anaconda. I also deleted the folder found in the Users Directory .anaconda3 it was. I reinstalled like normal and have run my script. After that I got 2 external windows to install packages from LaTex. (I didn't get them last time) </p> <p>BUT...
python|pandas|jupyter-notebook|latex
0
373,820
59,317,543
Expected object or Value while read the .json file in Python
<p>I am trying to read the .json file in python. Here is my python code:</p> <pre><code>import pandas as pd df_idf = pd.read_json('/home/lazzydevs/Data/datajs.json',lines = True) print("Schema:\n\n",df_idf.dtypes) print("Number of questions,columns=",df_idf.shape) </code></pre> <p>I checked my json file also it's a...
<p>The following piece of code seems to work on my machine.</p> <pre><code>import pandas as pd df_idf = pd.read_json('/home/lazzydevs/Data/datajs.json') print("Schema:\n\n",df_idf.dtypes) print("Number of questions,columns=",df_idf.shape) </code></pre>
python|json|pandas
1
373,821
59,297,543
Why do I get the 'loop of ufunc does not support argument 0 of type int' error for numpy.exp?
<p>I have a dataframe and I'd like to perform exponential calculation on a subset of rows in a column. I've tried three versions of code and two of them worked. But I don't understand why one version gives me the error.</p> <pre><code>import numpy as np </code></pre> <p>Version 1 (working)</p> <pre><code>np.exp(test...
<p>I guess your problem occurs because some NumPy functions explicitly require <code>float</code>-type arguments. Your code <code>np.exp(test)</code>, however, has type <code>int</code>.</p> <p>Try forcing it to be <code>float</code></p> <pre><code>import numpy as np your_array = your_array.float() output = np.exp(you...
python|numpy|exponential
36
373,822
59,396,520
calculate distacne of two cartesian coordinates
<p>I am still new to python and have practiced python as automation tool to get used to.</p> <p>Now I want to try mathematical calculation in python.</p> <p>I have tried to calculate distance of two cartesian coordinate I extracted from a hand practice data:</p> <p>in temp2:</p> <blockquote> <p>-0.329637489 3.481200...
<p>You can load the data directly in a numpy <code>array</code> using <code>np.loadtxt</code>:</p> <pre><code>a= np.loadtxt('../filename.txt') a array([[-0.32963749, 3.4812 , 1.7402 ], [ 2.38905981, 1.00023 , 8.65321 ]]) </code></pre> <p>Then perform operations to compute distance:</p> <pre><cod...
python|numpy
1
373,823
59,399,939
how to compare the sum score of men to sum score of women to get the count of countries?
<p>Let's say this is my data frame:</p> <pre><code>country Edition sports Athletes Medal Gender Score Germany 1990 Aquatics HAJOS, Alfred gold M 3 Germany 1990 Aquatics HIRSCHMANN, Otto silver M 2 Germany 1990 Aquatics DRIVAS, Dim...
<p>You can do this:</p> <pre><code>sum_men = df[df['Gender']=='M'].groupby ('Country' )['Score'].sum().reset_index() #watch the reset_index() sum_women = df[df['Gender']=='W'].groupby ('Country' )['Score'].sum().reset_index() new_df = sum_men.merge(sum_women, on="Country") new_df['diff'] = new_df['Score_x'] - new_df['...
python|pandas
1
373,824
59,427,330
How to save full list from pandas function into variable
<p>I was having a problem when I created a function like this: </p> <pre><code> def printlist(x): for column in x: global y print(list(x[column])) </code></pre> <p>I get a completely full list, as such: </p> <blockquote> <p>['MATCH', 'MATCH', 'MATCH'] ['MATCH', 'MATCH', 'MATCH'] ['B...
<p>Use this code:</p> <pre><code>def printlist(df): column_list = [] for column in df: column_list.append(df[column]) return column_list list = printlist(df) </code></pre>
python|pandas|list|function
0
373,825
59,178,625
Error message when read multiple text elements using selenium
<p>I am clicking on a certain link and would like to read all the text in a given class and return that as a row in pandas dataframe</p> <p>This is the code I have</p> <pre><code>page_link = 'http://beta.compuboxdata.com/fighter' wait = WebDriverWait(cdriver,10) wait.until(EC.visibility_of_element_located((By.ID,'s2i...
<p>Here is a solution. The Timeout exception will be handled here.</p> <pre><code> age_link = 'http://beta.compuboxdata.com/fighter' driver.get(age_link) wait = WebDriverWait(driver,10) wait.until(EC.visibility_of_element_located((By.ID,'s2id_autogen1'))).send_keys('Deontay Wilder') wait.until(EC.visibility_of_elem...
python|pandas|selenium|selenium-webdriver
0
373,826
59,078,267
How to count occurances of multiple items in numpy?
<p>Assume the folowing numpy array:</p> <pre><code>[1,2,3,1,2,3,1,2,3,1,2,2] </code></pre> <p>I want to <code>count([1,2])</code> to count all occurrences of 1 and 2, in a single run, yielding something like</p> <pre><code>[4, 5] </code></pre> <p>corresponding to a <code>[1, 2]</code> input.</p> <p>Is it supported...
<pre><code># Setting your input to an array array = np.array([1,2,3,1,2,3,1,2,3,1,2,2]) # Find the unique elements and get their counts unique, counts = np.unique(array, return_counts=True) # Setting the numbers to get counts for as a set search = {1, 2} # Gets the counts for the elements in search search_counts = [...
python|numpy
1
373,827
59,276,655
How to sum an ND array in python based on like entries?
<p>Let's say I have an ND array in python represented by the following scheme:</p> <pre><code>["Event ID", "Event Location", "Event Cost"] data = \ [[1, 0, 500] [1, 0, 250] [1, 1, 300] [2, 0, 750] [2, 1, 400] [2, 1, 500]] </code></pre> <p>How can I collapse this array to sum up the cost for entries with the same even...
<p>This is a classic use-case for <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow noreferrer">itertools.groupby</a>:</p> <pre class="lang-py prettyprint-override"><code>import itertools result = [ [i, loc, sum(cost for _, _, cost in costs)] for (i, loc), costs in ite...
python|numpy
1
373,828
59,233,282
Jupyter Pandas - dropping items which have average over a threshold
<p>I have a data frame with items and their prices, something like this: <code> ╔══════╦═════╦═══════╗ ║ Item ║ Day ║ Price ║ ╠══════╬═════╬═══════╣ ║ A ║ 1 ║ 10 ║ ║ B ║ 1 ║ 20 ║ ║ C ║ 1 ║ 30 ║ ║ D ║ 1 ║ 40 ║ ║ A ║ 2 ║ 100 ║ ║ B ║ 2 ║ 20 ║ ║ C ║ 2 ║ 30 ║ ║ D ║ ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> for <code>mean</code>s per groups with same size like original, so possible filter out by <a href="http://pandas.pydata.org/pandas-docs/stabl...
python|pandas|dataframe|jupyter|vaex
1
373,829
59,084,208
parse datetime resulting in ValueError
<p>I tried to parse a timestamp of a CSV file (first column named "time"). The timestamp has the format: <code>01.10.2016 00:10:00</code> (<code>dd.mm.yyyy HH:MM:SS</code>)</p> <pre><code> timestamp_parser = lambda x: pd.datetime.strptime(x, "%d.%m.%Y %H:%M:%S") df_pi_data = pd.read_csv( "pi_daten.csv", use...
<pre><code>time;temperature 01.10.2016 00:00; 23,13854599 01.10.2016 00:10; 23,24945831 01.10.2016 00:20; 23,16853714 </code></pre> <pre class="lang-py prettyprint-override"><code>import pandas as pd timestamp_parser = lambda x: pd.datetime.strptime(x, "%d.%m.%Y %H:%M") df = pd.read_csv("test.txt", sep=";", decimal='...
python|pandas|parsing
0
373,830
59,347,111
Pytorch RuntimeError: Expected object of device type cuda but got device type cpu for argument #1 'self' in call to _th_index_select
<p>I am training a model that takes tokenized strings which are then passed through an embedding layer and an LSTM thereafter. However, there seems to be an error in the input, as it does not pass through the embedding layer.</p> <pre class="lang-py prettyprint-override"><code>class DrugModel(nn.Module): def __ini...
<p>setting <code>model.device</code> to cuda does not change your inner module devices, so <code>self.lstm</code>, <code>self.char_embed</code>, and <code>self.dist_fc</code> are all still on cpu. correct way of doing it is by using <code>DrugModel().to(device)</code></p> <p>in general, it's better not to feed a <code...
runtime-error|gpu|pytorch|embedding
6
373,831
59,099,762
Python : Reverse Geocoding to get city name and state name in pandas
<p>I have a large dataset with latitudes and longitudes and i want to map city and state in front of them. Approach which i was using is this:</p> <pre><code>import pandas as pd import reverse_geocoder as rg import pprint df = pd.read_csv("D:\data.csv") </code></pre> <pre><code>def reverseGeocode(coordinates): ...
<p>Although others solution may be valid, but you can find more elegant one:</p> <pre><code>import pandas as pd import reverse_geocoder as rg import pprint df = pd.read_csv("data.csv") def reverseGeocode(coordinates): result = rg.search(coordinates) return (result) if __name__=="__main__": # Coordi...
python|pandas|mkreversegeocoder
1
373,832
59,085,947
Consume REStful API data with python => from JSON to pandas DataFrame
<pre><code>from flask import Flask, request from flask_restful import Resource, Api, reqparse #from flask_jwt import JWT, jwt_required from pymongo import MongoClient import pandas as pd app = Flask(__name__) app.secret_key = 'xxx' api = Api(app) class Data(Resource): def get(self): client = MongoClient("...
<p>It is an issue with your JSON data, try below:</p> <pre><code>data = r.text str_data = json.loads(data) json_data = json.loads(str_data) pd.DataFrame(json_data) </code></pre> <p>or</p> <pre><code>data = r.text json_data = json.loads(data) pd.read_json(json_data) </code></pre> <p><a href="https://i.stack.imgur.co...
python|pandas|flask-restful
2
373,833
59,121,560
Error in downloading mnist data unknown url type: HTTPS
<p>when I try to load the mnist dataset using the code </p> <pre><code>import tensorflow as tf import numpy as np from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import Convolution2D, MaxPooling2D from keras.utils import np_utils (X_train, y_train), (...
<p>In the <code>mnist.py</code> file, change the </p> <pre><code>origin_folder = 'https://storage.googleapis.com/tensorflow/tf-keras-datasets/' </code></pre> <p>to</p> <pre><code>origin_folder = 'http://storage.googleapis.com/tensorflow/tf-keras-datasets/' </code></pre>
python|tensorflow|keras|https|mnist
0
373,834
59,082,202
how to export data from python pandas with user defined message
<p>From the pandas data frame, I got the list of customer info and want to export it to an excel printing all the customer info like: </p> <p>"This customer James"</p> <p>"This customer Mark"</p> <p>''''''''</p> <p>''''''''</p> <p>but am getting only 1 customer to excel instead of 10.</p> <p>Below is the code i t...
<p>If you want it in separated cells then you have to change first (or second) argument in <code>write()</code></p> <p>I use <code>enumerate()</code> to have different values </p> <pre><code>import xlsxwriter workbook = xlsxwriter.Workbook('filename.xlsx') worksheet1 = workbook.add_worksheet() info = ['Adam','Ja...
python|pandas
2
373,835
59,366,048
Is there a way to write a custom BCE loss in pytorch?
<p>I am writing a custom BCE in pytorch but in some cases it returns -inf and nan most cases. Which is due to the log function.</p> <pre><code>bce_loss=y_true*torch.log2(y_pred) +(one_torch-y_true)*torch.log2(one_torch-y_pred) </code></pre> <p>Is there a way to rewrite this? Note y_pred is a sigmoid output which is b...
<p>You can clamp the preds to stop from log error.</p> <p><code>y_pred = torch.clamp(y_pred, 1e-7, 1 - 1e-7)</code></p>
python-3.x|machine-learning|neural-network|computer-vision|pytorch
1
373,836
59,312,917
Conditional repetitive cumulative sums on python
<p>I need to write code on python that computes cumulative sums from an axis of an array but every certain number of elements (for instance 200), the idea is that I want to add up error deviation but for the last 200 time step over an array of 10000, considering the first 200 time step as initial conditions of zero. Th...
<p>Why not compute cumulative sum to compute a sum over a running window</p> <pre><code>cx=x.cumsum() y=cx[step:] - cx[:-step] </code></pre>
python|numpy|anaconda
1
373,837
59,168,803
ModuleNotFoundError: No module named 'utils.datasets'
<p>I am using Python 3.6.8 on Windows 10<br> I installed <strong>tensorflow, keras, and utils</strong> using <strong>pip</strong>.</p> <p><code>pip install tensorflow</code> and it installs the version <strong>2.0.0</strong><br> <code>pip install keras</code> and it installs the version <strong>2.3.1</strong><br> <cod...
<p>The utils model what the code your provided want to import is the part of the <a href="https://github.com/oarriaga/face_classification/tree/master/src" rel="nofollow noreferrer">oarriaga/face_classification</a> project.</p> <p>The pip installed <code>utils</code> modul is <strong>quite different</strong> package, s...
python|tensorflow|machine-learning|keras
0
373,838
14,075,326
pandas RuntimeError in tseries/convertor when plotting
<p>When I execute the following statement:</p> <pre><code>DataFrame(randn(3,1),index=[date(2012,10,1),date(2012,9,1),date(2012,8,1)],columns=['test']).plot() </code></pre> <p>I get the following exception:</p> <p>File "/usr/local/lib/python2.7/dist-packages/pandas-0.10.0-py2.7-linux-x86_64.egg/pandas/tseries/conver...
<p>One workaround is to sort before plotting:</p> <pre><code>df.sort().plot() </code></pre> <p><em>It looks like a bug, so I posted it on <a href="https://github.com/pydata/pandas/issues/2609" rel="nofollow">github</a>!</em></p> <p>Note: this seems to plot ticks better if you use datetime rather than date:</p> <pre...
python|plot|pandas
0
373,839
13,924,047
NumPy: 1D interpolation of a 3D array
<p>I'm rather new to NumPy. Anyone have an idea for making this code, especially the nested loops, more compact/efficient? BTW, dist and data are three-dimensional numpy arrays.</p> <pre><code>def interpolate_to_distance(self,distance): interpolated_data=np.ndarray(self.dist.shape[1:]) for j in range(interp...
<p>Alright, I'll take a swag with this:</p> <pre><code>def interpolate_to_distance(self, distance): dshape = self.dist.shape dist = self.dist.T.reshape(-1, dshape[-1]) data = self.data.T.reshape(-1, dshape[-1]) intdata = np.array([np.interp(distance, di, da) for di, da in zip(di...
python|multidimensional-array|numpy|interpolation
3
373,840
14,124,474
Using __call__ method of a class as a input to Numpy curve_fit
<p>I would like to use a <code>__call__</code> method of a class as a input to a Numpy curve_fit function due to my rather elaborate function and data preparation process (fitting analytical model data to some measurements). It works just fine by defining a function, but I can't get it to work with classes.</p> <p>To ...
<p>Easy (although, not pretty), just change it to:</p> <pre><code>popt, pcov = curve_fit(goal.__call__, xdata, ydata) </code></pre> <p>It's interesting that numpy forces you to pass a function object to <code>curve_fit</code> rather than an arbitrary callable ...</p> <p>quickly inspecting the source for <code>curve_...
python|class|numpy|call|curve-fitting
3
373,841
14,119,892
Python 4D linear interpolation on a rectangular grid
<p>I need to interpolate temperature data linearly in 4 dimensions (latitude, longitude, altitude and time).<br> The number of points is fairly high (360x720x50x8) and I need a fast method of computing the temperature at any point in space and time within the data bounds.</p> <p>I have tried using <code>scipy.interpol...
<p>In the same ticket you have linked, there is an example implementation of what they call <em>tensor product interpolation</em>, showing the proper way to nest recursive calls to <code>interp1d</code>. This is equivalent to quadrilinear interpolation if you choose the default <code>kind='linear'</code> parameter for ...
python|numpy|scipy|interpolation
13
373,842
44,870,655
Do scipy and numpy svd or eig always return the same singular/eigen vector?
<p>Since the SVD decomposition is not unique (pairs of left and right singular vectors can have their sign flipped simultaneously), I was wondering to what extent the U and V matrix returned by <code>scipy.linalg.svd()</code> are 'deterministic' / always the same? </p> <p>I tried it a few times with a random array on ...
<p>SciPy and Numpy both compute the SVD by out-sourcing to the LAPACK <code>_gesdd</code> routine. Any deterministic implementation of this routine will produce the same results every time on a given machine with a given LAPACK implementation, but as far as I know there is no guarantee that different LAPACK implementat...
numpy|scipy|linear-algebra|svd|eigenvector
3
373,843
44,943,790
Applying function to Pandas with GroupBy along direction of the grouping variable
<p>I have a cohort of N people and I computed a correlation matrix of some quantities (q1_score,...q5_score)</p> <pre><code> df.groupby('participant_id').corr() Out[130]: q1_score q2_score q3_score q4_score q5_score participant_id ...
<p>Stack your data, and do another groupby:</p> <pre><code>df.groupby('participant_id').corr().stack().groupby(level = [1,2]).median() </code></pre> <p>Edit: Actually, you don't need to stack if you don't want to:</p> <pre><code>df.groupby('participant_id').corr().groupby(level = [1]).median() </code></pre> <p>work...
pandas|grouping
2
373,844
44,966,229
Unsupported type for timedelta
<p>I'm trying to increase dates in the pandas dataframe by values contained in the other column of the same dataframe like this</p> <pre><code>loans['est_close_date'] = loans['dealdate'] + loans['tenor_weeks'].apply(lambda x: dt.timedelta(weeks =x)) </code></pre> <p>but I keep getting error as:</p> <blockquote> <p...
<p>For me you solutions work perfectly, maybe necessary upgrade pandas/python.</p> <p>I add pure pandas solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_timedelta.html" rel="nofollow noreferrer"><code>to_timedelta</code></a>:</p> <pre><code>rng = pd.date_range('2017-04-03', perio...
python|pandas|numpy
4
373,845
44,882,372
How to learn relation between field description and possible categories
<p>I have a relation between products that looks like this</p> <p><a href="https://i.stack.imgur.com/lDFxF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lDFxF.png" alt="enter image description here"></a></p> <p>Is <a href="https://www.tensorflow.org/tutorials/seq2seq" rel="nofollow noreferrer"><e...
<p><code>Seq2Seq</code> essentially have two different recurrent neural networks tied together : an encoder RNN that takes input <code>text tokens</code> and an decoder RNN that starts generating <code>text tokens</code> based on the outputs from the encoder RNN. Its a sequence to a sequence network. But your case as i...
tensorflow
1
373,846
44,868,306
How to randomly mix N arrays in numpy?
<p>I have a list of N numpy arrays of the same shape. I need to combine them into one array in the following way. Each element of the output array should be randomly taken from the corresponding position of one of the input array.</p> <p>For example, if I need to decide what value to use at position [2,0,7], I take al...
<pre><code>import numpy as np import itertools as it x = np.random.choice(np.arange(10), (2,3,4)) # pass probabilities with p=... N = 10 a = [k*np.ones_like(x) for k in range(N)] # list of N arrays of same shape y = np.empty(a[0].shape) # output array # Generate list of all indices of arrays in a (no matter what s...
python|arrays|numpy|random
0
373,847
45,179,079
How to use a nested dictionary with .map for a Pandas Series? pd.Series([]).map
<p>I'm trying to <code>map</code> certain values of a series, while keeping the others intact. In this case, I was to change <code>dmso --&gt; dmso-2</code>, <code>naoh --&gt; naoh-2</code>, and <code>water --&gt; water-2</code> but I'm getting a <code>KeyError</code>.</p> <p>First I'm doing a boolean statement to se...
<p>If I understood correctly, you can do simply</p> <pre><code>Se_data.replace({ 'dmso': 'dmso-2', 'naoh': 'naoh-2', 'water': 'water-2', }) </code></pre> <p>which will leave all other values intact.</p> <hr> <p>For what it's worth, your code wasn't working because the expression</p> <pre><code>{"dmso":...
python|pandas|dictionary|vector|mapping
1
373,848
45,154,180
How to dynamically freeze weights after compiling model in Keras?
<p>I would like to train a GAN in Keras. My final target is BEGAN, but I'm starting with the simplest one. Understanding <em>how to freeze</em> weights properly is necessary here and that's what I'm struggling with.</p> <p>During the generator training time the discriminator weights might not be updated. I would like ...
<p>I've tried this example code a couple months ago and it worked: <a href="https://github.com/fchollet/keras/blob/master/examples/mnist_acgan.py" rel="noreferrer">https://github.com/fchollet/keras/blob/master/examples/mnist_acgan.py</a></p> <p>It's not the simplest form of GAN, but as far as I remembered, it's not to...
python|tensorflow|neural-network|keras|theano
13
373,849
45,216,258
Pandas: extend mask to set regions
<p>I have a Boolean mask in "python pandas", where I want to widen (smear?) each "True" sample. Suppose I have the following:</p> <pre><code>import pandas data = pandas.DataFrame({'col1': [False, True, False, False, False, False, True, False, False, False]}) </code></pre> <p>So the "True" mask looks like:</p> <pre><...
<p>One way you could do it is to use <code>rolling</code> and <code>max</code>:</p> <pre><code>n=1 window = n*2 + 1 data.col1.rolling(window, center=True, min_periods=1).max().astype(bool) </code></pre> <p>Output:</p> <pre><code>0 True 1 True 2 True 3 False 4 False 5 True 6 True 7 True ...
python|pandas
2
373,850
45,118,448
Can't run prediciton because of troubles with tf.placeholder
<p>Apologies, I am new in Tensorflow. I am developing a simple onelayer_perceptron script that just obtaining init parameters trains a Neural Network using Tensorflow:</p> <p>My compiler complains:</p> <blockquote> <p>You must feed a value for placeholder tensor 'input' with dtype float </p> </blockquote> <p>the e...
<p>You are not feeding the input to the place holder; you do it using a <code>feed_dict</code>.</p> <p>You should do something similar:</p> <pre><code> out = session.run(Tensor(s)_you_want_to_evaluate, feed_dict={input_tensor: input of size [batch_size,n_input], output_tensor: output of size [batch size, classes] }) ...
tensorflow|neural-network|perceptron
1
373,851
45,069,431
Python Pandas: Change value associated with each first day entry in every month
<p>I'd like to change the value associated with the first day in every month for a <code>pandas.Series</code> I have. For example, given something like this:</p> <pre><code>Date 1984-01-03 0.992701 1984-01-04 1.003614 1984-01-17 0.994647 1984-01-18 1.007440 1984-01-27 1.006097 1984-01-30 0.991546 198...
<p>One way would to be to use your <code>.groupby((m_ret.index.year, m_ret.index.month))</code> idea, but use <code>idxmin</code> instead on the index itself converted into a Series:</p> <pre><code>In [74]: s.index.to_series().groupby([s.index.year, s.index.month]).idxmin() Out[74]: Date Date 1984 1 1984-01-03...
python|pandas|datetime|dataframe
4
373,852
45,247,500
Incremental data load using pandas
<p>I am trying to implement incremental data import using pandas.</p> <p>I have two dataframes: df_old (original data, loaded before) and df_new (new data, to be merged with df_old). </p> <p>data in df_old/df_new are unique on multiple columns (for simplicity, lets say just 2: key1 and key2). other columns are data ...
<p>Here's one way to do this that's pretty fast:</p> <pre><code>merged = pd.concat([df_old.reset_index(), df_new.reset_index()]) merged = merged.drop_duplicates(["key1", "key2", "val1", "val2"]).drop_duplicates(["key1", "key2"], keep="last") # 100 loops, best of 3: 1.69 ms per loop # key1 key2 val1 val2 change_i...
python|pandas|merge
4
373,853
45,007,081
Convert mat file to pandas dataframe
<p>I want to convert <a href="https://www.dropbox.com/s/galg3ihvxklf0qi/cardio.mat?dl=0" rel="nofollow noreferrer">this file</a> to pandas dataframe.</p> <pre><code>import pandas as pd import scipy.io mat = scipy.io.loadmat('cardio.mat') cardio_df = pd.DataFrame(mat) </code></pre> <p>I get this error : <code>Excepti...
<p>It seems <code>mat</code> is a dict containing <code>X</code> of shape <code>(1831, 21)</code>, <code>y</code> with shape <code>(1831, 1)</code>, and some metadata. Assuming <code>X</code> is the data and <code>y</code> are the labels for the same, you can stack them horizontally with <code>np.hstack</code> and load...
python|pandas|dataframe|mat
10
373,854
44,966,528
Pandas: astype error string to float (could not convert string to float: '7,50')
<p>I am trying to convert a dataframe field from string to float in Pandas.</p> <p>This is the field:</p> <pre><code>In: print(merged['platnosc_total'].head(100)) Out: 0 0,00 1 4,50 2 0,00 3 0,00 4 0,00 5 4,50 6 6,10 7 7,99 8 4,00 9 7,69 10 7,50 </code></pre> <p>Note the...
<p>Need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.replace.html" rel="nofollow noreferrer"><code>replace</code></a> first:</p> <pre><code>print (merged['platnosc_total'].replace(',','.', regex=True).astype(float)) 0 0.00 1 4.50 2 0.00 3 0.00 4 0.00 5 4.50 6 6.10 7...
python|pandas
4
373,855
45,248,327
Numpy Cyclic Broadcast of Fancy Indexing
<p><code>A</code> is an <code>numpy</code> array with shape <code>(6, 8)</code></p> <p>I want:</p> <pre><code>x_id = np.array([0, 3]) y_id = np.array([1, 3, 4, 7]) A[ [x_id, y_id] += 1 # this doesn't actually work. </code></pre> <p>Tricks like <code>::2</code> won't work because the indices do not increase regular...
<p>You can convert <code>y_id</code> to a 2d array with the 2nd dimension the same as <code>x_id</code>, and then the two indices will be automatically broadcasted due to the dimension difference:</p> <pre><code>x_id = np.array([0, 3]) y_id = np.array([1, 3, 4, 7]) ​ A = np.zeros((6,8)) A[x_id, y_id.reshape(-1, x_id.s...
python|numpy|broadcast
2
373,856
45,127,605
Numpy Reshape to obtain monthly means from data
<p>I'm trying to obtain monthly means from an observed precipitation data set for the period 1901-2015. The current shape of my prec variable is <code>(1380(time), 360(lon), 720(lat))</code>, with 1380 being the number of months over a 115 year period. I have been informed that to calculate monthly means, the most effe...
<p>The following snippet will first dice the precipitation array year-wise. We can then use that array to get the monthly average of precipitation.</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; prec = np.random.rand(1380,360,720) &gt;&gt;&gt; ind = np.arange(12,1380,12) &gt;&gt;&gt; yearly_split = n...
python|numpy|mean|reshape
0
373,857
45,188,605
Adding spaces between strings after sum()
<p>Assuming that I have the following pandas dataframe:</p> <pre><code>&gt;&gt;&gt; data = pd.DataFrame({ 'X':['a','b'], 'Y':['c','d'], 'Z':['e','f']}) X Y Z 0 a c e 1 b d f </code></pre> <p>The desired output is:</p> <pre><code>0 a c e 1 b d f </code></pre> <p>When I run the following code, I get:</p>...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>apply</code></a> per rows by <code>axis=1</code> and <code>join</code>:</p> <pre><code>a = data.apply(' '.join, axis=1) print (a) 0 a c e 1 b d f dtype: object </code></pre> <p>Anot...
python|pandas
4
373,858
45,041,510
dictionaries with NaN key to pandas series
<p>I am trying to build a Pandas series by passing it a dictionary containing index and data pairs. While doing so I noticed an interesting quirk. When the dictionary contains <code>NaN</code> keys with an associated value, pandas Series retains the <code>NaN</code> key in the index but sets the corresponding value to ...
<p>Issue has been fixed in pandas 0.23.3 (answered in comments).</p>
python|python-2.7|pandas|dictionary|series
1
373,859
45,115,463
DynamicPartition returns single output instead of multiple
<p>Here is my code which constructs graph using DynamicPartition operation to split a vector [1, 2, 3, 4, 5, 6] by two vectors [1, 2, 3] and [4, 5, 6] using mask [1, 1, 1, 0, 0, 0]:</p> <pre><code>@Test public void dynamicPartition2() { Graph graph = new Graph(); Output a = graph.opBuilder("Const", "a") ...
<p>The <code>DynamicPartition</code> operation returns multiple outputs (one for each partition), but the <a href="https://www.tensorflow.org/api_docs/java/reference/org/tensorflow/Session.Runner.html#fetch(java.lang.String)" rel="nofollow noreferrer"><code>Session.Runner.fetch</code></a> call is only requesting the 0-...
java|tensorflow
1
373,860
45,025,538
Tensorflow session.run() does not proceed
<p>I am running <a href="https://github.com/lordet01/segan/blob/master/train_segan.sh" rel="nofollow noreferrer">https://github.com/lordet01/segan/blob/master/train_segan.sh</a> in my machine. The code does not proceed at line below (in model.py) :</p> <pre><code>sample_noisy, sample_wav, sample_z = self.sess.run([sel...
<p>As the question is old, and the repository is not up-to-date with the original master branch, the optimisation of the network is not working.</p> <p>Some of the changes that were introduced that are important are <a href="https://github.com/santi-pdp/segan/commits/master" rel="nofollow noreferrer">here</a>.</p> <p...
python|tensorflow
1
373,861
44,975,943
TensorFlow example but with middle layer
<p>I am trying to get this code to work. It may not look like it, but it comes mostly from the TensorFlow mnist example. I am trying to get three layers, though, and I've changed the input and output size. The input size is 12, the mid size is 6, and the output size is 2. This is what happens when I run this. It does n...
<p>The problem in this code is you calling <code>dropout</code> on the inputs. Yours is a single layer network and you don't need <code>dropout</code>. And use a momentum optimizer like <code>Adam</code> for training faster. The changes i made:</p> <pre><code>d_y_logits_1 = tf.matmul(d_x, d_W_1) + d_b_1 d_y_mid = tf.n...
python|tensorflow|mnist
0
373,862
45,260,736
how do I avoid strings being read as bytes when reading a HDF 5 file into Pandas?
<p>currently, the data in h5 file does not have prefix 'b'. I read h5 file with following code. I wonder whether there is some better way to read h5 and with no prefix 'b'.</p> <pre><code>import tables as tb import pandas as pd import numpy as np import time time0=time.time() pth='d:/download/' # read data data_trad...
<p>The best solution for performance is to stop trying to "remove the <code>b</code> prefix." The <code>b</code> prefix is there because your data consists of bytes, and Python 3 insists on displaying this prefix to indicate bytes in many places. Even places where it makes no sense such as the output of the built-in ...
python|pandas|hdf5
1
373,863
45,255,442
Sympy: How to compute Lie derivative of matrix with respect to a vector field
<p>I have a system(x'=f(x)+g(x)u), such that <code>f(x) is f:R3-&gt;R3</code> and <code>g(x) is g:R3-&gt;R(3x2)</code>. My system is</p> <p><a href="https://i.stack.imgur.com/SpMYF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SpMYF.png" alt="enter image description here"></a> <a href="https://i....
<p>The only error in your code is due to the tuple used for multiple inputs. For LieDerivative in Sympy.diffgeom to work you need a vector field defined properly. </p> <p>For single input systems, the exact code that you have works without the tuple, so, in that case, for example if you have <code>g = (cos(x1))*e_x1+...
python|numpy|vector|sympy|derivative
0
373,864
56,939,854
nyoka AttributeError: The layer has never been called and thus has no defined input shape
<p>I'm trying to output a trained Tensorflow 2.0 model to PMML using the nyoka package. When I do so, it errors out. The problem seems to be different from that in <a href="https://stackoverflow.com/questions/55321864/attributeerror-the-layer-has-never-been-called-and-thus-has-no-defined-input-sh">this answer</a>, even...
<p>This is Tensorflow's error. If you can print input_shape and output_shape or weights for each layer then you will be able to export it using Nyoka also.</p>
python|tensorflow|pmml
0
373,865
57,181,931
Converting dtype: period[M] to string format
<p>I have converted my dates in to an Dtype M format as I don't want anything to do with the dates. Unfortunately I cannot plot with this format so I want now convert this in to strings.</p> <p>So I need to group my data so I can print out some graphs by months. But I keep getting a serial JSON error when my data is i...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.strftime.html" rel="nofollow noreferrer"><code>Series.dt.strftime</code></a> for set <code>Series</code> to strings in last step:</p> <pre><code>df["Date_Modified"]= df["Date_Modified"].dt.strftime('%Y-%m') </code></pre> <p>Or ...
python|pandas|numpy
1
373,866
57,052,605
Unable to reload the config file on the fly in Tensorflow serving
<p>I am following the below link to create a script that reloads the config file of the tensorflow serving on the fly .</p> <p><a href="https://stackoverflow.com/questions/54440762/tensorflow-serving-update-model-config-add-additional-models-at-runtime/54455066#54455066">TensorFlow Serving: Update model_config (add ad...
<p>I resolved the issue by assigning the port number 8500 while invoking the tensorflow server using docker container and using the same port number in grpc client.</p>
tensorflow|tensorflow-serving
0
373,867
57,257,533
I need help to create mnist.pkl.gz from my own set of images
<p>I am new to python and machine learning. I successfully tested DBN.py examples from deeplearing. now I want to put my own set of images into mnist.pkl.gz format </p> <p>I already tried some code from a project named JPG-PNG-to-MNIST-NN-Format on github but it gives me idx format I used some code to convert this ...
<p>Thank you so much for answering my question. I made a project on GitHub and put all my data in it to create mnist.pkl.gz dataset for anyone who is like me at the beginning of deeplearning. </p> <p>you can find it here <a href="https://github.com/tikroute/mnist.pkl.gz-dataset-creator" rel="nofollow noreferrer">htt...
python|pandas|mnist
0
373,868
57,076,823
How to push rows of an existing dataframe to a new dataframe based on a condition?
<p>I currently have a dataframe with the elevation information for houses. I would like to separate this into different dataframes based on a condition. I have the following: </p> <pre><code>minor = data[data.NAVD88 &lt;= 5] moderate = data[data.NAVD88 &gt; 5] and data[data.NAVD88 &lt; 7] major = data[data.NAVD88 &gt;...
<p>Use botwise <code>and</code> by <code>&amp;</code> and because priority precedence add <code>()</code> for chained boolean masks:</p> <pre><code>minor = data[data.NAVD88 &lt;= 5] moderate = data[(data.NAVD88 &gt; 5) &amp; (data.NAVD88 &lt; 7)] major = data[data.NAVD88 &gt;= 7] </code></pre>
python|pandas
0
373,869
57,150,633
How to change a simple network dataframe to a correlation table?
<p>I have a dataframe which is in this format</p> <pre><code> from to weight 0 A D 3 1 B A 5 2 C E 6 3 A C 2 </code></pre> <p>I wish to convert this to a correlation-type dataframe which would look like this - </p> <pre><code> A B C D E A 0 0 2 0 3 B 5 0 0 0 0 C 0 0 0 0 6 D 0 0 0 0 0 E 0 0 0 0 0 </...
<p>IIUC, this is a pivot with reindex:</p> <pre><code>(df.pivot(index='from', columns='to', values='weight') .reindex(all_vals) .reindex(all_vals,axis=1) .fillna(0) ) </code></pre> <p>Output:</p> <pre><code>to A B C D E from A 0.0 0.0 2.0 3.0 0.0 B 5.0 0.0 0...
python|pandas|dataframe
1
373,870
57,067,335
How to identify duplicate entries in pandas
<p>I have a dataframe as follows.</p> <pre><code> title description 0 mmm mmm 1 mmm mmm 2 mmm mmm 3 mmm mmm 4 mmm mmm 5 mmm mmm 6 mmm mmm 7 nnn nnn 8 nnn nnn 9 lll lll 10 jjj jjj </code></pre> <p>I want to keep one entry and remove all other duplicate entries while returning another dataf...
<p>Method involved <code>duplicated</code>+<code>groupby.size</code></p> <p>First question </p> <pre><code>df[~df.duplicated()] title description 0 mmm mmm 7 nnn nnn 9 lll lll 10 jjj jjj </code></pre> <p>Second question </p> <pre><code>df[df.duplicated()].groupby(['titl...
pandas
1
373,871
57,113,644
Create 1-column dataframe from multi-index pandas series
<p>I have a multi-index series like this:</p> <pre class="lang-py prettyprint-override"><code>Year Month 2012 1 444 2 222 3 333 4 1101 </code></pre> <p>which I want to turn into:</p> <pre class="lang-py prettyprint-override"><code>Date Value 2012-01 444 2012-02 ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.to_frame.html" rel="nofollow noreferrer"><code>Index.to_frame</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> working ...
python|pandas|series
2
373,872
56,915,656
Inefficient preprocessing in Python
<p>I've to do preprocessing on <em>some</em> .csv file. These .csv file are matrix of audio feature from TIMIT dataset. Basically they are matrix of #samples * 123 features. I would like to do a sliding window over the samples.</p> <p>I wrote this class:</p> <pre class="lang-py prettyprint-override"><code>import glob...
<p>Try to divide your records into smaller chunks and then process them in parallel. Here is a great discussion with easy examples: <a href="https://stackoverflow.com/questions/2846653/how-to-use-threading-in-python">How to use threading in Python?</a></p> <p>Also, there is an option to use cython (Python + C (in big ...
python|pandas|numpy
1
373,873
56,979,461
How to use multi-gpu during inference in pytorch framework
<p>I am trying to make model prediction from unet3D built on pytorch framework. I am using multi-gpus</p> <pre><code>import torch import os import torch.nn as nn os.environ['CUDA_DEVICE_ORDER']='PCI_BUS_ID' os.environ['CUDA_VISIBLE_DEVICES']='0,1,2' model = unet3d() model = nn.DataParallel(model) model = model.to('cu...
<p>DataParallel handles sending the data to gpu.</p> <pre><code>import torch import os import torch.nn as nn os.environ['CUDA_DEVICE_ORDER']='PCI_BUS_ID' os.environ['CUDA_VISIBLE_DEVICES']='0,1,2' model = unet3d() model = nn.DataParallel(model.cuda()) result = model.forward(torch.tensor(input).float()) </code></pre>...
pytorch|multi-gpu
3
373,874
57,188,409
Assigning a parameter to the GPU sets is_leaf as false
<p>If I create a <code>Parameter</code> in PyTorch, then it is automatically assigned as a leaf variable:</p> <pre><code>x = torch.nn.Parameter(torch.Tensor([0.1])) print(x.is_leaf) </code></pre> <p>This prints out <code>True</code>. From what I understand, if <code>x</code> is a leaf variable, then it will be update...
<p>Answer is in <a href="https://pytorch.org/docs/stable/autograd.html#torch.Tensor.is_leaf" rel="nofollow noreferrer"><code>is_leaf</code></a> documentation and here is your exact case:</p> <pre><code>&gt;&gt;&gt; b = torch.rand(10, requires_grad=True).cuda() &gt;&gt;&gt; b.is_leaf False # b was created by the operat...
gpu|pytorch|autograd
2
373,875
57,001,183
How to extract Keras layer weights as trainable parameter?
<p>I'm training a GAN-like models, but not exactly the same. I'm using Keras with TensorFlow backend. </p> <p>I have two Keras models <code>G</code> and <code>D</code>. I want to output the <strong>weights parameter</strong> of a target layer in <code>G</code>, as <strong>the input of model D</strong>, and use the res...
<p>As you mention, <code>layer.get_weights()</code> will return the <em>current</em> weights of the matrix. What you want to feed for prediction is a the node in the computation graph representing such weights. You can use <code>layer.trainable_weights</code> instead, which will return two <code>tf.Variable</code> whic...
python|tensorflow|keras
2
373,876
56,922,806
Denormalizing a DataFrame of company names [Part 1]
<p>I have a Pandas DataFrame of company names which has the following structure:</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame({'name' : ['Nitron', 'Pulset', 'Rotaxi'], 'postal_code' : [1410, 1020, 1310], 'previous_name1' : ['Rotory', np.NaN, 'Datec'],...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>DataFrame.set_index</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>DataFrame.stack</...
python|pandas|dataframe
3
373,877
56,961,893
Detect if any value is above zero and change it
<p>I have the following array:</p> <pre><code>[(True,False,True), (False,False,False), (False,False,True)] </code></pre> <p>If any element contains a True then they should all be true. So the above should become:</p> <pre><code>[(True,True,True), (False,False,False), (True,True,True)] </code></pre> <p>My below code...
<p>You could try <code>np.any</code>, which <a href="https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.any.html" rel="nofollow noreferrer">tests whether any array element along a given axis evaluates to True</a>.</p> <p>Here's a quick line of code that uses a list comprehension to get your intended res...
python|numpy
2
373,878
56,928,479
plotly line graph iterate over columns and loop trace
<p>Taking this post <a href="https://stackoverflow.com/questions/55809312/plot-multiple-columns-on-line-graph-using-dash-plotly">Plot multiple columns on line graph using Dash/Plotly</a> as a reference, I'm looking to plot similar dataframe into line graph using plotly. What makes me stuck is how to put trace into a lo...
<p>Hope I got your idea correctly))</p> <p>I had a similar issue some time ago and was very happy to find the cufflinks package.</p> <p>To install cufflinks you need to execute the following commands:</p> <pre><code>pip install cufflinks pip install ipywidgets </code></pre> <p>and restart your notebook if you are u...
python|pandas|plotly
0
373,879
57,160,788
Appending to next row in dataframe, from within a for loop
<p>I've created a web scraper that scrapes the Yahoo Finance Summary and Statistics page of a stock for Python programming educational purposes only. It reads from the '1stocklist.csv' in the programs directory which looks like this:</p> <pre><code>Symbols SNAP KO </code></pre> <p>From there, it adds the new informatio...
<p><strong>UPDATE WITH ANSWER</strong></p> <p>I was able to figure it out!</p> <p>Basically, I changed the first dataframe that reads from the 1stocklist.csv to be its own dataframe, then created a new blank one to work with from within the first for loop. Here is the updated head that I created:</p> <pre><code># Us...
python|python-3.x|pandas
0
373,880
56,978,793
Create a dataset for chord diagram and plot
<p>I'm trying to convert the below dataset into the right format to then plot it into a chord diagram.</p> <pre><code> a b c d e f g h 0 1 0 0 0 0 1 0 0 1 1 0 0 0 0 0 0 0 2 1 0 1 1 1 1 1 1 3 1 0 1 1 0 1 1 1 4 1 0 0 0 0 0 0 ...
<p>I do not know a lot about which could be the best chord diagram library but may I help you a little bit:</p> <h2>first we define our data in a pandas dataset</h2> <pre class="lang-py prettyprint-override"><code>import pandas as pd data = [ [1, 0, 0, 0, 0, 1, 0, 0], [1, 0, 0, 0, 0, ...
python|python-3.x|pandas|numpy|holoviews
0
373,881
57,082,909
Using Percent (%) in Pandas and pyodbc SQL Server w/o Error
<p>I believe having <code>%</code> in my sql queries is causing issues in Python because of <code>%s</code> being used for variables. I have tried escaping character and have had no luck so far</p> <pre><code>import pyodbc import pandas as pd conn = pyodbc.connect('...') cursor = conn.cursor() sql_statement = """ sel...
<p>Typically just adding another '%' indicates that you're using '%' as a string and not a modulo. E.g.:</p> <pre><code>print('5%%') </code></pre> <p>Results in printing '5%'.</p>
python|pandas|pyodbc
2
373,882
57,172,827
How to rewrite the depth to normal map code using tensorflow keras for bath of inputs?
<p>Here is my python code to convert the depth map (256,256,1) to normal map (256,256,3) for single input. I want to rewrite the code in tensorflow keras for batch of predicted depth.</p> <pre><code>zy, zx = np.gradient(d_im) # You may also consider using Sobel to get a joint Gaussian smoothing and differentation # ...
<p>I solved it:</p> <pre><code>def depth_to_normal(y_pred): zy, zx = tf.image.image_gradients(y_pred) normal_ori = tf.concat([-zx, -zy, tf.ones_like(y_pred)], 3) new_normal = tf.square(zx) + tf.square(zy) + 1 normal = normal_ori/new_normal normal += 1 normal /= 2 return normal </code...
python-3.x|tensorflow|keras
0
373,883
56,984,561
How to print a message every time a chunksize is written to the database in pandas?
<pre><code>engine = create_engine('postgresql://user:password@server/db') df.to_sql('new_table', con=engine, if_exists='append', index=False, chunksize=20000) </code></pre> <p>I want to print a message every time a chunksize has to been written to the DB, so that I know the script is successfully running. How can I ac...
<p>You can always chunk it up manually and process chunks in a loop inside which you can setup message printing or a progress bar. See an example <a href="https://stackoverflow.com/a/39495229/11477031">here</a>.</p>
python-3.x|pandas
1
373,884
56,875,105
How to implement different ranking algorithms in tf-ranking framework?
<p>What is the algorithm behind tf-ranking? and can we use Lambdamart algorithm in tf-ranking .Can anyone suggest some good sources to learn these </p>
<p>TF Ranking provides a framework for you to implement your own algorithm. It helps you set up the components around the core of your model (input_fn, metrics and loss functions, etc.). But the scoring logic (aka scoring function) should be provided by the user.</p> <p>You probably have already seen these, but just i...
tensorflow|ranking|google-ranking
0
373,885
56,871,473
Render JSON response from BigQuery using Pandas?
<p>I'm a Ruby dev doing a lot of data work that's decided to switch to Python. I'm enjoying making the transition so far and have been blown away by Pandas, Jupyter Notebooks etc.</p> <p>My current task is to write a lightweight RESTful API that under the hood is running queries against Google BigQuery. </p> <p>I hav...
<p>From the BigQuery documentation-</p> <blockquote> <p>BigQuery supports functions that help you retrieve data stored in JSON-formatted strings and functions that help you transform data into JSON-formatted strings:</p> <p>JSON_EXTRACT or JSON_EXTRACT_SCALAR</p> <p><code>JSON_EXTRACT(json_string_expr,...
python|pandas|flask|google-bigquery
1
373,886
57,049,675
How to specify number of layers in keras?
<p>I'm trying to define a fully connected neural network in keras using tensorflow backend, I have a sample code but I dont know what it means.</p> <pre><code>model = Sequential() model.add(Dense(10, input_dim=x.shape[1], kernel_initializer='normal', activation='relu')) model.add(Dense(50, input_dim=x.shape[1], kernel...
<p>That should be quite easy.</p> <ol> <li><p>For knowing about the model's inputs and outputs use,</p> <pre><code>input_tensor = model.input output_tensor = model.output </code></pre> <p>You can print these <code>tf.Tensor</code> objects to get the <code>shape</code> and <code>dtype</code>.</p></li> <li><p>For fetc...
tensorflow|keras|deep-learning
0
373,887
57,085,982
Error while predicting a single value using a linear regression model
<p>I'm a beginner and making a linear regression model, when I make predictions on the basis of test sets, it works fine. But when I try to predict something for a specific value. It gives an error. The tutorial I'm watching, they don't have any errors.</p> <pre><code>dataset = pd.read_csv('Position_Salaries.csv') X =...
<p>According to the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html#sklearn.linear_model.LinearRegression.predict" rel="nofollow noreferrer">Scikit-learn documentation</a>, the input array should have shape <code>(n_samples, n_features)</code>. As such, if you want ...
machine-learning|scikit-learn|anaconda|sklearn-pandas
4
373,888
57,203,358
Copying int64 Column to a New Column and Appending Str to end of each record in Pandas DataFrame
<p>I have 11 columns in a DataFrame, and want to clone the first column to a new column to be the 12th column, to be named mail. The new mail column should contain all the column1 records and also add <code>str('@myexampledomain.com')</code> to it. The Column I want to copy to create the new column is the <code>"sAMAc...
<p>If I understand you correctly, you want to <code>copy</code> the <code>"sAMAccountName"</code> column and call it <code>"mail"</code>. Your current code:</p> <pre><code>import pandas as pd df = pd.read_csv('output.csv',) df_mail = df[df['sAMAccountName'] == 'mail'].copy() TypeError: invalid type comparison </code>...
python-3.x|pandas|dataframe
0
373,889
57,125,740
How to replace the entry of a column with different name by recognizing a pattern?
<p>I have a column let's say <code>'Match Place'</code> in which there are entries like <code>'MANU @ POR'</code>, <code>'MANU vs. UTA'</code>, <code>'MANU @ IND'</code>, <code>'MANU vs. GRE'</code> etc. So my columns have 3 things in its entry, the 1st name is <code>MANU</code> i.e, 1st country code, 2nd is <code>@/vs...
<p>You can use <a href="https://www.google.com/search?q=np+select&amp;rlz=1C1GCEU_enIN822IN823&amp;oq=np+select&amp;aqs=chrome..69i57j35i39j0l4.1884j0j7&amp;sourceid=chrome&amp;ie=UTF-8" rel="nofollow noreferrer"><code>np.select</code></a> to assign multiple conditions:</p> <pre><code>s=df['Match Place'].str.split().s...
python|string|pandas
3
373,890
56,906,887
How can I define variables for several columns
<p>I'm creating a program that returns different statistics form any file uploaded (with a certain data structure).</p> <p>I need to write some code that allows to define variables for the columns in each file, the problem is that in some cases there are 5 columns and in others 7, 8 or more.</p> <p>Any thoughts? May...
<p>If you don't specify the names of the headers then pandas will infer them. You can change them after you read them if you like or you can force them to be what you want.</p> <p>For instance, letting pandas infer the header names and then renaming them X1...</p> <pre><code>df = pd.read_csv('test.csv',header=None) ...
python|python-3.x|pandas
1
373,891
57,043,695
pandas - downsample a more frequent DataFrame to the frequency of a less frequent DataFrame
<p>I have two DataFrames that have different data measured at different frequencies, as in those csv examples:</p> <p>df1:</p> <pre><code>i,m1,m2,t 0,0.556529,6.863255,43564.844 1,0.5565576199999884,6.86327749999999,43564.863999999994 2,0.5565559400000003,6.8632764,43564.884 3,0.5565699799999941,6.863286799999996,435...
<p>IIUC, <code>i</code> is index column and you want to put <code>df2['t']</code> in bins and averaging the other columns. So you can use <code>pd.cut</code>:</p> <pre><code>groups =pd.cut(df2.t, bins= list(df1.t) + [np.inf], right=False, labels=df1['t']) # cols to copy cols = [col for ...
python|pandas|dataframe
1
373,892
57,017,223
Pandas: Use a dataframe to index another one and fill the gaps?
<p>I have two dataframes. df_0 is a complete list of dates and df_1 is a generic register indexed by incomplete dates. I need to make a dataframe that has df_0’s complete dates as an index, filled with df_1’s register in the matching dates. For dates without a register entry, I just need to repeat the last date’s regis...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>DataFrame.reindex</code></a> with parameter <code>method</code>:</p> <pre><code>df = df_1.reindex(df_0.index, method="ffill") </code></pre>
python|pandas|indexing|match|fill
2
373,893
57,273,888
Keras vs. TensorFlow code comparison sources
<p>This isn't really a question that's code-specific, but I haven't been able to find any answers or resources.</p> <p>I'm currently trying to teach myself some "pure" TensorFlow rather than just using Keras, and I felt that it would be very helpful if there were some sources where they have TensorFlow code and the eq...
<p>Here you have two models, in <code>Tensorflow</code> and in <code>Keras</code>, that are correspondent:</p> <pre><code>import tensorflow as tf import numpy as np import pandas as pd from keras.datasets import mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() </code></pre> <h1>Tensorflow</h1> <pre><co...
tensorflow|keras
4
373,894
57,223,666
Alternate optimization with two different optimizers in pytorch
<ul> <li>I have two loss functions <code>l1</code> and <code>l2</code>, each optimized by two separate ADAM optimizers <code>opt1</code> and <code>opt2</code>.</li> <li>The current value of my parameters is <code>x</code>.</li> <li>I want to update <code>x</code> using <code>opt1</code> and <code>opt2</code> separately...
<p>Following @UmangGupta comment, I did it by initializing three copies of <code>x</code>: two for <code>x1</code> and <code>x2</code>, and one for a backup of <code>x</code>. Then I do as follows</p> <pre class="lang-py prettyprint-override"><code>def copy(target, source): for x, y in zip(target.parameters(), sou...
optimization|pytorch|gradient-descent
0
373,895
57,024,439
Pandas retain index ordering
<p>I would like to plot a graph but pandas keeps reordering my index (N).</p> <p>I want the order to be <code>N= 50, 100, 200</code> where there are three columns for each <code>N</code> namely <code>2x2 3x3 4x4</code></p> <pre><code>f1 = pd.DataFrame({"User": ["2 x 2 x 2","3 x 3 x 3", "4 x 4 x 4","2 x 2 x 2","3 x 3 ...
<p>I'm guessing that the incorrect order you're seeing is 100, 200, 50. If that's the case, what's happening is that Pandas is sorting your index alphabetically.</p> <p>In that case, you have two options: the first is to sort the index from its numeric information, and you can check <a href="https://stackoverflow.co...
python|pandas
0
373,896
56,940,000
Trace a 3d graph with a black line where Z = 0?
<p>I have a functional 3d graph, but I want to make a trace line on the graph for when z = 0. </p> <p>I tried to split up the graphs for when z>=0 and z&lt;0 but this does not make a clear representation, as shown in code commented out. I want to trace this line in a different color. Another solution would be to have ...
<p>When just highlighting the Z=0 line you need to remember that at that point you no longer have a surface but a 2D plane. You then want to find where that 2D plane is equal to zero. You want to use what Poolka suggested which is <code>ax.contour(x,y,z,[0])</code>. I would suggest changing the transparency (<code>alph...
python|numpy|matplotlib|graphing
2
373,897
57,171,410
Python pandas pivot table between range of dates
<p>I'm trying to calculate the sum of quantity for every day for each combinaton of Profile-GeographicalZone-Town with the following sample df:</p> <pre><code>df = pd.DataFrame({ 'Profile': {0: 'P014', 1: 'P014', 2: 'P012', 3: 'P012', 4: 'P012', 5: 'P012', 6: 'P012', 7: 'P012', 8: 'P012', 9: 'P012'}, 'GeogaphicalZone'...
<p>Exploding it into daily make a very long data frame but here's how you do it:</p> <pre><code>df = pd.DataFrame({ 'Profile': {0: 'P014', 1: 'P014', 2: 'P012', 3: 'P012', 4: 'P012', 5: 'P012', 6: 'P012', 7: 'P012', 8: 'P012', 9: 'P012'}, 'GeogaphicalZone': {0: 'NORTH', 1: 'NORTH', 2: 'NORTH', 3: 'SOUTH', 4: 'SOUTH', ...
python|pandas|dataframe|pivot-table
0
373,898
57,206,434
How to get "reversed" time windows in pandas?
<p>(Note: I am pretty sure that this is not a duplicate question.)</p> <p>I need "reversed" time windows from a pandas Dataframe. "reversed" as in I need them to have the last time index after processing them. Example:</p> <pre><code>df = pd.DataFrame(data=[ [pd.Timestamp('2018-01-01 00:00:00'), 100], [pd.Tim...
<p>This is possible with a <code>reindex</code>... and then another <code>reindex</code>.</p> <pre><code>u = pd.date_range(df.index.min(), df.index.max() + pd.Timedelta('2s'), freq='1s') df.reindex(u).ffill().rolling(2).mean().shift(-1).reindex(df.index) </code></pre> <p></p> <pre><code> value t...
python|pandas
2
373,899
56,999,525
How to mask specific values in particular column in Python?
<p>I have a .csv file with 5 columns and about 5000 rows. In a particular column called 'summary' in the .csv file there is credit card numbers along with a few text. It looks like this</p> <blockquote> <p>hey this job needs to be done asap and pay with card# visa 5611000043310001</p> </blockquote> <p>I want to rea...
<p>With regex, you could do:</p> <pre><code>import re &gt;&gt; s = "hey this job needs to be done asap and pay with card# visa 5611000043310001" &gt;&gt; re.sub(r"(\d{12})\d{4}",r"\1****",s) 'hey this job needs to be done asap and pay with card# visa 561100004331****' </code></pre> <p>So basically, <code>(\d{12})</...
python|pandas
1