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 |
|---|---|---|---|---|---|---|
365,000 | 35,257,280 | Passing custom arguments to a Blender Operator as if it were a function | <p>I created a python script in Blender which obtains information about an object. Said information is then stored in a list of numpy arrays for later use. Initially, I wanted to use that information to have the camera move in a certain way, but running the script freezes the 3D enviornment until the end of execution.<... | <p>To move your camera and get an updated 3DView, try using a <a href="https://www.blender.org/api/blender_python_api_current/bpy.types.Operator.html#modal-execution" rel="nofollow">modal operator</a>. When <code>execute()</code> is called and it returns <code>{'RUNNING_MODAL'}</code>, the operators <code>modal()</code... | python|numpy|blender | 0 |
365,001 | 35,149,843 | Running max / limsup in Numpy: what optimization? | <p>In order to compute the <a href="https://en.wikipedia.org/wiki/Limit_superior_and_limit_inferior#Definition_for_sequences" rel="nofollow">limsup</a> of a sequence, let's compute, for each <code>i</code>, the <code>max(A[i:])</code>:</p>
<pre><code>import numpy as np
n = 10
A = np.random.random(n)
M = np.zeros(n)
f... | <p>You can replace your <code>for</code> loop with the following code:</p>
<pre><code>M = np.maximum.accumulate(A[::-1])[::-1]
</code></pre>
<p>This views the reverse of <code>A</code> and computes the cumulative maximum, then reverses this new array.</p>
<p>The performance of this code should be significantly bette... | python|arrays|performance|numpy|vectorization | 5 |
365,002 | 35,129,266 | Create line plot with 2 series splitted by column value | <p>I'm fighting with should be quite an easy task. Creation of line plot with 2 series. So far I managed to do so but I think it is not the fastest way. I wanted to ask if anyone knows how to do it faster/smarter?</p>
<p>The problem which I have is that values of this 2 series are in the same column 'values' and to ge... | <p>You <em>do</em> have to transform your data since you do not want to plot your columns as they are. But there is an easier way:</p>
<pre><code>>>> df.pivot(index='labels', columns='category', values='values').head()
category a b
labels
1 0.133046 0.762676
2 ... | python|pandas | 2 |
365,003 | 35,006,922 | Passing Values between functions using **kwargs | <p>I currently have one function <strong><em>run_prob</em></strong> that takes my models and returns the y_prob. It works perfectly. However, below, I have put together another two functions <strong><em>pred_prob</em></strong> and <strong><em>cal_prob</em></strong>, and I would like these two functions to work together... | <pre><code>def pred_prob(X, y, MODEL):
pred_prob = run_prob_cv(X, y, MODEL)
pred_churn = pred_prob[:,1]
is_churn = y == 1
# Number of times a predicted probability is assigned to an observation
counts = pd.value_counts(pred_churn)
# calculate true probabilities
true_prob = {}
for prob in... | python|pandas|lambda | 0 |
365,004 | 34,882,764 | pandas - linear regression of dataframe columns values | <p>I have a pandas dataframe <code>df</code> like:</p>
<pre><code>A,B,C
1,1,1
0.8,0.6,0.9
0.7,0.5,0.8
0.2,0.4,0.1
0.1,0,0
</code></pre>
<p>where the three columns have sorted values [0,1]. I'm trying to plot a linear regression over the three series. So far I was able to use <code>scipy.stats</code> as following:</p>... | <p>Perhaps something like this:</p>
<pre><code>x = pd.np.tile(xi, 3)
y = pd.np.r_[df['A'], df['B'], df['C']]
slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)
line4 = intercept + slope * xi
plt.plot(line4,'k-')
</code></pre> | python|pandas|scipy|statistics|regression | 2 |
365,005 | 34,884,536 | What is the point of views in pandas if it is undefined whether an indexing operation returns a view or a copy? | <p>I have switched from R to pandas. I routinely get SettingWithCopyWarnings, when I do something like</p>
<pre class="lang-py prettyprint-override"><code>df_a = pd.DataFrame({'col1': [1,2,3,4]})
# Filtering step, which may or may not return a view
df_b = df_a[df_a['col1'] > 1]
# Add a new column to df_b
df_b... | <p>Great question!</p>
<p>The short answer is: this is a flaw in pandas that's being remedied. </p>
<p>You can find a longer discussion of the nature of <a href="https://github.com/pydata/pandas/issues/10954">the problem here</a>, but the main take-away is that we're now moving to a "copy-on-write" behavior in which ... | python|pandas|views|slice | 11 |
365,006 | 35,056,012 | how to find avg of column of csv file | <pre><code>import csv
with open('Met.csv', 'r') as f:
reader = csv.reader(f, delimiter=':', quoting=csv.QUOTE_NONE)
for row in reader:
print row
</code></pre>
<p>I am not able to go ahead how to get a column from the csv file I tried </p>
<pre><code>print row[:column_name]
name id name reccla ... | <p>Try <code>pandas</code> instead of reading from <code>csv</code></p>
<pre><code>import pandas as pd
data = pd.read_csv('Met.csv')
</code></pre>
<p>It is far easier to grab columns and perform operations using <code>pandas</code>.
Here I am loading the csv contents to a dataframe.</p>
<p><strong>Loaded data :</str... | python|python-2.7|python-3.x|numpy | 4 |
365,007 | 35,063,946 | reading the last index from a csv file using pandas in python2.7 | <p>I have a .csv file on disk, formatted so that I can read it into a pandas DataFrame easily, to which I periodically write rows. I need this database to have a row index, so every time I write a new row to it I need to know the index of the last row written. </p>
<p>There are plenty of ways to do this: </p>
<ul>
<l... | <p>Reading the entire index column will still need to read and parse the whole file.</p>
<p>If no fields in the file are multiline, you could scan the file backwards to find the first newline (but with a check if there is a newline past the data). The value following that newline will be your last index.</p>
<p>Stori... | python-2.7|csv|pandas|pandasql | 1 |
365,008 | 34,896,455 | How to do Pearson correlation of selected columns of a Pandas data frame | <p>I have a CSV that looks like this:</p>
<pre><code>gene,stem1,stem2,stem3,b1,b2,b3,special_col
foo,20,10,11,23,22,79,3
bar,17,13,505,12,13,88,1
qui,17,13,5,12,13,88,3
</code></pre>
<p>And as data frame it looks like this:</p>
<pre><code>In [17]: import pandas as pd
In [20]: df = pd.read_table("http://dpaste.com/3P... | <p><s>Note there is a mistake in your data, there special col is all 3, so no correlation can be computed.</s></p>
<p>If you remove the column selection in the end you'll get a correlation matrix of all other columns you are analysing. The last [:-1] is to remove correlation of 'special_col' with itself.</p>
<pre><co... | python|pandas | 23 |
365,009 | 35,030,052 | How to replace no data value -3.4028231e+38 to numpy.nan | <p>I have an 2d array constructed from raster image. The raster image has no data value assigned to -3.4028231e+38, I am trying to replace this value with 'nan' but I am unable to find this value when I apply conditional operator on it.</p>
<p>my data is as following:</p>
<pre><code>>>> slice22 = inndvi[0:2,... | <p>Considering you know your real values is between -2 and 2, you can easily filter out anything outside of this range.</p>
<pre><code>a[(a < -2) | (a > 2)] = np.nan #option 1
a[np.abs(a) > 2] = np.nan #option 2
a[np.logical_or(a < -2, a > 2)] = np.nan #option 3
</code></pre> | python|numpy|raster | 2 |
365,010 | 30,898,824 | How can I modify my data in a CSV file and change the rows and columns? | <p>I have a CSV file and the format of my data is as follows:</p>
<pre><code>Countries variable 1995 1996 1997 1998 1999
USA GDP 10 11 12 12 13
USA Inf 100 120 130 120 110
USA Trade 200 220 210 235 250
GER GDP 8 9 ... | <p>You could use a Ordereddict to group the data:</p>
<pre><code>import csv
from collections import OrderedDict,defaultdict
from itertools import islice
with open("out.csv") as f:
od = OrderedDict()
r = csv.reader(f, delimiter=" ")
header = next(r)
years = header[2:]
zipped = zip(*r)
countries ... | python|csv|pandas | 3 |
365,011 | 30,794,325 | Python Pandas hdfstore's select(where='') return unqualified results | <p>When I query a large hdfstore file (>10G) like this:</p>
<pre><code>hdf = pd.HDFStore('raw_sample_storage.h5')
nrows = hdf.get_storer('raw_sample_all').nrows
chunksize = 300000
for i in xrange(nrows//chunksize + 1):
chunk = hdf.select('raw_sample_all', where=[pd.Term('node_id', '==', 1)], start=i*chunksize, st... | <p>This was a recently fixed bug in <code>PyTables</code>, see the related issue <a href="https://github.com/pydata/pandas/issues/9676" rel="nofollow">here</a>. In effect on some larger stores the indexers where not computed correctly when using a <code>where</code> and <code>start/stop</code>.</p>
<p>You will need to... | python|pandas|hdf5|hdfstore | 1 |
365,012 | 30,879,669 | Beatbox: How do I add a WHERE clause when pulling data from SFDC? | <p>In Pandas, I am creating a dataframe that merges data from two different Beatbox queries. First, I pull all my Opportunity data, then I pull all my Account data, and then I merge. </p>
<p>However I would like to optimize this process by only pulling data for account['ID'] that exists in the oppty['AccountID'] colum... | <p>You can use a SOQL semi-join to restrict the Account query to only those accounts with opportunities, e.g.</p>
<pre><code>svc.query("SELECT ID,Website FROM Account where ID in (SELECT accountId FROM Opportunity)")
</code></pre> | python|pandas|salesforce|beatbox | 2 |
365,013 | 30,764,955 | Python numpy: create 2d array of values based on coordinates | <p>I have a file containing 3 columns, where the first two are coordinates (x,y) and the third is a value (z) corresponding to that position. Here's a short example:</p>
<pre><code>x y z
0 1 14
0 2 17
1 0 15
1 1 16
2 1 18
2 2 13
</code></pre>
<p>I want to create a 2D array of values from the third row based on their ... | <p>Assuming the <code>x</code> and <code>y</code> values in your file directly correspond to indices (as they do in your example), you can do something similar to this:</p>
<pre><code>import numpy as np
x = [0, 0, 1, 1, 2, 2]
y = [1, 2, 0, 1, 1, 2]
z = [14, 17, 15, 16, 18, 13]
z_array = np.nan * np.empty((3,3))
z_ar... | python|arrays|numpy | 33 |
365,014 | 30,765,820 | python pandas read_excel returns UnicodeDecodeError on describe() | <p>I love pandas, but I am having real problems with Unicode errors. read_excel() returns the dreaded Unicode error:</p>
<pre><code>import pandas as pd
df=pd.read_excel('tmp.xlsx',encoding='utf-8')
df.describe()
---------------------------------------------------------------------------
UnicodeDecodeError ... | <p>Try this method suggested <a href="https://stackoverflow.com/questions/26856793/pandas-read-excel-with-chinese-filename">here</a>:</p>
<pre><code>df=pd.read_excel('tmp.xlsx',encoding=sys.getfilesystemencoding())
</code></pre> | python|excel|pandas|unicode | 4 |
365,015 | 31,112,330 | Call a function over elements of a list in python | <p>I am completely new to python and Pandas of course. I am trying to run a function "get url" which is function to get the complete/ extended url from small Url . I have a data frame in python consists all the short URLs. Now I am trying to do with following ways. One is to use "for" loop which loops and apply functio... | <p>If the short urls are a column in the pandas dataFrame, you can use the <code>apply</code> function (though I am not sure if they would resume on error, most probably not).</p>
<p>Syntax -</p>
<pre><code> df['<newcolumn>'] = df['<columnname>'].apply(<functionname>)
</code></pre>
<p>I am hoping a... | python|arrays|pandas | 1 |
365,016 | 30,844,987 | Why is the output of my function in binary? | <p>I wrote a differentiable Heaviside function and vectorised it. However, the output seems to be odd and binary. The code is as follows:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
def heaviside(x, epis):
if (x>= epis):
y=1
elif (x< -epis):
y=0;
else:
y... | <p>You need to specify when you <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html" rel="nofollow"><code>vectorize</code></a> the function that it should be using <code>float</code>s:</p>
<pre><code>vheaviside = np.vectorize(heaviside, [float])
</code></pre>
<p>otherwise, per the docume... | python|numpy|matplotlib | 3 |
365,017 | 30,945,748 | Reading a CSV file into Pandas Dataframe with invalid characters (accents) | <p>I am trying to read a csv file into a pandas dataframe. However, the csv contains accents. I am using Python 2.7</p>
<p>I've ran into a <code>UnicodeDecodeError</code> because there is an accent in the first column. I've read up on a bunch of sites like <a href="https://stackoverflow.com/questions/904041/reading-a-... | <p>Try adding this to the top of your script:</p>
<pre><code>import sys
reload(sys)
sys.setdefaultencoding('utf8')
</code></pre> | python|csv|pandas|utf-8|dataframe | 1 |
365,018 | 67,270,812 | Adjusting legend layout for multiple legends associated to one Python plot? | <p>I am creating a Python plot from a dataframe with 3 y-axes. For each y-axis, there are multiple y-values I want to plot. All data sets for the y-axes are plotted against a shared Date x-axis.</p>
<p>The code looks as follows:</p>
<pre><code>df = pd.read_excel (r'test.xlsx', sheet_name='test', engine='openpyxl')
fig,... | <p><code>ax.get_legend_handles_labels()</code> collects all the legend handles and their labels. Combining those for each of the axes, a new legend can be created.</p>
<p><code>bbox_to_anchor=</code> sets an anchor point for the legend, using <a href="https://matplotlib.org/stable/tutorials/advanced/transforms_tutorial... | python|pandas|dataframe|matplotlib|legend | 1 |
365,019 | 67,547,826 | Find frequencies and durations | <p>I have less experience with pandas/python, however, I would like to learn. Hopefully, anyone is prepared and able to help.</p>
<p>What does my data look like:
Several participants 'participant' are included which each is divided into 16 conditions 'condition'. Each condition takes 40 seconds 'matchtimesm'. 'Median' ... | <pre><code>df.groupby(['participant','condition']).size()
df.groupby(['participant','condition'])['matchtimesm'].sum() #, looks like you want some aggregation here, most likely sum.
</code></pre> | python|pandas|frequency|duration | 0 |
365,020 | 67,213,577 | While running pytorch i got an error 'TypeError: object of type'CatsAndDogsDataset' has no len()' and I want to know how to fix it | <p>I got an error while running pytorch
I train artificial intelligence with ResNet, and I wrote my own custom dataset for the dataset. After loading the data set from ResnNet, training data and test data were set separately by learning with artificial intelligence. But even though I ran it, an error occurred, but I do... | <p>You need to define the function <code>__len__</code> for your custom dataset (which you seem to have currently incorrectly defined as <code>__length__</code>).</p>
<p><a href="https://pytorch.org/tutorials/beginner/data_loading_tutorial.html#dataset-class" rel="nofollow noreferrer">This documentation</a> provides de... | pytorch|resnet | 0 |
365,021 | 67,572,796 | Joining multiple Pandas data frames into one | <p>I have list (<strong>lst</strong>) of data frames and my list has 2000 dataframes. I want to combine all of these data frames in one. Each dataframe has two columns and the first column of each dataframe is the same. For example:</p>
<pre><code>
#First dataframe
>>lst[0]
0 1
11 6363
... | <p>First we can set the first column as an index to ignore it in concatenation</p>
<pre><code>lst = [df.set_index(0) for df in lst]
</code></pre>
<p>Then we concatenate the columns and drop the 0 column back to being the column instead of the index</p>
<pre><code>df_out = pd.concat(lst, axis=1).reset_index()
</code></p... | python-3.x|pandas | 1 |
365,022 | 67,375,020 | Optimizing some Python to parse a string field | <p>I have a dataframe that has a column named <code>assignment_name</code> that is parsed but takes quite a long time, about 20 minutes for ~400k rows. I'd like some help in making this faster if possible. The input data in <code>assignment_name</code> is unfortunately all over the place, hence the parsing and cleaning... | <p>You can try regular expression:</p>
<pre><code>df["due_date"] = pd.to_datetime(
df["assignment_name"].str.extract(r"^(\d+[/\.-]\d+[/\.-]\d+)(?:\s|$)")[0]
)
print(df)
</code></pre>
<p>Prints:</p>
<pre class="lang-none prettyprint-override"><code> assignment_name due_date
... | python|python-3.x|pandas | 3 |
365,023 | 67,527,859 | How can I clean a column that has dates and variables at the same time on Pandas? | <p>I want to fix a data frame that has the following aspect:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>etiqueta</th>
<th>suma</th>
</tr>
</thead>
<tbody>
<tr>
<td>2015-10</td>
<td>33</td>
</tr>
<tr>
<td>Baja California</td>
<td>12</td>
</tr>
<tr>
<td>Campeche</td>
<td>21</td>
</tr>
<t... | <p>Let us do <code>pd.to_datetime</code> then mask those return <code>NaN</code> and fill it with <code>ffill</code></p>
<pre><code>df['new'] = df['etiqueta'].mask(pd.to_datetime(df['etiqueta'], format = '%Y-%m', errors='coerce').isna()).ffill()
out = df.query('etiqueta!=new').pivot_table(index = 'new',columns = 'etiqu... | python|pandas | 2 |
365,024 | 67,496,315 | How to efficiently multiply by torch tensor with repeated rows without storing all the rows in memory or iterating? | <p>Given a torch tensor:</p>
<pre><code># example tensor size 2 x 4
a = torch.Tensor([[1, 2, 3, 4], [5, 6, 7, 8]])
</code></pre>
<p>and another where every n rows are repeated:</p>
<pre><code># example tensor size 4 x 3 where every 2 rows repeated
b = torch.Tensor([[1, 2, 3], [4, 5, 6], [1, 2, 3], [4, 5, 6]])
</code></... | <p>Assuming that the first dimension of <code>a</code> is 1 as in your example, you could do the following:</p>
<pre><code>a = torch.Tensor([[1, 2, 3, 4]])
b_abbreviated = torch.Tensor([[1, 2, 3], [4, 5, 6]])
torch.mm(a.reshape(-1, 2), b_abbreviated).sum(axis=0, keepdim=True)
</code></pre>
<p>Here, instead of repeating... | python|pytorch|matrix-multiplication|tensor|torch | 2 |
365,025 | 67,310,006 | Pandas replace function does not work on Series of strings | <p>pandas.DataFrame.replace doesn't replace string.</p>
<pre><code>dic = {'Text': ['i8am going to school', 'i8am a very good boy']}
df = pd.DataFrame(dic)
d = df['Text'].replace(to_replace='i8am', value='i am')
print(d)
</code></pre>
<p>Expected output:</p>
<pre><code>I am going to school
I am a very good boy
</code></... | <p>We can use str accessor and then replace the string over it.</p>
<pre><code>d = df.Text.str.replace('i8am', 'I am')
</code></pre>
<p><strong>Output</strong></p>
<pre><code>0 I am going to school
1 I am a very good boy
</code></pre> | python|pandas|dataframe | 1 |
365,026 | 67,553,057 | (Python) How to calculate the average over a time period? | <p>I have a dataFrame and I am trying to add a new column that calculates the average amount spent with a card over the last 3 days.</p>
<p>I have tried using <code>df[avg_card_7days] = df.groupby('card')['amount'].resample('3D', on = 'date').mean()</code></p>
<p>The dataFrame currently looks like:</p>
<pre><code>card ... | <pre><code>df['date'] = pd.to_datetime(df.date, format='%m/%d/%y')
df = df.set_index('date')
df['avg_card_3days'] = df.groupby('card').expanding(3).amount.agg('mean').droplevel(0).sort_index()
df = df.reset_index()
df
</code></pre>
<p><strong>Output</strong></p>
<pre><code> date card amount avg_card_3days
0 ... | python|pandas|datetime|group-by | 0 |
365,027 | 67,248,376 | Change the form of existing DataFrame | <p>I want to change the form of existing dataframe to a new dataframe such that the value in the new dataframe matches the relationship of the existing two columns. Hence, in the new dataframe, "1" means there is a record in the existing dataframe and "0" means no record.</p>
<p>This is what I did s... | <p>try this:</p>
<pre><code>pd.crosstab(a_df[0], a_df[1])
</code></pre>
<p>Result:</p>
<pre><code>1 a c d
0
19 1 0 0
20 0 0 1
31 0 1 1
51 0 0 1
</code></pre> | python|pandas|dataframe | 2 |
365,028 | 67,531,746 | pandas better runtime, going trough dataframe | <p>I have a pandas dataframe, there I wanna search in one column for numbers, find it and put it in a new column.</p>
<pre><code>import pandas
import regex as re
import numpy as np
data = {'numbers':['134.ABBC,189.DREB, 134.TEB', '256.EHBE, 134.RHECB, 345.DREBE', '456.RHN,256.REBN,864.TREBNSE', '256.DREB, 134.ETNHR,245... | <p>Sure, use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.findall.html" rel="nofollow noreferrer"><code>Series.str.findall</code></a> instead loops:</p>
<pre><code>pattern = '134.[A-Z]{2,}'
df['mynumbers'] = df['numbers'].str.findall(pattern)
print(df)
... | python|pandas|dataframe|runtime | 4 |
365,029 | 67,198,105 | translate dataframe python to english and save the result into a cvs file | <p>I have a dataframe with 205232 rows, i want to translate the column 'ingredients_text' which can contain 1 or more languages in a single row to english. This is an example of the df</p>
<p><a href="https://i.stack.imgur.com/NOz8u.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NOz8u.png" alt="ente... | <p>Try <code>apply()</code> with lambda function. Then use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html" rel="nofollow noreferrer"><code>pandas.DataFrame.to_csv()</code></a> to convert dataframe to csv.</p>
<pre class="lang-py prettyprint-override"><code>import google... | python|pandas | 2 |
365,030 | 67,514,619 | Parse time from string in UTC format in a way comparable with the current time stamp | <p>I would like to do create a pandas date range ranging from a parsed time to the current time, both in <strong>UTC</strong>. This is my best effort so far:</p>
<pre><code>import dateutil
from datetime import datetime, timezone
start_time = dateutil.parser.isoparse ('2021-01-01T00Z')
end_time = datetime.now (timezone... | <p>I'm not a pro but I made some research and found this solution using <a href="https://www.kite.com/python/docs/datetime.datetime.astimezone" rel="nofollow noreferrer"><code>astimezone()</code></a>:</p>
<pre><code>import dateutil
from datetime import datetime, timezone
start_time = dateutil.parser.isoparse ('2021-01... | python|pandas|datetime|timezone|utc | 2 |
365,031 | 67,482,610 | count a range of elements with Numpy | <pre><code>np.unique([1, 3, 0, 3, 1, 1], return_counts=True)
</code></pre>
<p>returns</p>
<pre><code>(array([0, 1, 3]), array([1, 3, 2]))
</code></pre>
<p>which excludes missing elements, in this case, <code>2</code>.</p>
<p>Is there an easy and efficient way to get all counts, for example:</p>
<pre><code>count(ar=[1, ... | <p>You could use <a href="https://numpy.org/doc/stable/reference/generated/numpy.bincount.html" rel="nofollow noreferrer"><code>np.bincount</code></a>, passing it a <code>minlength</code> of the maximum value in the array plus 1:</p>
<pre class="lang-py prettyprint-override"><code>ar = np.array([1, 3, 0, 3, 1, 1])
np.b... | python|numpy | 4 |
365,032 | 67,451,311 | Nearly Constant training and validation accuracy | <p>I’m new to pytorch and my problem may be a little naive
I’m training a pretrained VGG16 network on my dataset which it’s size is near 33000 images in 8 classes with labels [1,2,…,8] and my classes are imbalanced. my problem is that during training, validation and training accuracy is low and doesn’t increase, is the... | <p>my problem was in <code>model.train()</code>. This phrase should be inside the training loop. but in my case I put it outside the training loop and when it comes to <code>model.eval()</code>, model maintained in this mode</p> | pytorch|transfer-learning | 1 |
365,033 | 67,351,682 | Writing formatted dataframe with space-tab delimiters | <p>The conventional <code>csv</code> is not human reader friendly and therefore, I am writing tab-separated pandas dataframe using following command:</p>
<pre><code>df.to_csv ('output.txt', index = False, header=True, float_format='%.3f', sep='\t')
</code></pre>
<p>This results in the output in the following format:</p... | <p>You can try <a href="https://numpy.org/doc/stable/reference/generated/numpy.savetxt.html" rel="nofollow noreferrer"><code>np.savetxt</code></a>:</p>
<pre><code>np.savetxt(
r"file.txt",
df.values,
fmt="%-10.3f",
header="".join("{:11}".format(c) for c in df.colum... | python|pandas | 1 |
365,034 | 67,568,711 | Efficient pandas between() for any of multiple values | <p>I have a pandas DataFrame looking like this</p>
<pre><code>data = [["2020-01-01", "2020-01-01"], ["2020-01-02", "2020-01-04"], ["2020-01-05", "2020-01-06"]]
df = pd.DataFrame(data, columns=["START", "END"]).astype({"END": "... | <p>We can broadcast the values in <code>START</code> and <code>END</code> columns to create a boolean mask, then reduce the resulting boolean mask along <code>axis=1</code></p>
<pre><code>t = timestamps.values
((df['START'].values[:, None] <= t) & (df['END'].values[:, None] >= t)).any(1)
</code></pre>
<hr />
... | python|pandas | 4 |
365,035 | 67,248,859 | How to open a file whose name is stored in a pandas cell, manipulate the contents and store in a new column | <h1>Dataframe Example</h1>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>index</th>
<th>fileName</th>
<th>startline</th>
<th>endline</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>293104.java</td>
<td>30</td>
<td>40</td>
</tr>
<tr>
<td>1</td>
<td>288951.java</td>
<td>183</td>
<td>247</td>
</... | <p>If you use <code>apply</code>, which will apply the function to each row, you write the function to take a single row of the dataframe and then you can use dot notation to access the columns in the function.</p>
<pre><code>def snippetMaker(row):
file = open(row.fileName,'r').read()
snippet = file.split('\n... | python|pandas | 1 |
365,036 | 67,229,134 | Porting pre-trained keras models and run them on IPU | <p>I am trying to port two pre-trained keras models into the IPU machine. I managed to load and run them using IPUstrategy.scope but I dont know if i am doing it the right way. I have my pre-trained models in .h5 file format.
I load them this way:</p>
<pre><code>def first_model():
model = tf.keras.models.load_model... | <p>To add some context, the Graphcore TensorFlow wheel includes a port of Keras for the IPU, available as <code>tensorflow.python.ipu.keras</code>. You can access the API documentation for IPU Keras at <a href="https://docs.graphcore.ai/projects/tensorflow-user-guide/en/latest/api.html#module-tensorflow.python.ipu.kera... | keras|tensorflow2.0|ipu | 1 |
365,037 | 67,571,125 | export tables from database to mdf file | <p>i am python beginner. i have Database that has 5 tables, i use python to export all those tables to mdf file using asammdf.</p>
<pre><code>path_data = os.path.join('..\\Data', 'db_2021-05-06_11-49-42_day.db')
con = sqlite3.connect(path_data)
cursor = con.cursor()
cursor.execute('SELECT name FROM sqlite_master WHERE ... | <p>The phrase "can only concatenate str (not "tuple") to str" means "trying to concatenate str and non-str (tuple)".
Therefore, we need to match the type of either one we are trying to combine.</p>
<pre><code>df = pd.read_sql_query('select * from' + str(equipment) , con)
df = pd.read_sql_... | python|pandas|mdf|asammdf | 0 |
365,038 | 67,504,591 | How can I assign each .csv file to a single subplot? | <p>This is my code so far - what I am trying to achieve:</p>
<p>I have 3 .csv files (i.e. replicas) with two columns each: time (X-Axis) and potential energy (Y-Axis)
Since they have similar paths, I am reading them through filename = with %s for each replica and wanna plot each in one of the subplots so that I can the... | <p>Replace the two <code>for</code> loops:</p>
<pre><code>for i in range(3):
for replica in replicas:
</code></pre>
<p>with a loop over <a href="https://book.pythontips.com/en/latest/enumerate.html" rel="nofollow noreferrer"><code>enumerate</code></a>:</p>
<pre><code>for i, replica in enumerate(replicas):
</code><... | python|pandas|csv|matplotlib|subplot | 0 |
365,039 | 67,405,101 | Get mask of watermark from image in Python | <p>Given a series of photos that are watermarked, I want to isolate the watermark, and generate a mask.</p>
<p>I'm using Python and numpy.</p>
<p>I've added the pictures on top of each other:</p>
<pre><code>def compare_n_img(array_of_img_paths):
img_float_array = []
for path in array_of_img_paths:
img_float_array... | <p>You can try blurring the image before using the canny edge detector. As the detected edges would be too thin, an iteration of dilation and erosion would fix the problem.</p>
<p>After the edges are detected, there would most likely be a lot of noise in the background, so filtering out the contours with a small area w... | python|numpy|opencv|watermark|edge-detection | 4 |
365,040 | 67,396,590 | Geopandas: buffer operation seems to ignore the unit of measure of the CRS | <p>My goal here is to make a geodataframe from a couple of columns of coordinates in an existing dataframe, take those 1677 geographic points and add a buffer circle around each, then union the resulting polygons into a multipolygon. Where I keep getting wrapped around the axle is the .buffer() part of geopandas doesn'... | <p>GeoPandas does exactly what is expected to do. You have to re-project your geometries to a target CRS, simply assigning it does not do anything.</p>
<p>When creating the GeoDataFrame, make sure you specify in which CRS your data is. In this case it is EPSG:4326 aka geographical projection in degrees.</p>
<pre class=... | python|geopandas|pyproj | 1 |
365,041 | 67,546,129 | Using Boost Python Numpy ndarray as a Class member variable | <p>I'm looking forward to pass an Python-Object to an Boost Python Class. This Object has an ndarray as attribute and I want to store this ndarray as a private member variable in this Class to use it later on. I could'n find a proper way to do this and I get Compiler Errors when declaring a boost::python::numpy::ndarra... | <p>The problem is that your constructor for <code>FlatlandCBS</code> is invalid.
As per <a href="https://en.cppreference.com/w/cpp/language/constructor" rel="nofollow noreferrer">cppreference</a>:</p>
<blockquote>
<p>Before the compound statement that forms the function body of the constructor begins executing, initial... | python|c++|numpy|boost|boost-python | 1 |
365,042 | 67,576,415 | Error using Pandas read_csv from S3 bucket in AWS lambda function - Expected 1 fields in line 5, saw 2 | <p>Reading a csv file from an S3 bucket using Pandas read_csv in AWS lambda function and keep seeing a tokenisation error relating to the contents of the csv.</p>
<p>First 5 lines as follows (pasted from text editor)</p>
<pre><code>ItemID | NameID | Users | Days | Pricing | Expiration | Status
-------------... | <p>Got this error a couple of times, solved it by using lineterminator like this. The default value is \r\n. I think AWS changed the way to store values.</p>
<pre><code>rawdata = pd.read_csv(io.BytesIO(obj['Body'].read()),sep=',', lineterminator='\n')
</code></pre> | python|pandas|amazon-s3|aws-lambda|boto3 | 0 |
365,043 | 67,223,276 | Selecting specific rows in pandas dataframe merging | <p>I have 4 dataframes in the array that I keep.</p>
<pre><code> 0 1 2
0 0.0 1.0 2.0
1 0.0 1.0 2.0
2 0.0 1.0 2.0
3 0.0 1.0 2.0
4 0.0 2.0 3.0
5 0.0 2.0 3.0
6 0.0 3.0 4.0
7 0.0 3.0 4.0
0 1 2
0 1.0 4.0 4.0
1 1.0 5.0 5.0
0 1 2
0 2.0 6.0 4.0
0 1 ... | <p>First, rename the columns of <code>df2</code>, <code>df3</code>, <code>df4</code> from 0,1,2 to 3,4,5</p>
<pre class="lang-py prettyprint-override"><code>for df in [df2, df3, df4]:
df.rename(columns={0:3, 1:4, 2:5}, inplace=True)
</code></pre>
<p>Second, change the index of these columns to the row index where y... | python|pandas|dataframe|merge|rows | 1 |
365,044 | 67,239,379 | Getting the datetime index of a value in a column | <p>I am working on a technical analysis project for which I need to annotate the <code>matplotlib</code> chart for buy/sell signals. As I am getting data from the <code>yfinance</code> module, I automatically have a <code>DateTimeIndex</code> in my <code>DataFrame</code>.
My <code>DataFrame</code> looks like this:</p>
... | <p>Equivalent to your code:</p>
<pre><code>>>> pd.DatetimeIndex(df.loc[df["Sell"].notna(), "Date"])
DatetimeIndex(['2020-05-21', '2020-05-22'], dtype='datetime64[ns]', name='Date', freq=None)
</code></pre> | python|pandas|dataframe | 0 |
365,045 | 67,327,234 | Reindex dataframe inside loop | <p>I'm trying to reindex the columns in a set of dataframes inside a loop. This only seems to work outside the loop. See sample code below</p>
<pre><code>import pandas as pd
data1 = [[1,2,3],[4,5,6],[7,8,9]]
data2 = [[10,11,12],[13,14,15],[16,17,18]]
data3 = [[19,20,21],[22,23,24],[25,26,27]]
index = ['a','b','c']
col... | <p>That happens for the same reason this happens:</p>
<pre><code>a = 5
b = 6
for i in [a, b]:
i = 4
>>> a
5
</code></pre>
<p>Why? See <a href="https://stackoverflow.com/questions/9967173/how-to-change-variables-fed-into-a-for-loop-in-list-form">this accepted answer</a>.</p>
<p>Concerning your problem,... | python|pandas|dataframe|loops|reindex | 0 |
365,046 | 67,209,575 | Pandas - list of unique strings in a column | <p>i have a dataframe column which contains these values:
A
A
A
F
R
R
B
B
A
...
I would like to make a list summarizing the different strings, as [A,B,F,...].
I've used groupby with nunique(), but I don't need counting.
How can I make the list ?
Thanks</p> | <p><code>unique()</code> is enough</p>
<pre class="lang-py prettyprint-override"><code>df['col'].unique().tolist()
</code></pre>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.nunique.html" rel="nofollow noreferrer"><code>pandas.Series.nunique()</code></a> is to return the number o... | pandas | 0 |
365,047 | 67,276,456 | Seaborn Box Plot Whiskers Not Matching Calculations | <p>The <code>Q3+1.5*IQR</code> portion of the box plot does not match the actual calculation and trying to figure out why. I show that it should be 10.24 but the plot shows about 8.5. Wondering if I am missing something obvious or something else is going on. I deliberately put <code>whis=1.5</code> as an argument.</p>
... | <p>This is because seaborn flags 10.3 as an outlier. With <code>whis=1.5</code>, this is the outlier threshold:</p>
<pre class="lang-py prettyprint-override"><code>whis = 1.5
q_75 + whis*iqr
# 10.2375
</code></pre>
<p>If you remove value 10.3 (index 17) when computing <code>iqr_pos</code>, you'll also get 8.6 as refle... | python|pandas|matplotlib|seaborn | 0 |
365,048 | 67,539,912 | Reverse operation of torch.cat | <p>Suppose I have a tensor like <code>[A,A,A,A...,A]</code>.</p>
<p>How can I quickly obtain <code>[[A],[A],[A],...,[A]]</code> as a tensor in torch?</p> | <p>You can use <code>torch.chunk</code> as the inverse of <code>cat</code>, but it looks like you want <code>unsqueeze(1)</code>:</p>
<pre class="lang-py prettyprint-override"><code>A = torch.randn(2, 3)
A_rep = (A, A, A, A, A, A, A, A)
catted = torch.cat(A_rep)
#uncatted = torch.chunk(catted, len(A_rep))
catted.unsqu... | python|pytorch|torch | 1 |
365,049 | 67,187,347 | Trying to get players data from nbcsport | <p>i've been trying to scrape this site</p>
<pre><code> import pandas as pd
import requests
from bs4 import BeautifulSoup
r = requests.get("https://www.nbcsports.com/edge/basketball/nba/injury-report")
soup = BeautifulSoup(r.content,"lxml")
st1 = soup.find("div", attrs={... | <pre><code>import requests
import pandas as pd
def main(url):
params = {
"sort": "-start_date",
"filter[player.team.meta.drupal_internal__id]": 176,
"filter[player.status.active]": 1,
"filter[active]": 1,
"include"... | pandas|web-scraping|beautifulsoup | 1 |
365,050 | 67,565,759 | filter in a dataframe by values of another data frame in python (pandas) | <p>i have two data frames:<br />
<strong>df1</strong> :</p>
<pre>
ID COUNT
0 202485 6
1 215893 8
2 181840 8
3 168337 7
</pre>
<p>and another dataframe<br />
<strong>df2</strong>:</p>
<pre>
ID
0 202485
1 215893
2 181840
</pre>
<p>i want to filter /left join the two dataframes:<br />
desired resul... | <pre><code>df1 = pd.DataFrame({'ID':[202485,215893,181840,168337],'COUNT':[6,8,8,7]})
df2 = pd.DataFrame({"ID":[202485,215893,181840]})
out_df = pd.merge(df1,df2)
print(out_df)
</code></pre>
<p>This gives the desired result</p>
<pre><code> ID COUNT
0 202485 6
1 215893 8
2 181840 8
</code></pr... | python|pandas | 0 |
365,051 | 67,275,912 | Pandas Python probelm | <pre><code>import pandas as pd
nba = pd.read_csv("nba.csv")
names = pd.Series(nba['Name'])
data = nba['Salary']
nba_series = (data, index=[names])
print(nba_series)
</code></pre>
<p>Hello I am trying to convert the columns 'Name' and 'Salary' into a series from a dataframe. I need to set the names as the inde... | <p>Maybe try <code>set_index</code>?</p>
<pre><code>nba.set_index('name', inlace = True )
nba_series = nba['Salary']
</code></pre> | python|pandas|dataframe|series | 0 |
365,052 | 67,460,242 | How to select rows with a certain percentage of a string column? (pandas) | <p>I have a dataset with many car brands.
I want to select the brands that take up a certain percentage.
For example %5.</p>
<p>Syntax of what I'm trying to do:
dataframe[(dataframe["brands"] >= %5) & (dataframe["brands"] <= %100)]</p>
<p>But since the brands are strings I can't use that s... | <p>IIUC let's try groupby transform to get the size of each group, divide by the length of the dataframe to get the percentage of the frame the given brand takes up, then filter on that value:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
# Sample Data with
# 50 As, 40 Bs, 5 Cs, 3 Ds, 2 Es
df... | python|pandas|numpy | 0 |
365,053 | 67,468,909 | Acces to last convolutional layer transfer learning | <p>I'm trying to get some heatmaps from a computervision model that's it's already working to classify images but I'm finding some difficulties.
This is the model summary:</p>
<pre><code>model.summary()
</code></pre>
<pre><code>Model: "model_4"
Layer (type) Output Shape Param # ... | <p>I found you can use
<code>.get_layer()</code>
twice to acces layers inside functional densenet model embebeed in the "main" model.</p>
<p>In this case I can use <code>model.get_layer('densenet121').summary()</code> to check all thje layer inside the embebeed model, and then use them with this code: <code>m... | python|tensorflow|keras|heatmap|transfer-learning | 0 |
365,054 | 67,434,627 | How can i split my data in pandas into specified buckets e.g. 40-40-20? | <p>All,</p>
<p>i am trying to split my data into 3 buckets that is 40%, 40% and 20%. How can i do this using pandas?
e.g. so you get the bottom lowest 40%, middle 40% and top 20% :</p>
<pre><code>pd.cut(df['count'], 5,labels = ['1','2','3','4','5'],retbins=True)
</code></pre>
<p>above splits into 5 quintiles, but i wou... | <p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.qcut.html" rel="nofollow noreferrer"><code>qcut</code></a> instead:</p>
<pre class="lang-py prettyprint-override"><code>df["quantile"] = pd.qcut(df["count"], q=[0, 0.4, 0.8, 1],
labels=["lowest", &... | python|pandas|statistics|binning | 2 |
365,055 | 67,295,499 | nesting numpy.where functions | <p>I am adding a few simple data frames together consisting of 1 column and 10 rows. each element in the dataframe can be "1", "0" or "P"</p>
<pre><code>criteria_1 = df['c1] + df['c2'] + df['c3] + df['c4']
criteria_1_mapped = criteria_1.map(lambda x: 'P' if 'P' in x else sum(map(int, list... | <p>IIUC, you can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.select.html" rel="nofollow noreferrer"><code>np.select</code></a> as follows:</p>
<pre class="lang-py prettyprint-override"><code>cond_list = [criteria_1_mapped.str.contains("P"), criteria_1_mapped == 4]
choice_list = ["... | python|pandas|dataframe|numpy | 2 |
365,056 | 67,300,601 | Multiple conditional statements on list comprehension | <p>So this is my code and I want to know if I can use list comprehension to execute the same operation (count the clusters within <strong>rows</strong> and output a list of length <code>df.shape[0]</code>). There are at least two rows for the same cluster number, but it can be more and they cycles. I tried but couldn't... | <p>Do you want this?</p>
<pre><code>from itertools import groupby
result = [0 if index == 0 and key == 0
else index
for index, (key, group) in enumerate(groupby(my_values))
for _ in group
]
print(result)
</code></pre>
<p>Replace my_values in the list comprehension via - df['cl... | python|pandas|list|list-comprehension | 2 |
365,057 | 67,209,659 | pandas: groupby + store in another dataframe | <p>I asked a <a href="https://stackoverflow.com/questions/67139587/pandas-how-to-sum-columns-on-data-frame-based-on-value-of-another-data-frame">similar question</a> last week and now I have a similar issue, but I cannot convert the answer I received in this case.</p>
<p>Basically, I have a dataframe called comms which... | <p>Use <code>groupby()</code> then <code>count()</code> on one column. At last, map the result with <code>articleID</code> columns of <code>arts</code>.</p>
<pre class="lang-py prettyprint-override"><code>arts['commentNumber'] = arts['articleID'].map(comms.groupby('articleID')['Material'].count())
</code></pre>
<pre><c... | python-3.x|pandas|dataframe | 3 |
365,058 | 67,604,103 | Skip rows when loading txt file | <p>I have roughly 8000 gzipped files that are basically .txt files. Each files contains something in the order of 5 million rows. Additionally, each row either has 7 or 10 columns. The number of columns is defined by one column which has the value -1 or 1 respectively.</p>
<p>The thing is I need to load all files, do s... | <p>As the first option, you can read only the 'filter' column and determine which rows you want to keep:</p>
<pre><code>df = pd.read_csv('path', usecols='col')
selector = df[df['col'] != 1].index
df = pd.read_csv('path', skiprows=selector)
</code></pre>
<p>As the second option, your can read data in chunks and filter ... | python|pandas|performance | 2 |
365,059 | 67,251,969 | Python/Numpy: get top k largest values in a 2D matrix as a mask | <p>Let's say I have a 3x3 matrix like this:</p>
<pre><code>array([[8, 6, 3],
[6, 7, 2],
[0, 8, 9]])
</code></pre>
<p>Now I want to get the top k largest values in the matrix, and create a mask from it. If the number is in the top k largest, it has value 1, else 0. Let <code>k=2</code>. In the example abov... | <p>How about this?</p>
<pre class="lang-py prettyprint-override"><code>def is_topk(a, k=1):
_, rix = np.unique(-a, return_inverse=True)
return np.where(rix < k, 1, 0).reshape(a.shape)
</code></pre>
<p>Example on your array:</p>
<pre class="lang-py prettyprint-override"><code>>>> is_topk(a, 1)
array(... | python|arrays|numpy | 1 |
365,060 | 67,427,028 | Duplicating objects in a list such that they repeat | <p>How do I duplicate elements in a lists such that they repeat?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>Input: ListA = [1,2,3,4,5,6,7,8,9]
Output: ListA = [1,1,2,... | <p>We can use <code>np.repeat()</code></p>
<pre><code>ListA = [1,2,3,4,5,6,7,8,9]
ListA = np.repeat([1,2,3,4,5,6,7,8,9], 2)
ListA
</code></pre>
<p><strong>Output</strong></p>
<pre><code>array([1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9])
</code></pre> | python|pandas | 1 |
365,061 | 67,445,064 | How to drop all rows except specific one in pandas? | <p>Is there another, more simple way to drop all table rows except the first one?</p>
<pre><code> df = df.drop([1, 2, 3, 4, 5, 6 ,7 ,8 ,9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45... | <pre><code>df.drop( df.index.to_list()[1:] ,axis = 0 )
</code></pre> | python|python-3.x|pandas|dataframe | 4 |
365,062 | 67,235,505 | Can I find the number of specific numeric data in this MNIST training, test data? | <pre><code>import torchvision.datasets as dsets
import torchvision.transforms as transforms
import torch.nn.init
import torch.nn.functional as F
device = "cuda" if torch.cuda.is_available() else "cpu"
print(device)
learning_rate = 0.001
training_epochs = 15
batch_size = 100
mnist_train = dsets.M... | <p>You can access the data and labels of the dataset, for either split, using the <code>data</code> and <code>targets</code> attributes respectively. So, for example, here you can access the training data and labels using <code>mnist_train.data</code> and <code>mnist_train.labels</code> respectively.</p>
<p>Since the <... | python|machine-learning|pytorch | 1 |
365,063 | 67,438,164 | How to make stacked line chart with different y-axis in matplotlib? | <p>I am wondering how should I make stacked line chart which is gonna take different columns in matplotlib. The point is when we are doing aggregation, I need to do data aggregation on two different columns, I think I need to make one big dataframe that will be used for plotting. I didn't find prettier and handy way to... | <p>Pandas groupby feature is very versatile, and you can reduce the lines of code considerably to achieve the final dataframe for plotting.</p>
<pre><code>plotdf = df_re.groupby([ 'retail_item',df_re['date'].dt.year,df_re['date'].dt.week]).agg({'number_of_ads':'sum','price_gap':'mean'}).unstack().T
</code></pre>
<p>Onc... | python|pandas|matplotlib|seaborn | 4 |
365,064 | 67,355,618 | python - numpy array gets imported as str using read_csv() | <p>I am importing a df like</p>
<pre><code>dbscan_parameter_search = pd.read_csv('./src/temp/05_dbscan_parameter_search.csv',
index_col=0)
type(dbscan_parameter_search['clusters'][0])
</code></pre>
<p>which results in <code>str</code>.</p>
<p>How can I keep the datatype as numpy a... | <p>Thanks to hpaulj, the problem was rather the export but the import. String was literally saved with dots. For quick workaround see here:
<a href="https://stackoverflow.com/questions/67379614/python-how-to-to-csv-with-an-column-of-arrays#67379827">python - how to to_csv() with an column of arrays</a></p> | python-3.x|numpy | 0 |
365,065 | 67,394,705 | Open excel file in Python: XLRDError: Excel xlsx file; not supported | <p>I want to open an Excel file in Python, using:</p>
<pre><code>import xlrd
loc = (r"C:\Users\my_path\my_file.xlsx")
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
sheet.cell_value(0, 0)
</code></pre>
<p>and it caught error:</p>
<pre><code>--------------------------------------------------------... | <p>The lastest version of xlrd is only support .xls file, so you can install the older version</p>
<pre><code>pip uninstall xlrd
pip install xlrd==1.2.0
</code></pre> | python|excel|pandas | 9 |
365,066 | 67,306,126 | How to continue training serialized AllenNLP model using `allennlp train`? | <p>Currently training models using AllenNLP 1.2:</p>
<pre><code>allennlp train -f --include-package custom-exp /usr/training_config/mock_model_config.jsonnet -s test-mock-out
</code></pre>
<p>The config is very standard:</p>
<pre><code>"dataset_reader" : {
"reader": "params"
... | <p>OK, so to continue the training, one solution is to load the model <code>from_archive</code>. Assuming you have the serialization directory, make a <code>model.tar.gz</code> archive of the folder. Then, you can make a new config that is identical, except for the <code>model</code> key which uses <code>from_archive... | machine-learning|pytorch|transfer-learning|allennlp | 1 |
365,067 | 67,227,864 | AttributeError: module 'tensorflow_estimator.python.estimator.api._v1.estimator' has no attribute 'inpus' | <p>I am trying to use linear classifier to predict, the constructing and training of the estimator is listed here:</p>
<pre><code>model = tf.estimator.LinearClassifier(
n_classes = 2,
model_dir = "ongoing",
feature_columns = categorical_features + continuous_features
(
FEATURES = ['Age', 'Gender', 'ICD9... | <p>Your issue can be resolved if you can change <code>tf.estimator.inpus.numpy_input_fn</code> to <code>tf.estimator.inputs.numpy_input_fn</code>. It's typo error.</p>
<pre><code>import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import json
import os
import... | python|tensorflow|tensorflow-estimator | 0 |
365,068 | 34,702,338 | replace string in pandas dataframe | <p>I have a dataframe with multiple columns. I want to look at one column and if any of the strings in the column contain @, I want to replace them with another string. How would I go about doing this?</p> | <p>A dataframe in pandas is composed of columns which are series - <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html" rel="noreferrer">Panda docs link</a></p>
<p>I'm going to use regex, because it's useful and everyone needs practice, myself included! <a href="http://pandas.pydata.org/pandas-docs/vers... | python|pandas|replace|dataframe | 7 |
365,069 | 34,479,794 | python np.c_ error"CClass object is not callabel" | <p>I'm using ipython 4.0.1 and python 3.5.1, when I call np.c_(), it shows an error</p>
<pre><code>CClass object is not callable.
</code></pre>
<p>This is my code:</p>
<pre><code>import numpy as np
rows = []
with open('ntumlone.dat') as f:
rows = [list(map(float, L.split())) for L in f]
arr = np.array(rows)
... | <p>Try</p>
<pre><code>date = np.c_[np.ones(len(arr)), arr]
</code></pre>
<p>Check its docs. You 'call' it with square brackets, as though you are indexing, not with <code>()</code>. If the distinction is too confusing stick with <code>concatenate</code> or one of the <code>stack</code> functions. I think in this us... | python|numpy | 18 |
365,070 | 34,447,448 | StringIO and pandas read_csv | <p>I'm trying to mix StringIO and BytesIO with pandas and struggling with some basic stuff. For example, I can't get "output" below to work, whereas "output2" below does work. But "output" is closer to the real world example I'm trying to do. The way in "output2" is from an old pandas example but not really a useful... | <p><code>io.StringIO</code> here is behaving just like a file -- you wrote to it, and now the file pointer is pointing at the end. When you try to read from it after that, there's nothing after the point you wrote, so: no columns to parse.</p>
<p>Instead, just like you would with an ordinary file, <code>seek</code> t... | python|pandas | 65 |
365,071 | 34,457,239 | NumPy 2D array Ordinary Slicing vs Boolean based Slicing | <p>I am new to Numpy, and I was experimenting with 2D Arrays Numpy,
I made the following observations when an array is sliced in 2 different ways</p>
<pre><code>a = numpy.array([[1,2,3,4,5],[1,2,3,4,5]])
slice1 = a[:,:3]
slice1[0,0] = 100
print(a)
-- gives, 100 2 3 4 5
1 2 3 4 5
</code></pre>
<p>This be... | <p>From the <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/arrays.indexing.html" rel="nofollow">NumPy indexing documentation</a>:</p>
<blockquote>
<p>Advanced indexing always returns a <em>copy</em> of the data (contrast with basic slicing that returns a <a href="http://docs.scipy.org/doc/numpy-1.10.0/glo... | python|arrays|numpy | 2 |
365,072 | 34,550,289 | calculating 2D rms in python | <p>I have a Nx2 array that stores the x,y coordinates of N different points. I have to calculate the spread of the data (I'm thinking of the rms). Are there any functions in scipy that do this job? If not, what is the most efficient way to compute this?</p> | <p><a href="https://en.wikipedia.org/wiki/Root_mean_square#Relationship_to_the_arithmetic_mean_and_the_standard_deviation" rel="nofollow">The root mean square is the standard deviation</a>:</p>
<pre><code>In [100]: np.random.seed(2015)
In [101]: A = np.random.random((10,2))
In [102]: A
Out[102]:
array([[ 0.73759523... | python|arrays|numpy|scipy|statistics | 1 |
365,073 | 34,762,505 | Inception style convolution | <p>I have the necessity to keep the model as small as possible to deploy an image classifier that can run efficiently on an app (the accuracy is not really relevant for me)</p>
<p>I recently approached deep learning and I haven't great experience, hence I'm currently playing with the cifar-10 example.
I tried to repla... | <p>It seems you're attempting to compute 64 features (for each 3x3 patch) in the first convolutional layer and feed this directly into the second convolutional layer, with no intermediate pooling layer. Convolutional neural networks typically have a structure of stacked convolutional layers, followed by contrast normal... | deep-learning|tensorflow|conv-neural-network | 2 |
365,074 | 34,505,529 | Creating binned histograms in Spark | <p>Suppose I have a dataframe (df) (Pandas) or RDD (Spark) with the following two columns: </p>
<pre><code>timestamp, data
12345.0 10
12346.0 12
</code></pre>
<p>In Pandas, I can create a binned histogram of different bin lengths pretty easily. For example, to create a histogram over 1 hr, I do the following:<... | <p><strong>Spark >= 2.0</strong></p>
<p>You can use <code>window</code> function</p>
<pre><code>from pyspark.sql.functions import window
(df
.groupBy(window("timestamp", "3 minute").alias("ts"))
.sum()
.orderBy("ts")
.show())
## +--------------------+---------... | python|pandas|apache-spark|histogram|pyspark | 3 |
365,075 | 34,565,283 | How to reassign numpy indices after linear transformation | <p>Suppose I have rotated all the indices of a numpy array by an angle (matrix mult with rotation matrix). </p>
<p>These rotated indices are in a tensor of dimensions (width_img*height_img,2) (assume width= height for this case) where img is the numpy array.</p>
<p>Is there a way of of using these indices to rotate t... | <p>Not sure this reflects what you need, but following this answer
<a href="https://stackoverflow.com/questions/15920070/increment-given-indices-in-a-matrix">increment-given-indices-in-a-matrix</a>, you should consider using ravel:</p>
<pre><code>import numpy as np
m = np.array([0,1,2,3]).reshape(2,2)
indices_r90 = n... | python|numpy | 2 |
365,076 | 60,110,807 | Replace multiple characters from one column with NaN in Python | <p>I want to replace the position words from <code>strings</code> column: if they are either present sole or in multiple but join with <code>,</code> and <code>space</code>.</p>
<pre><code> id strings
0 1 south
1 2 north
2 3 ... | <p>First use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>Series.str.split</code></a>, forward filling for replace missing values, test if all matched values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.D... | python|regex|pandas|dataframe|replace | 2 |
365,077 | 60,332,014 | Setting values to MultiIndex DataFrame is getting slow while running | <p>I have a <code>11729 rows × 8 columns</code> DataFrame, I'd like to convert it to a <code>11729 × 30 × 8</code> matrix with MultiIndex, which 30 means every 30 lines of 11729 rows from 0 to <code>11728 - 30</code></p>
<p>for a shorter example:</p>
<p>the origin 2d DataFrame looks like:</p>
<pre><code> col0 ... | <p>You should not be adding one by one. Here's what I would do:</p>
<pre><code># toy data:
df = pd.DataFrame(np.arange(11792*8).reshape(-1,8));
window = 30
new_len = len(df) - window + 1
# create new dataframe, ignoring the index
new_df = pd.concat(df.iloc[i:i+window] for i in range(new_len))
# modify the index
new_... | pandas|dataframe | 1 |
365,078 | 60,315,524 | QueryItems azure-cosmos package | <p>I'm trying to query a cosmos db and store a table into a pandas data frame (or just as a list, the problem is the same), using the following code</p>
<pre><code>table_link= 'dbs/'+database_name+'/colls/'+container_name
query= 'SELECT * FROM '+container_name
df=pd.DataFrame(client.QueryItems(table_link,query,
... | <p>Please check the <code>Target API</code> for your Cosmos DB account. More than likely it is <code>Table API</code>. If the API is not SQL API, you will need to use the SDK specific for a particular API of Cosmod DB account.</p> | python|pandas|azure|dataframe|azure-cosmosdb | 1 |
365,079 | 59,915,163 | pandas sort_index documentation | <p>the <a href="http:///https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_index.html" rel="nofollow noreferrer">documentation</a> for DataFrame.sort_index is:</p>
<p><em>DataFrame.sort_index(self, axis=0, level=None, ascending=True, inplace=False, kind='quicksort', na_position='last', so... | <p>Per source code...</p>
<blockquote>
<p>"if by is not None:</p>
<p>warnings.warn(</p>
<p>"by argument to sort_index is deprecated, "</p>
<p>"please use .sort_values(by=...)"</p>
</blockquote> | python|pandas|sorting|documentation | 0 |
365,080 | 60,013,241 | Bad shape in LSTM model | <p>I'm using <strong><em>tensorflow js</em></strong> and I have this code to build my model of recurrent neural network to a classification problem with 3 classes, instances of size 250, .
I have the following error message when I try to fit my model:</p>
<p><strong><em>Error: Error when checking target: expected dens... | <p>You need to change the layers dimension by returning <code>false</code> to the lstm layer</p>
<pre><code>model.add(tensorflow.layers.lstm({units: embeddingSize, returnSequences: false}));
</code></pre> | tensorflow.js | 1 |
365,081 | 60,029,829 | function to get month values N-(x) from today's month in a dataframe | <p>I have been spending hours trying to write a function to detect trend in a time series by taking the past 4 months months of data prior to today. I organized my monthly data with dt.month but the issue is that I cannot get the previous year's 12th month if today is january. Here is a toy dataset:</p>
<pre><code>dat... | <p>I don't think you need <code>check_trend()</code>. </p>
<p>There are built-in functions for this:<br>
<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.is_monotonic_increasing.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.is_m... | python|pandas | 1 |
365,082 | 60,263,064 | Merge Multi-Index Pandas Data Frames | <p>I have three multi-index Pandas data frames -</p>
<pre><code>df1 = {('parity', np.nan): {('20194', 1990): 0.3333333333333333,
('22204', 1990): 0.0,
('24060', 1990): 0.3333333333333333},
('parity', 0.0): {('20194', 1990): 0.0,
('... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> with <code>MultiIndex</code> with levels <code>zip</code> and <code>year</code> in index and <code>MultiIndex</code> with 2 levels in columns:</p>
<pre><code>#convert columns ... | python|pandas | 2 |
365,083 | 60,038,442 | GroupBy and Sum with a RangeIndex | <p>I'm reading in a CSV with wide data, which I convert to long data. The data contains daily values for all of 2020. I'm trying to aggregate this by month and sum. This is what I have tried:</p>
<pre><code>import pandas as pd
df = pd.read_csv('Notebooks/updated_predicted_data.csv', parse_dates=['Unnamed: 0'])
df.rena... | <p>You can add <code>key</code> parameter in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Grouper.html" rel="nofollow noreferrer"><code>Grouper</code></a> for pass column name of datetimes with <code>name</code> column in list and added aggregation function <code>sum</code>:</p>
<pre><code... | python-3.x|pandas | 1 |
365,084 | 59,929,398 | How to remove portion of string after certain character for each element of a Pandas series (or list)? | <p>I have a Pandas series like ['AAA.B', 'BBB.C', 'CCC.D']. I want to remove the portion of each string after the period, inclusive. In other words, the desired result here would be ['AAA', 'BBB', 'CCC']. I can't figure out how to do it without iterating through each element one at a time to operate on them individuall... | <p>Using <code>str.split</code></p>
<p><strong>Ex:</strong></p>
<pre><code>s = pd.Series( ['AAA.B', 'BBB.C', 'CCC.D'])
print(s.str.split(".").str[0])
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>0 AAA
1 BBB
2 CCC
dtype: object
</code></pre> | python|pandas|split | 2 |
365,085 | 59,933,918 | Rolling sum then get random int using this rollingsum | <p>I have this Dataframe:</p>
<pre><code> Date A
0 2014-11-21 11:00:00 1
1 2014-11-21 11:00:03 2
2 2014-11-21 11:00:04 5
3 2014-11-21 11:00:05 3
4 2014-11-21 11:00:07 9
5 2014-11-21 11:00:08 6
6 2014-11-21 11:00:10 3
7 2014-11-21 11:00:11 1
8 2014-10-24 10:00:55 8
9 2014-10-24 10:... | <p>The newest developer version of <code>numpy</code> could do this out of the box, but since you likely do not have that, what you need is a vectorized version of <code>np.random.randint</code>:</p>
<pre><code>>>> def randint(x):
... return np.random.randint(-x, x)
...
>>> np.vectorize(randint)(df.... | python|pandas | 1 |
365,086 | 59,976,809 | How to sequence row based on another row? | <p>I am trying to convert a formula from excel to pandas.</p>
<p>The DataFrame looks like this: </p>
<pre><code>Column A Column B
H
H
H
J
J
J
J
K
K
</code></pre>
<p>I want to fill column B to increment while the value in column A remains the same. In the example above, this would be:</p>
<pre... | <p>This can be done using the following vectorised method:</p>
<p><strong>Code:</strong></p>
<pre><code>>>> df = pd.DataFrame({'A':['H', 'H', 'H', 'J', 'J', 'J', 'J', 'K', 'K']})
>>> df['B'] = df.groupby((df['A'].shift(1) != df['A']).cumsum()).cumcount() + 1
</code></pre>
<p><strong>Output:</strong... | python|excel|pandas|dataframe|sequence | 0 |
365,087 | 60,079,986 | Matplotlib is printing the line plot twice/multiple times | <p>What could be the problem if Matplotlib is printing a line plot twice or multiple like this one:</p>
<p><a href="https://i.stack.imgur.com/ScWtl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ScWtl.png" alt="enter image description here"></a></p>
<p>Here is my code:</p>
<pre><code>import panda... | <p>This is because plotting <code>df[1:]</code> is plotting the entire dataframe as the x-axis. </p>
<pre><code>>>> df[1:]
Wavelength Blue Green Red NIR Pan
1 355 0.001463 0.000800 0.000504 0.000532 0.000619
2 360 0.000866 0.000729 0.000391 0.000674... | python|pandas|dataframe|matplotlib|scipy | 1 |
365,088 | 60,109,045 | How to divide multilevel columns in Python | <p>I have a df like this:</p>
<pre><code>arrays = [['bar', 'bar', 'baz', 'baz'],
['one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(3, 4), index=['A', 'B', 'C'], columns=index)
df.head()
</code></p... | <p>You can select both levels by only one <code>[]</code>:</p>
<pre><code>df1 = df["bar"]/df["baz"]
print (df1)
second one two
A 1.564478 -0.115979
B 14.604267 -19.749265
C -0.511788 -0.436637
</code></pre>
<p>If want add <code>MultiIndex</code> add <a href="http://pandas.pydata.org... | python-3.x|pandas|hierarchy | 2 |
365,089 | 60,106,364 | "SyntaxError: invalid syntax" when using lambda function in pandas.apply | <p>Thanks for helping me today with my question.</p>
<p>I have a df like this below
<a href="https://i.stack.imgur.com/ZzDSd.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>As you can see there is dict type in the column <strong>value</strong></p>
<p>There are three keys for these dict in the ... | <p>When you use <code>if</code> in an expression, you <strong>must</strong> write an <code>else</code> clause too. For example:</p>
<pre class="lang-py prettyprint-override"><code>>>> x = 5
>>> 1 if x > 0 else 0
1
>>> 1 if x > 0
File "<stdin>", line 1
1 if x > 0
... | python|pandas|lambda | 0 |
365,090 | 60,092,000 | Tensorflow Serving Model Server continuously re-adding the same models when polling s3 for config file | <p>I am using Tensorflow Serving to run models which are stored in an s3 bucket. I am also keeping the model config file in a separate s3 bucket. My use case is that in order to dynamically add models without needing to restart the server I will poll this config file for changes periodically.</p>
<p>In order to do thi... | <p>This all looks normal.</p>
<p>Looking at the code <a href="https://github.com/tensorflow/serving/blob/master/tensorflow_serving/model_servers/server_core.cc" rel="nofollow noreferrer">(server_core.cc)</a>, it seems that these messages are displayed when reading the model.config file rather than when loading the mod... | tensorflow-serving | 1 |
365,091 | 59,916,568 | What is the equivalent R code for this TensorFlow program in Python? | <p>I am working on learning to solve equations in R and I am interested in doing it through TensorFlow (I already know how to do it using GA and Simulated Annealing).
I am building equivalent code in R for this python program which does Y = X + Z and solves for Z (found it in this <a href="https://medium.com/@liccowee/... | <p>Getting gradient is relatively easy, applying them to variable I cannot quite figure out how to do it on tf$Variable.. Maybe this still can help:</p>
<pre><code>library(tensorflow)
optimizer <- tf$keras$optimizers$Adam(0.001)
x = tf$constant(c(1.,2.))
y = tf$constant(c(12,4))
Z = tf$Variable(tf$zeros(2,1))
w... | python|r|tensorflow|keras|rstudio | 0 |
365,092 | 60,129,783 | Tensorflow object detection in C++ | <p>I've been training object detection models in the last few days mainly with tensorflow and yolov3.
Projects:</p>
<ul>
<li><a href="https://github.com/EdjeElectronics/TensorFlow-Object-Detection-API-Tutorial-Train-Multiple-Objects-Windows-10" rel="nofollow noreferrer">Tensorflow GPU object detection models</a></li>
... | <p><a href="https://www.tensorflow.org/tfx/serving/docker" rel="nofollow noreferrer">Tensorflow Serving</a> provides HTTP REST and gPRC APIs for using trained models without any conversion. I used it in Java-based project, but you can use it in C++ as well (Tensorflow Serving is written in C++, by the way).</p> | c++|tensorflow|object-detection | 1 |
365,093 | 60,062,491 | Trying to do SDV (Synthetic Data Vault) demo and getting error: TypeError: cannot astype a datetimelike from [datetime64[ns]] to [int32] | <p>I'll start by saying I am NOT a Python developer. But I have a need for synthetic data and was trying to use the Synthetic Data Vault (<a href="https://github.com/sdv-dev/SDV" rel="nofollow noreferrer">https://github.com/sdv-dev/SDV</a>). </p>
<p>I have Python 3.7 installed (on Windows, I'm doing this right on my... | <p>Actually, I found a solution - not being a Python developer, not sure if it's the best solution but it cleared up the error.</p>
<p>In the datetime.py code on line 41, I changed:</p>
<pre><code>integers = datetimes.astype(int).astype(float).values
</code></pre>
<p>to</p>
<pre><code>integers = datetimes.astype(np... | python|pandas|sdv | -1 |
365,094 | 59,996,593 | How to check if time delta is greater than one minute in a dataframe? | <p>I am trying to compare different time stamps in a dataframe and print an output when time difference is greater than one minute. This is the code I am trying to run:</p>
<pre><code>for e in TestDF['date']:
delta = TestDF.date.iloc[e+1] - TestDF.date.iloc[e]
if delta > datetime.timedelta(minutes=1):
... | <p>You just need to use a combination of shift and boolean filtering:</p>
<p>note i've changed your last row to show a difference bigger than 1 minute.</p>
<pre><code>print(df)
date open high low close
0 2020-01-28 07:00:00 311.83 311.89 311.62 311.81
1 2020-01-28 07:01:00 311.80 31... | python|pandas|finance | 1 |
365,095 | 60,072,782 | find dataframe2 colum in dataframe1 column similar to the sql like operator and list the result from dataframe2 using pandas | <pre><code>import pandas as pd
xls1='C:\\Downloads\\Allparts.xlsx'
df = pd.read_excel(xls1,sheet_name='Data')
df=df['Part Number'].head(10)
xls2='C:\\Downloads\\Part_Details.xlsx'
dz = pd.read_excel(xls2,sheet_name='Data')
dz=dz.drop(dz.columns[[2, 4]], axis = 1)
dz=dz.drop(dz.columns[[3, 4, 5]], axis = 1)
for ... | <h1>Below code solved my purpose. Hope it helps others.</h1>
<p>fdf=pd.dataframe()</p>
<p>for zd in dz['Name']:</p>
<pre><code> for fd in df['Part Number']:
if str(zd) in str(fd):
res=df[df['Part Number']==fd]
fdf = pd.concat([fdf, res], axis=0)
</code></pre> | python|pandas|dataframe | 0 |
365,096 | 60,285,334 | How to freeze a layer's weights for some number of iterations? | <p>I'm trying to train two MLP's jointly, each one to predict a different real-valued variable. I want to minimize a loss over these two outputs, but I want to fix one of them for some number of "warm-up" iterations. </p>
<p>I'm new to tensorflow, but basically I'm looking for the equivalent of something like this in ... | <p>I ended up doing the following:</p>
<p>In a main loop, </p>
<pre><code>mlp = UncertaintyMLP(805, 1)
loss_fn = GaussianNLL()
optimizer = tf.keras.optimizers.Adam(learning_rate=1e-3)
epochs = 1000
for epoch in range(epochs):
for step, (x_batch, y_batch) in enumerate(train_dataset):
... | python-3.x|tensorflow | 0 |
365,097 | 60,004,482 | Why do I get this graph disconnected error? | <p>I'm trying to create a densenet but when I try to compile the model I get this error message. Here's my model:</p>
<pre><code>from tensorflow import keras
from keras.utils import plot_model
dropoutRate = 0.2
def globalAvgPooling(x):
height = np.shape(x)[2]
width = np.shape(x)[1]
poolSize = [width, height]
... | <p>The error comes from the line:</p>
<pre><code>x = tf.keras.layers.BatchNormalization()(inputs=inputX, training=self.training)
</code></pre>
<p>as I think you have a bad <code>inputs</code> parameter in it.
It should looks like:</p>
<pre><code>x = tf.keras.layers.BatchNormalization()(inputs=x, training=self.traini... | python|tensorflow|keras|deep-learning | 0 |
365,098 | 60,095,370 | Fill the values with each column combination with some default values in pandas data frame | <p>I have a dataframe like this,</p>
<pre><code>df
col1 col2 col3
1907 CD 49
1907 FR 33
1907 SA 34
1908 PR 1
1908 SA 37
1909 PR 16
1909 SA 38
</code></pre>
<p>Now CD is not present with col1 1908 and 1909 values, FR not present with 1908 and 1909 v... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.unstack.html" rel="nofollow noreferrer"><code>DataFrame.unstack</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>DataFrame.stack</code... | python|pandas|dataframe | 2 |
365,099 | 59,970,510 | Dropconnect implementation in pytorch | <p>I am trying to code dropconnect for Conv2D and transposeconv2D layer. Followed the tutorial in <a href="https://pytorchnlp.readthedocs.io/en/latest/_modules/torchnlp/nn/weight_drop.html" rel="nofollow noreferrer">https://pytorchnlp.readthedocs.io/en/latest/_modules/torchnlp/nn/weight_drop.html</a> to create it. </p>... | <p>I couldn't quite get that method to work either (had a different error though), but here's a simpler method that seems to be working:</p>
<pre><code>for i in range(num_batches):
orig_params = []
for n, p in model.named_parameters():
orig_params.append(p.clone())
p.copy_(F.dropout(p.data, p=... | deep-learning|pytorch | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.