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
355,600
48,038,568
Understanding vocabulary size in word2vec
<p>I am trying to understand word2vec algorithm but some issues makes me really confused. I am using the code from <a href="https://github.com/tensorflow/tensorflow/blob/r1.4/tensorflow/examples/tutorials/word2vec/word2vec_basic.py" rel="nofollow noreferrer">TensorFlow</a>. The issue is that my data size is 184 million...
<p>If you look at the <a href="https://github.com/tensorflow/tensorflow/blob/438604fc885208ee05f9eef2d0f2c630e1360a83/tensorflow/examples/tutorials/word2vec/word2vec_basic.py#L71" rel="nofollow noreferrer">build_dataset</a> function in the code you'll see that anything above the vocabulary size gets turned into unk, an...
python|tensorflow|word2vec
0
355,601
48,322,421
Pandas resample FutureWarning
<p>I have a 1-Minute bar OHLC price CSV file that I am trying to resample to 15-Minute bars. The code that I am using is from this <a href="http://sacbnctrading.blogspot.in/2016/10/convert-1m-ohlc-data-into-other.html" rel="nofollow noreferrer">link</a>, and is follows:</p> <pre><code>ohlc_dict = {'open':'first', 'hig...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.resample.Resampler.aggregate.html" rel="nofollow noreferrer"><code>Resampler.agg</code></a>:</p> <pre><code>price15m = df.resample('15Min', closed='right').agg(ohlc_dict).dropna(how='any') </code></pre>
python|pandas|apply
4
355,602
48,138,491
Generate a row with values = values of previous row + variation
<p>I'm trying to create a pandas dataframe in which the value of each cell is the value of the cell above it + a variation. </p> <p>I've found a way to do almost what I want...</p> <pre><code>import pandas as pd, random max_deviation = 20 nb_periods = 5 colnames = ["col1", "col2"] df = pd.DataFrame(columns = colnam...
<p>This should give you what you're looking for. Generate N * M random numbers, find their cumulative sum along the 0<sup>th</sup> axis, add the offset (which is <code>500</code>), and load into a dataframe.</p> <pre><code>i = 5 # number of rows j = 2 # number of columns max_dev = 20 # maximum d...
python|pandas
3
355,603
48,043,004
How do I generate a sine wave using Python?
<p>I'm trying to generate a sine wave of a given frequency for a given duration and then write it into a .wav file. I'm using numpy's sin function and scipy's wavfile function. I'm getting a weird sound that is definitely not a sine wave.</p> <pre><code>import numpy as np from scipy.io import wavfile fs = 44100 f = ...
<p>Change</p> <pre><code>samples = np.arange(t * fs) </code></pre> <p>to</p> <pre><code>samples = np.linspace(0, t, int(fs*t), endpoint=False) </code></pre> <p>(This assumes that <code>fs*t</code> results in an integer value.)</p> <p>Or, as Paul Panzer suggests in a comment,</p> <pre><code>samples = np.arange(t *...
python|numpy|scipy|waveform|trigonometry
13
355,604
48,400,225
pytorch model.cuda() runtime error
<p>I'm building a text classifier using pytorch, and got into some trouble with .cuda() method. I know that .cuda() moves all parameters into gpu so that the training procedure can be faster. However, error occurred in .cuda() method like this: </p> <pre class="lang-python prettyprint-override"><code>start_time = tim...
<p>model.cuda() is called inside your training/test loop, which is the problem. As the error message suggests, you repeatedly convert parameters(tensors) in your model to cuda, which is not the right way to convert model into cuda tensor.</p> <p>model object should be created and cuda-ize outside the loop. Only traini...
pytorch
4
355,605
48,356,464
How to model Convolutional recurrent network ( CRNN ) in Keras
<p>I was trying to port <a href="https://github.com/meijieru/crnn.pytorch/blob/master/models/crnn.py" rel="noreferrer">CRNN</a> model to Keras.</p> <p>But, I got stuck while connecting output of Conv2D layer to LSTM layer.</p> <p>Output from CNN layer will have a shape of <strong>( batch_size, 512, 1, width_dash)</st...
<p>You don't need to permute the batch axis in Keras. In a pytorch model you need to do it because a pytorch LSTM expects an input shape <code>(seq_len, batch, input_size)</code>. However in Keras, the <code>LSTM</code> layer expects <code>(batch, seq_len, input_size)</code>.</p> <p>So after defining the CNN and squee...
keras|lstm|recurrent-neural-network|pytorch
6
355,606
48,344,806
Making a custom window type for pandas rolling mean
<p>I understand rolling allows you to specify the window type used for calculating the rolling mean. The docs list a variety of windows type options available <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rolling.html" rel="nofollow noreferrer">here</a>. However, I am trying to use a ...
<p>Create a kernel like this:</p> <pre><code>import numpy as np kernel = np.array([1,2,2,1])/6 </code></pre> <p>then convolve with your series:</p> <pre><code>np.convolve(rs,kernel,'same') </code></pre>
python|pandas|mean|moving-average
3
355,607
48,255,828
How to use tf.layers.conv2d to train a autoencoder with tied weights
<p>If I want to train an autoencoder with tied weights (encoder and decoder has same weight parameters), how to use <code>tf.layers.conv2d</code> to do that correctly?</p> <p>I cannot just simply share variables between corresponding <code>conv2d</code> layers of encoder and decoder, because the weights of decoder is ...
<p>Use <a href="https://www.tensorflow.org/api_docs/python/tf/nn/conv2d" rel="nofollow noreferrer"><code>tf.nn.conv2d</code></a> (and <a href="https://www.tensorflow.org/api_docs/python/tf/nn/conv2d_transpose" rel="nofollow noreferrer"><code>tf.nn.conv2d_transpose</code></a> correspondingly). It's a low-level function ...
tensorflow|conv-neural-network|convolution|recurrent-neural-network|autoencoder
1
355,608
48,185,809
Copy argument vs Series.Copy()
<pre><code>y = pd.Series(x, copy=True,dtype=float) z = pd.Series(x, copy=True) a = pd.Series(x) f = pd.Series.copy(x) </code></pre> <p>All the above expressions give the same output of x value and even after updating the x value the change is not reflecting. So I need to know what is the use of copy as argument and th...
<p>If we look at the source code of pandas <code>Series</code> we can see the following,</p> <pre><code>def __init__(self, data=None, index=None, dtype=None, name=None, copy=False, fastpath=False): if not isinstance(data, SingleBlockManager): data = SingleBlockManager(data, index, fastpath=Tr...
python|pandas
1
355,609
48,380,129
Take N first values from every row in NumPy matrix that fulfill condition
<p>I have a <code>numpy vector</code>, and a <code>numpy array</code>.</p> <p>I need to take from every row in the matrix the first N (lets say 3) values that are smaller than (or equal to) the corresponding line in the vector. </p> <p>so if this is my vector:</p> <pre><code>7, 9, 22, 38, 6, 15 </code></pre> <p>and...
<p><strong>Approach #1</strong></p> <p>Here's one with <a href="https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html" rel="nofollow noreferrer"><code>broadcasting</code></a> -</p> <pre><code>def takeN_le_per_row_broadcasting(a, b, N=3): # a, b : 1D, 2D arrays respectively # First col indices in e...
python|arrays|numpy|matrix|mask
3
355,610
48,310,230
Creating a new column for historical information on a time-sensitive dataset in pandas
<p>I want to create a new dataframe that groups by 'id' and creates a new column for everything on and before 2016. Effectively, I am trying to flatten the dataframe below. Here is the original dataframe:</p> <pre><code>Year | id | issue_1 | issue_2 =====|====|=========|======== 2014 | 11 | 1 | 0 2015 | 11 | 0 ...
<p>Try .pivot_table (see code and output below).</p> <pre><code>df = df.pivot_table(index=['id'], columns='Year', values=['issue_1','issue_2']) </code></pre> <p><a href="https://i.stack.imgur.com/FmlCS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FmlCS.png" alt="enter image description here"></a...
python|pandas|dataframe
2
355,611
48,204,702
Python .sum() is giving me a different result to plt.bar() and sns.barplot(), which is correct?
<p>I have a dataset which looks something like:</p> <pre><code>User ID | Group | Revenue 101 | 1 | 0 102 | 2 | 1.3 103 | 2 | 0.5 103 | 1 | 2.3 104 | 1 | 1.4 ... | ... | ... </code></pre> <p>I want to know the revenue per group. I've done this:</p> <pre><cod...
<p>Once you've done a group by, you can plot the bar chart using that group by object:</p> <pre><code>In [8]: df = pd.DataFrame([[1, 343], [1, 300], [2, 300], [2, 51.47]], columns=['Group', 'Revenue']) In [9]: df.groupby('Group').Revenue.sum().plot.bar() Out[9]: &lt;matplotlib.axes._subplots.AxesSubplot at 0x7f97345e...
python|pandas|matplotlib
1
355,612
48,369,864
How do I open a binary matrix and convert it into a 2D array or a dataframe?
<p>I have a binary matrix in a txt file that looks as follows:</p> <pre><code>0011011000 1011011000 0011011000 0011011010 1011011000 1011011000 0011011000 1011011000 0100100101 1011011000 </code></pre> <p>I want to make this into a 2D array or a dataframe where there is one number per column and the rows are as shown...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_fwf.html" rel="nofollow noreferrer"><code>read_fwf</code></a> with parameter <code>widths</code>:</p> <pre><code>df = pd.read_fwf("a1data1.txt", header=None, widths=[1]*10) print (df) 0 1 2 3 4 5 6 7 8 9 0 0 0 1 1 0 1 ...
python|arrays|pandas|numpy|dataframe
3
355,613
48,395,966
Converting list of dictionaries into single dictionary in python 3
<p>I have a snippet of data from which I need to extract specific information. The Data looks like this:</p> <pre><code> pid log Date 91 json D1 189 json D2 276 json D3 293 json D4 302 json D5 302 json D6 343 json ...
<p>I believe you need:</p> <pre><code>df = pd.DataFrame({'log':['{"Before":{"freq_term":"Daily","ideal_pmt":"637.5","datetime":"2015-01-08 06:26:11"},"After":{"freq_term":"Weekly","ideal_pmt":"3346.88","datetime":"2015-02-02 06:16:07"}}','{"Before":{"buy_rate":"1.180","irr":"31.63","uwfee":"","freq_term":"Weekly"}, "A...
python|pandas|dictionary
1
355,614
48,066,370
Diff Between numpy.random.exponential and random.expovariate
<p>What is the difference between <code>numpy.random.exponential</code> and <code>random.expovariate</code>? I'm familiar with how random.exponential works.</p>
<p>I assume you mean "What is the difference between <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.exponential.html" rel="noreferrer"><code>numpy.random.exponential</code></a> and <a href="https://docs.python.org/3/library/random.html#random.expovariate" rel="noreferrer"><code>random.expova...
python-3.x|numpy
4
355,615
48,312,529
How to create pandas dummies based on column values
<p>I would like to create dummies based on column values...</p> <p>This is what the df looks like<br> <img src="https://i.imgur.com/1Uyvc2Pl.jpg" alt=""></p> <p>I want to create this<br> <img src="https://i.imgur.com/AmTu21a.jpg" alt=""></p> <p>This is so far my approach</p> <pre><code>import pandas as pd df =pd.re...
<p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.get_dummies.html" rel="nofollow noreferrer"><code>pandas.Series.str.get_dummies</code></a>. This will alllow you to split the column directly with a delimiter.</p> <pre><code>df = pd.concat([df.ID, df.Values.str.get_dummi...
python|python-3.x|pandas|dataframe|multiple-columns
1
355,616
48,035,246
Intersect multiple 2D np arrays for determining zones
<p>Using this small reproducible example, I've so far been unable to generate a new integer array from 3 arrays that contains unique groupings across all three input arrays. </p> <p>The arrays are related to topographic properties:</p> <pre><code>import numpy as np asp = np.array([8,1,1,2,7,8,2,3,7,6,4,3,6,5,5,4]).r...
<p>Each location in the grid is associated with a tuple composed of one value from <code>asp</code>, <code>slp</code> and <code>elv</code>. For example, the upper left corner has tuple <code>(8,9,13)</code>. We would like to map this tuple to a number which uniquely identifies this tuple.</p> <p>One way to do that wou...
python|numpy|multidimensional-array|numpy-ndarray
4
355,617
48,248,821
How to efficiently dropna when the NaNs are contained in the index?
<p>I have a series looking like this:</p> <pre><code>s = pd.Series( np.array([0, 0, 1, 1, 2, 2]), index=np.array([ 0., 1., 2., 4., np.nan, 3.]) ) 0.0 0 1.0 0 2.0 1 4.0 1 NaN 2 3.0 2 dtype: int64 </code></pre> <p>You'll notice the NaN in the index I want to drop. What's th...
<pre><code>In [22]: s[s.index.notna()] Out[22]: 0.0 0 1.0 0 2.0 1 4.0 1 3.0 2 dtype: int32 </code></pre>
python|performance|pandas|numpy
3
355,618
48,188,547
Python dataset aggregation
<p>I have a dataset as follows, stored in <code>pd.DataFrame</code> object:</p> <pre><code>df topic student level week 1 sun a 1 1 1 sun b 2 1 1 moon a 3 1 2 tree a 1 2 2 tree b 2 2 2 tree a 3 2 2 tree ...
<p>I think you need aggregate by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow noreferrer"><code>agg</code></a> with function <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.SeriesGroupBy.nunique.html" rel="...
python|pandas|aggregation
1
355,619
48,350,616
Invalid syntax error when passing a list of modules in Pytorch
<p>I have two blocks in my deep models which are defined as follows:</p> <pre><code>def make_conv_bn_relu(in_channels, out_channels, kernel_size=3, stride=1, padding=1): return [ nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, bias=False), nn.BatchNorm2...
<p>You can't use multiple unpacks in python2. But if you really want to use it then just concatenate lists:</p> <pre><code>nn.Squential(*(make_foo() + make_bar())) </code></pre>
python|python-2.7|pytorch
1
355,620
48,117,288
XGBoost: Convert dmatrix into a numpy.array
<p>I'd like to inspect the <code>DMatrix</code> object. The <a href="http://xgboost.readthedocs.io/en/latest/python/python_api.html#xgboost.DMatrix" rel="noreferrer">documentation mentions</a> the methods to get the number of rows and columns and also the slice at each row:</p> <pre><code>dmatrix.slice(index) </code><...
<p>DMatrix is a one-way street! Once you get DMatrix, you cannot get back its content as <code>numpy.ndarray</code> or <code>pandas.DataFrame</code>.</p> <p>[Update] A library is implemented only for the particular task of convert XGBoost's DMatrix format to <code>numpy.array</code>: <a href="https://github.com/aporia-...
python|arrays|numpy|xgboost
2
355,621
48,256,315
Pandas: filter large (50M rows) dataframe if row lat/lng falls inside a bounding box?
<p>I have a large data set that I'm evaluating various means of parsing on. It's a set of csv with each file having ~40 million rows. Reading into a pandas dataframe I have the following sample data. (The data that follows was randomly generated) The account identifiers will repeat from time to time, some in the box, s...
<p>Not too beautiful, but to combine both conditions, you can use the <code>|</code> operator. Note the parenthesis around both box conditions.</p> <pre><code>box1_cond = (bottom &lt;= df.lat) &amp; (df.lat &lt;= top) &amp; (left &lt;= df.lng) &amp; (df.lng &lt;= right) box2_cond = (bottom2 &lt;= df.lat) &amp; (df.lat...
python|pandas
1
355,622
48,391,568
Matplotlib - Creating plot for black background presentation slides
<p>I'm successfully using Python and Matplotlib to create transparent PNG figures that look good when I add the plots to a Powerpoint slide that has a white background. Below is an example:</p> <p><a href="https://i.stack.imgur.com/cmSPV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/cmSPV.png" alt="enter i...
<p>If the predesigned <a href="https://matplotlib.org/devdocs/gallery/style_sheets/dark_background.html" rel="noreferrer"><code>dark_background</code> style</a> does not match the expectations, one may set the respective rcParams manually. The following might produce the desired plot. </p> <pre><code>import matplotlib...
python|pandas|matplotlib|plot
20
355,623
48,212,110
Average weights in keras models
<p>How to average weights in Keras models, when I train few models with the same architecture with different initialisations?</p> <p>Now my code looks something like this?</p> <pre><code>datagen = ImageDataGenerator(rotation_range=15, width_shift_range=2.0/28, ...
<p>So let's assume that <code>models</code> is a collection of your models. First - collect all weights:</p> <pre><code>weights = [model.get_weights() for model in models] </code></pre> <p>Now - create a new averaged weights:</p> <pre><code>new_weights = list() for weights_list_tuple in zip(*weights): new_weigh...
tensorflow|neural-network|keras|deep-learning|keras-layer
18
355,624
48,056,612
Read data from hive tables using tensorflow
<p>I want to fetch data from hive tables using Tensorflow. How can i connect hive tables and tensorflow?</p>
<p>from pyspark.sql import HiveContext</p>
hadoop|tensorflow|hive
0
355,625
48,059,985
pandas create boolean column using groupby transform
<p>I am trying to create a boolean column using <code>GroupBy.transform</code> on a <code>df</code> like this,</p> <pre><code>id type 1 1.00000 1 1.00000 2 2.00000 2 3.00000 3 2.00000 </code></pre> <p>the code is like,</p> <pre><code>df['has_two'] = df.groupby('id')['type'].transform(lambda x:...
<p>For me it working nice, I get boolean column:</p> <pre><code>df['has_two'] = df.groupby('id')['type'].transform(lambda x: x == 2) print (df) id type has_two 0 1 1.0 False 1 1 1.0 False 2 2 2.0 True 3 2 3.0 False 4 3 2.0 True </code></pre> <p>But maybe is possible only comp...
python|python-3.x|pandas|pandas-groupby
2
355,626
48,379,205
How to manual convert `BGR` image to `grayscale` (Python OpenCV)?
<p>I want to manually convert a RGB image to Grayscale image. What I want to know is how to get the Red/Blue/Green values of a RGB pixel ?</p> <pre><code>img = cv2.imread("images/penguins.jpg",0) grey = img for i in range(0,grey.shape[0]-1): for j in range(0,grey.shape[1]-1): img[i,j]=[ ] </code></pre> <p...
<p>Gray formular:</p> <blockquote> <p>gray = 0.21 R + 0.72 G + 0.07 B</p> </blockquote> <p>Prefer to use matrix multiply, other than loop. Here is the code:</p> <pre><code>#!/usr/bin/python3 # 2018.01.22 18:55:20 CST import cv2 import numpy as np import time ## Read as BGR img = cv2.imread("test.png") ## (1) Lo...
python|arrays|image|numpy|opencv
5
355,627
48,558,653
splitting a column and accessing the resulting list
<p>I have a dataframe called standard, with a column named '# genes'. I'd like to split that one and assign elements of the resulting list to a new column. That is, it looks like this:</p> <pre><code>standard['# genes'].str.split("+") 0 [3798 , 144 part] 1 [3556 , 138 part] 2 [3783 , 135 part] 3 [39...
<p>Use parameter <code>expand=True</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>split</code></a> for convert <code>list</code>s to columns:</p> <pre><code>df = standard['# genes'].str.split("+", expand=True) </code></pre> <p>If ...
pandas
0
355,628
48,735,708
How can I write new columns that is being generated after each iteration in pandas
<p>I have 38 columns that I am pre-processing one by one. The result of each column must be written in csv file. Every time I run the code, only last processed column is written in csv. How can I add each column one by one onto output file using pandas?</p> <p>Here is my code:</p> <p>def min_max(my_data1):</p> <pre>...
<p>I think you dont need loops, better is use pandas functions <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sub.html" rel="nofollow noreferrer"><code>sub</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.div.html" rel="nofollow noreferrer">...
python|pandas
1
355,629
48,570,269
How to access next row after dataframe ix?
<p>I am trying to access next row of entry of dataframe at <code>index01</code>: ex:</p> <p>next row of <code>df.ix[index01]</code>?</p> <p>thanks</p>
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.get_loc.html" rel="nofollow noreferrer">index.get_loc</a> and keep in mind that <code>ix</code> is deprecated:</p> <pre><code>df.iloc[df.index.get_loc(index01) + 1] </code></pre> <p>This assumes <code>index01</code> is the label. If t...
python|pandas|dataframe
3
355,630
48,736,366
Printing yearwise popular movies from csv in Python
<p>I have a collection of movie data in an Excel format. It has columns with year, title, and popularity. My goal is to create a dataframe with yearwise movies with top popularity. For now I am able to create only the year and the popularity rating. I want to add the movie title too.</p> <pre><code>df=pd.DataFrame(data...
<p>You just need to transform the index.</p> <p>Let's say this is your data:</p> <pre><code>release_year, popularity, movie 1999, 5, a 1999, 4, c 2000, 3, b 2000, 4, d </code></pre> <p>Do the following:</p> <pre><code>import pandas as pd data= pd.read_csv('data.csv') idx = data.groupby(['release_year'])['popularity...
python|pandas|csv
0
355,631
48,694,900
Pandas: Iterate over existing columns and create new columns based on conditionals
<p>The best version of a question that relates to my question is found <a href="https://stackoverflow.com/questions/42586934/pandas-dataframe-multiplying-columns-and-creating-new-columns">here</a>. But I'm running into a hiccup somewhere.</p> <p>My dataframe:</p> <pre><code>df = pd.DataFrame({'KEY': ['100000003', '10...
<p>Use <code>filter</code> + <code>isin</code> + <code>rename</code>, for a single pipelined transformation of your data.</p> <pre><code>v = (df.filter(regex='^RO_') # select columns .isin([4, 1]) # check if the value is 4 or 1 .astype(int) # convert the `bool` result to `int` ...
python|pandas|loops
2
355,632
48,788,447
Calculate count of all the elements in nested list
<p>I have list of lists and would like to create data frame with count of all unique elements. Here is my test data:</p> <pre><code>test = [["P1", "P1", "P1", "P2", "P2", "P1", "P1", "P3"], ["P1", "P1", "P1"], ["P1", "P1", "P1", "P2"], ["P4"], ["P1", "P4", "P2"], ["P1", "P1", "P...
<p>Here is one way.</p> <pre><code>from collections import Counter from itertools import chain test = [["P1", "P1", "P1", "P2", "P2", "P1", "P1", "P3"], ["P1", "P1", "P1"], ["P1", "P1", "P1", "P2"], ["P4"], ["P1", "P4", "P2"], ["P1", "P1", "P1"]] c = Counter(chain.from_iterabl...
python|python-3.x|list|pandas|dictionary
6
355,633
48,858,377
what's the difference between np.array[:,0] and np.array[:,[0]]?
<p>I have a numpy array cols2:</p> <pre><code>print(type(cols2)) print(cols2.shape) &lt;class 'numpy.ndarray'&gt; (97, 2) </code></pre> <p>I was trying to get the first column of this 2d numpy array using the first code below, then i got a vector instead of my ideal one column of data. the second code seem to get me ...
<p><code>cols2[:, 0]</code> specifies that you want to slice out a 1D vector of length <code>97</code> from a 2D array. <code>cols2[:, [0]]</code> specifies that you want to slice out a 2D sub-array of shape <code>(97, 1)</code> from the 2D array. The square brackets <code>[]</code> make all the difference here. </p> ...
python|arrays|numpy|slice|sub-array
3
355,634
48,709,805
Getting diagonal elements over several dimensions
<p>I'd like to transform a tensor T of size (n x n x m x m) into a tensor U of size (n x m x m) while only retreiving the diagonal elements of T over the (NxN) chunks (i.e. Uikl=Tiikl). torch.diag() only works with 2-D tensors and I really fail to see how to do this without looping on the indexes of the elements (whic...
<p>When applied to 2d matrices, <code>torch.diag()</code> is an alias for <code>torch.diagonal()</code>.</p> <p><code>diagonal</code> itself allows you to specify which two dimensions of an arbitrary rank tensor the diagonal is taken from, by default these are 0 and 1:</p> <pre class="lang-py prettyprint-override"><cod...
python|numpy|pytorch
0
355,635
48,804,698
Repeat last column in numpy array
<h3> Problem </h3> I am trying to repeat the last column in a Numpy array. Is there a more "elegant" way than resizing the array, copying the values and repeating the last row x times? <h3> What I want to achieve </h3> <pre><code>Input Array: Output Array: [[1,2,3], [[1,...
<p>One possible solution:</p> <pre><code>a = np.hstack((arr, np.tile(arr[:, [-1]], 2))) print (a) [[1 2 3 3 3] [0 0 0 0 0] [0 2 1 1 1]] </code></pre>
python|arrays|performance|numpy|optimization
6
355,636
48,723,487
How PCA in TensorBoard projector is connected to the trained model?
<p>I am trying to implement a multi-label classifier on structured data in TensorFlow. I am using a NN with two fully connected layers, but I have also integrated embeddings as described in this <a href="https://www.tensorflow.org/programmers_guide/embedding" rel="nofollow noreferrer">example</a>, so I can see the PCA ...
<p>What tensor do you give for embedding projection? If you give your output vector: as your models are supposed to give the same output, it will give you a somewhat similar projection as models are trained to output the same thing. </p> <p>To get a difference, you would probably need to create an embedding on one of ...
tensorflow|pca|tensorboard
0
355,637
48,634,528
Check if string within strings in pandas DataFrame column
<p>I have a pretty simple pandas DataFrame and I want to select the portion of the DataFrame that has data within a column that contains within it another string</p> <p>So if this is my DataFrame and I want those columns that contain <code>some</code> within the <code>Loc</code> column how can this be done?</p> <pre>...
<p>You need to use <code>contains</code>, one of the string accessor methods.</p> <pre><code>&gt;&gt;&gt; df['Loc'].str.contains('some') 0 True 1 False Name: Loc, dtype: bool </code></pre> <p>One would then use boolean indexing on the result to select the relevant rows of your dataframe.</p>
python|pandas|dataframe
5
355,638
48,807,989
Error in loading model in PyTorch
<p>I Have the following code snippet </p> <pre><code>from train import predict import random import torch ann=torch.load('ann.pt') #importing trained model while True: k=raw_input("User:") intent,top_value,top_index = predict(str(k),ann) print(intent) </code></pre> <p>when I run the script it is...
<p>When trying to save both parameters and model, pytorch pickles the parameters but only store path the model Class. For instance, changing tree structure or refactoring can break loading. Therefore as the <a href="https://github.com/pytorch/pytorch/blob/761d6799beb3afa03657a71776412a2171ee7533/docs/source/notes/seri...
python|pytorch
2
355,639
48,484,257
difference between host and docker container
<p>I have been trying to train a 3DCNN network with a specific architecture. I wanted to create a dockerfile with all the steps necessary to have the network working. The issue is that If I run the neural network network in the host I have no problem, everything works fine. But doing almost the same on a docker contain...
<p>A docker image will resolve, at runtime, will resolve its system calls by the host kernel.<br> See "<a href="https://stackoverflow.com/a/32842491/6309">How can Docker run distros with different kernels?</a>".</p> <p>In your case, your Error is</p> <pre><code>Your CPU supports instructions that this TensorFlow bina...
docker|tensorflow|gpu|nvidia-docker
1
355,640
48,593,118
Rolling max with pandas on large datasets is very slow
<p>I have a pandas dataframe <code>df</code> which has a DatatimeIndex spanning about 2 years, 2 columns and over 30 million rows of float64 data. I quickly noticed that there is a stark difference in performance between <code>df.rolling('1d').mean()</code> and <code>df.rolling('1d').max()</code></p> <pre><code>&gt;&g...
<p>Pandas is using naive implementation of running max, with <a href="https://github.com/pandas-dev/pandas/blob/master/pandas/_libs/window.pyx#L1215" rel="nofollow noreferrer">linear scan over the window for every sample</a>. Thus, it is linear complexity times size of the window, i.e. for few hundred+ samples per day ...
python|pandas
4
355,641
48,712,198
Tensorflow, tf.gradients calculations
<p>I am learning how to use Tensorflow and at this 1 particular point I am really stuck and can not make a sense around it. Imagine I have a 5 layer network and the output is represented by <code>output</code>. Now suppose I want to find the gradient of <code>output</code> with respect to <code>layer_2</code>. For that...
<p>Tensorflow will create a graph for your model, where each node is an operation (e.g. addition, multiplication, or a combination of them). Basic ops have manually defined gradient functions, and those functions will be used when applying the chain rule while traveling backwards through the graph. </p> <p>If you writ...
python|tensorflow|deep-learning
0
355,642
48,730,195
dataframe compound calculation on aggregations
<pre><code>import pandas as pd times = pd.to_datetime(pd.Series(['2014-07-4', '2014-07-15','2014-08-25','2014-08-25','2014-09-10','2014-09-15'])) strategypercentage = [0.01, 0.02, -0.03, 0.04,0.5,-0.3] df = pd.DataFrame({'Strategy': strategypercentage}, index=times) ##lambda x: ((1+x).cumprod()-1) df.resample("1M"...
<p>It seems you need:</p> <pre><code>df['new'] = df.resample("1M")['Strategy'].apply(lambda x: ((1+x).cumprod()-1)) print (df) Strategy new 2014-07-04 0.01 0.0100 2014-07-15 0.02 0.0302 2014-08-25 -0.03 -0.0300 2014-08-25 0.04 0.0088 2014-09-10 0.50 0.5000 2014-09-15 -0....
python|pandas|pandas-groupby
0
355,643
48,822,583
How to convert INDArray to Json in java?
<pre><code>INDArray image = loader.asMatrix(file); </code></pre> <p>How to convert INDArray to Json String and from Json String to INDArray. I searched in google it is not showing any results recording this.</p>
<p>Fiddling around I see that <code>INDArray</code> has a <code>data()</code> method (See <a href="https://nd4j.org/doc/org/nd4j/linalg/api/ndarray/INDArray.html" rel="nofollow noreferrer">INDArray API</a>)</p> <p>This gives you a <code>DataBuffer</code> which in turn has methods to export it as a Java array (See <a h...
java|multidimensional-array|dl4j|numpy-ndarray
3
355,644
48,648,240
Tensorflow placeholder error when run operation
<p>I am totally new in both python &amp; tensorflow (&lt;1 week). </p> <p>Now i want to build a linear regression by using tensorflow, however i am facing an error of placeholder. </p> <p>I have set the cost by using placeholder, and i have checked the shape of the input variables, it looks no any problem about the s...
<p>You need to provide a feed_dict to the eval function as well because when you evaluate the cost, you need the values of X and y. <code> tempCost= cost.eval(feed_dict={Xp: newX, y: Y}) </code> You can also refer to this other question: <a href="https://stackoverflow.com/questions/42140211/tensorflow-eval-error-you-mu...
python|tensorflow|linear-regression
0
355,645
48,564,533
tf.nn.sigmoid_cross_entropy_with_logits does it share weights?
<p>I am planning to use </p> <pre><code>tf.nn.sigmoid_cross_entropy_with_logits </code></pre> <p>for creating N binary classification models. I want these N models to be independent binary models and not share weights? Can I achieve it using this function? </p>
<p>Yes, you can, this function just applies sigmoid to the given logits, and then computes the cross-entropy loss. It does not have weights at all.</p>
tensorflow|neural-network|classification|multilabel-classification
1
355,646
48,825,785
How can I filter tf.data.Dataset by specific values?
<p>I create a dataset by reading the TFRecords, I map the values and I want to filter the dataset for specific values, but since the result is a dict with tensors, I am not able to get the actual value of a tensor or to check it with <code>tf.cond()</code> / <code>tf.equal</code>. How can I do that?</p> <pre><code>def...
<p>I am answering my own question. I found the issue!</p> <p>What I needed to do is <code>tf.unstack()</code> the label like this:</p> <pre><code>label = tf.unstack(features['label']) label = label[0] </code></pre> <p>before I give it to <code>tf.equal()</code>:</p> <pre><code>result = tf.reshape(tf.equal(label, 's...
python|tensorflow|tensorflow-datasets
6
355,647
48,841,370
Datetime behaviour TypeError: parser() missing 1 required positional argument:
<p>I have modified this</p> <pre><code>def parser(x): return datetime.strptime('190'+x, '%Y-%m') </code></pre> <p>because my monthly date goes from 2002-2017</p> <pre><code>def parser(x,y): return datetime.strptime('20'+x+y, '%Y-%m') </code></pre> <p>When I run</p> <pre><code>s = read_csv('output.csv', hea...
<p>The documentation for <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer"><code>pandas.read_csv</code></a> states:</p> <blockquote> <p><strong>date_parser</strong> : function, default None</p> <p>Function to use for converting a sequence of string c...
python|pandas
1
355,648
48,678,275
Replacing curly braces { } in a Series
<p>I did a group by to concatenate strings in a dataframe in Python. It gave a Series output with curly braces. I'm trying to replace the braces using Replace function. It is not working. This is what I tried. </p> <pre><code>df_final['Word'].replace(to_replace=["{"],value="",inplace=True) </code></pre>
<p>Look like you need</p> <pre><code>df_final['Word'] = df_final['Word'].str.replace("{", "").str.replace("}", "") </code></pre>
python|pandas
1
355,649
48,652,950
substrings in multiple pandas series
<p>I am trying to find a way to search for substrings in strings for a problem like this</p> <pre><code>findin = pd.Series({1:'abcab', 2: 'abab',3: 'abcdaa', 4:'cabca'}) what = pd.Series({1:'b',2: 'a',3: 'bc',4: 'abc'}) </code></pre> <p>where "what" is what I am seeking and "findin" is the values I want to search I ...
<p>You can use regex in a function and apply if on <code>findin</code> Series:</p> <pre><code>c = iter(range(1, 5)) def func(x): ind = next(c) return [i.start() for i in re.finditer(what[ind], x)] findin.apply(func) </code></pre> <p>Out:</p> <pre><code>1 [1, 4] 2 [0, 2] 3 [1] 4 [1] dtype:...
python|string|pandas
1
355,650
48,872,674
Pandas - Lower of Dates when not null
<p>I have a dataframe, it has many timestamps, what I'm trying to do is get the lower of two dates <strong>only</strong> if both columns are not null. For example.</p> <pre><code> Internal Review Imported Date Lower Date 1 2/9/2018 19:44 2 2/15/2018 1:20 2/13/2018 2:18 2/13/2018 2:18 3 2/7/2018 23...
<p>The following code should do the trick : </p> <pre><code>df['Lower Date'] = df[( df['Internal Review'].notnull() ) &amp; ( df['Imported Date'].notnull() )][['Internal Review','Imported Date']].min(axis=1) </code></pre> <p>The new column will be filled by the minimum if both are not null.</p> <p>Nicolas</p>
python|pandas|date
1
355,651
48,792,405
How to combine dataframe rows
<p>I have the following code:</p> <pre><code>import os import pandas as pd from pandas import ExcelWriter from pandas import ExcelFile fileName= input("Enter file name here (Case Sensitve) &gt; ") df = pd.read_excel(fileName +'.xlsx', sheetname=None, ignore_index=True) xl = pd.ExcelFile(fileName +'.xlsx') SystemCoun...
<p>If I understand it clearly </p> <pre><code> df1=df1.apply(lambda x : pd.to_numeric(x,errors='ignore')) d=dict(zip(df1.columns[1:],['sum']*df1.columns[1:].str.contains('System').sum()+['first'])) df1.fillna(0).groupby('Email').agg(d) Out[95]: System1 System2 System3 System4 ...
python|python-3.x|pandas|dataframe|rows
2
355,652
48,670,780
Pandas read csv adds zeros
<p>I have a problem with reading in a csv with an id field with mixed dtypes from the original source data, i.e. the id field can be 11, 2R399004, BL327838, 7 etc. but the vast majority of them being 8 characters long.</p> <p>When I read it with multiple versions of pd.read_csv and encoding='iso-8859-1' it always conv...
<p>Basically the column looks like this</p> <p>Column_ID 10 HGF6558 059 KP257 0001</p>
python|pandas|csv|encoding|iso-8859-1
0
355,653
48,677,616
Pandas loop taking way to much time - better way?
<p>I have a loop that is taking way too much time and I wonder if there is a better way? Or if I am making rookie mistakes?</p> <p>The reason I am doing a loop is that the first value is different and the need for previous values.</p> <pre><code># create var and set to 0 df [ 'amt_model' ] = 0 # create the cashflow ...
<p>My solution, with:</p> <pre><code>df = pd.DataFrame(columns=['cf','cash_in','cash_out','transfer','contrib','pct_model']) for c in df.columns: df[c] = np.random.rand(100)*100 print(df.head()) cf cash_in cash_out transfer contrib pct_model 0 18.478061 80.073920 19.041986 8.859406 85....
python|pandas
1
355,654
48,704,526
Split pandas dataframe into chunks of N
<p>I'm currently trying to split a pandas dataframe into an unknown number of chunks containing each N rows.</p> <p>I have tried using numpy.array_split() this funktion however splits the dataframe into N chunks containing an unknown number of rows.</p> <p>Is there a clever way to split a python dataframe into multip...
<p>You can try this:</p> <pre><code>def rolling(df, window, step): count = 0 df_length = len(df) while count &lt; (df_length -window): yield count, df[count:window+count] count += step </code></pre> <p>Usage:</p> <pre><code>for offset, window in rolling(df, 100, 100): # | | ...
python|pandas|numpy
7
355,655
48,726,005
Transposing the list
<p>I have the following list:</p> <pre><code>y = [[0], [0], [0], [0], [1], [1], [1], [1]] </code></pre> <p>I would like to transpose it and have it in the following form:</p> <pre><code>[[0] [0] [0] [0] [1] [1] [1] [1]] </code></pre> <p>When I did <code>numpy.transpose(y)</code>, I got the following:</p> <pre><cod...
<pre><code>[[0], [0], [0], [0], [1], [1], [1], [1]] </code></pre> <p>is exactly the same as this form:</p> <pre><code>[[0] [0] [0] [0] [1] [1] [1] [1]] </code></pre> <p>You had a matrix with 8 rows and 1 column. Transposition executed on the matrix converted it to a matrix with just 1 row and 8 columns, so the outpu...
python|numpy|transpose
2
355,656
48,868,919
Tensorflow: Softmax cross entropy with logits becomes inf
<p>I am working on the <a href="https://codelabs.developers.google.com/codelabs/tensorflow-for-poets/#4" rel="nofollow noreferrer">Tensorflow for poets</a> tutorial. Most of the time, training fails with an error <code>Nan in summary histogram</code>. I run the following command on the original data to retrain:</p> <p...
<p>I had searched about compatibility as I was doing in 2.7 also, but it said 3.5 is the best version now with all latest tensorflow support. So I created virtual environment with python 3.5. I think that's why the stability issue.</p>
tensorflow|histogram
1
355,657
48,713,989
mysterious conversion in pandas dataframe, how to disable that
<p>I have a code looking like this:</p> <pre><code> series_tmp = pd.Series() series_tmp["date"] = pd.Timestamp(str(msg.date)) series_tmp["Timestamp_downloaded"] = pd.Timestamp.now(self._timezone_to_use) series_tmp["contract_str"] = contract_str_now series_tmp["open"] = float(msg....
<p>I cannot solve the problem in the series level. But after i got the corresponding dataframe, I do something like:</p> <pre><code>historical_data_df["date"] = pd.to_datetime(historical_data_df["date"]) historical_data_df["Timestamp_downloaded"] = pd.to_datetime(historical_data_df["Timestamp_downloaded"]).dt.tz_loca...
python|pandas
0
355,658
48,458,438
Why is numpy.int32 not recognized as an int type
<p>I just spent half an hour looking into a bug in statsmodels' SARIMAX functionality that I could finally trace back to the fact that numpy.int32 fails type checks for int.</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; foo = np.int32(3) &gt;&gt;&gt; isinstance(foo, int) False </code></pre> <p>Is there ...
<p><code>__mro__</code> lists the inheritance stack of a class:</p> <pre><code>np.int32.__mro__ Out[30]: (numpy.int32, numpy.signedinteger, numpy.integer, numpy.number, numpy.generic, object) int.__mro__ Out[31]: (int, object) </code></pre> <p>For a basic array:</p> <pre><code>x=np.array([1,2,3]) x.dtype ...
python|numpy|types
9
355,659
71,025,482
How to left merge table_one with table_two based on latest month_year column?
<p>table_one has distinct IDs. I want to left merge <strong>table_one</strong> on <strong>table_two</strong> based on <strong>latest date in month_year</strong> column. I did the following but didn't work.</p> <pre><code>import datetime import pandas as pd today = datetime.date.today() first = today.replace(day=1) las...
<p>You have to keep only last date per ID before merging. In order to do that, convert your <code>month_year</code> column into a proper <code>datetime64</code> then sort by date and drop duplicates for each ID.</p> <pre><code>df3 = df1.merge( df2.assign(dt=pd.to_datetime(df2['month_year'], format='%m_%Y')) ...
python|pandas|string|datetime|machine-learning
0
355,660
70,974,189
Group by don't work after used for third time
<p>I don't know what I am doing wrong, but my dataframe does not groupby as I would expect it to do:</p> <p>This is actual result of my script, but i wanted to fourth to be also grouped - see images below</p> <p><a href="https://i.stack.imgur.com/GXG8x.png" rel="nofollow noreferrer">Actual result</a></p> <p><a href="ht...
<p>You code is working fine, but you need to sort the index for the display to look grouped (only consecutive identical labels look &quot;merged&quot;):</p> <pre><code>df = (df.set_index([&quot;first&quot;, &quot;first_numbers&quot;, &quot;second&quot;, &quot;second_numbers&quot;, &quot;fourth&quot;...
python|pandas|group-by|pandas-groupby
1
355,661
71,011,333
Pytorch expects each tensor to be equal size
<p>When running this code: <code>embedding_matrix = torch.stack(embeddings)</code></p> <p>I got this error:</p> <pre><code>RuntimeError: stack expects each tensor to be equal size, but got [7, 768] at entry 0 and [8, 768] at entry 1 </code></pre> <p>I'm trying to get embedding using BERT via:</p> <pre><code> split_s...
<p>As per <a href="https://pytorch.org/docs/1.9.1/generated/torch.stack.html" rel="nofollow noreferrer">PyTorch Docs</a> about <code>torch.stack()</code> function, it needs the input tensors in the same shape to stack. I don't know how will you be using the <code>embedding_matrix</code> but either you can add padding t...
python|pytorch|tensor|bert-language-model
4
355,662
70,976,576
Highest diff between max and min values in a pandas df
<p>I have this df:</p> <pre class="lang-py prettyprint-override"><code>values = {'a':[1,2,3,4], 'b':[1,2,5,9], 'c':[10,1000,20,30]} d=pd.DataFrame(values) </code></pre> <p>What's the best way to get the column with the highest spread between max and min values?</p> <p>The output shoub be: <code>c</code> because <code>1...
<p>Short and simple way:</p> <pre><code>d.apply(lambda x: max(x)-min(x)).idxmax() </code></pre> <p>Output:</p> <pre><code>c </code></pre>
python-3.x|pandas
2
355,663
71,004,885
different method of running pytorch on gpu
<p>See the code block below (the source of the code can be found <a href="https://github.com/cshwhale/Med3D" rel="nofollow noreferrer">here</a>, also you don't need to read the whole block, I will explain and highlight the important part)</p> <pre><code>def train(data_loader, model, optimizer, scheduler, total_epochs, ...
<p>In general, in order to harness the full power of GPUs, every <em>stateful</em> <code>Module</code> should be sent to a <code>cuda</code> device before the forward step. A stateful <code>Module</code> has an internal state, e.g. <code>Parameter</code> (weights).</p> <p>This is not usually the case of <code>Loss</cod...
python-3.x|pytorch
1
355,664
70,943,839
Geomean of large numbers with numpy
<p>I want to calculate the geomean of some large numbers. Problem is that the result of the product of large numbers is overflow. Example:</p> <pre><code>a = array([168116745,168117411,168117729,168118170,168118695,168119286,168119610]) print(a.prod()) print(a.prod()**(1.0/len(a))) </code></pre> <p>Output</p> <pre><cod...
<p>One solution is to use logarithms. Try this:</p> <pre><code>a = array([168116745,168117411,168117729,168118170,168118695,168119286,168119610]) print('GM =', np.exp(np.average(np.log(a)))) </code></pre> <p>Alternatively, scipy has a <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gmean.html"...
python|numpy
4
355,665
70,841,944
Pandas. Why is it splitting up df into multiple rows when I do groupby and agg count?
<p>I have the below, that is looping through and reading 3 csv files that are about 120MB each with the same columns. I'm doing a group by and counting the impression_id, then combining the df's into a final df.</p> <p>But for some reason the below, is splitting out my rows, but if I total the IMP_ID_COUNT rows its the...
<p>It's hard to tell without some sample data, but I can see only 2 possibilities:</p> <p><strong>1. Grouping variables <em>looks</em> the same, but they aren't</strong></p> <p>If the combination <code>('NORMALIZED_PAGE_URL', 'TS', 'USER_IP_COUNTRY')</code> is unique for each file, that's the only possible explanation....
python-3.x|pandas
1
355,666
70,851,006
how do you skip failed items from the api call using Python
<p>I read from a csv file to populate a data frame. From this data frame, I go through each host:</p> <pre><code> 1. build an api 2. request the api 3. if api request is successful, I extract the data from the response json and build a data frame. 4. I keep going though each host and add the json ouput to my final...
<p>You simply need to change the order of your loops and put the except where it matters: around your request. Not sure if I understood you correctly so there's code for two versions in the except block.</p> <pre class="lang-py prettyprint-override"><code>finalDF = pd.DataFrame(...) for env_id in envs: host_data = [...
python|pandas|dataframe
1
355,667
70,834,612
Count number of matches in pairs of pandas dataframe rows
<p>I have been trying to count the number of times different values in a row of dataframe matches with column-wise values in other rows and provide an output. To illustrate, I have a dataframe (df_testing) as follows:</p> <pre><code>import pandas as pd df_testing = pd.DataFrame([ [0,23,1, 3, 4,2], [1,33,3, 2, 4...
<p>You could use <a href="https://docs.python.org/3.9/library/itertools.html#itertools.combinations" rel="nofollow noreferrer"><code>itertools.combinations</code></a>, a dictionary comprehension and the <code>Series</code> constructor:</p> <pre><code>from itertools import combinations df2 = df_testing.set_index(['SN',...
python|pandas|match
2
355,668
70,821,374
Stateful LSTM VAE: Invalid argument: You must feed a value for placeholder tensor 'decoder_input' with dtype float and shape [batch_size, latent_dim]
<p>I am solving a Timeseries problem using LSTM VAE(Variational auto-encoder), I have built my VAE model as below</p> <pre><code>import tensorflow as tf tf.compat.v1.disable_eager_execution() class VAE: def __init__(self, hidden_layer_units, hidden_layer_leakyrelu_alphas, ...
<p>I solved the problem, by changing the loss calculation logic, instead of defining the functions to calculate reconstruction and KL loss in the VAE class, I moved the loss calculation part outside the VAE class as below</p> <pre><code># Build Variational AutoEncoder(VAE) LSTM Model: def build_lstm_neural_network(lstm...
tensorflow|machine-learning|lstm|stateful|invalid-argument
0
355,669
70,886,725
How Can I convert my csv files pixel data into image
<p>I am totally beginner in this field. I started working with neural network for image classification purpose. My question is I loaded one row through panda. now I want to see that image like from which category it is. it has label 0. so how i can convert that pixels values into image.</p> <pre><code>import matplotlib...
<p>You can visualise an image using matplotlib (<code>plt.imshow</code>) or seaborn (<code>sns.heatmap</code>). Note that in all cases you'll probably want to <a href="https://matplotlib.org/stable/tutorials/colors/colormaps.html" rel="nofollow noreferrer">change the colour map to something other than the default.</a><...
python|pandas|dataframe|csv|neural-network
1
355,670
71,079,354
I get the exception "input that isn't a symbolic tensor". Can I convert numpy.ndarray to a tensor?
<p>I am currently trying to implement ArcFace as loss function for my Inception v4 model. I use a pretrained model from <a href="https://github.com/tensorflow/models/tree/master/research/slim" rel="nofollow noreferrer">tensorflow.slim</a>, which returns the pre-activation logits and endpoints as result as stated in <a ...
<p>I have tried this code on tf 2.8 and the issue does not exist please upgrade your tf to 2.x version to resolve this.</p>
python|tensorflow|machine-learning|keras|computer-vision
0
355,671
70,763,324
How to print the maximum memory used during Keras's model.fit()
<p>I wrote a neural network model using <code>Keras</code> and <code>Tensorflow</code> and was able to train and run it. At this point, I want to know how much memory was required for training the model. How can I print this information during the training phase? I tried the <code>Keras</code> model profiler below but ...
<p>I would suggest using a <code>Keras Callback</code> and printing the GPU usage after every epoch for example. You can get the GPU information with <code>tf.config.experimental.get_memory_info('GPU:0')</code>. Here is a working example:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf clas...
python|tensorflow|keras|memory
0
355,672
71,014,206
Map Id's in one dataframe with the corresponding names in another dataframe
<p>I have below 2 dataframes:</p> <pre><code>df_1: | | assign_to_id | | | ------------ | | 0 | 1, 2 | | 1 | 2 | | 2 | 3,4,5 | df_2: | | id | name | | | ------------| -----------| | 0 | 1 | John | | 1 | 2 | Adam | | 2 | 3 | Max ...
<p>Idea is mapping column splitted by <code>,</code> by dictionary and then join back by <code>,</code>:</p> <pre><code>d = df_2.assign(id = df_2['id'].astype(str)).set_index('id')['name'].to_dict() f = lambda x: ','.join(d[y] for y in x.split(',') if y in d) df_1['assign_to_name'] = df_1['assign_to_id'].replace('\s+',...
python|pandas
0
355,673
70,786,249
PyTorch/NumPy: Create binary mask from rgb image
<p>I have a tensor containing a batch of 4 RGB 128x128 images. So the the tensor has the shape (4,128,128,3). I need to create a binary mask from this tensor where each pixel is black if the image is black and white if the image is not black. I tried the following <code>masks = torch.where(image &gt; 0, 1.0, 0.)</code>...
<p>I solved it by applying <code>sum</code> along the rgb channels before calling <code>where</code>.</p> <pre><code>images_sum = images.sum(axis=3) masks = torch.where(images_sum &gt; 0, 1.0, 0.) </code></pre>
numpy|pytorch
0
355,674
70,776,090
pandas Dataframe divide a column with a specific value and create new column with the result?
<pre><code> A B 0 0.119 5.344960e+08 1 0.008 7.950629e+09 2 318.575 1.996548e+05 3 153.644 ...
<p>You can do something like this:</p> <pre class="lang-py prettyprint-override"><code>df['B'] = df['A'].rdiv(my_sum).replace(np.inf, 0).astype('int64') </code></pre> <p>You can also change the view option of pandas:</p> <pre class="lang-py prettyprint-override"><code>pd.set_option('display.float_format', lambda x: '%....
python|pandas|dataframe|series
1
355,675
71,000,585
Create a new column in Pandas Dataframe based on the 'NaN' values in another column
<p>I have a dataframe:</p> <pre><code>A B 1 NaN 2 3 4 NaN 5 NaN 6 7 </code></pre> <p>I want to create a new column <code>C</code> containing the value from <code>B</code> that aren't NaN, otherwise the values from <code>A</code>. This would be a simple matter in Excel; is it easy in Pandas?</p>
<p>Yes, it's simple. Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.where.html" rel="nofollow noreferrer"><code>pandas.Series.where</code></a>:</p> <pre><code>df['C'] = df['A'].where(df['B'].isna(), df['B']) </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; df A B C 0 1 NaN 1 1 2 ...
python|pandas
2
355,676
70,959,660
torch.nn.functional.interpolate: difference between "linear" and "bilinear"?
<p>In <a href="https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html?highlight=interpolate#torch.nn.functional.interpolate" rel="nofollow noreferrer">torch.nn.functional.interpolate</a> what's the difference between the modes <code>linear</code> and <code>bilinear</code>?</p> <p>To me, these ar...
<p>Pytorch is explicitly differentiating between 1d interpolation (<code>linear</code>) and 2d interpolation (<code>bilinear</code>).</p> <p>They differ in the the dimensionality of the <code>input</code> argument they are allowed to work on ( <a href="https://github.com/pytorch/pytorch/blob/07e9f86a4bb0116d61724a2b898...
python|pytorch|interpolation|image-resizing
4
355,677
70,994,743
RuntimeError: Only tuples, lists and Variables are supported as JIT inputs/outputs. Dictionaries and strings are also accepted
<p>I was trying to convert my pytorch model to onnx but I am facing <code>RuntimeError: Only tuples, lists and Variables are supported as JIT inputs/outputs. Dictionaries and strings are also accepted, but their usage is not recommended. Here, received an input of unsupported type: DGLHeteroGraph</code> Error</p> <pre ...
<p>I think that your dummy_input is not something torch supports for export. I guess get_graph_from_smile returns DGLHeteroGraph which torch cannot trace/jit to then export it in ONNX.</p> <p>I don’t know well the data types you use but in general, you should provide the same kind of input (only a batch with N=1 should...
python|machine-learning|pytorch|onnx|onnxruntime
0
355,678
70,961,572
Python Tkinter - 2 combo boxes to filter dataset - first combobox lists states, second combobox lists only facilities in that state
<p>new to Tkinter... I am trying to make a mini app in Tkinter where the user selects the state of a medical facility in one combobox and the specific name of a facility in a second combobox from that state. Right now, I've been able to work get my dataframe to filter to the values selected in the state (first combobox...
<p>You need to update the values in your second combobox when you select your state. To do this, you need to bind the <code>&quot;&lt;&lt;ComboboxSelected&gt;&gt;&quot;</code> event in the first combobox with a function that changes the second combobox values.</p> <pre><code># Function for when first combobx selected d...
python|pandas|dataframe|tkinter|combobox
1
355,679
70,799,909
map output the key value if key not in dict
<pre><code>import pandas as pd d = {'user': ['bob','alice','bob', 'kk'], 'item': ['apple','coconut','pear', 'ajay']} df = pd.DataFrame(data = d) d = {'apple':1.0,'coconut':0.0} df['item'] = df['item'].map(d) Output: df Out[22]: user item 0 bob 1.0 1 alice 0.0 2 bob NaN 3 kk NaN Expecte...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.fillna.html" rel="nofollow noreferrer"><code>Series.fillna</code></a> by original column:</p> <pre><code>d = {'apple':1.0,'coconut':0.0} df['item'] = df['item'].map(d).fillna(df['item']) print (df) user item 0 bob 1.0 1 ...
pandas
3
355,680
70,905,032
How to install Tensorflow in Raspberry pi 4b 8gb , i am aslo try but getting this error . plese give some good suggestion, how to install?
<p>from tensorflow import keras Traceback (most recent call last):</p> <p>File &quot;&quot;, line 1, in from tensorflow import keras</p> <p>ImportError: cannot import name 'keras' from 'tensorflow' (unknown location)<a href="https://i.stack.imgur.com/0hkCS.png" rel="nofollow noreferrer">enter image description here</a...
<p>Install Tensorflow lite on Raspberry pi.</p> <p>TensorFlow Lite with Python is great for embedded devices based on Linux, such as Raspberry Pi.</p> <pre><code>python3 -m pip install tflite-runtime </code></pre> <p>Follow the instructions mentioned <a href="https://www.tensorflow.org/lite/guide/python" rel="nofollow ...
python|tensorflow
1
355,681
70,980,801
string 'None' and NoneType in python's dataframe
<p>Make a list containing two elements : 'None' and None.</p> <pre><code>x = ['None',None] x ['None', None] print(x) ['None', None] </code></pre> <p>It is obvious that the first is a string whose value is <code>'None'</code>, the second is a NoneType <code>None</code> in python.</p> <p>Create a dataframe which contain ...
<p>First of all, in normal cases, there should not be two types of data in one column of a completed <code>DataFrame</code>. Therefore a <code>str</code> and a <code>NoneType</code> cannot show themselves together after data washing.</p> <p>And in normal cases, we don't want to see so many <code>''</code> in a string c...
python|pandas|dataframe
1
355,682
71,004,860
How to scrape dates of News Site
<p>I am trying to scrap the news website with news that are valid of a certain date. The output of the function return :</p> <pre><code>&lt;li class=&quot;meta-data&quot;&gt;&lt;time data-datetime=&quot;relative&quot; datetime=&quot;2022-01-30T08:56:09Z&quot; title=&quot;2022-01-30T08:56:09Z&quot;&gt;January 30, 2022 0...
<p>Considering <code>i</code> as a string (if not typecase the variable <code>i</code> to a string using built in method <code>i = str(i)</code>)</p> <pre><code>i = str(i) i = i.split(&quot;&gt;&lt;&quot;)[1] i = i.split(&quot;datetime=&quot;)[2] i = i.split(&quot;\&quot;&quot;)[1] print(i) # 2022-01-30T08:56:09Z </...
python|html|pandas|selenium|web-scraping
0
355,683
70,962,308
Scatter plotting geographical coordinates
<p>I have a column Loc in my dataframe that contains coordinates I want to plot I transform it into an array with</p> <pre><code>z =pd.DataFrame(df.Loc) z.to_numpy() </code></pre> <p>Which gives the following output:</p> <pre><code>array([['45.34301499763467, -73.80926407774574'], ['45.8563638, -73.9631463'], ...
<p>DataFrames can generally not contain more complex types, such as lists or tuples. Hence your cordinates are strings. You can use <code>ast.literal.eval</code> to evaluate your strings directly from dataframe for instance with list comprehension:</p> <pre><code>import ast z = np.array([ast.literal_eval(row) for row i...
python|pandas
1
355,684
71,031,598
Random Search: Constructing set of unit directions
<p>I am currently looking into an example implementation of <a href="https://github.com/jermwatt/machine_learning_refined/blob/gh-pages/notes/2_Zero_order_methods/2_5_Random.ipynb" rel="nofollow noreferrer">Random Search</a> from <em>Machine Learning Refined</em> and have trouble understanding the following code snippe...
<p>As wong.lok.yin pointed out in the comments, the line</p> <pre><code>norms = np.sqrt(np.sum(directions*directions,axis = 1))[:,np.newaxis] </code></pre> <p>sums over axis=1 (the column axis) and adds a new axis to the resulting vector by <code>[:,np.newaxis]</code>. There is a good explanation of how np.newaxis work...
python|numpy|machine-learning|optimization
0
355,685
71,034,091
Tensorflow: accuracy remains the same
<p>I'm trying to build simple NN model, however accuracy remains the same during all epochs in the training: here is the code</p> <p>editing data:</p> <pre><code>train = pd.read_csv('../input/mercedes-benz-greener-manufacturing/train.csv.zip') test = pd.read_csv('../input/mercedes-benz-greener-manufacturing/test.csv.zi...
<p>loss=tf.keras.losses.mae - this is loss for regression models</p> <p>metrics=['accuracy'] - this is metric for classification models</p>
pandas|tensorflow|keras|sequential
0
355,686
70,916,322
Appending a Pandas Series to a Dataframe in a loop
<p>I am trying to append the results of my nmap scan into a dataframe.</p> <pre><code>def vulnScan(targets): portInfo =[] columnNames = [&quot;Port&quot;,&quot;Protocol&quot;,&quot;State&quot;,&quot;Service&quot;] for target in targets: portsDF = pd.DataFrame(columns = columnNames) print(&qu...
<p><code>pandas.DataFrame.append</code> is not in-place, so it returns a new objects, as the docs page you linked says. Therefore, you'd usually do something like this:</p> <pre><code>portsDF = portsDF.append(newRow, ignore_index=True) </code></pre> <p>But in this case, you're populating the dataframe in a loop, so run...
python|pandas
0
355,687
70,813,337
creating a dataframe by using a list - python
<p>i have a list of 270 listitems and i would like to transfer to a dataframe. I would like to divide the content of the list into three dataframe columns containing 90 items per column. #</p> <p>Col A Col B Col C</p> <p>[0:89] [90:179] [180:269]</p> <p>of course i could use List slicing and so on for this c...
<p>You could simply use <code>range</code> and slices:</p> <pre><code>df = pd.DataFrame({f'Col{i + 1}': lst[i * 90: (i+1) * 90] for i in range(len(lst)//90)}) </code></pre> <p>The good news is that this will silently ignore additional values if the length of the list is not an exact multiple of 90.</p...
python|pandas|dataframe
-1
355,688
70,811,473
PAGE_FAULT_IN_NONPAGED_AREA - Pytorch
<p>The BSOD follows the opening of a VRAM-intensive application while training runs on the GPU. I've opened such applications regularly in the past without problems, with even bigger models, and the applications would utilize shared memory if they didn't have enough (which training <em>cannot</em> do) - no clue what's ...
<p>I had the same issue. PAGE_FAULT_IN_NONPAGED_AREA, nvlddmkm.sys, python.exe running pytorch. I was able to reproduce it consistently.</p> <p>The solution was to use <a href="https://www.guru3d.com/files-details/display-driver-uninstaller-download.html" rel="nofollow noreferrer">DDU</a> to nuke the NVIDIA drivers, th...
python|windows|pytorch|bsod
0
355,689
70,768,591
How to delete 0's after last 1's
<p>I have written code that deletes all the rows after the first occurrence of value 1 in target but I want it to happen after the last.</p> <p><a href="https://i.stack.imgur.com/6X0V6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6X0V6.png" alt="enter image description here" /></a></p> <p>I want t...
<p>In your solution remove <code>shift</code> and for remove <code>0</code> from back per groups change ordering of values in group by <code>iloc[::-1]</code>:</p> <pre><code>mask = (df.groupby('user_id')['target'] .apply(lambda x: x.iloc[::-1].eq(1).cumsum().ne(0).iloc[::-1])) df = df[mask] </code></pre> <p>...
python|pandas
1
355,690
70,794,195
Pandas dataframe rows won't drop
<p><strong>Background -</strong> I am trying to drop rows from a pandas dataframe (<code>exceptions_df</code>) if all 3x conditions are met.</p> <p><strong>Conditions -</strong></p> <ol> <li><code>Ownership Audit Note</code> column value contains partial string values of either <code>ignore</code> or <code>Ignore</code...
<p>Use of wrong partition brackets. Lets try</p> <pre><code>exceptions_df = exceptions_df[(~(exceptions_df['Ownership Audit Note'].str.contains('ignore'|'Ignore'))) &amp; (~(exceptions_df['% Ownership'] == 100)) &amp; ( ~(exceptions_df['Account # %'] == 'Entity...
python|pandas|string
0
355,691
70,947,599
Jupyter Notebook List Python Dataframes
<p>Can someone explain how I can see all python dataframes in my Jupyter Notebook kernal occupying my memory?</p> <p>For context in Spyder IDE, I can see all variables ive assigned within it.</p> <p>Outcome: Id like to see a list of ones still sitting in my memory and by how much ram they are occuying. % of total would...
<p>This will do the job:</p> <pre><code>import pandas as pd %whos DataFrame </code></pre>
python-3.x|pandas|dataframe|jupyter-notebook
1
355,692
70,759,938
set_table_styles not displaying in VSCode
<p>Python 3.9.5</p> <p>Pandas 1.2.4</p> <p>I'm trying to learn about using Styling to my pandas and specifically applying borders. However I can't seem to get my display to reflect correctly when using set_table_styles. Even doing a direct copy of another website.</p> <p><a href="https://www.geeksforgeeks.org/display...
<p>Maybe you can try this:</p> <pre><code># making a yellow border html=df.style.set_table_styles( [{&quot;selector&quot;: &quot;&quot;, &quot;props&quot;: [(&quot;border&quot;, &quot;10px solid yellow&quot;)]}] ).render() # write html to file text_file = open(&quot;index.html&quot;, &quot;w&quot;) text_file.wri...
python|pandas|visual-studio-code|styling
0
355,693
71,026,019
Do rolling on all dataframe rows
<p>I would like to find in dataframe of prices all all-time highs in that were in history.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>timestamp</th> <th>close</th> <th>ath</th> </tr> </thead> <tbody> <tr> <td>x</td> <td>1234</td> <td>0</td> </tr> <tr> <td>x</td> <td>2000</td> <td>1</td...
<p>Try this:</p> <pre><code>df['ath'] = df.groupby('timestamp')['close'].shift(1).lt(df['close']).astype(int) </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; df timestamp close ath 0 x 1234 0 1 x 2000 1 2 x 1956 0 3 x 1884 0 4 x 2234 1 </code></p...
python|pandas|dataframe|data-science
2
355,694
70,857,783
How to use a Python data frame to generate a list/sequence that can be added as a column
<p>I have created a data frame from a sql query that generates bin data for a histogram: min, max, and bin size. I want to use this data to create a list of bins that I can then merge back into the original data frame</p> <p><a href="https://i.stack.imgur.com/9DKro.jpg" rel="nofollow noreferrer">Here is a sample of my ...
<p>This code will generate the desire output you want. You didn't mentioned how to calculate bin_seq.</p> <blockquote> <pre><code>import pyodbc import pandas as pd bin_sql = &quot;&quot;&quot; select 'test_model_1' model, 0 initial_bin , 435 maximum , 7 bin_size from analytics.model_data &quot;&quot;&quot...
python|pandas|list|for-loop|sequence
0
355,695
71,011,135
Is it possible to run scatter matmul in pytorch?
<p>Edit: apparently DGL is working on it already: <a href="https://github.com/dmlc/dgl/pull/3641" rel="nofollow noreferrer">https://github.com/dmlc/dgl/pull/3641</a></p> <p>I have several types of embeddings and each one needs its own linear projection. I can solve the problem with a for loop of type:</p> <pre><code>em...
<p>Just found out that DGL is working on this feature already: <a href="https://github.com/dmlc/dgl/pull/3641" rel="nofollow noreferrer">https://github.com/dmlc/dgl/pull/3641</a></p>
pytorch|embedding|scatter|pytorch-geometric|dgl
0
355,696
70,891,128
torch meshgrid warning: in an upcoming release, it will be required to pass the indexing argument
<p>I am trying to execute LIIF(<a href="https://github.com/yinboc/liif" rel="nofollow noreferrer">https://github.com/yinboc/liif</a>) and the following warning appears:</p> <pre><code>/usr/local/lib/python3.7/dist-packages/torch/functional.py:445: UserWarning: torch.meshgrid: in an upcoming release, it will be required...
<p>My answer might not be the direct solution, but can be somehow relevant. I met the same warning but it was caused by calling <code>torch.cartesian_prod(*tensors)</code>.</p> <pre><code>/opt/conda/lib/python3.7/site-packages/torch/functional.py:1069: UserWarning: torch.meshgrid: in an upcoming release, it will be req...
python|pytorch|grid|torch|user-warning
0
355,697
70,838,065
How to combine two dataframes with different shapes on multiple column values
<p>Thank you in advance for your time and effort to answer. I'm trying to <strong>combine two dataframes (one containing current data, the other containing future prediction data) with different shapes</strong>.</p> <p>For example,</p> <pre><code>df1 = ['Date', 'ColA', 'ColB', 'ColC', 'GroupNumber'] df2 = ['Date', 'Co...
<p>You can use pandas <code>merge</code> to perform a <code>left join</code>:</p> <pre><code>import pandas as pd final_df = pd.merge(df1,df2,on=['GroupNumber','Date'],how='left') </code></pre>
python|pandas|dataframe
2
355,698
70,955,863
Why does curve_fit produce "too deep for desired array"?
<p>I am trying to fit a polynomial curve into my data. <code>x</code> is the input and <code>y</code> is the expected output. for this aim I used the following code:</p> <pre><code>import numpy as np from scipy.optimize import curve_fit def objective(x, a, b, c): return a * x + b * x**2 + c psnr_bitrate = np.vsta...
<p>I have to use <code>x[:,0]</code> instead of <code>x</code>, and for <code>y</code> is the same.</p>
python|python-3.x|numpy|curve-fitting
0
355,699
70,900,282
TypeError: new(): data must be a sequence (got numpy.float64)
<p>I do not know what to do with this problem. I am running a model training. The following part is what I got</p> <pre><code> mean_train = torch.Tensor(np.mean(train_vertices, axis=0)) TypeError: new(): data must be a sequence (got numpy.float64) </code></pre> <p>My code is:</p> <pre><code>mean_train = torch.Tenso...
<p>You have a <code>numpy</code> array and you want to create a pytorch tensor from it. You can use <code>torch.from_numpy</code> to achieve this. Note that <code>torch.from_numpy</code> expects an <code>np.ndarray</code> not a <code>np.float64</code> so you'll need to figure out your shapes.</p> <p>However, if you don...
python|pytorch
1