Unnamed: 0
int64
0
378k
id
int64
49.9k
73.8M
title
stringlengths
15
150
question
stringlengths
37
64.2k
answer
stringlengths
37
44.1k
tags
stringlengths
5
106
score
int64
-10
5.87k
3,400
73,446,860
Can tensorflow's tf.function be used with methods of dataclasses?
<p>Can methods of <code>dataclass</code>es be decorated with <code>@tf.function</code>? A straight-forward test</p> <pre><code>@dataclass class Doubler: @tf.function def double(a): return a*2 </code></pre> <p>gives an error</p> <pre><code>d = Doubler() d.double(2) </code></pre> <p>saying that <code>Doub...
<p>I think the official recommendation from Tensorflow is to use <code>tf.experimental.ExtensionType</code>:</p> <pre><code>import tensorflow as tf class Doubler(tf.experimental.ExtensionType): @tf.function def double(self, a): return a*2 d = Doubler() d.double(2) </code></pre> <p>According to the <a h...
python|tensorflow|python-dataclasses
2
3,401
67,341,689
How to convert all images in one folder to numpy files?
<p>I need to do Semantic image segmentation based on Unet.</p> <p>I have to work with Pascal VOC 2012 dataset, however I don't know how to do it, do I manually select images for the train &amp; val and convert them into numpy and then load them into the model? Or is there another way?</p> <p>If this is the first one I ...
<p>if i understood correctly, you just need to go through all the files from the folder and add them to the numpy table?</p> <pre><code>numpyArrays = [yourfunc(file_name) for file_name in listdir(mypath) if isfile(join(mypath, file_name))] </code></pre> <p>yourfunc is the function you need to write to convert one file ...
python|numpy
0
3,402
67,246,859
How to convert rows into columns and filter using the ID
<p>I have a CSV file that looks like this:</p> <pre><code>customer_id | key_id. | quantity | 1 | 777 | 3 | 1 | 888 | 2 | 1 | 999 | 3 | 2 | 777 | 6 | 2 | 888 | 1 | </code></pre> <p>and I would like ...
<p>You can pivot into <code>key_id</code> columns using <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pivot_table.html" rel="nofollow noreferrer"><strong><code>pivot_table()</code></strong></a>:</p> <pre class="lang-py prettyprint-override"><code>df.pivot_table(index='customer_id', columns='key...
python|python-3.x|pandas|dataframe|csv
2
3,403
60,200,831
Replace value one last valid item - Pandas
<p>I want to replace a value in a column based off another column in a <code>pandas</code> df. Specifically, where <code>col B == X</code>, I want to change the value in <code>col C</code>, but for the last <code>X</code> in a given sequence. I can change all respective <code>X's</code> in <code>C</code>. But I only wa...
<p>You can use <code>shift</code> along with <code>numpy.where</code></p> <pre><code>import numpy as np b1 = df["B"].shift(-1) df["C"] = np.where((df["B"]=="X") &amp; (b1!="X"), "str" , df["C"]) </code></pre> <p>Output:</p> <pre><code> A B C 0 1 X 1 1 1 X 1 2 1 X str 3 1 D 1 4 1 ...
python|pandas|dataframe
3
3,404
65,319,496
Days calculation in DataFrame in Python Pandas?
<p>I have DataFrame with clients' agreements like below:</p> <pre><code>rng = pd.date_range('2020-12-01', periods=5, freq='D') df = pd.DataFrame({ &quot;ID&quot; : [&quot;1&quot;, &quot;2&quot;, &quot;1&quot;, &quot;2&quot;, &quot;2&quot;], &quot;Date&quot;: rng}) </code></pre> <p>And I need to create new DataFrame wit...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.rsub.html" rel="nofollow noreferrer"><code>Series.rsub</code></a> for subtract from right side with today and convert timedeltas to days by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.days.htm...
python|pandas|dataframe|date
0
3,405
65,212,488
Mapping graph/relationship based values in a DataFrame in python
<p>I have an input DataFrame in the below format:</p> <pre><code>input_data = [[1000, 1002], [1002, 1003], [1004, 1000],[1010,1050],[1060,1002],[1050,1100],[1200,1250],[1300,1200]] input_df = pd.DataFrame(input_data, columns = ['Value1', 'Value2']) print(input_df) </code></pre> <p>Ignored the index for readability,</p...
<p>Use <a href="https://networkx.github.io/documentation/stable/reference/generated/networkx.convert_matrix.from_pandas_edgelist.html" rel="nofollow noreferrer"><code>convert_matrix.from_pandas_edgelist</code></a> with <a href="https://networkx.github.io/documentation/networkx-1.10/reference/generated/networkx.algorith...
python|python-3.x|pandas|dataframe
2
3,406
49,919,300
Tensorflow vs OpenCV
<p>I'm new into the AI world, I've start doing some stuff using Python &amp; OpenCV for face detection and so on. I know that with the implementation of some algorithms I can develop AI system using Python &amp; OpenCV. So my question is : What is the position of Tensorflow here? Can I say Tensorflow is an alternative ...
<p>The main difference is that TensorFlow is a framework for machine learning, and OpenCV is a library for computer vision. It can be a good start to check the link below to get a grasp for the difference between framework and library: <a href="https://stackoverflow.com/questions/148747/what-is-the-difference-between-a...
opencv|tensorflow|artificial-intelligence
67
3,407
50,069,340
Create new pandas column with same list as every row?
<p>I would like to create a new column in a dataframe that has a list at every row. I'm looking for something that will accomplish the following:</p> <pre><code>df = pd.DataFrame(data={'A': [1, 2, 3], 'B': ['x', 'y', 'z']}) list_=[1,2,3] df['new_col] = list_ A B new_col 0 1 x [1,2,3] 1 2 ...
<pre><code>df = pd.DataFrame(data={'A': [1, 2, 3], 'B': ['x', 'y', 'z']}) list_=[1,2,3] df['new_col'] = [list_]*len(df) </code></pre> <p>Output: </p> <pre><code> A B new_col 0 1 x [1, 2, 3] 1 2 y [1, 2, 3] 2 3 z [1, 2, 3] </code></pre> <p>Tip: <code>list</code> as a variable name is not advi...
python|list|pandas|dataframe
2
3,408
63,947,336
A question that involves permutations of pairs of row elements
<p>Consider two numpy arrays of integers. U has 2 columns and shows all (p,q) where p&lt;q. For this question, I'll restrict myself to 0&lt;=p,q&lt;=5. The cardinality of U is C(6,2) = 15.</p> <pre><code>U = [[0,1], [0,2], [0,3], [0,4], [0,5], [1,2], [1,3], [1,4], [1,5], ...
<p>To get rows of an array, without repetitions (in your sense), you can run:</p> <pre><code>VbyRows = V[np.lexsort(V[:, ::-1].T)] sorted_data = np.sort(VbyRows, axis=1) result = VbyRows[np.append([True], np.any(np.diff(sorted_data, axis=0), 1))] </code></pre> <p>Details:</p> <ul> <li><code>VbyRows = V[np.lexsort(V[:, ...
arrays|numpy
1
3,409
63,927,648
Can't iterate through PyTorch DataLoader
<p>I am trying to learn PyTorch and create my first neural network. I am using a custom dataset, here is a sample of the data:</p> <pre><code>ID_REF cg00001854 cg00270460 cg00293191 cg00585219 cg00702638 cg01434611 cg02370734 cg02644867 cg02879967 cg03036557 cg03123104 cg03670302 cg04146801 cg04570540 cg...
<p>Use <code>Numpy</code> array instead of <code>dataframe</code>. You can use <code>to_numpy()</code> to convert dataframe to numpy array.</p> <pre class="lang-py prettyprint-override"><code>train_dl = DataLoader(train_df.to_numpy(), bs, shuffle=True) test_dl = DataLoader(test_df.to_numpy(), len(test_df), shuffle=Fals...
python|pandas|deep-learning|iterator|pytorch
2
3,410
46,766,048
How does pandas argsort work? How do I interpret the result?
<p>I have the following pandas series:</p> <pre><code>&gt;&gt;&gt;ser num let 0 a 12 b 11 c 18 1 a 10 b 8 c 5 2 a 8 b 9 c 6 3 a 15 b 10 c 11 </code></pre> <p>When I use argsort, I get this:</p> <pre>...
<p>Per the documentation: <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.argsort.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.argsort.html</a></p> <p><code>pd.Series.argsort()</code> </p> <p>does the same job as <code>np.ndarray.ar...
python|pandas
3
3,411
62,995,703
Transform pd.DataFrame() to narrower, longer dataframe
<p>I have a pandas data frame in which each case contains multiple sets of interesting information. In short, I want the columns to decrease and the data frame to become longer according to pre-specified relationships.</p> <p>My old data frame looks like this:</p> <pre><code>old = pd.DataFrame(columns=['index', 'reside...
<p>You can first set the columns which remains single for each index as index , then split the column names to create a Multiindex and then use <code>stack</code>:</p> <pre><code>old_ = old.set_index(['index','residency','gen_rating']) old_.columns = old_.columns.str.split('_',expand=True) (old_.stack().reset_index(['...
python|pandas|dataframe
1
3,412
62,947,466
The gradient cannot be calculated automatically
<p>I am a beginner of Deep Learning and trying to making discriminator that judge cats/non-cats. <br> But When I run the code following, runtime error occured.</p> <p>I know that &quot;requires_grad&quot; must be set to True in order to calculate the gradient automatically, <br>but since X_train and Y_train are variabl...
<p>I believe your problem is that you are mixing numpy arrays and torch tensors. Pytorch tensors are a bit like numpy arrays, but they also kept in a computational graph that is responsible for the backward pass.</p> <p>The description of your received variables <code>X_train, Y_train, X_test, Y_test</code> says they a...
pytorch
0
3,413
62,899,856
groupby column in pandas
<p>I am trying to groupby columns value in pandas but I'm not getting.</p> <p>Example:</p> <pre><code>Col1 Col2 Col3 A 1 2 B 5 6 A 3 4 C 7 8 A 11 12 B 9 10 ----- result needed grouping by Col1 Col1 Col2 Col3 A ...
<p>Try this</p> <pre><code>( df .groupby('Col1') .agg(lambda x: ','.join(x.astype(str))) .reset_index() ) </code></pre> <p>it outputs</p> <pre><code> Col1 Col2 Col3 0 A 1,3,11 2,4,12 1 B 5,9 6,10 2 C 7 8 </code></pre>
python-3.x|pandas|pandas-groupby
1
3,414
63,088,861
How to transform survey pandas dataframe into a different format usable with BI tools in Python?
<p>I need to convert survey results into something that is usable in a BI tool like Tableau.</p> <p>The survey is in the format of the following dataframe</p> <pre><code>df = pd.DataFrame({'Respondent': ['Sally', 'Tony', 'Fred'], 'What project did you work on with - Chris?': ['Project A','Project B', np....
<pre><code>new_data = pd.DataFrame(columns = [&quot;Assessor&quot;, &quot;Project Name&quot;,&quot;NPS Score&quot;,&quot;Feedback&quot;, &quot;Name&quot;]) i = 1 while i &lt; (len(df.columns)): data = df.iloc[:,[0,i,i+1,i+2]] data[&quot;Name&quot;] = str(data.columns[-1].split(&quot; &quot;)[-1]) data.colum...
python|pandas|dataframe|transformation|unpivot
1
3,415
63,229,611
Learning rate setting when calling the function tff.learning.build_federated_averaging_process
<p>I'm carrying out a federated learning process and use the function tff.learning.build_federated_averaging_process to create an iterative process of federated learning. As mentioned in the TFF tutorial, this function has two arguments called client_optimizer_fn and server_optimizer_fn, which in my opinion, represen...
<p>In <a href="https://arxiv.org/abs/1602.05629" rel="nofollow noreferrer">McMahan et al., 2017</a>, the clients communicate the <em>model weights</em> after local training to the server, which are then averaged and re-broadcast for the next round. No server optimizer needed, the averaging step updates the global/serve...
tensorflow-federated
3
3,416
63,299,860
python, count unique list values of a list inside a data frame
<p>I have a dataframe which contains two columns of user feedback.</p> <p>The first column is from a multi-choice answer of the survey. In each row of the column is a list of the answers they selected.</p> <p>the next column is a category of age range. so one row will contain a list of the users colour preferences and ...
<p>Set the index of dataframe as <code>age</code>, then use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.explode.html" rel="nofollow noreferrer"><code>Series.explode</code></a> on column <code>what colours do you like?'</code> then use <code>groupby</code> on <code>level=0</code> an...
python|pandas|list|split|count
3
3,417
63,022,461
Pandas: Sort DataFrame Cells across columns if unordered
<p>Looks like my last question was closed, but I forgot to mention the update below the first time. Only modifying a few of the columns and not all.</p> <p>What is the best way to modify (sort) a Series of data in a Pandas DataFrame? For example, after importing some data, colums should be in ascending order, but I nee...
<p>The best way is to use the sort_values() function and only allow it work on the columns which require sorting.</p> <pre><code>for index, rows in df.iterrows(): df[['col1','col2','col3']] = df[['col1','col2','col3']].sort_values(by=[index], axis = 1, ascending = True) </code></pre> <p>This loops through every ro...
python|pandas|dataframe
2
3,418
67,894,649
ValueError with NERDA model import
<p>I'm trying to import the NERDA library in order use it to engage in a Named-Entity Recognition task in Python. I initially tried importing the library in a jupyter notebook and got the following error:</p> <pre><code>Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; Fil...
<p>Take a look at the <a href="https://github.com/huggingface/huggingface_hub/blob/59ea9998ee2331acf1c50a9fe2f93e5606c5fefb/src/huggingface_hub/file_download.py#L35-L37" rel="nofollow noreferrer">source code of the used huggingface_hub lib</a>. They comparing the version of your python version to do different imports.<...
python|huggingface-transformers|named-entity-recognition
1
3,419
61,263,787
Folium FeatureGroup in Python
<p>I am trying to create maps using Folium Feature group. The feature group will be from a pandas dataframe row. I am able to achieve this when there is one data in the dataframe. But when there are more than 1 in the dataframe, and loop through it in the for loop I am not able to acheive what I want. Please find attac...
<p>This is an example dataset because I didn't want to format your df. That said, I think you'll get the idea.</p> <pre><code>print(df_addresses) Latitude Longitude Group 0 34.962637 -90.069019 B 1 34.962637 -90.069019 B 2 35.035367 -89.898428 A 3 35.165115 -89.952624 B 4 35.821835 -90.70503...
python|pandas|folium
10
3,420
61,242,103
every time when I train the model I receive a different result - why?
<ul> <li>I don't understand what I do wrong - every time when I launch this code I receive a <a href="https://drive.google.com/drive/folders/1iSOJ3ZE5OAY6Lqg1Qz-jpXhaGaZdU040?usp=sharing" rel="nofollow noreferrer">different result</a>. </li> <li>I figured out that the result will be different when I change the batch si...
<p>In the <a href="https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit" rel="nofollow noreferrer">fit</a> function there is a parameter called <code>shuffle</code>:</p> <blockquote> <p>Boolean (whether to shuffle the training data before each epoch) or str (for 'batch'). 'batch' is a special option for dea...
tensorflow|tensorflow2.0
0
3,421
61,321,028
operate only on filtered elements in an array in python
<p>Consider this simple problem: in a list of integers I need multiply all even number by 10. I can certainly do element-wise operation such as:</p> <pre><code>[if x%2==0: x=x*10 for x in arr] </code></pre> <p>But what if I the operation has to be operated on the array level? The trouble I am having is after the ope...
<pre><code>&gt;&gt;&gt; a = np.arange(10) &gt;&gt;&gt; a array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) &gt;&gt;&gt; a[a%2 == 0] *= 10 &gt;&gt;&gt; a array([ 0, 1, 20, 3, 40, 5, 60, 7, 80, 9]) </code></pre>
python|arrays|numpy|if-statement
1
3,422
61,325,958
scaler.inverse_transform() is giving an error while taking LSTM NN predictions into real data values
<p>I have converted my data between 0 and 1 and fed it via LSTM NN .The results also stay between 0 and 1 and to have the proper output i need to convert it back to as it was same with my original data values.</p> <p>But</p> <pre><code>scaler=MinMaxScaler(feature_range=(0,1)) scaler.inverse_transform(result) </code>...
<p>It is just what the error is saying. when using scikit-learn modules, they usually have a fit(), transform(), or in case of classifiers also predict() methods. after making an instance of a Class like MinMaxScaler() in your case, you need to fit it on some data, just call its fit method and pass your training exampl...
python|tensorflow|machine-learning|keras|lstm
0
3,423
61,348,293
Python Retain function. Use value from previous row in calculation
<pre><code>In [10]: df Out[10]: PART AVAILABLE_INVENTORY DEMAND 1 A 12 6 2 A 12 2 3 A 12 1 4 B 24 1 5 B 24 1 6 B 24 4 7 B 24 3 </code></pre> <p>Output wa...
<p>you can do it with <code>groupby</code> with <code>cumsum</code> on the column 'DEMAND' and <code>shift</code> on the column 'AI_AFTER' just created before:</p> <pre><code>df['AI_AFTER'] = df['AVAILABLE_INVENTORY'] - df.groupby('PART')['DEMAND'].cumsum() df['AI'] = df.groupby('PART')['AI_AFTER'].shift().fillna(df['...
python|pandas|retain
1
3,424
68,543,621
How to flat in one row Dataframe and concatenate them
<p>I have several Dataframes with the same structure :</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>0</th> <th>1</th> </tr> </thead> <tbody> <tr> <td><strong>0</strong></td> <td>TITLE</td> <td>TITLE1</td> </tr> <tr> <td><strong>1</strong></td> <td>A</td> <td>A1</td> </tr> <tr> ...
<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 transpose and then <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat<...
python|python-3.x|pandas|dataframe
1
3,425
68,796,689
How to get values return by Tuple Object in Maskcrnn libtorch
<p>I’m new in C++ and libtorch, I try load model by torchscript and execute inference, the codes like below:</p> <pre class="lang-cpp prettyprint-override"><code> torch::jit::script::Module module; try { module = torch::jit::load(&quot;../../weights/card_extraction/pytorch/2104131340/best_model_27_mAP=0.998...
<p>You can get access to the element like here: I can parse Tuple arguments and get access to it like in Tensor format. It can help u.<br></p> <pre><code>auto output1_t = output.toTuple()-&gt;elements()[0].toTensor(); auto output2_t = output.toTuple()-&gt;elements()[1].toTensor(); </code></pre> <p><a href="https://disc...
c++|pytorch|libtorch|torchscript
2
3,426
68,500,441
Groupby() and bfill() with condition
<p>I had DataFrame with ID, Tenure, and several variables:</p> <pre><code> ID Tenure var1 var2 A 1 NaN NaN A 2 NaN 30 A 3 40 50 A 4 NaN 60 B 1 NaN NaN B 2 NaN NaN B ...
<p>Try use <code>loc</code> assign</p> <pre><code>df.loc[df['Tenure']&lt;3 ,['var1','var2']] = df[['ID','var1','var2']].groupby('ID').bfill() df Out[146]: ID Tenure var1 var2 0 A 1 40.0 30.0 1 A 2 40.0 30.0 2 A 3 40.0 50.0 3 A 4 NaN 60.0 4 B 1 40.0 50.0 5 B 2 ...
python|pandas
1
3,427
68,696,629
Resampling in pandas to split a datetime series into "n" minute buckets & counts for each
<p>I want to break down a list of datetimes into 15 (or 10 or 30 maybe) minute buckets, and count how many objects are in each bucket.</p> <p>The ideal output is a list of integers, each item being a count for a 15 minute bucket, the list in the original datetime order from earliest to latest</p> <p>The actual dates an...
<p>You almost had it, but<code>sum</code> will concatenate the strings. You need to <code>count</code> instead:</p> <pre><code>qbert = dfs[&quot;created_at&quot;].resample(&quot;15T&quot;).count() </code></pre>
python|pandas|datetime
3
3,428
68,523,007
How to use mobilenet as feature-extractor for high resolution images?
<p>How can i use a mobilenet model as a feature-extractor for images with way higher resolution than 224x224? I guess i need to change a certain layer after it's loaded to increase the input size? My current code is this:</p> <pre><code>const featureExtractor = await tf.loadGraphModel('http://localhost:3000/mobilenet_v...
<p>MobileNet v2 technically starts with a fully convolutional layer with 32 filters. So, yes you can train the model with larger images, however you'd be starting from scratch. The feature-extracted models that seem to be available are mostly trained on datasets of 224x224.</p> <p>If you believe this will remove impo...
machine-learning|tensorflow.js|mobilenet|tfjs-node
2
3,429
52,968,814
Fanccy Indexing vs View in Numpy part II
<p><a href="https://stackoverflow.com/questions/52967957/fancy-indexing-vs-views-in-numpy">Fancy Indexing vs Views in Numpy</a></p> <p>In an answer to this equation: is is explained that different idioms will produce different results. </p> <p>Using the idiom where fancy indexing is to chose the values and said value...
<p>Python evaluates each set of [] separately. <code>a[x, :][:, y] = 100</code> is 2 operations.</p> <pre><code>temp = a[x,:] # getitem step temp[:,y] = 100 # setitem step </code></pre> <p>Whether the 2nd line ends up modifying <code>a</code> depends on whether <code>temp</code> is a view or copy.<...
python|numpy
1
3,430
53,245,243
Count occurences in pandas column database and bar plot with matplotlib
<p>So I have a pandas database with 4 columns.</p> <p>Date A B C.</p> <p>The dates contain all daily dates from year 2018, 2019 and 2020.</p> <p>These columns A B C contains numbers from 1 to 7. No decimals. I want to count each of this number occurences and stack them into a bar plot. Count all 1's, 2's, 3's ect.</...
<p>Using <code>melt</code> with <code>value_counts</code></p> <pre><code>df.melt('Date').value.value_counts().plot(kind='bar') </code></pre>
pandas|matplotlib
0
3,431
53,136,542
What is the numpy way to conditionally merge arrays?
<p>I have two numpy arrays <code>(1000,)</code> filled with predictions from two models:</p> <pre><code>pred_1 = model_1.predict(x_test) pred_2 = model_2.predict(x_test) </code></pre> <p><code>model_1</code> is attractive due to extremely low <code>FP</code>, but consequently high <code>FN</code>.</p> <p><code>model...
<p>You're looking for <a href="https://www.numpy.org/devdocs/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a>:</p> <pre><code>a = model_1.predict(x_test) b = model_2.predict(x_test) out = np.where(a &gt; 0.5, a, b) </code></pre>
python|numpy|text-classification
3
3,432
65,608,713
Tensorflow GPU Could not load dynamic library 'cusolver64_10.dll'; dlerror: cusolver64_10.dll not found
<p>When i run</p> <pre><code>import tensorflow as tf tf.test.is_gpu_available( cuda_only=False, min_cuda_compute_capability=None ) </code></pre> <p>I get the following error</p> <p><a href="https://i.stack.imgur.com/Mv2p5.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Mv2p5.jpg" alt="enter image descrip...
<strong>Step 1</strong> <pre><code> Move to C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.2\bin </code></pre> <strong>Step 2</strong> <pre><code>Rename file cusolver64_11.dll To cusolver64_10.dll </code></pre> <p><a href="https://i.stack.imgur.com/3xHxB.jpg" rel="noreferrer"><img src="https://i.stack.imgur....
python|tensorflow|gpu
98
3,433
65,845,222
When using the Deepbrain libary error message "module 'tensorflow' has no attribute 'Session"
<p>I am trying to use the library Deepbrain to extract brains from the entire MRIs scan I am using the code</p> <pre><code>def Reduce_Brain(img): img_data = img.get_fdata() prob = ext.run(img) print(prob) img = nib.load('ADNI_002_S_0295.nii') Reduce_Brain(img) </code></pre> <p>however, when I tried this...
<p>In TF 2.x you should use <code>tf.compat.v1.Session()</code> instead of <code>tf.Session()</code>. Take a look at <a href="https://www.tensorflow.org/guide/migrate/migrate_tf2" rel="nofollow noreferrer">Migrate_tf2 guide</a> for more information</p> <p>To get TF 1.x like behaviour in TF 2.0 add below code</p> <pre><...
python|tensorflow
0
3,434
63,327,569
Only select year from date
<p>My dataframe look like this:</p> <pre><code> mth account_type interest_rate 1057 1977-01-01 Special 6.5 1061 1977-02-01 Special 6.5 1065 1977-03-01 Special 6.5 1069 1977-04-01 Special 6.5 1073 1977-05-01 Special 6.5 ... ......
<p>If your column <code>mth</code> is already <code>datetime</code>:</p> <pre><code>df['mth'] = df['mth'].dt.year </code></pre> <p>If it is a <code>string</code> you have to first convert to <code>datetime</code>:</p> <pre><code>df['mth'] = pd.to_datetime(df['mth']) </code></pre>
pandas|datetime|time-series
1
3,435
63,331,532
tensor elements assignment in tensorflow
<p>I'm trying to create a for loop function as part of a convolutional neural network code to modify a variable if this variable is in a certain location of a 60 by 60 image. how can I do this in Tensorflow/Keras?</p> <p>I always get this error: TypeError: 'Tensor' object does not support item assignment</p> <pre><code...
<p>TensorFlow does not support item assignment for now... Try numpy first, then convert it to tf.float32.</p>
tensorflow|keras|conv-neural-network
0
3,436
71,850,728
Realtime JSON data to panda dataframe
<p>I have been trying to normalize my JSON file which I retrieved from Firebase Realtime Database, and turn it into a python panda data-frame but I keep getting everything as a row.</p> <p>my JSON file is structured as following:</p> <pre><code>{ “Device 1” { “ID-1”{ “key”: value “t...
<p>Here's how I would do it. Since each Device is a table, I'll split them into individual dataframes. We can always unite them later if need be.</p> <p>I'll suppose you have your JSON data in a dict called <code>devices</code></p> <pre><code>import pandas as pd dataframes = [] for device, id_data in devices.items(): ...
python|json|pandas
0
3,437
72,075,933
finding a row in pandas through input
<p>I made a small script that iterates over a certain column through a given name and prints all its rows</p> <p>I would like to make it search through its rows through a user input but not have to give it its full name.. last 3 letters would be sufficient for it.</p> <p><a href="https://i.stack.imgur.com/Hb5Kp.png" re...
<p>Use <code>str</code> accessor:</p> <pre><code>import re file = &quot;path&quot; df = pd.read_excel(f&quot;{file}&quot;, &quot;DDR5 UDIMM&quot;) ... # set_option # memory &lt;- 67U memory = re.escape(input(&quot;enter a number : &quot;)) if df['IDC S/N'].str[-3:] == memory print('true') else: print('false')...
python|pandas
0
3,438
56,630,896
How to benchmark USB Accelerator coral beta by google?
<p>I want to benchmark the USB Accelerator coral beta by google with use the function time.time() of Python.</p> <p>I started by install Edge TPU runtime library. I found the procedure on <a href="https://coral.withgoogle.com/docs/accelerator/get-started/" rel="nofollow noreferrer">Google</a>.</p> <p>Then, I followed...
<p>There are two problems. First, to get "correct" benchmark numbers, you have to run several times (rather than just one). Why? Usually, it takes some extra time to prepare the running environment and there might be variance between runs. Second, the <code>engine.ClassifyWithImage</code> includes image processing time...
tensorflow-lite|google-coral
1
3,439
56,809,095
Implementing 2D max subarray function as custom loss function in Keras
<p>I'm trying to implement a custom loss function in Keras (Tensorflow backend). </p> <p>My aim is to create a loss function takes y_pred of size (150, 200, 1) (i.e. image of 150x200 with 1 channel), take the difference between it and a corresponding tensor y_true, then scan the resulting "difference" array for subarr...
<p>A simple convolution of 1 filter with all-ones followed by a maxpooling would do it. </p> <pre><code>subArrayX = 3 subArrayY = 3 inputChannels = 1 outputChannels = 1 convFilter = K.ones((subArrayX, subArrayY, inputChannels, outputChannels)) def local_loss(true, pred): diff = K.abs(true-pred) #you might also t...
python|arrays|tensorflow|keras|cython
0
3,440
56,659,143
How to use pd.DataFrame method to manually create a dataframe from info scraped using beautifulsoup4
<p>I made it to the point where all <code>tr</code> data data has been scraped and I am able to get a nice printout. But when I go to implement the <code>pd.DataFrame</code> as in <code>df= pd.DataFrame({"A": a})</code> etc, I get a syntax error</p> <p>Here is a list of my imported libraries in the Jupyter Notebook:</...
<p>If you want to create manually, with bs4 4.7.1 you can use <code>:not</code>, <code>:contains</code> and <code>:nth-of-type</code> pseudo classes to isolate the two columns of interest, then construct a dict then convert to df</p> <pre><code>import pandas as pd import urllib from bs4 import BeautifulSoup as bs sou...
pandas|web-scraping|beautifulsoup
0
3,441
56,631,871
How to compare list items to a pandas DataFrame value
<p>I want a method to match a whole value of the loaded_list DataFrame with an item from the domain_list. If an email in loaded_list contains a domain in domain_list then it should be populated in match_list.</p> <p>I have tried many methods such as contains(domain_list), loaded_list == domain_list - with [row] and Da...
<p>Did you try generating a regex with your domain_list by concatening the values separated by "|" then filter loaded_list using this generated pattern ?</p> <p>Example:</p> <pre><code>In[1]: loaded_list=pd.Series([ "abc@gmail.com", "def@blaa.com", "ghi@hotmail.co.uk", "jkl@hotmail.com", "mnop@yah...
python-3.x|pandas
1
3,442
56,737,541
Get row data from a pandas dataframe as a list
<p>I want to get row data as a list in a pandas dataframe. I can get the data in the correct order(column order) in jupiter notebook but when i run the code as a python file in ubuntu terminal the list is not in order.infact it seemes the list is in assending order.</p> <p>this is the data frame</p> <pre><code>Src_ma...
<p>If you are using <code>pandas</code> you can consider to use</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np df = pd.DataFrame(np.arange(9).reshape(3,3)) df.values.tolist() </code></pre> <p>This returns</p> <pre class="lang-py prettyprint-override"><code>[[0, 1, 2], [...
python|pandas|list|dataframe
2
3,443
66,857,825
Counting rows in df against string
<p>I have a df with a feature that contains some pattern of +/- for the prior N days. For each row in the df, I'm trying to count the number of times that given pattern appears in a string (and add this count as a new column in df)</p> <p>For example</p> <pre><code>d = {'day': [1, 2, 3], 'pattern': ['++-', '+++', '-+-'...
<p>You can use <a href="https://docs.python.org/3/library/stdtypes.html#str.count" rel="nofollow noreferrer"><code>str.count</code></a> along with pandas' <code>apply</code></p> <pre><code>&gt;&gt;df['pattern'].apply(s.count) 0 3 1 1 2 1 Name: pattern, dtype: int64 </code></pre>
python|pandas|count
3
3,444
66,993,186
Split a string with , and split a string even no , present in a dataframe column
<p>I have a dataframe column and i need to split a column with &quot;,&quot; and even if no &quot;,&quot; present in the value.</p> <pre><code>Value ===== 59.5 59.5, 5 60 60,5 </code></pre> <p>desired output</p> <pre><code>value1 value2 ====== ====== 59.5 59.5 5 60 60 5 </code></pre> <p>Tr...
<p>You could search for &quot;,&quot; first and only do the split if str contains &quot;,&quot;.</p>
python|pandas
0
3,445
68,159,503
using f1 score sklearn in pytorch ignite custom metric
<p>I would like to use the f1_score of sklearn in a custom metric of PyTorch-ignite.<br /> I couldn't find a good solution. although on the official website of PyTorch-ignite, there is a solution of</p> <pre><code> precision = Precision(average=False) recall = Recall(average=False) F1 = Fbeta(beta=1.0, avera...
<p>The solution is first create a custom metric:</p> <pre class="lang-py prettyprint-override"><code>import torch from ignite.metrics import Metric from sklearn.metrics import f1_score class F1Score(Metric): def __init__(self, *args, **kwargs): self.f1 = 0 self.count = 0 super().__init__(...
python|scikit-learn|deep-learning|pytorch|pytorch-ignite
0
3,446
68,106,870
From a pandas DataFrame, how can I create copy-and-pasteable text that will re-create the same DataFrame, including the index?
<h3>Motivation:</h3> <p>I have a CSV with some data, which is then loaded into a pandas DataFrame <code>raw_data</code>. While unit testing I want to do some aggregation or other process on <code>raw_data</code>, to create a new DataFrame, <code>df</code>, and then confirm that the results (i.e. <code>df</code>) are wh...
<p>I had a typo in my original code, which obscured the fact that <code>to_json(orient='table')</code> works:</p> <pre class="lang-py prettyprint-override"><code>ser_de_df = pd.read_json(df.to_json(orient='table'), orient='table') </code></pre> <p>This preserves both the index labels and the names.</p> <p>For a Python ...
python|pandas|dataframe
1
3,447
68,384,132
BERT: AttributeError: 'RobertaForMaskedLM' object has no attribute 'bert'
<p>I am trying to freeze some layers of my masked language model using the following code:</p> <pre><code>for param in model.bert.parameters(): param.requires_grad = False </code></pre> <p>However, when I execute the code above, I get this error:</p> <pre><code>AttributeError: 'RobertaForMaskedLM' object has no att...
<p>If you look at the source code of <code>RobertaForMaskedLM</code> code <a href="https://huggingface.co/transformers/_modules/transformers/models/roberta/modeling_roberta.html#RobertaForMaskedLM" rel="nofollow noreferrer">here</a>, you can observe that there is no object with the name <code>bert</code>. Instead, they...
python|bert-language-model|huggingface-transformers|huggingface-tokenizers
0
3,448
45,836,553
Pandas MultiIndex: Selecting a column knowing only the second index?
<p>I'm working with the following DataFrame:</p> <pre><code> age height weight shoe_size 0 8.0 6.0 2.0 1.0 1 8.0 NaN 2.0 1.0 2 6.0 1.0 4.0 NaN 3 5.0 1.0 NaN 0.0 4 5.0 NaN 1.0 NaN 5 3.0 0.0 1.0 0.0 </code></pre> <p>I a...
<p>You could use <code>get_level_values</code></p> <pre><code>In [700]: df.loc[:, df.columns.get_level_values(1) == 'RHS'] Out[700]: age RHS 0 8.0 1 8.0 2 6.0 3 5.0 4 5.0 5 3.0 </code></pre>
python|pandas|dataframe|multi-index
2
3,449
50,906,831
GroupBy aggregate count based on specific column
<p>I've been looking for a few hours and can't seem to find a topic related to that exact matter.</p> <p>So basically, I want to apply on a groupby to find something else than the mean. My groupby returns two columns 'feature_name' and 'target_name', and I want to replace the value in 'target_name' by something else :...
<pre><code>import pandas as pd import numpy as np def my_func(x): # Create your 3 metrics here calc1 = x.min() calc2 = x.max() calc3 = x.sum() # return a pandas series return pd.Series(dict(metric1=calc1, metric2=calc2, metric3=calc3)) # Apply the function you created df.groupby(...)['colum...
python|pandas
1
3,450
66,434,570
Numpy's "shape" function returns a 1D value for a 2D array
<p>so I have created this array as an example:</p> <pre><code>a = np.array([[1, 1, 1, 1, 2], [2, 2, 2, 3], [3, 3, 3, 4], [13, 49, 13, 49], [10, 10, 2, 2], [11, 1, 1, 1, 2], [22, 2, 2, 3], [33, 3, 3, 4], [133, 49, 13, 49], [100, 10, 2, 2], [5, 1, 1, 1, 2], [32, 2, 2, 3], [322, 3, 3, 4], [13222,...
<h3>Tl;dr. Your individual lists are of variable length thus forcing your NumPy array to be a 1D array of list objects rather than a 2D array of integers/floats</h3> <p>Numpy arrays can only be defined when each axis has the same number of elements. Otherwise, you are left with an 1D array of objects.</p> <p><a href="h...
python|arrays|python-3.x|numpy|multidimensional-array
5
3,451
66,712,176
Round off list values in Pandas column
<pre><code> column1 column2 0 name1 [(0, 0.12561743), (1, 0.12500079), (2, 0.1250000)] 1 name2 [(0, 0.1251732), (1, 0.12597172), (2, 0.623854998)] </code></pre> <p>How can I round off the values in column2 in 3 decimal places like this:</p> <pre><c...
<p>You need to loop twice:</p> <pre><code># don't use .column2 to assign df['column2'] = df.column2.apply(lambda x: [tuple(round(z, 3) for z in y) for y in x]) </code></pre> <p>Output:</p> <pre><code> column1 column2 0 name1 [(0, 0.126), (1, 0.125), (2, 0.125)] 1 name2 [(0, 0.125),...
python|pandas
2
3,452
57,716,363
Explicit broadcasting of variable batch-size tensor
<p>I'm trying to implement a custom Keras <code>Layer</code> in Tensorflow 2.0RC and need to concatenate a <code>[None, Q]</code> shaped tensor onto a <code>[None, H, W, D]</code> shaped tensor to produce a <code>[None, H, W, D + Q]</code> shaped tensor. It is assumed that the two input tensors have the same batch size...
<p>You need to use the dynamic shape of <code>y</code> to determine the batch size. The dynamic shape of a tensor <code>y</code> is given by <code>tf.shape(y)</code> and is a tensor op representing the shape of <code>y</code> evaluated at runtime. The modified example demonstrates this by selecting between the old shap...
python|keras|tensorflow2.0|tf.keras
4
3,453
73,136,069
Check if values in each first coulmn in df startswith ! using pandas
<pre><code>types={} for col in df.columns[0]: if df[col].dtype == object: print('Check values inside column') if '!' in df[col].values : print(&quot;\nThis value exists in Dataframe&quot;) </code></pre> <p>I have a couple of the data frames. I need to check two thigs:</p> <ul> <l...
<p>This should do the trick:</p> <pre class="lang-py prettyprint-override"><code>df.iloc[:, 0].astype(str).str.startswith('!').any() </code></pre> <p>This assumes that the other possible dtypes do not result in a string representation that starts with a <code>!</code>, which should work in the vast majority of applicat...
python|pandas
1
3,454
70,432,235
Pandas None series has 0
<p>I want to generate a pandas series with null values, with int type. I use this:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd pd.Series(None, index=[1, 2, 3], dtype=int) </code></pre> <p>And it returns</p> <pre class="lang-py prettyprint-override"><code>1 0 2 0 3 0 dtype: int64 </c...
<p>Use <code>Int64</code> for <a href="https://pandas.pydata.org/docs/user_guide/integer_na.html" rel="nofollow noreferrer"><code>nullable integer type</code></a>:</p> <pre><code>s = pd.Series(None, index=[1, 2, 3], dtype='Int64') print (s) 1 &lt;NA&gt; 2 &lt;NA&gt; 3 &lt;NA&gt; dtype: Int64 </code></pre> <hr ...
python|pandas
3
3,455
51,256,360
How to take remote data access (from stock market) and combine them into a single dataframe?
<p>I tried grabbing data from morningstar and combining different stock, but I can't figure out how to combine the data properly. I want to organize it by Date, but it just stacks the data on top of each other.</p> <pre><code>print('test') print('testing') #this program will read data from morningstar and interpret th...
<p>You can add <code>reset_index</code> at the end when you create your new dataframe</p> <pre><code>stocks = pd.DataFrame({"MSFT": microsoft["Volume"].reset_index(level=0,drop=True), "AAPL": apple["Volume"].reset_index(level=0,drop=True), "GOOG": google["Volume"].reset_index(level...
python|pandas|dataframe|matplotlib|join
0
3,456
71,037,820
Can't install scikit-learn on mac
<p>I am trying to install scikit-learn and scipy packages in Python. I've already installed NumPy and Pandas successfully. Then I used following command:</p> <pre><code>pip install scikit-learn </code></pre> <p>and I received following error:</p> <pre><code>File &quot;/private/tmp/pip-build-env-w7wmv28v/overlay/lib/pyt...
<p>Have you tried this?:</p> <pre><code>pip install sklearn </code></pre>
python|numpy|scikit-learn|pip
0
3,457
70,990,504
Replace values in column based on same or closer values from another columns pandas
<p>I have two dataframes look like:</p> <p>DF1:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Score 1</th> <th>Avg_life</th> </tr> </thead> <tbody> <tr> <td>4.033986</td> <td>3482.0</td> </tr> <tr> <td>9.103820</td> <td>758.0</td> </tr> <tr> <td>-1.34432</td> <td>68000.0</td> </tr> <tr> <...
<p>First we find the value if <code>df1['Score1']</code> that is the closest to each value in <code>df2['Score1']</code>, and put it into <code>df2['match']</code>:</p> <pre><code>df2['match'] = df2['Score1'].apply(lambda s : min(df1['Score1'].values, key = lambda x: abs(x-s))) </code></pre> <p><code>df2</code> now loo...
python|python-3.x|pandas|dataframe|numpy
4
3,458
35,962,462
ploting 3D surface using array
<pre><code>Z=np.array([[10.,12.,12.,5.], [10.,0.,0.,5.], [10.,0.,0.,5.], [10.,20.,20.,20.]]) X = np.arange(0, 4, 1) Y = np.arange(0, 4, 1) </code></pre> <p>I have a 2D 4x4 array with. I want to make a 3D plot with x and y axes having discrete integer values from 0 to 4. Can someone help me with...
<p>you first need to make 2D arrays of your X,Y vectors:</p> <pre><code>import numpy as np X2D,Y2D = np.meshgrid(X,Y) </code></pre> <p>then you can use a surface plot (or wireframe):</p> <pre><code>from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = Axes3D(fig) ax.p...
python|numpy|matplotlib|mplot3d
0
3,459
41,968,714
Eliminate one of the columns from pivot_table for changing the grouping logic
<p>I have this <code>dataframe</code>:</p> <pre><code>df = GROUP HOUR TOTAL_SERVICE_TIME TOTAL_WAIT_TIME IS_EVALUATED IS_NEGATIVE_GRADE AAA 7 24 32 0 0 AAA 7 23 30 1 0 AAA 8 25 31 ...
<p>Without <code>columns='Hour'</code>, you no longer need to <code>stack</code></p> <pre><code>piv_df = df.pivot_table(index='GROUP', fill_value=0) avg_tot = piv_df[['TOTAL_SERVICE_TIME', 'TOTAL_WAIT_TIME']].add_prefix("AVG_") avg_pct1 = piv_df['IS_EVALUATED'].mul(100).astype(int) avg_pct2 = piv_df['IS_NEGATIVE_GRADE...
python|python-2.7|pandas
3
3,460
41,736,954
convolution of .mat file and 1D array
<p>my code is:</p> <pre><code>import numpy as np import scipy.io as spio x=np.zeros((22113,1),float) x= spio.loadmat('C:\\Users\\dell\\Desktop\\Rabia Ahmad spring 2016\\' 'FYP\\1. Matlab Work\\record work\\kk.mat') print(x) x = np.reshape(len(x),1); h = np.array([0.9,0.3,0.1],float) print(h) h =...
<pre><code>{'__globals__': [], '__version__': '1.0', 'ans': array([[ 0.13580322, 0.13580322], [ 0.13638306, 0.13638306], [ 0.13345337, 0.13345337], ..., [ 0.13638306, 0.13638306], [ 0.13345337, 0.13345337], ..., [ 0.13638306, 0.13638306], [ 0.13345337, 0.13345337], ..., [-0.09136963, -0.09136963], [-0.124420...
python|python-3.x|numpy
1
3,461
41,723,419
Why can itertools.groupby group the NaNs in lists but not in numpy arrays
<p>I'm having a difficult time to debug a problem in which the float <code>nan</code> in a <code>list</code> and <code>nan</code> in a <code>numpy.array</code> are handled differently when these are used in <code>itertools.groupby</code>:</p> <p>Given the following list and array:</p> <pre><code>from itertools import...
<p>Python lists are just arrays of pointers to objects in memory. In particular <code>lst</code> holds pointers to the object <code>np.nan</code>:</p> <pre><code>&gt;&gt;&gt; [id(x) for x in lst] [139832272211880, # nan 139832272211880, # nan 139832272211880, # nan 139832133974296, 139832270325408, 13983213397429...
python|arrays|list|numpy|nan
9
3,462
37,887,796
pandas DataFrame add fill_value NotImplementedError
<p>I have:</p> <pre><code>import pandas as pd import numpy as np np.random.seed([3,1415]) df = pd.DataFrame(np.random.choice((1, 2, np.nan), (5, 5))) s = pd.Series(range(5)) </code></pre> <p>I want to add <code>s</code> to <code>df</code> and broadcast across rows. Usually I'd:</p> <pre><code>df.add(s) </code></pr...
<p>I ran into this issue also. In my case it's because I was adding a series to a dataframe. </p> <p>The <code>fill_value=0</code> instruction works for me when adding a series to a series or adding a dataframe to a dataframe. </p> <p>I just made a new dataframe with the series as its only column and now I can add th...
python|pandas
3
3,463
64,239,738
TensorFlow Lite does not recognize op VarHandleOp
<p>I am attempting to convert a TF model to TFLite. The model was saved in <code>.pb</code> format and I have converted it with the following code:</p> <pre><code>import os import tensorflow as tf from tensorflow.core.protobuf import meta_graph_pb2 export_dir = os.path.join('export_dir', '0') if not os.path.exists('e...
<p>It's certainly hard to provide a minimal reproducible example in the case of model conversion, as the SO guidelines recommend, but the questions would benefit from better pointers. For example, instead of saying “I took this function from a tutorial on the TF website”, it is a much better idea to provide a link to t...
python|tensorflow|tensorflow2.0|tensorflow-lite
1
3,464
64,223,955
Selecting top results from the Sparse csr matrix in Python
<p>I am working on sparse.csr.csr_matrix of size (4860x89462 sparse matrix of type '&lt;class 'numpy.float64'&gt;'with 9111761 stored elements) and using jupyter notebook 3.7.4</p> <p>My requirement is to extract the top 2 results based on the Value of the elements in sparse matrix.</p> <p>I am sharing one example of m...
<pre><code>top_n = 2 out = [] for r in arr: if r.data.size &lt;= top_n: out.append(r) else: top_hits = np.argsort(r.data)[-1 * top_n:] out.append(sparse.csr_matrix((r.data[top_hits], r.indices[top_hits], np.array([0,len(top_hits)])), shape=(1, arr.shape[1]))) out = sparse.vstac...
python|numpy|scipy|sparse-matrix
0
3,465
64,365,215
Finding means and stds of a bunch of torch.Tensors (that are converted from ndarray images)
<pre><code>to_tensor = transforms.ToTensor() img = to_tensor(train_dataset[0]['image']) img </code></pre> <p>Converts my images values between 0 and 1 which is expected. It also converts <code>img</code> which is an <code>ndarray</code> to a <code>torch.Tensor</code>.</p> <p>Previously, without using <code>to_tensor</...
<p>Here is a working example:</p> <pre><code>import torch from torchvision import transforms train_dataset = torch.rand(100, 32, 32, 3) image_arr = [] to_tensor = transforms.ToTensor() for i in range(len(train_dataset)): # to tensor will give you a tensor which is emulated here by reading the tensor at i image...
python|numpy|pytorch|mean|numpy-ndarray
2
3,466
64,321,976
Why the exactly identical keras model predict different results for the same input data in the same env
<p>I have two models that proven to be identical as following:</p> <pre><code>if len(m_s.layers) != len(m_m.layers): print(&quot;number of layers are different&quot;) for i in range(len(m_s.layers)): weight_s = m_s.layers[i].get_weights() weight_m = m_m.layers[i].get_weights() if len(weight_s) &gt...
<p>I found out the reason by extracting layer by layer. There are BatchNormalizing layers in the model and weight changed although I set them as not trainable.</p>
tensorflow|keras|imagenet
0
3,467
64,581,993
I have an error on Pytorch and in particular with nllloss
<p>I want to appply the criterion, where <code>criterion = nn.NLLLoss()</code> I apply it on output and labels</p> <pre><code>loss = criterion(output.view(-1,1), labels.long()) </code></pre> <p>where:</p> <p>*the shape of the labels</p> <pre><code>labels tensor([ 1, 4, 1, 1, 4, 1, 2, 3, 2, 4, 2, 3, 3, 4, ...
<p>Your label and output shapes must be <code>[batch_size]</code> and <code>[batch_size, n_classes]</code> respectively.</p>
pytorch
1
3,468
47,952,930
How can I use LSTM in pytorch for classification?
<p>My code is as below:</p> <pre><code>class Mymodel(nn.Module): def __init__(self, input_size, hidden_size, output_size, num_layers, batch_size): super(Discriminator, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.output_size = output_size ...
<h2>Theory:</h2> <p>Recall that an LSTM outputs a vector for every input in the series. You are using sentences, which are a series of words (probably converted to indices and then embedded as vectors). This code from the LSTM <a href="http://pytorch.org/tutorials/beginner/nlp/sequence_models_tutorial.html#lstm-s-in-p...
pytorch
8
3,469
49,161,202
Pandas: aggregate column based on values in a different column
<p>Lets say I start with a dataframe that looks like this:</p> <pre><code> Group Val date 0 home first 2017-12-01 1 home second 2017-12-02 2 away first 2018-03-07 3 away second 2018-03-01 </code></pre> <p>Data types are [string, string, datetime]. I would like to get a dataframe tha...
<p>First select the indeces of the dataframe whose variable value is maximum</p> <pre><code>max_indeces = df.groupby(['Group'])['date'].idxmax() </code></pre> <p>and then select the corresponding rows in the original dataframe, maybe only indicating the actual value you are interested in:</p> <pre><code>df.iloc[max_...
python|python-3.x|pandas|pandas-groupby
1
3,470
58,979,090
What could be driving a SyntaxError when trying to combine two columns to create dataframe names?
<p>I am aiming to develop multiple dataframe names using two columns from my source dataframe as naming conventions for each col1 col2 combination .</p> <p>For instance, if <code>period</code> and <code>dps</code> are columns in the source dataframe I want to create dataframes for each <code>period-dps</code> combinat...
<p>Don't use <code>exec</code>. Create a <code>dict</code> to store your dataframes.</p> <pre><code>period = ['a','b','c'] dps = ['x','y','z'] frames = {} for d in dps: for p in period: frames[f'{p}{d}'] = pd.DataFrame() </code></pre> <p>You might also consider nested dicts.</p> <pre><code>from collecti...
python|pandas
1
3,471
58,953,816
Pandas merging with condition on columns
<p>Greeting all, </p> <p>Does anybody know how to join two dataframes according specific behavior using <strong>pandas</strong> please using pandas no other libraries.</p> <p>like <code>df1 inner join df2 where df1.t &lt; df2.t ..</code></p>
<p>Do it in sql, it comes with Python's standard library. </p> <pre><code>from sqlite3 import sqlite3 import pandas # define your dataframes here df1 = ... df2 = ... # load the dataframes to memory sql_ptr = sqlite3.connect(':memory:') df1.to_sql('df1', sql_ptr) df2.to_sql('df2', sql_ptr) # execute the query df3 =...
python|pandas|merge
1
3,472
58,948,939
How can i create a new column that inserts the cell value of grouped column 'ID' (in time) when 'interaction' is 1
<p>I have three relevant columns: time, id, and interaction. How can i create a new column with the id values that have a '1' in column 'interaction' in the given time window? </p> <p>Should look something like this:</p> <pre><code>time id vec_len quadrant interaction Paired with 1 3271 0.9 7 0 ...
<pre class="lang-py prettyprint-override"><code>import numpy as np # initialize dict for all time blocks dict_time_ids = dict.fromkeys(df.time.unique(), set()) # populate dictionary with ids for each time block where interaction == 1 dict_time_ids.update(df.query('interaction == 1').groupby('time').id.apply(set).to_d...
python|pandas|dataframe|if-statement|iteration
1
3,473
70,137,677
Plotting Stackbar chart in Seaborn for showing clustering
<p>Here is my data where I have Wines%, Fruits%, etc which sums up to 1 and is based on the Total_Spent column. There's also a cluster columns that you can see:</p> <p><a href="https://i.stack.imgur.com/E6Atz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/E6Atz.png" alt="enter image description here...
<p>Ok, I achieved the solution with this:</p> <pre><code>df_test = df[['Wines%', 'Fruits%', 'Meat%', 'Fish%', 'Sweets%','Gold%', 'Clusters']] df_unpivoted = df_test.melt(id_vars=['Clusters'], var_name='Category', value_name='Spend%') df_unpivoted.head() df_new = pd.pivot_table(df_unpivoted, index=['Clusters','Category'...
python|pandas|matplotlib|seaborn
-1
3,474
55,699,801
Can I do data augmentation with gaussian blur on my tf.Dataset using my GPU?
<p>I would like to change my old queue based pipeline to the new dataset API on tensorflow for reasons of performance. However, once my code changed, it runs in 8 hours instead of 2. </p> <p>The use of my GPU was about 30/40% and it's now between 0 and 6%.</p> <p>I found the line which making it so slow, and it's whe...
<p>Although I have not tried this on a tf dataset, this should be applicable. I found this combination to be highly performant and simplistic:</p> <pre><code>import tensorflow as tf import tensorflow_addons as tfa dummy_dataset = tf.ones((1000, 224, 224, 3)) blurred_dummy_dataset = tf.map_fn(tfa.image.gaussian_filter2...
tensorflow|tensorflow-datasets|gaussianblur
0
3,475
55,975,063
Is there a quick way to strip out a specific character from all the rows in one column in a pandas DataFrame?
<p>I am trying to strip out the date from a column and make it a new column. I wrote a function to do it, but I'm not sure how to apply it to the pandas framework. </p> <p>Here's the original df:</p> <pre><code>ID var1 var2 abc_20190503_xyz 100 10 fds_20190503_fnk 234 32...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.replace.html" rel="nofollow noreferrer"><code>Series.str.replace</code></a> with <code>regex</code> for this to extract all numbers from your ID column.</p> <pre><code>df['New_ID'] = df['ID'].str.replace('([0-9]+)', ''...
python|pandas
3
3,476
55,938,627
Traversing groups of group by object pandas
<p>I need help with some big pandas issue.</p> <p>As a lot of people asked to have the real input and real desired output in order to answer the question, there it goes: So I have the following dataframe</p> <pre><code>Date user cumulative_num_exercises total_exercises %_exercises 2017-01-01 1 ...
<p>Given no sense of what calculations you wish to accomplish, this is my best guess at what you're looking for. However, I'd re-iterate <a href="https://stackoverflow.com/questions/55938627/traversing-groups-of-group-by-object-pandas#comment98530627_55938627">Datanovice's point</a> that the best way to get answers is ...
python|pandas|pandas-groupby
0
3,477
55,716,916
Efficient enumeration of non-negative integer composition
<p>I would like to write a function <code>my_func(n,l)</code> that, for some positive integer <code>n</code>, efficiently enumerates the ordered non-negative integer composition* of length <code>l</code> (where <code>l</code> is greater than <code>n</code>). For example, I want <code>my_func(2,3)</code> to return <code...
<p>Use the <a href="https://en.wikipedia.org/wiki/Stars_and_bars_(combinatorics)" rel="nofollow noreferrer">stars and bars</a> concept: pick positions to place <code>l-1</code> bars between <code>n</code> stars, and count how many stars end up in each section:</p> <pre><code>import itertools def diff(seq): return...
python|python-3.x|numpy|permutation|combinatorics
4
3,478
65,010,583
If/Then Pandas Condition
<p>I am looking to put in a Pandas condition that basically assigns a new value to an existing condition if it meets the criteria. The following psuedo code explains further what I mean:</p> <p>if postal code is 33707 AND number of bedrooms equals 2 then rent = SquareFeet * 1200</p> <p>So far the closest I have come to...
<p>Its better to use <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a> for such cases:</p> <pre><code>import numpy as np df['Rent'] = np.where(df['PostalCode'].eq(33707) &amp; df['BedroomsTotal'].eq(2), df['LivingArea'] * 2, df.Rent) </cod...
python|pandas|dataframe
1
3,479
64,830,587
Regex syntax for replacing multiple strings: where have I gone wrong?
<p>I have a dataframe with the column 'purpose' that has a lot of string values that I want to standardize by finding a string and replacing it.</p> <p>For instance, some very similar values are <em>car purchase, buying a second-hand car, buying my own car, cars, second-hand car purchase, car, to own a car, purchase of...
<p>You are making the regular expression too restrictive and using the wrong character for alternation. You can use <code>\b</code> to match a word boundary, <code>|</code> to match multiple patterns and IGNORECASE to cover case issues. So for example</p> <pre><code>credit_data.purpose.str.replace(r'\b(real estate|hous...
python|regex|pandas
1
3,480
64,951,910
What loss function and metric should I use for multi-label classification in keras?
<p>Model's final activation is softmax.(output means importance in my case.) I want to pick top 3, then I used categorical crossentropy for loss function / accuracy for metric.</p> <p>for example: prediction : [0.44, 0.03, 0.01, 0.02, 0.30, 0.20] true: [1, 0, 0, 0, 1, 1 ]</p> <p>Is it right to u...
<h1>What loss function and metric to use for multi-label classification?</h1> <p>For a multi-label classification problem, use <code>sigmoid</code> (<em>not softmax</em>).</p> <p>For a loss function use <code>tf.keras.losses.binary_crossentropy</code></p> <p>For example, lets say you have pictures as <em>X</em> and <em...
python|tensorflow|keras
1
3,481
64,725,275
How to configure dataset pipelines with Tensorflow make_csv_dataset for Keras Model
<p>I have a structured dataset(csv features files) of around 200 GB. I'm using <a href="https://www.tensorflow.org/api_docs/python/tf/data/experimental/make_csv_dataset" rel="nofollow noreferrer">make_csv_dataset</a> to make the input pipelines. Here is my code</p> <pre><code>def pack_features_vector(features, labels):...
<p>In the snippets, you wrote</p> <pre><code>model.fit(train_ds, validation_data=validate_ds, validation_steps=1, steps_per_epoch= 1, epochs=20, verbose=1) </code></pre> <p>Is the <code>steps_per_epoch= 1</code> a typo? If not, that would mean you only use one batch per...
python|tensorflow|machine-learning|tensorflow2.0|tensorflow-datasets
1
3,482
64,962,033
python dataframe income column cleanup
<p>This maybe a simple solution, but I am finding it hard to make this function work for my dataset.</p> <p>I have a salary column with variety of data in it. Example dataframe below:</p> <pre><code>ID Income desired Output 1 26000 26000 2 45K ...
<p>I would like to reiterate if this are only possible combinations of the data, then i have done and provided the below code.</p> <p>Even if there is any small change you will need to edit to cater to new change. Let me explain what i have done, for all the strings that you want to replace with &quot;&quot; i have cre...
python|pandas|data-cleaning
1
3,483
40,051,478
Simple Logistic Regression Error in Python
<p>Here is the line of code. I know the issue is that I only have a 1-d array but I cannot figure the code for casting it to a 2-d array inline.</p> <pre><code>def classification_model(model, data, predictors, outcome): model.fit(data[predictors],data[outcome]) </code></pre> <p>where data is a 1-d array that has ...
<pre><code>data[col_name].values.reshape(len(data), 1) </code></pre> <p>As given by Michael K above</p>
python|arrays|pandas|scikit-learn
0
3,484
39,809,650
selecting rows in a tuplelist in pandas
<p>I have a list of tuples as below in python:</p> <pre><code> Index Value 0 (1,2,3) 1 (2,5,4) 2 (3,3,3) </code></pre> <p>How can I select rows from this in which the second value is less than or equal 2?</p> <p><strong><em>EDIT:</em></strong></p> <p>Basically, the da...
<p>You could slice the <code>tuple</code> by using <code>apply</code>:</p> <pre><code>df[df['Value'].apply(lambda x: x[1] &lt;= 2)] </code></pre> <p><a href="https://i.stack.imgur.com/MZBwY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MZBwY.png" alt="Image"></a></p> <hr> <p>Seems, it was a lis...
python|pandas|tuples
2
3,485
39,578,466
pandas date to string
<p>i have a datetime <code>pandas.Series</code>. One column called "dates". I want to get 'i' element in loop like string.</p> <p><code>s.apply(lambda x: x.strftime('%Y.%m.%d'))</code> or <code>astype(str).tail(1).reset_index()['date']</code> or many other solutions don't work.</p> <p>I just want a string like <code>...
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.strftime.html" rel="nofollow"><code>strftime</code></a> for convert <code>datetime</code> column to <code>string</code> column:</p> <pre><code>import pandas as pd start = pd.to_datetime('2015-02-24 10:00') rng = pd....
python|datetime|pandas|time-series
4
3,486
69,306,507
Creating multiple additional calculated columns to a dataframe in pandas using a for statement
<p>I am trying to create an additional column to my dataframe using a loop, where the additional columns would be a multiple of a current column, but that multiple will change. I understand that this can be solved relatively easily by just creating a new column for each, but this is part of a larger project that I cant...
<p>Do you want something like this ?</p> <pre><code>for i in range(2,5): df[&quot;Amout i={}&quot;.format(i)] = df['Amount']*i </code></pre> <p>Output :</p> <pre><code> Time Amount Amout i=2 Amout i=3 Amout i=4 0 20 10 20 30 40 1 10 5 10 15 20...
python|pandas
2
3,487
69,619,509
How can I separate a column in new columns
<p>I don't know how to ask this question, but i'll try do explain my case.</p> <p>I have a dataset with the data as following:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Product</th> <th>Value</th> <th>Value type</th> <th>year</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>21,5</td> <...
<p>Use <code>pivot</code>:</p> <pre><code>out = df.pivot(index=['Product', 'year'], columns='Value type', values=['Value']) \ .droplevel(0, axis=1).reset_index().rename_axis(None, axis=1) \ [['Product', 'Price', 'Volume', 'year']] </code></pre> <pre><code>&gt;&gt;&gt; out Product Price Volume year ...
python|pandas|dataframe
1
3,488
69,466,183
Python: I need to find the average over x amount of rows in a specific column of a large csv file
<p>I have a large CSV file with two columns in it as shown below:</p> <p><a href="https://i.stack.imgur.com/FZc1D.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FZc1D.png" alt="enter image description here" /></a></p> <p>I have already filtered the data. I need to calculate the average pressure ever...
<p>numpy - <a href="https://numpy.org/doc/stable/reference/generated/numpy.average.html" rel="nofollow noreferrer">average</a> &amp; <a href="https://numpy.org/doc/stable/reference/generated/numpy.reshape.html" rel="nofollow noreferrer">reshape</a></p> <pre><code>n = 3 x = df['Pressure'] # calculates the average avg...
pandas
0
3,489
54,222,063
How move some cell in pandas dataframe?
<p>I am trying to move some data in a pandas data frame.</p> <p>I have this data now:</p> <p><img src="https://i.stack.imgur.com/KBkpR.jpg" alt="enter image description here"></p> <p>My expected behavior is:</p> <p><img src="https://i.stack.imgur.com/8rhOW.jpg" alt="enter image description here"></p> <p>So when <c...
<p>You can try this:</p> <pre><code>df.loc[1:,'B':] = df.loc[1:,'B':].shift(1, axis=1).fillna(0) </code></pre> <p>Output:</p> <pre><code> A B C D E 0 1 8 2011-06-01 ABC ABC 1 2 0 2011-06-01 ABC ABC </code></pre>
python|pandas|dataframe
0
3,490
53,803,058
value range in Pandas
<p>I have a simple code for titanic data:</p> <pre><code>import pandas as pd def pClassSurvivorDetails(df,pClass): print('\nResults for Pclass =', pClass, '\n -------------------- ') print("The following did not survive") notSurvive = df['Sex'][df['Survived']==0][df['Pclass']==pClass] print(notSurvive...
<p>To cycle through all values between two variables in Python, you can use:</p> <pre><code>for i in range(x, y): </code></pre> <p>Or, since it is up to and not including y, you could include y with:</p> <pre><code>for i in range(x, y + 1): </code></pre> <p>To get all values in this range, and then access only one,...
python|pandas
0
3,491
53,874,275
Error when filtering Dataframe (TypeError: invalid type comparison)
<p>I am trying to filter out a Dataframe based on a column but I get an error <code>TypeError: invalid type comparison</code></p> <p>Given below is view of my Dataframe:</p> <pre><code>id,name,start_date,new_customer 101,customer_1,2018-12-01,True 102,customer_2,2018-11-21,False 103,customer_3,2018-12-11,True 104,cus...
<p>Use <code>True</code> without apostrophe</p> <pre><code>df = df['new_customer'] == True </code></pre>
pandas
1
3,492
38,231,168
Problems with Tensorboard on Ubuntu 16.04
<p>I'm running code from <a href="https://github.com/MorvanZhou/tutorials/blob/master/tensorflowTUT/tf15_tensorboard/full_code.py" rel="nofollow">https://github.com/MorvanZhou/tutorials/blob/master/tensorflowTUT/tf15_tensorboard/full_code.py</a> on my own computer, which is a sample of how to use Tensorboard, however, ...
<p>I think I have solved the problem: I typed a redundant space to the command line:</p> <pre><code>tensorboard --logdir = 'logs' --inspect </code></pre> <p>which should be:</p> <pre><code>tensorboard --logdir ='logs' --inspect </code></pre> <p>or:</p> <pre><code>tensorboard --logdir 'logs' --inspect </code></pre...
google-chrome|ubuntu|tensorflow|tensorboard
0
3,493
38,264,881
Write numpy.ndarray with Russian characters to file
<p>I try to write <code>numpy.ndarray</code> to file. I use</p> <pre><code>unique1 = np.unique(df['search_term']) unique1 = unique1.tolist() </code></pre> <p>and next try 1)</p> <pre><code>edf = pd.DataFrame() edf['term'] = unique1 writer = pd.ExcelWriter(r'term.xlsx', engine='xlsxwriter') edf.to_excel(writer) wri...
<p>The second example should work if you encode the strings as utf8. </p> <p>The following works in Python2 with a utf8 encoded file:</p> <pre><code># _*_ coding: utf-8 import pandas as pd edf = pd.DataFrame() edf['term'] = ['foo', 'bar', u'русском'] writer = pd.ExcelWriter(r'term.xlsx', engine='xlsxwriter') edf.t...
python|excel|numpy|pandas|utf-8
0
3,494
65,917,546
How to change the color channel of the OpenCV input frame to fit the model?
<p>I am still new to deep learning. So, I am trying to run OpenCV to capture frames and pass those frames to my trained model. The input required for the model has dimensions of (48,48,1).</p> <p>The first layer in the model:</p> <pre><code>model.add(Conv2D(input_shape=(48,48,1),filters=64,kernel_size=(3,3),padding=&qu...
<p>openCV images are just numpy arrays, so they can be manipulated easily using numpy commands.</p> <p>E.g.:</p> <pre><code>import numpy as np x = np.array(range(48*48)).reshape(48,48) x.shape </code></pre> <blockquote> <p>(48, 48)</p> </blockquote> <pre><code>x = x.reshape(48,48,1) x.shape </code></pre> <blockquote>...
python|numpy|opencv|image-processing|image-resizing
1
3,495
66,287,204
np.meshgrid using up too much ram Google Colab
<p>So I'm working on this assignment for my class and I'm having an issue where Google Colab says that I've used up all the RAM when the np.meshgrid line is executed. I understand the meshgrid is using like 50GB of space but I can't figure out how to reduce that. Can someone help me understand what I'm doing wrong plea...
<p>So your 3 <code>arange</code> have about the same size</p> <pre><code>In [38]: np.arange(-32,32,.05).shape Out[38]: (1280,) </code></pre> <p><code>meshgrid</code> makes 3 &quot;cubes&quot; with 1280 points on each dimension</p> <pre><code>In [42]: (1280**3)/1e9 Out[42]: 2.097152 </code></pre> <p>That's 2G of points,...
python|numpy|machine-learning|scikit-learn
1
3,496
52,750,090
Categorical dtype changes after using melt
<p>In answering <a href="https://stackoverflow.com/q/52749898/6671176">this question</a>, I found that after using <code>melt</code> on a pandas dataframe, a column that was previously an ordered Categorical dtype becomes an <code>object</code>. Is this intended behaviour?</p> <p>Note: not looking for a solution, just...
<p>In <a href="https://github.com/pandas-dev/pandas/commit/9dc9d805fe58cf32a8a3c8ab2277517eaf73d4c6#diff-9d24108841e0a76fe806a808d84f4561" rel="nofollow noreferrer">source</a> code . 0.22.0(My old version)</p> <pre><code> for col in id_vars: mdata[col] = np.tile(frame.pop(col).values, K) mcolumns = id_var...
python|pandas
2
3,497
52,510,275
I am getting tensorflow installation error on pycharm
<p><a href="https://i.stack.imgur.com/iIDcz.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iIDcz.jpg" alt="Error on pycharm"></a></p> <p>pip version I am using is 18.0 and tensorflow I was trying to install version 1.11.0rc2. I tried it with other versions of pip too but didn't work.</p>
<p>That's because there is no release for Python 3.7: <a href="https://pypi.org/project/tensorflow/1.11.0rc2/#files" rel="nofollow noreferrer">https://pypi.org/project/tensorflow/1.11.0rc2/#files</a></p>
python|python-3.x|tensorflow|pip|pycharm
1
3,498
46,238,307
How to filter out rows from multiple data frames that are inside a dictionary in python
<p>I have a <code>dictionary</code> that contains many <code>dataframes</code>.</p> <p>Sample data:</p> <pre><code>dataframe1 = pd.DataFrame({"variable1":["a","a","b"]}) dataframe2 = pd.DataFrame({"variable1":["b","a","b"]}) dictionary = dict(zip(["dataframe1","dataframe2"],[dataframe1,dataframe2])) </code></pre> <p...
<p>Use dict comprehension with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html" rel="nofollow noreferrer"><code>query</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a>....
python|python-3.x|pandas|dictionary
4
3,499
46,354,509
Transfer unmasked elements from maskedarray into regular array
<p>I have a <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/maskedarray.html" rel="nofollow noreferrer"><code>MaskedArray</code></a> <code>a</code> of shape (L,M,N), and I want to transfer the unmasked elements to a normal array <code>b</code> (with the same shape), such that along the last dimension, the fi...
<p>Adapting @divakar's answers from the linked 'pad with 0s' questions,</p> <p><a href="https://stackoverflow.com/questions/38619143/convert-python-sequence-to-numpy-array-filling-missing-values">Convert Python sequence to NumPy array, filling missing values</a></p> <pre><code>In [464]: a=np.array([[0,1,2,0,7,0,5],[3...
python|arrays|numpy|slice
2