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 |
|---|---|---|---|---|---|---|
1,800 | 42,804,939 | Functional API Keras alternate solution for predict_classes() | <p>Please refer <a href="https://stackoverflow.com/questions/42440274/training-on-the-merged-layer-in-keras">here</a> for my previous question for background information. As per <a href="https://stackoverflow.com/a/42456188/7103753">answer</a> suggested by <a href="https://stackoverflow.com/users/7137636/nassim-ben">Na... | <p>Nassim answer is great but I want to share with you the experience I have with similiar tasks:</p>
<ol>
<li><strong>Never use <code>predict_proba</code> Keras</strong> for version. <a href="https://stackoverflow.com/questions/41716380/keras-output-of-model-predict-proba/41729210#41729210">Here</a> you could find wh... | python|tensorflow|deep-learning|keras|convolution | 2 |
1,801 | 42,818,202 | TensorFlow GPU Support Mac - OpenCL | <p>Does <code>TensorFlow</code> have GPU support for a late 2015 <code>mac</code> running an <code>AMD Radeon R9 M370X</code></p>
<pre><code>AMD Radeon R9 M370X:
Chipset Model: AMD Radeon R9 M370X
Type: GPU
Bus: PCIe
PCIe Lane Width: x8
VRAM (Total): 2048 MB
Vendor: ATI (0x1002)
Device ID: 0x6821
Revision ... | <p>OpenCL is currently not supported.</p>
<p>You can follow the progress here: <a href="https://github.com/tensorflow/tensorflow/issues/22" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/issues/22</a></p> | macos|tensorflow | 1 |
1,802 | 42,624,350 | Adding two matrix with different dimension | <p>Let <code>A</code> be a matrix with <code>[m x n]</code> elements and <code>B</code> another matrix with <code>[m x n x o]</code> elements.
Is there any linear algebraic way to add both matrices such that <code>C = A + B</code> where <code>C</code> will be in <code>[m x n x o]</code> without any sort of looping alon... | <p>In MATLAB this can be done using implicit expansion (R2016b onward) or <code>bsxfun(@plus,...)</code>. </p>
<p>The following would work in all recent MATLAB versions:</p>
<pre><code>C = bsxfun(@plus,A,B);
</code></pre>
<p>In NumPy, this behavior is known as "broadcasting".</p> | python|matlab|numpy|multidimensional-array|linear-algebra | 5 |
1,803 | 27,321,489 | Trouble accessing column in pandas dataframe | <p>I created a DataFrame like so:</p>
<pre><code>stock_data = pd.read_csv('http://www.google.com/finance/historical?output=csv&q=AAPL')
</code></pre>
<p>It has a <code>Date</code> column but when I call <code>stock_data['Date']</code> I get a key error.
How do I access the date for each row?</p> | <p>It looks like some junk (in particular, a UTF-8 BOM) found its way into that column name:</p>
<pre><code>In [16]: stock_data = pd.read_csv('http://www.google.com/finance/historical?output=csv&q=AAPL')
In [17]: stock_data.columns
Out[17]: Index([u'Date', u'Open', u'High', u'Low', u'Close', u'Volume'], dtype='ob... | python|python-2.7|pandas | 2 |
1,804 | 27,284,749 | Timedelta error; version 0.15.1-=np19py27_0 | <p>This problem was asked at:</p>
<p><a href="https://stackoverflow.com/questions/15149265/pandas-timedelta-error">pandas Timedelta error</a></p>
<p>However, the solution (to get the latest version of pandas) did not work for me. </p>
<p>I've got the same problem (installed using anaconda, on Windows 7), and trying ... | <p>I had this problem recently, and it turned out to be because I had recently used conda to install some packages from the command prompt, but had forgetten to launch the command prompt as administrator.</p>
<p>In my case I was able to fix the problem by launching command prompt as administrator, and reinstalling the... | pandas|timedelta | 2 |
1,805 | 27,263,805 | Pandas column of lists, create a row for each list element | <p>I have a dataframe where some cells contain lists of multiple values. Rather than storing multiple
values in a cell, I'd like to expand the dataframe so that each item in the list gets its own row (with the same values in all other columns). So if I have:</p>
<pre><code>import pandas as pd
import numpy as np
df = ... | <h2>Pandas >= 0.25</h2>
<p>Series and DataFrame methods define a <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html#pandas.DataFrame.explode" rel="noreferrer"><strong><code>.explode()</code></strong></a> method that explodes lists into separate rows. See the docs section ... | python|pandas|list | 148 |
1,806 | 27,061,168 | Inverse of a symmetric matrix | <p>An inverse of a real symmetric matrix should in theory return a real symmetric matrix (the same is valid for Hermitian matrices). However, when I compute the inverse with numpy or scipy the returned matrix is asymmetric. I understand that this is due to numerical error.</p>
<p>What is the best way to avoid this asy... | <p>Luckily for you, this inverse is symmetric. Unluckily for you you can't compare floating points this way:</p>
<pre><code>>>> import numpy as np
>>>
>>> n = 1000
>>> a =np.random.rand(n, n)
>>> a_symm = (a+a.T)/2
>>>
>>> a_symm_inv = np.linalg.inv(a_sy... | python|arrays|numpy|scipy | 1 |
1,807 | 30,691,797 | Writing and Reading numpy objects an plain text | <p>In Python, I would like to store numpy arrays, matrices and possibly later other objects in plain text format.</p>
<p>My idea was to use ConfigParser and define parser <code>array2string</code>, <code>matrix2string</code>, <code>string2array</code> and <code>string2matrix</code> (there is <code>numpy.array2string</... | <p>Answer in this post gives a nice function which works well:</p>
<p><a href="https://stackoverflow.com/questions/35612235/how-to-read-numpy-2d-array-from-string">how to read numpy 2D array from string?</a></p>
<pre><code>import configparser
import re
import ast
import numpy as np
def str2array(s):
# Remove sp... | python|python-2.7|numpy | 0 |
1,808 | 39,111,347 | How do I convert a MultiIndex to type string | <p>consider the MultiIndex <code>idx</code></p>
<pre><code>idx = pd.MultiIndex.from_product([range(2013, 2016), range(1, 5)])
</code></pre>
<p>When I do</p>
<pre><code>idx.to_series().str.join(' ')
</code></pre>
<p>I get</p>
<pre><code>2013 1 NaN
2 NaN
3 NaN
4 NaN
2014 1 NaN
2 ... | <p>Something like this?</p>
<pre><code>idx.to_series().apply(lambda x: '{0}-{1}'.format(*x))
</code></pre> | python|pandas|multi-index | 5 |
1,809 | 39,253,672 | pandas.DataFrame.query keeping original multiindex | <p>I have a dataframe with multiindex:</p>
<pre><code>>>> df = pd.DataFrame(np.random.randint(0,5,(6, 2)), columns=['col1','col2'])
>>> df['ind1'] = list('AAABCC')
>>> df['ind2'] = range(6)
>>> df.set_index(['ind1','ind2'], inplace=True)
>>> df
col1 col2
ind1 i... | <p><code>df.loc[A]</code> returns you a DF (or a "view") with a regular ("single") index:</p>
<pre><code>In [12]: df.loc['A']
Out[12]:
col1 col2
ind2
0 1 1
1 0 3
2 1 2
</code></pre>
<p>so <code>.query()</code> will be applied on that DF with a regular index...</p> | python|pandas|dataframe|multi-index | 1 |
1,810 | 39,335,149 | if negative then with weighted average | <p>I have a DataFrame:</p>
<pre><code>a = {'Price': [10, 15, 20, 25, 30], 'Total': [10000, 12000, 15000, 14000, 10000],
'Previous Quarter': [0, 10000, 12000, 15000, 14000]}
a = pd.DataFrame(a)
print (a)
</code></pre>
<p>With this raw data, i have added a number of additional columns including a weighted average pric... | <p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.cummax.html" rel="nofollow"><code>cummax</code></a>: </p>
<pre><code>a['WAP'] = (a['Cum Sum Amount'] / a['Total']).cummax()
print (a['WAP'])
0 10.000000
1 10.833333
2 12.666667
3 12.666667
4 12.666667
Name: W... | python|pandas | 3 |
1,811 | 38,965,471 | How to slice pandas DataFrame by disjunction statement (logical "or")? | <p>I would like to slice a <code>pandas.DataFrame</code> which satisfies condition A <strong>or</strong> condition B. Most of the search results only show how to slice dataframe using <strong>"and"</strong>. So I wonder if it is possible to use <strong>"or"</strong> operator without converting (A and B) to (not (not A ... | <p>You need to use the logical or symbol <code>|</code></p>
<pre><code>df[(df['c1'] == x1) | (df['c2'] == x2)]
</code></pre>
<p>For <code>and</code>, you would need to use <code>&</code> </p>
<pre><code>df[(df['c1'] == x1) & (df['c2'] == x2)]
</code></pre> | python|pandas|dataframe | 11 |
1,812 | 33,695,157 | .eigenvals creates a new variable | <p>I'm calculating the eigenvalues of a matrix with the .eigenvals() function. When I do so for my matrix, a new variable that I never declared occurs in the solution and I don't know where it comes from, nor do I expect it to happen, but it definitly influences the solution.
I have the problem with numpy and sympy.
He... | <p><code>I</code> is the imaginary unit <code>sqrt(-1)</code>.</p>
<pre><code>>>> from sympy import I
>>> complex(I)
1j
</code></pre>
<p>For example,</p>
<pre><code>>>> from sympy import poly
>>> from sympy.abc import x
>>> p = poly(x**2 + 1)
>>> p.root(0)
-I
>... | python|python-2.7|numpy|sympy|eigenvalue | 2 |
1,813 | 22,592,163 | solve an integral equation by python | <p>I need to solve an integral equation by python 3.2 in win7.</p>
<p>I want to find an initial guess solution first and then use "fsolve()" to solve it in python.</p>
<p>This is the code:</p>
<pre><code>import numpy as np
from scipy.optimize.minpack import fsolve
from cmath import cos, exp
from scipy.integrate.quad... | <p>Just made the following change and it should work (it worked for me).</p>
<p>remove:</p>
<pre><code>from cmath import exp, cos
</code></pre>
<p>include:</p>
<pre><code>from numpy import exp, cos
</code></pre>
<p>as explained in the comments, the <code>cmath</code> functions accept only <code>float</code> inputs... | python|python-3.x|numpy|scipy | 3 |
1,814 | 62,417,486 | Count ids based by occurence and on sequencial order Pandas | <p>Current dataset:</p>
<pre><code>month ID Bool
1 333 0
2 444 0
3 111 0
4 222 0
5 999 0
6 111 1
7 111 1
8 111 1
9 222 1
10 555 1
11 666 1
12 777 1
</code></pre>
<p>Two things need to be defined in one column named level... | <p>You can do <code>cumcount</code> with <code>reversed</code> order </p>
<pre><code>df['level']=df.iloc[::-1].groupby('ID').cumcount()
df
Out[66]:
month ID Bool Level level
0 1 333 0 0 0
1 2 444 0 0 0
2 3 111 0 4 4
3 4 222 0 1 ... | python|pandas | 1 |
1,815 | 62,345,730 | Python: I have 1000 x values and need corresponding y values | <p>I have this vector <code>x=np.linspace(0,100,1000)</code>, and a function: </p>
<pre><code>(-1/(math.log(2)/5700))*math.log(x/100)
</code></pre>
<p>How can I calculate the corresponding <code>y</code> values and put them in a vector?</p> | <p>Use <a href="https://numpy.org/doc/1.18/reference/generated/numpy.log.html" rel="nofollow noreferrer"><code>np.log</code></a> instead of <code>math.log</code> for a vectorised approach, specially given that you're already using numpy:</p>
<pre><code>y = (-1/(np.log(2)/5700))*np.log(x/100)
</code></pre> | python|list|function|numpy|vector | 1 |
1,816 | 51,213,544 | Multiple Axes and Plots | <p>sorry if the post, is not that good. It's the first one for me on Stack Overflow.
I have Datasets in the following structure:</p>
<pre><code> Revolution1 Position1 Temperature1 Revolution2 Position2 Temperature2
1/min mm C 1/min m C
datas... | <p>If I understand correctly what you want is to get subplots from the <code>Dataframe</code>.</p>
<p>You can achieve such using the <code>subplots</code> parameter within the <code>plot</code>function you have under the <code>Dataframe</code> object.</p>
<p>With below toy sample you can get a better idea on how to a... | pandas|matplotlib | 2 |
1,817 | 51,290,347 | Pandas is Trying to convert my path to a float when inputing to csv cell? | <p>I'm trying to save a path into a cell of a csv file for reference, but it's giving me error: ValueError: could not convert string to float: <em>[path]</em>
class Program:</p>
<pre><code>def __init__(self, master):
self.data = pd.read_csv("SourcingPython\\ProgramData.csv")
if pd.isnull(self.data.User... | <p>I was able to resolve this issue. For null values- it appears that you don't need to include ".at" to input the values.</p>
<p>so a simple:</p>
<pre><code>self.data.Input= askopenfilename()
</code></pre>
<p>was sufficient for this.</p>
<p>Thank you</p> | python|pandas | 0 |
1,818 | 48,371,569 | merge pandas MultiIndex is very slow | <p>I notice that pandas is very slow on merge DataFrames based on MultiIndex. Assign value is also sometimes slow</p>
<pre class="lang-python prettyprint-override"><code>import pandas as pd
import numpy as np
from pandas_datareader import data
import datetime
import string
import random
start = datetime.datetime(2002... | <p>Let use <code>join</code>:</p>
<pre><code>%timeit df1.join(df2)
1 loop, best of 3: 647 ms per loop
</code></pre> | python|pandas|merge | 0 |
1,819 | 48,195,277 | Writing lognormal function in python | <p>I'm trying to write an inverse lognormal function in python:</p>
<pre><code>import numpy as np
import scipy.stats as sp
from scipy.optimize import curve_fit
def lognorm1(x,s,scale):
ANS = sp.lognorm(s,scale=scale).ppf(x)
return ANS
curve_fit(lognorm1,x,y)
</code></pre>
<p>I have no troubles fitting the c... | <p>Indeed, <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.lognorm.html" rel="nofollow noreferrer">SciPy documentation says</a></p>
<blockquote>
<p>A common parametrization for a lognormal random variable Y is in terms of the mean, mu, and standard deviation, sigma, of the unique normally d... | python|numpy|scipy | 0 |
1,820 | 48,299,174 | How to run predict_generator on large dataset with limited memory? | <p>Currently I am feeding all the images at once to predict_generator. <strong>I want to be able to feed small set of images which are being stored in the validation_generator and make predictions on them so that there are no memory issues with large datasets</strong>. How should I change the following code? </p>
<pre... | <p>i ran a loop over the object and then stored the data in a list to get rid of memory issues.</p>
<pre><code> validation_generator= ImageDataGenerator(rescale=1./255).flow_from_directory(path, target_size=(img_width, img_height),
batch_size=32,sh... | tensorflow|machine-learning|keras|imagenet | 1 |
1,821 | 48,039,409 | pandas getattr(df, "mean") doesn't work like df.mean() | <p>When I use <code>getattr()</code> to dynamically access the mean of a pandas dataframe or series, it returns a Series.mean object. However, when I use <code>df.mean()</code> to access the mean, it returns a float.</p>
<p>Why doesn't <code>getattr()</code> return the same thing that the normal method does?</p>
<p>M... | <p>Since returned atttribute by getattr is callable, try: </p>
<pre><code>print(getattr(s, "mean")())
</code></pre> | python|pandas|numpy|dynamic | 6 |
1,822 | 48,669,802 | After doing ML how to save predicted output to CSV files using PANDAS lib or CSV lib | <p>After doing Machine Learning in Python 3.5.x How to save predicted output to CSV files using PANDAS library or CSV library??</p> | <p>If you have a pandas DataFrame <code>df</code>, it can be saved to a CSV file using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html" rel="nofollow noreferrer">to_csv</a> frunction.</p>
<pre><code>df.to_csv("some_file.csv")
</code></pre> | python|pandas|csv|machine-learning|scikit-learn | 2 |
1,823 | 48,692,997 | Loading sqlite table in a Pandas DataFrame gives AttributeError | <p>I'm trying to import data from sqlite database and load it into a pandas <code>DataFrame</code>. Sounds easy right?</p>
<pre><code>import pandas as pd
import sqlite3 as sql
pd.set_option('precision',7)
db = sql.connect('D:\db\crypto_db.db')
cursor = db.cursor()
cursor.execute('''select * from price''')
data_sql = ... | <p><code>pandas</code> can actually do extract + convert to dataframe at the same time.
You can do:</p>
<pre><code>pd.read_sql(con=cursor, sql="select * from price")
</code></pre>
<p>Reference: <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql.html" rel="nofollow noreferrer">https://pand... | python|pandas | 1 |
1,824 | 48,599,009 | Python error setting an array element with a sequence for different loops | <p>My code is as follows (there's about 100 lines before of setting values for the loop which seem to be working so I've just included necessary values):</p>
<pre><code>fraction=np.array([0.5, 0.3, 0.2])
tauC=np.array([30.,300.,100000.])
dC_memory=np.zeros((1,3))
dC_frac=np.zeros((1,3))
for j in range(0,ens_num)... | <p>Your example code is not complete. But I think the bug is clear.</p>
<p>By defining</p>
<pre><code> dC_frac=np.zeros((1,3))
</code></pre>
<p>You <code>dC_frac</code> is a <em>multidimensional</em> array of shape <code>(1, 3)</code>. Use <code>dC_frac.shape</code> you will find it's <code>(1, 3)</code>, <em>not</... | python|arrays|loops|numpy|indexing | 2 |
1,825 | 48,694,286 | Python - pandas xls import - difficulties removing certain row + | <p>[miniconda, python 3]</p>
<p>my data .xls to download: (password: stack)
<a href="http://download.hellshare.cz/file-xls/66813293/" rel="nofollow noreferrer">Download .xls</a></p>
<p>0)
You can notice that my xls file has big merged cell in the first row and also some merged cells in the rows 2 and 3. Is this a pr... | <p>I think you want the header function option on read in</p>
<pre><code>df = pd.read_excel("file.xls", header =[0,1,2])
</code></pre>
<p>Then you can drop the headers you don't want:</p>
<pre><code> df.columns = df.columns.droplevel([0,1])
</code></pre>
<p>or something along those lines. The sheet is a little mess... | python|excel|pandas|xls | 1 |
1,826 | 48,696,016 | Find flattened indices of symmetric elements of a 2D array | <p>I have an 5 x 5 numpy array:</p>
<pre><code>a = np.arange(25).reshape(5, 5)
</code></pre>
<p>If <code>a</code> is flattened:</p>
<pre><code> b = a.flatten()
>> [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24]
</code></pre>
<p>I am trying to find the indices of symmetry of <code>... | <p>I'll take a shot for square matrices. It will not be too hard to generalize the algorithm to non-square matrices if you know how the symmetry is defined for those cases.</p>
<p>First, create a 2D array of flattened indices:</p>
<pre><code>ind = np.arange(a.size).reshape(a.shape)
mid = a.shape[0] // 2
odd = a.shape... | python|arrays|numpy|indexing | 1 |
1,827 | 70,837,552 | Return elements of a column based on a different column in Pandas | <p>I want to write a program to return names in a list based on the number of reports in descending order.
like ['Jack', 'Joe', 'Rick'....]</p>
<pre><code>df=
Number_of_reports Name
5 Rick
4 Amanda
7 Joe
8 Jack
2 Ryan
</code></pr... | <p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer"><code>sort_values</code></a> and <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.tolist.html" rel="nofollow noreferrer"><code>to_list</code></a>:</p>
<p><code>names = df.... | python|python-3.x|pandas | 3 |
1,828 | 70,906,013 | Best way to replicate SQL "update case when..." with Pandas? | <p>I have this sample data set</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>City</th>
</tr>
</thead>
<tbody>
<tr>
<td>LAL</td>
</tr>
<tr>
<td>NYK</td>
</tr>
<tr>
<td>Dallas</td>
</tr>
<tr>
<td>Detroit</td>
</tr>
<tr>
<td>SF</td>
</tr>
<tr>
<td>Chicago</td>
</tr>
<tr>
<td>Denver</td>
</tr... | <p>You can directly replace the values like this:</p>
<pre><code>replacement_dict = {"LAL": "Los Angeles", "NYK": "New York"}
for key, value in replacement_dict.items():
df['City'][df['City'] == key] = value
</code></pre> | python|pandas|dataframe|str-replace | 1 |
1,829 | 70,979,489 | Why do I get negative dimensions are not allowed merging rasterio datasets? | <p>I am trying to use Python's rasterio library to analyze GIS wind data available <a href="https://www.nrel.gov/gis/assets/images/us-wind-data.zip" rel="nofollow noreferrer">here</a>. I've written this reduced program:</p>
<pre><code>import numpy as np
import rasterio as rio
from rasterio.merge import merge
file1 = ... | <p>What's so mysterious about?</p>
<pre><code>In [142]: np.zeros((10,-2))
Traceback (most recent call last):
File "<ipython-input-142-c7db7030b12c>", line 1, in <module>
np.zeros((10,-2))
ValueError: negative dimensions are not allowed
</code></pre>
<p>One or more of</p>
<pre><code>(output_c... | pandas|numpy|rasterio | 0 |
1,830 | 51,867,278 | how to understand this python code ,thanks a lot | <pre><code>import numpy as np
p = np.array([[1,2,3]])
print(p[np.array([0]), np.array([1,0,0])])
# output:[2,1,1]
</code></pre>
<p>I am trying to understand why this output is coming.</p> | <p><code>p</code> is (1,3) shape array. The indexing, which can also be written as</p>
<pre><code>p[ 0, [1,0,0]]
</code></pre>
<p>selects <code>p[0,1]</code>, <code>p[0,0]</code> and <code>p[0,0]</code>, that is the 2 and 1 (twice).</p>
<p>It's straight forward indexing with a list or array, also called advanced in... | python-3.x|numpy | 1 |
1,831 | 51,684,220 | google.protobuf.text_format.ParseError: 9:18 : Couldn't parse integer: 03 | <p>Im using python 3.6 tensorflow 1.5
im following the link</p>
<p>But got the error:</p>
<p>doe@doe:~/anaconda3/envs/tensorflow/models/research/object_detection$ python3 train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/ssd_mobilenet_v1_coco.config
WARNING:tensorflow:From /home/doe/anacond... | <p>I faced a similar problem relating to label_map_path when running on local machine. Solved by removing spaces between lines in the label map pbtxt file. Please check config file as well.</p> | python-3.x|ubuntu|tensorflow|video-processing|object-detection-api | 0 |
1,832 | 41,708,059 | Python Pandas: selecting 1st element in array in all cells | <p>What I am trying to do is select the 1st element of each cell regardless of the number of columns or rows (they may change based on user defined criteria) and make a new pandas dataframe from the data. My actual data structure is similar to what I have listed below.</p>
<pre><code> 0 1 2
0 [1, ... | <p>You can use <code>apply</code> and for selecting first value of list use <a href="http://pandas.pydata.org/pandas-docs/stable/text.html#indexing-with-str" rel="noreferrer">indexing with str</a>:</p>
<pre><code>print (zz.apply(lambda x: x.str[0]))
0 1 2
0 1 2 3
1 4 1 4
2 1 2 3
3 4 1 4
</code></pre>
... | arrays|python-3.x|pandas|dataframe | 11 |
1,833 | 42,087,542 | Pip help install | <p>I am trying to install tensorflow on ubuntu from: <a href="https://www.tensorflow.org/get_started/os_setup#virtualenv_installation" rel="nofollow noreferrer">https://www.tensorflow.org/get_started/os_setup#virtualenv_installation</a>
But when I get to the step: <code>pip install --upgrade $ TF_BINARY_URL</code>
I ge... | <p>That's because the environment variable <code>$TF_BINARY_URL</code> is not set. you must export it first, like described in the docs you provided.</p>
<blockquote>
<pre><code># Ubuntu/Linux 64-bit, CPU only, Python 2.7
(tensorflow)$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow... | python|tensorflow|pip|ubuntu-16.04 | 0 |
1,834 | 64,331,477 | Optimize a double loop with mesh grids involved | <p>I am doing a double loop to sum a function that has mesh grids as an input. The problem is that it runs very slow... I want to optimize the code with an alternative procedure, maybe using vectorize function of numpy, but I don't see how can be implemented. I show you the code that I have:</p>
<pre><code>import numpy... | <p>If you notice, the terms of the sum are completely separable: they don't share any loop variables. You can therefore create independent (smaller) arrays for the sum over <code>XX</code>, <code>n</code> and <code>YY</code>, <code>m</code>, and take the trig functions and sum of those. The final grid can be accumulate... | python|numpy|optimization | 0 |
1,835 | 64,474,589 | RASA --- ERROR: Could not find a version that satisfies the requirement tensorflow | <p>I am trying to install rasa and there is a problem with the tensorflow (Windows 10)</p>
<p>As a pre-requisite, I have installed Anaconda, VC++</p>
<p>Steps -</p>
<ol>
<li>Open Anaconda with admin rights</li>
<li>activate rasa</li>
<li>pip install rasa-x --extra index url <a href="https://pypi.rasa.com/simple" rel="n... | <p>You need use Python version 3.6 or 3.7. Check on that
<a href="https://i.stack.imgur.com/RkSTZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RkSTZ.png" alt="enter image description here" /></a></p> | tensorflow|rasa | 0 |
1,836 | 64,292,736 | Pandas dataframe conditional cumulative sum based on date range | <p>I have a pandas dataframe:</p>
<pre><code> Date Party Status
-------------------------------------------
0 01-01-2018 John Sent
1 13-01-2018 Lisa Received
2 15-01-2018 Will Received
3 19-01-2018 Mark Sent
4 02-02-2018 W... | <p>If you set <code>Date</code> as index and convert <code>Status</code> temporary to a categorical you can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rolling.html" rel="nofollow noreferrer"><code>pd.rolling</code></a> with a little trick</p>
<pre><code>df = df.set_index('D... | python|pandas|dataframe | 2 |
1,837 | 64,309,862 | Perform numpy product over non-zero elements of a row | <p>I have a 2d array <code>r</code>. What I want to do is to take the product of each row (excluding the zero elements in that row). For example if I have:</p>
<pre><code>r = [[1 2 0 3 4],
[0 2 5 0 1],
[1 2 3 4 0]]
</code></pre>
<p>Then what I want is to have another 2d array <code>result</code> such that:</p... | <p>I think I figured it out:</p>
<pre><code>np.prod(r, axis = 1, where = r > 0, keepdims = True)
</code></pre>
<p>Output:</p>
<pre><code>array([[24],
[10], ... | python|numpy | 1 |
1,838 | 64,481,705 | how to get row total in pandas | <p><a href="https://i.stack.imgur.com/IZebn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IZebn.png" alt="enter image description here" /></a></p>
<p>I am trying to get Row total and column total from my dataframe. I have no issue with the column total. However, My row total is adding up all the jo... | <p>First preselect the columns you wish to add row wise, then use df.sum(axis=1).</p>
<p>I think you're after:</p>
<pre><code>df.loc[:,'Total'] = df.loc[:,'20-29':'UP TO 20'].sum(axis=1)
</code></pre> | pandas|dataframe|plotly | 1 |
1,839 | 47,972,344 | How to update GAN Generator and Discriminator asynchronously in Tensorflow? | <p>I want to develop a GAN with Tensorflow, with the Generator being an autoencoder and the Discriminator a Convolutional Neural Net with binary output. There is no problem to develop an autoencoder and the CNN, but my idea is to train 1 epoch for each one of the components (Discriminator and Generator) and repeat this... | <p>If you have two ops called <code>train_step_generator</code> and <code>train_step_discriminator</code> (each of which are, for example, of the form <code>tf.train.AdamOptimizer().minimize(loss)</code> with an appropriate loss for each), then your training loop should be something similar to the following structure:<... | tensorflow|generative|adversarial-machines | 2 |
1,840 | 48,968,675 | Tensorflow GPU import error | <p>I have CUDA 8.0, and I can download cuDNN. Currently, I have cuDNN version 7.0.5 for Linux. </p>
<p>I do not have administrator privileges. </p>
<p>When I tried to install TensorFlow version 1.4 for GPU, I got this error:</p>
<pre><code> ImportError: libcudnn.so.6: cannot open shared object file: No such file or ... | <p>Yes if you register at nvidia you can also download older versions of cuDNN. It‘s a little hidden though. Make sure you download the right version which is compatible to your cuda version. Also don‘t forget to set CUDA_HOME environment variable for tensorflow to find your GPU.</p> | tensorflow | 0 |
1,841 | 58,615,866 | Iterative Creation and Naming of DataFrames | <p>Posting in continuation of <a href="https://stackoverflow.com/questions/58609931/pandas-multiple-dataframes-from-other-dataframes/58612808?noredirect=1#comment103540713_58612808[Text]">Pandas Multiple DataFrames from other DataFrames</a>. </p>
<p>Managed to iterate over multiple smaller dataframes (please note that... | <p>...continuing from the previous question...
I see what's happening here:
when you do <code>merged_dataframe.name = str(df)</code> you seem to want the name of the variable from which the dataframe came,
What actually happens is that you take the whole dataframe that df refers to (an original supermarket dataframe) ... | python|pandas|dataframe | 1 |
1,842 | 58,869,684 | using model prediction inside another model | <p>How can one use model.predict inside another model? I need to add a layer at the end of model that uses predictions form another model.</p>
<p>I get this error:</p>
<pre><code>ValueError: When feeding symbolic tensors to a model, we expect the tensors to have a static batch size. Got tensor with shape: (None, 10)
... | <p>I think I found it, I am using this instead: </p>
<pre><code>model1_outputs = model1(model1_inputs)
model2 = Model(inputs=model2_inputs, outputs=model1_outputs)
</code></pre> | python|tensorflow|keras|deep-learning | 0 |
1,843 | 70,125,424 | Python: convert output of confidence interval to excel | <p>I calculated a 95% confidence interval in Python with this code:</p>
<pre><code>d = st.t.interval(alpha=0.95, df=len(df_efw)-1, loc=np.mean(df_efw).mean(), scale=st.sem(df_efw.stack()))
</code></pre>
<p>My output is: <code>(2540.3603658087004, 2640.3233923612343)</code></p>
<p>I want to convert this into an exisitin... | <p>Using the row and column notation, access the tuple items individually and increment the row when writing with <code>ws.cell</code>.</p>
<pre class="lang-py prettyprint-override"><code>ws.cell(row=4, column= 3).value = d[0] # C4
ws.cell(row=5, column= 3).value = d[1] # C5
</code></pre> | python|excel|pandas | 1 |
1,844 | 70,363,964 | How to add a array to a column of a matrix? (python numpy) | <p>Like this:</p>
<pre><code>import numpy as np
a = np.zeros((3,3))
b = np.ones((3,1))
a[:,2] += b
</code></pre>
<p>expected:</p>
<pre><code>a =
0,0,1
0,0,1
0,0,1
</code></pre>
<p>in fact:</p>
<pre><code>ValueError: non-broadcastable output operand with shape (3,) doesn't match the broadcast shape (3,3)
</code></pre>
... | <p>Specifying the range of column is required</p>
<p>e.g. <code>a[:,0:1]</code> for column 0, <code>a[:,1:2]</code> for column 1, and <code>a[:,2:]</code> for column 2.</p>
<pre><code>import numpy as np
a = np.zeros((3,3))
b = np.ones((3,1))
a[:,2:] += b
</code></pre>
<p>output:</p>
<blockquote>
<pre><code>array([[0., ... | python|numpy | 1 |
1,845 | 70,208,833 | Add/Substract datetime in pyspark.pandas | <p>I got an error in calculating the date using pyspark.pandas.
Is there any way to calculate the date with pyspark.pandas?</p>
<pre><code>import pyspark.pandas as ps
import pandas as pd
df = pd.DataFrame({'year': [2015, 2016],
'month': [2, 3],
'day': [4, 5]})
df = ps.DataFrame(df... | <p>I did have a similar problem on <code>pyspark==3.2.1</code>, and this seemed to be the only solution, as like</p>
<pre><code>(
ps.to_datetime(pd.Series(['2015-02-04', '2016-03-05']))
.apply(lambda single_dt: single_dt + pd.Timedelta(days=3))
)
</code></pre>
<p>Newer versions of Pyspark have <code>to_timedelt... | python|pandas|datetime|pyspark|databricks | 0 |
1,846 | 70,357,808 | How can I get the sum of one column based on year, which is stored in another column? | <p>I have this code.</p>
<pre><code>cheese_sums = []
for year in milk_products.groupby(milk_products['Date']):
total = milk_products[milk_products['Date'] == year]['Cheddar Cheese Production (Thousand Tonnes)'].sum()
cheese_sums.append(total)
print(cheese_sums)
</code></pre>
<p>I am trying to sum all the ... | <p>I got it. It should be:</p>
<pre><code>cheese_sums = []
for year in milk_products['Date']:
total = milk_products[milk_products['Date'] == year]['Cheddar Cheese Production (Thousand Tonnes)'].sum()
if total not in cheese_sums:
cheese_sums.append(total)
print(cheese_sums)
</code></pre> | python|pandas | 1 |
1,847 | 56,181,967 | Group dataframe by week and get min and max dates within a week to new column | <p>I have a dataframe which includes columns "call_date", which is date of call and "call_week", which is number of week (week does not necessarily start on Monday or Sunday and does not necessarily last exactly 7 days):</p>
<p><a href="https://i.stack.imgur.com/5Kor0.png" rel="nofollow noreferrer"><img src="https://i... | <p>Better is use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.strftime.html" rel="nofollow noreferrer"><code>Series.dt.strftime</code></a>:</p>
<pre><code>df['WEEK_TEXT'] = df['min'].dt.strftime("%d.%m.%Y") + ' - ' + df['max'].dt.strftime("%d.%m.%Y")
</code></pre>
<p>In your sol... | python-3.x|pandas|pandas-groupby | 1 |
1,848 | 56,061,579 | Inferencing from tflite model in Java | <p>I have exported a <code>tflite</code> model and using Python code on <a href="https://www.tensorflow.org/lite/convert/python_api?fbclid=IwAR1ie4Fq6dvKbCocYCQ2WG_l9x2XSs1Nr0_2ECyXhmrGC_TZUNOMOLrS0po#using_the_interpreter_from_model_data_" rel="nofollow noreferrer">this</a> link, I am able to do inferencing from this ... | <p>You can paste the TFLite model in your assets folder of your app. And then, use this code to load its <code>MappedByteBuffer</code>.</p>
<p> </p>
<pre><code>private MappedByteBuffer loadModelFile() throws IOException {
String MODEL_ASSETS_PATH = "recog_model.tflite";
AssetFileDescriptor assetFileDe... | java|tensorflow | 2 |
1,849 | 56,110,001 | Pandas Dataframe resample week, starting first day of the year | <p>I have a dataframe containing hourly data, i want to get the max for each week of the year, so i used resample to group data by week</p>
<pre><code>weeks = data.resample("W").max()
</code></pre>
<p>the problem is that week max is calculated starting the first monday of the year, while i want it to be calculated st... | <p>Find the starting day of the year, for example let say it's Friday, and then you can specify an <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#anchored-offsets" rel="nofollow noreferrer">anchoring suffix</a> to resample in order to calculate week starting first day of the year:
<code>weeks = da... | python|pandas|dataframe|resampling|week-number | 3 |
1,850 | 56,109,029 | How to add label to numpy.ndarray? | <p>I just trying to add label to numpy.ndarray.</p>
<pre><code>numpy.ndarray's shape is (?, 1, 100, 100)
[[[ 1 1 1 ... 1 1 1]
...
[ 1 1 1 ... 1 1 1]]]
</code></pre>
<p>and label is <code>[1,0]</code> or <code>[0,1]</code></p>
<p>so i want shape like this</p>
<pre><code>[[[ 1 1 1 ... 1 1 1]
..... | <p>i found answer by myself!</p>
<p>this is my code</p>
<pre class="lang-py prettyprint-override"><code>data_train = []
true_list = true_data.tolist()
for index in range(len(true_list)):
true_list[index].append([1,0])
temp = np.asarray(true_list[index])
data_train.append(temp)
</code></pre> | python|numpy|tensorflow | 0 |
1,851 | 55,838,535 | How to add border in pandas dataframe to html table row header? | <p>Pandas style options let me format the data but i want to add border to the column headers, that is row 0. </p>
<pre><code>htmlFooterOutdatedList = dfServerOutdated[['System Name','IP Address','Last Communication','DAT (VSE)','OS Type','Status']].style.hide_index().set_properties(**{'font-size': '10pt','background-... | <p>Inside your (admittedly very long) line of code, you already have:</p>
<pre><code>.set_table_styles([{'selector': 'th', 'props': [('font-size', '12pt')]}])
</code></pre>
<p>which you can expand by common CSS attributes, e.g.:</p>
<pre><code>.set_table_styles([{'selector': 'th', 'props': [('font-size', '12pt'),('b... | python|html|python-3.x|pandas | 9 |
1,852 | 64,922,890 | Plotly vs Plotly Dash & Performance Issues | <p>I have been wondering what are the actual differences between Plotly and Plotly Dash in terms of performance. For an example, there is a functionality called "webgl" which allows GPU to render the data points on the graph in stead of a traditional SVG ("webgl" can be used both on Plotly & Plo... | <p>Well plotly dash is a deployment platform for analytical applications. Vanilla plotly is a graphing library.</p>
<p>Its sort of difficult to compare the two in terms of performance because they serve different purposes. Obviously the overhead of dash is more intensive because its hosting a web server that will most ... | python|pandas|plot|plotly|plotly-dash | 2 |
1,853 | 64,848,149 | split dataset into train and test using tensorflow | <p>I want to split my full dataset(every raw data has multiple features) into train and test sets. Rather than using scikit-learn 's train-test-split is there any other proper way to split my data? as well as I need to shuffle my data when splitting.
(If the suggested method is based on tensorflow, it's too better.)</p... | <p>Try this code:</p>
<pre><code>import tensorflow as tf
input = tf.random.uniform([100, 5], 0, 10, dtype=tf.int32)
input = tf.random.shuffle(input)
train_ds = input[:90]
test_ds = input[-10:]
</code></pre> | tensorflow|machine-learning|train-test-split | 1 |
1,854 | 64,808,971 | TypeError: Cannot convert value <tensorflow.python.keras.losses.CategoricalCrossentropy object ...> to a TensorFlow DType | <p>I want to implement a Word2Vec using negative sampling with pure TensorFlow 2. When I want to compute the gradient I get this error in the last line. I'm struggling to find the problem.</p>
<p>the code is fairly simple:</p>
<pre><code>import tensorflow as tf
import numpy as np
x, y = (('self', 'the'), ('self', 'vio... | <p><a href="https://www.tensorflow.org/api_docs/python/tf/keras/losses/CategoricalCrossentropy" rel="nofollow noreferrer"><code>tf.keras.losses.CategoricalCrossentropy</code></a> needs to be instantiated before being called:</p>
<pre><code>loss = tf.keras.losses.CategoricalCrossentropy()(y, prediction)
</code></pre>
<p... | python|tensorflow|keras|tensorflow2.0|gradient | 3 |
1,855 | 64,679,220 | Keep groups where at least one element satisfies condition in pyspark | <p>I've been trying to reproduce in pyspark something that is fairly easy to do in Pandas, but I've been struggling for a while now.
Say I have the following dataframe:</p>
<pre><code>df = pd.DataFrame({'a':[1,2,2,1,1,2], 'b':[12,5,1,19,2,7]})
print(df)
a b
0 1 12
1 2 5
2 2 1
3 1 19
4 1 2
5 2 7
</c... | <p>I've figured out a simple enough solution. The first step is to filter out rows where the values in <code>b</code> are in the list using <code>isin</code> and <code>filter</code>, and then keeping the unique grouping keys (<code>a</code>) in a list.</p>
<p>Then by merging back with the dataframe on <code>a</code> we... | python|pandas|pyspark | 2 |
1,856 | 64,734,190 | How to return NumPy array from Pandas MultiIndexed Dataframe? | <p>I have a MultiIndexed pandas Dataframe and I would like to convert this into a numpy array where each element in the first level of the MultiIndex corresponds to a row of the matrix. So given the dataframe below :</p>
<pre><code>df = pd.DataFrame(np.array([[1, 2, 3, 4 ], [2 ,1, 2, 3], [1, 3, 4 , 7], [1, 3, 5 , 7], [... | <p>Try this:</p>
<pre><code>[i.to_numpy().tolist() for _, i in df.groupby('a')]
</code></pre>
<p>Output:</p>
<pre><code>[[[3, 4], [4, 7], [5, 7]], [[2, 3], [4, 5]]]
</code></pre>
<p>Use list comprehension with <code>groupby</code> level 0 or 'a' in this dataframe.</p> | python|pandas|numpy|dataframe | 2 |
1,857 | 44,116,787 | Search for treshold values based on key from three columns(or more) | <p>I need help with dataset that looks like this:</p>
<pre><code>Name1 Name2 Name3 Temp Height
Alon Walon Balon 105 34 ]
Alon Walon Balon 106 42 |
Alon Walon Balon 105 33 ]-- Samples of Spot: Alon-Walon-Balon
Alon Walon Kalon 101 11 ]
Alon Walon Kalon 102... | <p>Here is a solution, that uses pandas groupby and is definitely more efficient than the loop.</p>
<pre><code>grouped = df.groupby(('Name1', 'Name2', 'Name3'))
count = grouped.size()
temp = grouped.apply(lambda x: x[x['Temp']>105].shape[0])
height = grouped.apply(lambda x: x[x['Height']<13].shape[0])
result =... | python|excel|csv|pandas | 1 |
1,858 | 44,104,584 | Slice a dataframe based on one column starting with the value of another column | <p>I have a dataframe called <code>data</code>, that looks like like this:</p>
<p><code>|...|category|...|ngram|...|</code></p>
<p>I need to slice this dataframe to instances where <code>category</code> starts with the value of <code>ngram</code>. So for example, if I had the following instance:</p>
<ul>
<li>categor... | <pre><code>#use df.apply to filter the rows with category starts with ngram.
data[data.apply(lambda x: x.category.startswith(x.ngram), axis=1)]
</code></pre> | python|pandas|sql-like|string-matching | 0 |
1,859 | 69,605,807 | pandas barplot choose color for each variable | <p>I usually use matplotlib, but was playing with pandas plotting and experienced unexpected behaviour. I was assuming the following would return red and green edges rather than alternating. What am I missing here?</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({"col1":[1... | <p>I think plotting each column separately and setting the <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.bar.html" rel="nofollow noreferrer"><code>bottom</code></a> argument to stack the bars provides the output you desire.</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
i... | python|pandas | 1 |
1,860 | 69,564,472 | Python: how to get all the first values row-wise from a 2D numpy array when using a 2D boolean mask | <p>I have two large 2D arrays, one with values and the other ones with a mask of "valid" values.</p>
<pre><code>vals = np.array([
[5, 2, 4],
[7, 8, 9],
[1, 3, 2],
])
valid = np.array([
[False, True, True],
[False, False, True],
[False, True, True],
])
</code></pre>
<p>My goal is to ge... | <p>Try:</p>
<pre><code>vals[np.arange(len(vals)), np.argmax(valid,axis=1)]
</code></pre>
<p>Or use <a href="https://numpy.org/doc/stable/reference/generated/numpy.take_along_axis.html#numpy.take_along_axis" rel="nofollow noreferrer"><code>np.take_along_axis</code></a>:</p>
<pre><code>np.take_along_axis(vals, np.argmax(... | python|arrays|numpy|performance|vectorization | 2 |
1,861 | 41,065,945 | Tensorflow Install from Source ImportError | <p>I am trying to install tensorflow directly from the source using</p>
<p><code>git clone https://github.com/tensorflow/tensorflow</code> and following the provided tutorial to build a wheel. Here is a full list of my commands used (bazel already installed) :</p>
<pre><code>git clone https://github.com/tensorflow/te... | <p>The missing symbol <code>_PyCObject_Type</code> suggests that TensorFlow's C++ Python extension was compiled against a different version of Python from the one that built the PIP package. When you run <code>./configure</code> before the <code>bazel build</code>, make sure that you answer the following prompt:</p>
<... | git|installation|tensorflow|importerror|python-wheel | 2 |
1,862 | 40,841,019 | My code shows invalid literal for float() | <p><strong>This is my code in editor:</strong></p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
x,y = np.loadtxt('D:\Tanjil\Python\directory\Matplot_trial1.csv',
unpack=True , delimiter='\s')
plt.plot(x,y,'r',label='angle=30 Degree'),
plt.ylabel('Power Input (kW)'),
plt.xlabel('S... | <p>You should call <code>plt.axis()</code> with a list of integers like this :</p>
<pre><code>plt.axis([750, 1400, 3, 4])
</code></pre> | python|numpy|matplotlib | 1 |
1,863 | 53,894,900 | Why doesn't tensorflow on google deep learning VM use GPU? | <p>I am using a google deep learning VM from google marketplace and I opted for a NvdiaK80 GPU. I am trying to train an object detection model using object detection API. However, I notice that tensorflow is not using GPU by default(code to check is below)</p>
<p>My assumption here is that this instance comes with all... | <p>I was able to resolve this by deleting the old instance and starting fresh with a new instance. My guess is the tensorflow GPU installation got corrupted while installing object detection API. Followed the steps here to install <a href="https://cloud.google.com/solutions/creating-object-detection-application-tensorf... | tensorflow|gpu|google-dl-platform | 2 |
1,864 | 66,027,370 | Make all entries before a zero to zeroes in a dataframe column | <p>I would like to convert all non zero values to zeros up to the last zero occurrence in a python dataframe column for each groups.</p>
<pre><code>group | value | Result
a | 1 | 0
a | 2 | 0
a | 0 | 0
a | 1 | 0
a | 0 | 0
a | 1 | 1
a | 2 | 2
b | 1 | ... | <p>You can test if all values to last <code>0</code> by compare values by <code>0</code>, swapped values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.iloc.html" rel="nofollow noreferrer"><code>Series.iloc</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/referen... | python|pandas|dataframe|filter | 1 |
1,865 | 66,266,170 | Save scraped list object text as column to pandas dataframe | <p>I want to scrape text from webpages and put it in to pandas dataframe. If I can scrape a table I get no problem but this here is no table and make me much trouble.</p>
<pre><code>driver = webdriver.Firefox()
driver.get('https://example.com/')
time.sleep(3)
number = driver.find_elements_by_xpath("//span[@class... | <p>Create list first for both <code>number</code> and <code>name</code> and then pass into pandas.</p>
<pre><code>number =[count.text for count in driver.find_elements_by_xpath("//span[@class='blaaal']")]
name = [names.text for names in driver.find_elements_by_xpath("//span[@class='blaaal2']")]
df ... | python|pandas|dataframe|selenium|selenium-webdriver | 1 |
1,866 | 66,100,040 | Filter Numpy Array with optional argument | <p>I am building a function which should prepare my data depending on the input. The variable <code>x_imp</code> contains indices on which features are important. However sometimes I still need all features so if 'x_imp = None' nothing should happen.</p>
<p>My solution was this (this is not the whole function just the ... | <p>This happens because slicing by <code>None</code> is an alias for <code>np.newaxis</code>. Is there a reason not to just add an explicit <code>if</code> statement?</p>
<pre><code>def get_train_data(x_cat, x_num,x_imp = None):
if x_imp is not None:
x_cat = x_cat[:,x_imp]
x_num = x_num[:,x_imp]
... | python|numpy|indexing | 0 |
1,867 | 66,275,500 | Cannot find the source code for `tf.quantization.fake_quant_with_min_max_args` | <p>Where one can find the github source code for <code>tf.quantization.fake_quant_with_min_max_args</code>. Checking the <a href="https://www.tensorflow.org/api_docs/python/tf/quantization/fake_quant_with_min_max_args" rel="nofollow noreferrer">TF API documentation</a>, there is no link to the github source file, and I... | <p>The kernel for this op is defined here:</p>
<p><a href="https://github.com/tensorflow/tensorflow/blob/ac74e1746a28b364230072d4dac5a45077326dc2/tensorflow/core/kernels/fake_quant_ops.cc#L63-L98" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/blob/ac74e1746a28b364230072d4dac5a45077326dc2/tensorflow... | tensorflow|tensorflow2.0 | 2 |
1,868 | 52,772,757 | Analyzing data flow of Dask dataframes | <p>I have a dataset stored in a tab-separated text file. The file looks as follows:</p>
<pre><code>date time temperature
2010-01-01 12:00:00 10.0000
...
</code></pre>
<p>where the <code>temperature</code> column contains values in degrees Celsius (°C).
I compute the daily average temperature using Dask. He... | <p>1) The data are read by the workers. The client does read a little ahead of time, to figure out the column names and types and, optionally, to find line-delimiters for splitting files. Note that all workers must be able to reach the file(s) of interest, which can require some shared file-system when working on a clu... | pandas|dask|dask-distributed | 1 |
1,869 | 58,259,518 | Groupy all columns and keep the non numeric | <p>I have a dataset with almost 200 columns. All of those columns are numeric. However I have 3 columns which are not numeric and I want to keep them - I don't want to group them. </p>
<p>Example:</p>
<pre><code>team_ref num_1 num_2 num_3 matchday match_id season_id
a 1 1 1 A AeD 2... | <p>We can do </p>
<pre><code>df.groupby('team_ref').agg(lambda x : x.mean() if x.dtype!= 'object' else ','.join(x))
Out[26]:
num_1 num_2 num_3 matchday match_id season_id
team_ref
a 1.5 1.5 1.5 A,B AeD,AbD 2018
b 3.5 ... | python|python-3.x|pandas|dataframe | 3 |
1,870 | 58,231,987 | How to Find Year-wise Mean from Date-wise CSV Data In Pandas For Plotting bar chart | <p>I have Sample Data as</p>
<pre><code>Company,Date,Open,High,Low,Close,Adj Close,Volume
ADANIPORTS,5/6/2008,150,153.570007,147.820007,151.149994,134.313477,1782030
ADANIPORTS,5/7/2008,152,154.460007,150.240005,153.309998,136.232864,1180015
ADANIPORTS,5/8/2008,152.19996.759995,150.199997,155.889999,138.525497,1856245... | <p>this will help you groupby year and take the means:</p>
<pre><code>df.groupby(pd.Grouper(key='date', freq='Y'))['Open','Close'].mean()
</code></pre>
<p>otherwise you can resample method:</p>
<pre><code>df.set_index('date').resample('Y')['Open','Close'].mean()
</code></pre> | python|pandas|analysis | 1 |
1,871 | 58,406,428 | numpy: combine image mask with RGB to get colored image mask | <p>how can I combine a binary mask image array (<code>this_mask</code> - shape:4,4) with a predefined color array (<code>mask_color</code>, shape:3)</p>
<pre><code>this_mask = np.array([
[0,1,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
])
this_mask.shape # (4,4)
mask_color = np.array([128, 128, 64])
mask_color.shape # (3)... | <p>This might work:</p>
<pre><code> this_mask = np.array([
[0,1,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
])
mask_color = np.array([128, 128, 64])
res = []
for row in new:
tmp = []
for col in row:
tmp.append(np.array([1,1,1]) * col)
r... | python|numpy|image-processing | 1 |
1,872 | 58,327,692 | Updating a slice in rank3 tensorflow tensor along the third axis (Z) given a location (X,Y) | <p>I am trying to re-implement the below function (written in numpy) using <code>Tensorflow 1.9.0</code>. </p>
<pre class="lang-py prettyprint-override"><code>def lateral_inhibition2(conv_spikes,SpikesPerNeuronAllowed):
vbn = np.where(SpikesPerNeuronAllowed==0)
conv_spikes[vbn[0],vbn[1],:]=0
return conv_s... | <p>The last dim of <code>updates</code> in <code>tf.scatter_nd_update</code> should be 3, which is equal to the last dim of <code>ref</code>. </p>
<pre><code>update = tf.scatter_nd_update(conv_spikes_tf, output, np.zeros(output.shape[0], 3))
</code></pre>
<p>If I understand correctly, you want to apply <code>SpikesPe... | python|python-2.7|tensorflow | 1 |
1,873 | 69,135,257 | train a model which is instantiated in another model ( Pytorch) | <p>I have two classes of networks of neurons one of GNN type and the other simple of linear type, the latter is instantiated in the first !!! how can I train both at the same time?
here is an example:</p>
<pre><code>class linear_NN(nn.Module):
def __init__(self, input_dim, out_dim...):
super().__init__()
de... | <p>You must declare it in the <code>__init__(...)</code>:</p>
<pre class="lang-py prettyprint-override"><code>class GNN(nn.Module):
def __init__(self, input_dim, n-hidden, out_dim, ...):
super().__init__()
self.linear = linear_NN(input, out..)
def forward(self, h, dim = 0):
'''Forward pass'''
self.... | python|neural-network|pytorch | 1 |
1,874 | 69,009,968 | Reading a JSON file using pandas in a desired format | <p>I have a JSON file that contains:</p>
<pre><code>{
"getYearsListOverview": {
"sp_name": "analytics.year_overview_drop_down",
"sp_input_params": {
"req_url_query_params": [],
"req_body_params": []
},
... | <p>To simply rename the columns</p>
<pre><code>for col in df_1.columns:
new_col_name = col.split('.')[-1]
df_1.rename(columns = {col: new_col_name},inplace=True)
print(df_1.columns)
</code></pre>
<p>Output:</p>
<pre><code>Index(['sp_name', 'req_url_query_params', 'req_body_params',
'sp_output_datasets', 'pag... | python|json|pandas | 0 |
1,875 | 60,982,927 | Append contents of previous row to the next one | <p>A bit stuck here. Seems easy but for some reason can't seem to get it to work.</p>
<p>I have a csv file that I need to read from and then add contents of the previous row to the next one. So for example if original data looks like this:</p>
<pre><code> 0
0 a
1 b
2 c
3 d
</code></pre>
<p>Then I need to get i... | <p>Just a for loop would do:</p>
<pre><code>for i in range(1,3):
# may need to replace '0' with 0 or the actual column name
# also i with f'{i}' if you want column name as string
df[i] = df['0'].shift(i, fill_value=0)
# another column to shift:
df[f'other_col_{i}'] = df['other_col'].shift(i, fill_... | python|pandas|dataframe|recursion | 2 |
1,876 | 60,850,984 | Using a loaded tensorflow model outside of session | <p>I want to load a TensorFlow model (checkpoint) and use in in a while loop. </p>
<p>Loading the model takes some time, so I want to do that before the while loop.
If I use:</p>
<pre><code>with tf.Graph().as_default():
with tf.Session() as sess:
print("loading checkpoint ...")
saver = tf.train.i... | <p>From your illustration code, I guess you're using TensorFlow version 1.x (with tf.Graph, tf.Session ...). Is this right?</p>
<p>So, about your question: "Is there another way of running a loaded model (as in the code above) outside of a session?",</p>
<p>I have a suggestion: have you ever tried to convert your cod... | python|tensorflow|tensorflow-serving | 0 |
1,877 | 61,126,560 | keras load_model not work in google colab | <p>I tried load model that i created in my local machine,so first i upload my model(.h5) in to google drive and then i access my model in colab using following code</p>
<pre><code>from google.colab import drive
drive.mount('/content/drive')
</code></pre>
<p>then i tried with following code</p>
<pre><code>from keras.... | <p>I suspect this is due to an incompatiblity between keras 2.2 and tensorflow 2.x. You should be able to fix the issue by updating to keras 2.3 or newer:</p>
<pre><code>!pip install -U keras
</code></pre>
<p><em>Edit 2020-04-10: it looks like Keras 2.3 is now the default in Colab, so the above fix is no longer neces... | tensorflow|machine-learning|keras|deep-learning|google-colaboratory | 2 |
1,878 | 71,687,578 | how to get unique value in the pandas column? | <p>I have 2 dataframe as below:</p>
<pre><code>df.head(10)
key program
0 A emp
1 A dep
2 A emp
3 A dep
4 A dep
5 B emp
6 B dep
7 B emp
8 B emp
9 B emp
df1.head()
key program value1 value2
0 A emp 10000 100000
1 A dep 5000... | <p>You can modify your <code>merge</code> by creating a new index column:</p>
<pre><code>df_merge = (
df.merge(df1, how='left',
left_on=['key', 'program', df.groupby(['key', 'program']).cumcount()],
right_on=['key', 'program', df1.groupby(['key', 'program']).cumcount()])
.drop(columns='key_2'... | python|pandas | 0 |
1,879 | 71,495,344 | Splitting the array in python on the based of position | <p>I have a array in python as:</p>
<pre><code>newarray=['Title',
'Salary USD',
'Equity %',
'Equity USD',
'Work location',
'Years of Experience',
'Years at Startup',
'Stage',
'Size',
'Staff electrical engineer',
'$226,000',
'0.002%',
'$650,000',
'San Francisco',
'8.0',
'3.0',
'Series H',
'1001-5000 emp... | <p>IIUC, you want a single 2D array? Then <a href="https://numpy.org/doc/stable/reference/generated/numpy.reshape.html" rel="nofollow noreferrer"><code>reshape</code></a>:</p>
<pre><code>out = arr.reshape((-1,9))
</code></pre>
<p><em>NB. be careful, <code>reshape</code> requires that you have a multiple of the dimensio... | python|python-3.x|numpy | 1 |
1,880 | 71,486,886 | Batched input shows 3d, but got 2d, 2d tensor | <p>I have this training loop</p>
<pre class="lang-py prettyprint-override"><code>def train(dataloader, model, loss_fn, optimizer):
size = len(dataloader.dataset)
model.train()
for batch, (X, y) in enumerate(dataloader):
X, y = torch.stack(X).to(device), torch.stack(y).to(device)
# Compute p... | <p>Your code:</p>
<pre class="lang-py prettyprint-override"><code>hidden = (torch.zeros(self.num_layers, self.hidden_size), torch.zeros(self.num_layers, self.hidden_size))
x, _ = self.BELT_LSTM(x, hidden)
</code></pre>
<p>Here hx and cx are both 2-D tensors. The correct way should be:</p>
<pre class="lang-py prettyprin... | pytorch|tensor | 2 |
1,881 | 71,651,439 | Error in creating new dataframe from comparison of 2 dataframe in puthon | <p>I have 2 dataframe whose sample is as below:</p>
<p>df1:</p>
<pre><code> Table Field
0 AOI AEDAT
1 AEI AEDTZ
2 AOI AEENR
3 AEO AENAM
4 ... | <p>Check with <code>merge</code></p>
<pre><code>df3 = df1.merge(df2, how = 'left', on = 'Field')
</code></pre> | python|pandas|dataframe | 2 |
1,882 | 42,369,953 | How to apply several functions to a single pandas dataframe column? | <p>I am curious about if it is possible to apply several functions to a single pandas dataframe column. For example, let's say that I have three functions:</p>
<p>In:</p>
<pre><code>def foo(col):
if 'hi' in col:
return 'TRUE'
def bar(col):
if 'bye' in col:
return 'TRUE'
def baz(col):
if... | <p>Why not lump all functions into one giant function?</p>
<pre><code>def oneGaintFunc(col):
def foo(col):
if 'hi' in col:
return 'TRUE'
def bar(col):
if 'bye' in col:
return 'TRUE'
def baz(col):
if 'ok' in col:
return 'TRUE'
a = foo(co... | python|python-3.x|pandas|map-function | 4 |
1,883 | 42,241,963 | fill in missing DataFrame indices | <p>Given two pandas dataframes <code>dfa</code> and <code>dfb</code>, how can I ensure the MultiIndex of each DataFrame contains all rows from the other?</p>
<pre><code>In [147]: dfa
Out[147]:
c
a b
0 5 10.0
1 6 11.0
2 7 12.0
3 8 13.5
4 9 14.0
In [148]: dfb
Out[148]:
c
a b
0 5 10
2 7 ... | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sub.html" rel="nofollow noreferrer"><code>DataFrame.sub</code></a> with parameter <code>fill_value</code> if need replace <code>NaN</code> to some value:</p>
<pre><code>df = dfa.sub(dfb, fill_value=0)
print (df)
... | pandas|dataframe|union|nan|multi-index | 1 |
1,884 | 69,837,581 | Replace duplicated time index and fullfilling by time interpolation | <p>I have a dataframe with a wrong time stamp</p>
<p>The time index is wrong, instead of being sampled in periods of 1 min contains duplicated indexes with multiples of 10minutes</p>
<pre><code>2021-08-01 00:00:00
2021-08-01 00:00:00
2021-08-01 00:00:00
2021-08-01 00:00:00
...
2021-08-01 00:10:00
2021-08-01 00:10:00
..... | <p>Yo can add timedeltas by 1 minutes by counter by duplicated indices by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>GroupBy.cumcount</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pand... | python|pandas|datetime|reindex | 1 |
1,885 | 70,019,109 | Finding similarities between two columns in two datasets in Python: optimization of approach | <p>Imagine i have the following datasets:</p>
<pre><code>import difflib as dl
import numpy as np
import pandas as pd
df1 = pd.DataFrame([[1,'one'],[2,'two'],[3,'three'],[4,'four'],[5,'five'],[7,'seven']], columns=['number', 'name'])
df2 = pd.DataFrame([[1,'one'],[2,'two'],[3,'three'],[4,'four'],[5,'five'],[55,'five'],... | <p>not sure exactly what output you are expecting but you can use <code>.isin()</code> method <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.isin.html" rel="nofollow noreferrer">see pandas docs</a></p>
<p>This would be a lot faster than doing a merge.</p>
<p>So something like</p>
<... | python|pandas | 1 |
1,886 | 43,050,898 | How to use .apply function on a pandas DataFrame that has been filtered by regex? | <p>I have a pandas DataFrame with data scraped from a couple Wiki tables. The DataFrame has a column for names and some of these names are followed by "\r\n(head coach)". I would like to remove that and so I tried this:</p>
<pre><code>df['name'][df.name.str.contains(r'coach')] =\
df['name'][df.name.str.contains(r'coac... | <p>You can try this:</p>
<pre><code>mask = df.name.str.contains(r'coach')]
df.loc[mask, 'name'] = df.loc[mask, 'name'].str[:-14]
</code></pre>
<p>Or as @piRSquared commented, this simple line should also work:</p>
<pre><code>df.loc[mask, 'name'] = df.name.str[:-14]
</code></pre> | python|regex|pandas|dataframe | 3 |
1,887 | 50,458,413 | Transposing a specific column into row in python dataframe | <p>I try to transpose a dataframe with a specific format :
Here is my current dataframe called df :
<a href="https://i.stack.imgur.com/0c7Rd.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0c7Rd.jpg" alt="enter image description here"></a> </p>
<p>and the result of transpose shoud be :
<a href="http... | <p>You can try using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow noreferrer"><code>pd.pivot_table</code></a>:</p>
<pre><code>res = df.pivot_table(index=['pid', 'Accuracy'], columns=['TreeFeatures'],
values='Importance 1', aggfunc='first', ... | python|python-3.x|pandas|dataframe | 2 |
1,888 | 50,300,972 | matmul function for vector with tensor multiplication in tensorflow | <p>In general when we multiply a vector <code>v</code> of dimension <code>1*n</code> with a tensor <code>T</code> of dimension <code>m*n*k</code>, we expect to get a matrix/tensor of dimension <code>m*k</code>/<code>m*1*k</code>. This means that our tensor has <code>m</code> slices of matrices with dimension <code>n*k<... | <p>You can do it with:</p>
<pre><code>tf.reduce_sum(tf.expand_dims(v,2)*T,1)
</code></pre>
<p>Code:</p>
<pre><code>m, n, k = 2, 3, 4
T = tf.Variable(tf.random_normal((m,n,k)), name="tensor")
v = tf.Variable(tf.random_normal((1,n)), name="vector")
c = tf.stack([v,v]) # m times, here set m=2
out1 = tf.matmul(... | tensorflow|tensor|vector-multiplication | 1 |
1,889 | 45,626,789 | TensorFlow Estimator restoring all variables properly, but loss spikes up afterwards | <p>I am using TensorFlow 1.2.1 on Windows 10, and using the Estimator API. Everything runs without any errors, but whenever I have to restore the parameters from a checkpoint, some aspect of it doesn't work. I've checked that the values of every variable in classifier.get_variable_names() does not change after an eval... | <p>I figured out the issue, I was creating data pipelines with the interactive session I created, and then having my input function evaluate the examples (like a feed-dictionary). The reason this is an issue is that the Estimator class creates it's own session (a MonitoredTraininSession), and since the graph operation... | tensorflow | 0 |
1,890 | 45,687,352 | Training neural network by making batch_size increase to avoid shocking | <pre><code>... build the graph ...
train_step =
tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy)
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
for _ in range(1000):
batch_xs, batch_ys = data.next_batch(batch_size)
sess.run(train_step, feed_dict={x: batch_xs, y_: ba... | <p><strong>If your descent is noisy:</strong></p>
<p>Increasing the <code>batch_size</code> will stabilise the fluctuations, as the gradient will be averaged over a higher number of samples. </p>
<p>The effect of halfing the <code>learning_rate</code> is similar to that of doubling the <code>batch_size</code>, but no... | tensorflow|neural-network | 1 |
1,891 | 62,847,023 | Assign value to column based on lookup table using pandas | <p>I've the following matrix:</p>
<pre><code>destinations = ["DC","NY","SF","AL"]
workinDays = [[3, 5, 7, 7],
[5, 5, 7, 7],
[7, 7, 7, 7],
[7, 7, 7, 7]]
working_days_df = pd.DataFrame(data=workinDays, columns=destinations,
... | <p>IIUC, you can perform a lookup:</p>
<pre><code>df_other['new'] = working_days_df.lookup(df_other['dest1'], df_other['dest2'])
</code></pre>
<p>Here, <code>working_days_df</code> is your matrix DataFrame, while <code>df_other</code> is the one you'd like to lookup values for.</p> | python|pandas | 1 |
1,892 | 62,766,853 | Determine all the possible combinations between the main elements of the parent list | <p>I'm working on designing a dataset and I'm facing an issue with a specific part of it. I provided the example below to simplify and relate to my issue.</p>
<p>I have a list of lists</p>
<pre><code>list = ['b',['c','g','d'],['h','l']]
</code></pre>
<p>and I'm interested in a <strong>general solution</strong> to deter... | <p>You can use <a href="https://docs.python.org/3/library/itertools.html#itertools.product" rel="nofollow noreferrer"><code>itertools.product()</code></a>:</p>
<pre><code>import itertools
my_list = ['b', ['c','g','d'], ['h','l']]
print(list(itertools.product(*my_list)))
</code></pre>
<p>output:</p>
<pre><code>[('b', '... | python-3.x|pandas|numpy | 0 |
1,893 | 62,800,305 | Repeat pandas rows based on content of a list | <p>I have a large pandas dataframe df as:</p>
<pre><code>Col1 Col2
2 4
3 5
</code></pre>
<p>I have a large list as:</p>
<pre><code>['2020-08-01', '2021-09-01', '2021-11-01']
</code></pre>
<p>I am trying to achieve the following:</p>
<pre><code>Col1 Col2 StartDate
2 4 8/1/2020
3 5 ... | <p>Let use list comprehension with <code>assign</code> and <code>pd.concat</code>:</p>
<pre><code>l = ['2020-08-01', '2021-09-01', '2021-11-01']
pd.concat([df1.assign(startDate=i) for i in l], ignore_index=True)
</code></pre>
<p>Output:</p>
<pre><code> Col1 Col2 startDate
0 2 4 2020-08-01
1 3 5 2... | pandas|python-3.8 | 4 |
1,894 | 62,602,528 | Splitting an excel file into dataframes and then creating two new files from them in Python | <p>Sorry about the poorly worded title. On this project I am bringing in multiple excel files that need to be manipulated and then sent back out as multiple csv files(eventually heading into BigQuery). Several things I am trying to do is eliminate the final 6 rows (this is a watermark that is not needed), and then cr... | <p>The split part of the problem was you said was already working well, and you can use append and merge to accomplish this, but I think <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.insert.html" rel="nofollow noreferrer"><code>df.insert</code></a> (<code>df.insert(0, column="... | python|pandas|dataframe | 0 |
1,895 | 54,446,886 | how to keep value and value below shift (1) | <p>I want to know how to keep a value and a value below when it is equal to ("NaN"). Thank you.example</p>
<pre><code>df = pd.DataFrame ({'list': ["juan", "NaN", "Maria", "NaN", "juan", "juanita", "juan", "NaN"]})
</code></pre>
<p>I just want to continue</p>
<pre><code>df = pd.DataFrame ({'list': ["juan", "NaN", "ju... | <p>First, we'll get the indices of each row that contains "juan" and has a row below it that contains "NaN:</p>
<pre><code>cond1 = df['list'] == 'juan'
cond2 = df['list'].shift(-1) == 'NaN'
idxs = cond1 & cond2
idxs = idxs[idxs == True]
</code></pre>
<p>We're almost done, but since you want to include the subsequ... | database|pandas|numpy|dataframe|data-science | 1 |
1,896 | 54,669,673 | Change the cell values , using Pandas (Python) | <p>I need some help with pandas dataframe.
Look the image:
<a href="https://i.stack.imgur.com/XfnCw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XfnCw.png" alt="enter image description here"></a></p>
<p>As you can see, I have some rows where the value are equal, like for example <strong>"Type add... | <p>You could iterate over the column and replace them as needed. Something like this maybe:</p>
<pre><code>counter = 1
result = []
for i in df.iloc[:, 0]:
if i == "Type address":
result.append(f"{i} {counter}")
else:
result.append(i)
counter += 1
df.iloc[:, 0] = result
</code></pre>
<p... | python-3.x|pandas | 1 |
1,897 | 54,495,737 | How to get prediction when computing loss function in convolutional neural network (tensorflow)? | <p>I built a convolutional neural network with tensorflow by following these steps:
<a href="https://www.tensorflow.org/tutorials/estimators/cnn" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/estimators/cnn</a></p>
<p>I want to compute the loss with my own loss function and therefore need to get the p... | <p>This is how you compute the softmax and get the probabilities afterwards:</p>
<pre><code># Probabities for each element in the batch for each class.
softmax = tf.nn.softmax(logits, axis=1)
# For each element in the batch return the element that has the maximal probability
predictions = tf.argmax(softmax, axis=1)
</... | python|tensorflow|conv-neural-network|prediction|loss-function | 0 |
1,898 | 73,676,483 | Can Horovod with TensorFlow work on non-GPU instances in Amazon SageMaker? | <p>I want to perform <strong>distributed training</strong> on <strong>Amazon SageMaker</strong>. The code is written with <strong>TensorFlow</strong> and similar to the following code where I think CPU instance should be enough:
<a href="https://github.com/horovod/horovod/blob/master/examples/tensorflow_word2vec.py" r... | <p>Yeah you should be able to use both CPU's and GPU's with Horovod on Amazon SageMaker. Please follow the below example for the same</p>
<p><a href="https://github.com/aws/amazon-sagemaker-examples/blob/main/sagemaker-python-sdk/tensorflow_script_mode_horovod/tensorflow_script_mode_horovod.ipynb" rel="nofollow norefer... | tensorflow|amazon-sagemaker|distributed-training|horovod | 0 |
1,899 | 73,818,490 | tensorflow keras load models weights | <p>I have recently saved some models which I have trained in another machine, and didn't save it like I have seen in another models, with the <code>h5</code> extension. I don't grasp yet how to load the weights. I can load the model, but without the weights means like nothing. Please help :-)</p>
<pre><code>from keras.... | <p>Since you haven't saved the model in the h5 format, I'll assume you used the SavedModel format like this:</p>
<pre><code>model.save('path/to/location')
</code></pre>
<p>If this is what you did, then loading the model like this is enough:</p>
<pre><code>model = keras.models.load_model('path/to/location')
</code></pre... | tensorflow|keras | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.