question_id
int64
59.5M
79.7M
creation_date
stringdate
2020-01-01 00:00:00
2025-07-15 00:00:00
link
stringlengths
60
163
question
stringlengths
53
28.9k
accepted_answer
stringlengths
26
29.3k
question_vote
int64
1
410
answer_vote
int64
-9
482
59,648,509
2020-1-8
https://stackoverflow.com/questions/59648509/batch-normalization-when-batch-size-1
What will happen when I use batch normalization but set batch_size = 1? Because I am using 3D medical images as training dataset, the batch size can only be set to 1 because of GPU limitation. Normally, I know, when batch_size = 1, variance will be 0. And (x-mean)/variance will lead to error because of division by 0. B...
variance will be 0 No, it won't; BatchNormalization computes statistics only with respect to a single axis (usually the channels axis, =-1 (last) by default); every other axis is collapsed, i.e. summed over for averaging; details below. More importantly, however, unless you can explicitly justify it, I advise against...
11
18
59,713,016
2020-1-13
https://stackoverflow.com/questions/59713016/plotly-express-how-to-fix-the-color-mapping-when-setting-color-by-column-name
I am using plotly express for a scatter plot. The color of the markers is defined by a variable of my dataframe, as in the example below. import pandas as pd import numpy as np import plotly.express as px df = px.data.iris() fig = px.scatter(df[df.species.isin(['virginica', 'setosa'])], x="sepal_width", y="sepal_length...
Short answer: 1. Assign colors to variables with color_discrete_map : color_discrete_map = {'virginica': 'blue', 'setosa': 'red', 'versicolor': 'green'} or: 2. Manage the order of your data to enable the correct color cycle with: order_df(df_input = df, order_by='species', order=['virginica', 'setosa', 'versicolor']...
12
10
59,707,973
2020-1-12
https://stackoverflow.com/questions/59707973/how-to-disable-keyword-text-suggestion-in-spyder-4
Specifically this popup box: It appears almost every time I type anything, and it's kind of getting in the way. I have disabled code completion in the settings, and uninstalled Kite, and disabled Jedi. Any ideas?
(Spyder maintainer here) To disable those completions (called fallback completions) in Spyder 5, you need to go to Tools > Preferences > Completion and Linting > General and deactivate the option called Enable Fallback provider. For Spyder 4, please go to Tools > Preferences > Completion and Linting > Advanced and deac...
28
36
59,642,902
2020-1-8
https://stackoverflow.com/questions/59642902/how-to-handle-file-upload-validations-using-flask-marshmallow
I'm working with Flask-Marshmallow for validating request and response schemas in Flask app. I was able to do simple validations for request.form and request.args when there are simple fields like Int, Str, Float etc. I have a case where I need to upload a file using a form field - file_field. It should contain the fi...
You can use fields.Raw: import marshmallow class CustomSchema(marshmallow.Schema): file = marshmallow.fields.Raw(type='file') If you are using Swagger, you would then see something like this: Then in your view you can access the file content with flask.request.files. For a full example and more advanced topics, check...
12
9
59,687,514
2020-1-10
https://stackoverflow.com/questions/59687514/how-to-write-a-case-when-like-statement-in-numpy-array
def custom_asymmetric_train(y_true, y_pred): residual = (y_true - y_pred).astype("float") grad = np.where(residual>0, -2*10.0*residual, -2*residual) hess = np.where(residual>0, 2*10.0, 2.0) return grad, hess I want to write this statement: case when residual>=0 and residual<=0.5 then -2*1.2*residual when residual>=0...
This statement can be written using np.select as: import numpy as np residual = np.random.rand(10) -0.3 # -0.3 to get some negative values condlist = [(residual>=0.0)&(residual<=0.5), (residual>=0.5)&(residual<=0.7), residual>0.7] choicelist = [-2*1.2*residual, -2*1.0*residual,-2*2.0*residual] residual = np.select(cond...
8
9
59,684,765
2020-1-10
https://stackoverflow.com/questions/59684765/is-it-possible-to-put-numbers-on-top-of-a-matplot-histogram
import matplotlib.pyplot as plt import numpy as np randomnums = np.random.normal(loc=9,scale=6, size=400).astype(int)+15 Output: array([25, 22, 19, 26, 24, 9, 19, 32, 30, 25, 29, 17, 21, 14, 17, 27, 27, 28, 17, 17, 20, 21, 16, 28, 20, 24, 15, 20, 20, 13, 33, 21, 30, 27, 8, 22, 24, 25, 23, 13, 24, 20, 16, 32, 15, 26, 3...
An adapted version of the answer I linked in the comments of the question. Thanks a lot for the suggestions in the comments below this post! import matplotlib.pyplot as plt import numpy as np h = np.random.normal(loc=9,scale=6, size=400).astype(int)+15 fig, ax = plt.subplots(figsize=(16, 10)) ax.hist(h, density=False) ...
7
14
59,719,323
2020-1-13
https://stackoverflow.com/questions/59719323/removing-sep-token-in-bert-for-text-classification
Given a sentiment classification dataset, I want to fine-tune Bert. As you know that BERT created to predict the next sentence given the current sentence. Thus, to make the network aware of this, they inserted a [CLS] token in the beginning of the first sentence then they add [SEP] token to separate the first from the ...
Im not quite sure why BERT needs the separation token [SEP] at the end for single-sentence tasks, but my guess is that BERT is an autoencoding model that, as mentioned, originally was designed for Language Modelling and Next Sentence Prediction. So BERT was trained that way to always expect the [SEP] token, which means...
11
6
59,702,785
2020-1-12
https://stackoverflow.com/questions/59702785/what-does-dim-1-or-2-mean-in-torch-sum
let me take a 2D matrix as example: mat = torch.arange(9).view(3, -1) tensor([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) torch.sum(mat, dim=-2) tensor([ 9, 12, 15]) I find the result of torch.sum(mat, dim=-2) is equal to torch.sum(mat, dim=0) and dim=-1 equal to dim=1. My question is how to understand the negative dimension he...
The minus essentially means you go backwards through the dimensions. Let A be a n-dimensional matrix. Then dim=n-1=-1, dim=n-2=-2, ..., dim=1=-(n-1), dim=0=-n. See the numpy doc for more information, as pytorch is heavily based on numpy.
21
13
59,660,939
2020-1-9
https://stackoverflow.com/questions/59660939/default-value-of-gamma-svc-sklearn
I'm using SVC from sklearn.svm for binary classification in python. For the gamma parameter it says that it's default value is . I'm having a hard time understading this. Can you tell me what's the default value of gamma ,if for example, the input is a vector of 3 dimensions(3,) e.g. [3,3,3] and the number of input ve...
This is easy to see with an example. The array X below has two features (columns). The variance of the array is 1.75. The default gamma is therefore is 1/(2*1.75) = 0.2857. You can verify this by checking the ._gamma attribute of the classifier. import numpy as np from sklearn.svm import SVC X = np.array([[-1, -1], [-2...
7
5
59,700,903
2020-1-12
https://stackoverflow.com/questions/59700903/importerror-cannot-import-name-parser
I have a bunch of modules. The modules and their imports are listed below: ast.py: import enum from abc import ABC, abstractmethod err.py: none lexer.py: from token import TokenTag, Token parser.py: from ast import * from err import UndeclaredIdentError, SyntaxError from token import TokenTag as Tag from type import Ty...
Open parser.py file and change the code for from parser import Parser to from .parser import Parser
7
1
59,697,971
2020-1-11
https://stackoverflow.com/questions/59697971/is-there-a-way-i-can-run-a-python-script-when-a-button-programmed-in-flutter-is
Essentially , what I want to do is , press a button that I program in Flutter and when that button is pressed , a python script should start running on my Android device . I want to use youtube-dl (used to download Youtube videos) library in python but I wanna know if there is a way to run the library in flutter . An...
I know it's quite old now but may be someone else can get help out of it. There is library called starflut and it can incorporate python code inside your flutter app. Take a look here https://pub.dev/packages/starflut
22
13
59,721,120
2020-1-13
https://stackoverflow.com/questions/59721120/find-equal-columns-between-two-dataframes
I have two pandas data frames, a and b: a1 a2 a3 a4 a5 a6 a7 1 3 4 5 3 4 5 0 2 0 3 0 2 1 2 5 6 5 2 1 2 and b1 b2 b3 b4 b5 b6 b7 3 5 4 5 1 4 3 0 1 2 3 0 0 2 2 2 1 5 2 6 5 The two data frames contain exactly the same data, but in a different order and with different column names. Based on the numbers in the two data fr...
Here's one way leveraging broadcasting to check for equality between both dataframes and taking all on the result to check where all rows match. Then we can obtain indexing arrays for both dataframe's column names from the result of np.where (with @piR's contribution): i, j = np.where((a.values[:,None] == b.values[:,:,...
19
18
59,737,875
2020-1-14
https://stackoverflow.com/questions/59737875/keras-change-learning-rate
I'm trying to change the learning rate of my model after it has been trained with a different learning rate. I read here, here, here and some other places i can't even find anymore. I tried: model.optimizer.learning_rate.set_value(0.1) model.optimizer.lr = 0.1 model.optimizer.learning_rate = 0.1 K.set_value(model.optim...
You can change the learning rate as follows: from keras import backend as K K.set_value(model.optimizer.learning_rate, 0.001) Included into your complete example it looks as follows: from keras.models import Sequential from keras.layers import Dense from keras import backend as K import keras import numpy as np model ...
57
65
59,686,945
2020-1-10
https://stackoverflow.com/questions/59686945/django-postgres-percentile-median-and-group-by
I need to calculate period medians per seller ID (see simplyfied model below). The problem is I am unable to construct the ORM query. Model class MyModel: period = models.IntegerField(null=True, default=None) seller_ids = ArrayField(models.IntegerField(), default=list) aux = JSONField(default=dict) Query queryset = ( ...
You can create a Median child class of the Aggregate class as was done by Ryan Murphy (https://gist.github.com/rdmurphy/3f73c7b1826cacee34f6c2a855b12e2e). Median then works just like Avg: from django.db.models import Aggregate, FloatField class Median(Aggregate): function = 'PERCENTILE_CONT' name = 'median' output_fie...
7
19
59,741,453
2020-1-14
https://stackoverflow.com/questions/59741453/is-there-a-general-way-to-run-web-applications-on-google-colab
I would like to develop web apps in Google colab. The only issue is that you need a browser connected to local host to view the web app, but Google colab doesn't have a browser inside the notebook. But it seems that there are ways around this. For example run_with_ngrok is a library for running flaks apps in colab/jup...
You can plan to start a server on a port, e.g. port=8000. Find the URL to use this way. from google.colab.output import eval_js print(eval_js("google.colab.kernel.proxyPort(8000)")) # https://z4spb7cvssd-496ff2e9c6d22116-8000-colab.googleusercontent.com/ Then, start the server, e.g. !python -m http.server 8000 And cl...
30
44
59,718,130
2020-1-13
https://stackoverflow.com/questions/59718130/what-are-c-classes-for-a-nllloss-loss-function-in-pytorch
I'm asking about C classes for a NLLLoss loss function. The documentation states: The negative log likelihood loss. It is useful to train a classification problem with C classes. Basically everything after that point depends upon you knowing what a C class is, and I thought I knew what a C class was but the documenta...
Basically you are missing a concept of batch. Long story short, every input to loss (and the one passed through the network) requires batch dimension (i.e. how many samples are used). Breaking it up, step by step: Your example vs documentation Each step will be each step compared to make it clearer (documentation on to...
8
8
59,732,335
2020-1-14
https://stackoverflow.com/questions/59732335/is-there-any-disadvantage-in-using-pythondontwritebytecode-in-docker
In many Docker tutorials based on Python (such as: this one) they use the option PYTHONDONTWRITEBYTECODE in order to make Python avoid to write .pyc files on the import of source modules (This is equivalent to specifying the -B option). What are the risks and advantages of setting this option up?
When you run a single python process in the container, which does not spawn other python processes itself during its lifetime, then there is no "risk" in doing that. Storing byte code on disk is used to compile python into byte code just upon the first invocation of a program and its dependent libraries to save that st...
83
84
59,734,277
2020-1-14
https://stackoverflow.com/questions/59734277/filerequiredvalidator-doesnt-work-when-using-multiplefilefield-in-my-form
My UploadForm class: from app import app from flask_wtf.file import FileRequired, FileAllowed from wtforms.fields import MultipleFileField from wtforms.validators import InputRequired,DataRequired class UploadForm(FlaskForm): . . . roomImage = MultipleFileField('Room',validators=[FileAllowed(['jpg', 'png'], 'Image onl...
This works for me (found on GitHub "between the lines"): multi_file = MultipleFileField("Upload File(s)", validators=[DataRequired()]) However FileAllowed(["xml", "jpg"]) is ignored and does not work for me. EDIT: No, sadly, it does not work... It returns True for form.validate() and for form.validate_on_submit() bu...
8
2
59,649,413
2020-1-8
https://stackoverflow.com/questions/59649413/violin-plot-for-positive-values-with-python
I find violin plots very informative and useful, I use python library 'seaborn'. However, when applied to positive values, they nearly always show negative values at the lower end. I find this really misleading, especially when working with real-life datasets. In the official documentation of seaborn https://seaborn.py...
You can use the keyword cut=0 to limit your plot to the data range. If the data doesn't have negative values, this will chop the end of the violin to zero. Using the same example as you, try: ax = sns.violinplot(x="day", y="total_bill", hue="smoker",data=tips, palette="muted", split=True,cut=0)
10
13
59,725,560
2020-1-13
https://stackoverflow.com/questions/59725560/finding-all-the-combinations-of-free-polyominoes-within-a-specific-area-with-a-s
I am new to the world of SAT solvers and would need some guidance regarding the following problem. Considering that: ❶ I have a selection of 14 adjacent cells in a 4*4 grid ❷ I have 5 polyominoes (A, B, C, D, E) of sizes 4, 2, 5, 2 and 1 ❸ these polyominoes are free, i.e. their shape is not fixed and can form differe...
One relatively straightforward way to constrain a simply connected region in OR-Tools is to constrain its border to be a circuit. If all your polyominos are to have size less than 8, we don’t need to worry about non-simply connected ones. This code finds all 3884 solutions: from ortools.sat.python import cp_model cells...
19
5
59,721,109
2020-1-13
https://stackoverflow.com/questions/59721109/why-are-deep-learning-libraries-so-huge
I've recently downloaded all packages from PyPI. One interesting observation was that of the Top-15 of the biggest packages, all execept one are deep learning packages: mxnet: mxnet-cu90 (600 MB), mxnet-cu92, mxnet-cu101mkl, mxnet-cu101 (and 6 more mxnet versions) cntk: cntk-gpu (493MB) H2O4GPU (366MB) tensorflow: ten...
Deep learning frameworks are large because they package CuDNN from NVIDIA into their wheels. This is done for the convenience of downstream users. CuDNN are the primitives that the frameworks call to execute highly optimised neural network ops (e.g. LSTM) The unzipped version of CuDNN for windows 10 is 435MB.
12
6
59,711,301
2020-1-13
https://stackoverflow.com/questions/59711301/install-pyqt5-5-14-1-on-linux
pip3 install PyQt5 Collecting PyQt5 Using cached https://files.pythonhosted.org/packages/3a/fb/eb51731f2dc7c22d8e1a63ba88fb702727b324c6352183a32f27f73b8116/PyQt5-5.14.1.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/usr/lib/py...
I think the initial pip install woes were due to PyQt5 switching to the manylinux2014 platform tag for the latest release (see the wheels on PyPI for 5.14.1 vs 5.14.0). Only pip versions >= 19.3 recognize this platform tag (ref), so if you happen to have an older version of pip, it would instead try to install from sou...
37
70
59,659,146
2020-1-9
https://stackoverflow.com/questions/59659146/could-not-import-pillow-version-from-pil
While importing, Python (Anaconda) gives the following error: ImportError: cannot import name 'PILLOW_VERSION' from 'PIL' I tried removing pillow and then conda install but the error persists.
Pillow 7.0.0 removed PILLOW_VERSION, you should use __version__ in your own code instead. https://pillow.readthedocs.io/en/stable/deprecations.html#pillow-version-constant Edit (2020-01-16): If using torchvision, this has been fixed in v0.5.0. To fix: Require torchvision>=0.5.0 If Pillow was temporarily pinned, re...
34
33
59,682,542
2020-1-10
https://stackoverflow.com/questions/59682542/typeerror-len-is-not-well-defined-for-symbolic-tensors-activation-3-identity
I am trying to implement a DQL model on one game of openAI gym. But it's giving me following error. TypeError: len is not well defined for symbolic Tensors. (activation_3/Identity:0) Please call x.shape rather than len(x) for shape information. Creating a gym environment: ENV_NAME = 'CartPole-v0' env = gym.make(ENV_N...
The reason this breaks is because, tf.Tensor TF 2.0.0 (and TF 1.15) has the __len__ overloaded and raises an exception. But TF 1.14 for example doesn't have the __len__ attribute. Therefore, anything TF 1.15+ (inclusive) breaks keras-rl (specifically here), which gives you the above error. So you got two options, Down...
14
9
59,741,934
2020-1-14
https://stackoverflow.com/questions/59741934/python-pandas-merge-multiple-columns-into-a-dictionary-column
I have a dataframe (df_full) like so: |cust_id|address |store_id|email |sales_channel|category| ------------------------------------------------------------------- |1234567|123 Main St|10SjtT |idk@gmail.com|ecom |direct | |4567345|345 Main St|10SjtT |101@gmail.com|instore |direct | |1569457|876 Main St|51FstT |404@gmai...
Use to_dict, columns = ['store_id', 'email', 'sales_channel', 'category'] df['metadata'] = df[columns].to_dict(orient='records') And if you want to drop original columns, df = df.drop(columns=columns)
11
20
59,740,434
2020-1-14
https://stackoverflow.com/questions/59740434/how-to-print-intercept-and-slope-of-a-simple-linear-regression-in-python-with-sc
I am trying to predict car prices (by machine learning) with a simple linear regression (only one independent variable). The variables are "highway miles per gallon" 0 27 1 27 2 26 3 30 4 22 .. 200 28 201 25 202 23 203 27 204 25 Name: highway-mpg, Length: 205, dtype: int64 and "price": 0 13495.0 1 16500.0 2 16500.0 3 ...
Essentially, what caused the strange looking coef_ and intercept_ was the fact that your data had 205 features and 205 targets with only 1 sample. Definitely not what you wanted! You probably want 1 feature, 205 samples, and 1 target. To do this, you need to reshape your data: from sklearn.linear_model import LinearReg...
10
24
59,739,434
2020-1-14
https://stackoverflow.com/questions/59739434/how-to-force-all-strings-to-floats
I have a small dataframe, consisting of just two columns, which should have all floats in it. So, I have two fields name 'Price' and 'Score'. When I look at the data, it all looks like floats to me, but apparently something is a string. Is there some way to kick out these things that are strings, but look like floats? ...
You could try using pd.to_numeric like so: df = df.apply(pd.to_numeric, errors='coerce', downcast='float') Which would try to convert your data to float, and the data that is not float will be returned as Nan. Then df.dropna(how='any', axis=0, inplace=True) which just drops any rows with at least 1 Nan value in it.
8
5
59,733,820
2020-1-14
https://stackoverflow.com/questions/59733820/django-rest-framework-drf-typeerror-register-got-an-unexpected-keyword-arg
I have updated to djangorestframework==3.11.0 from older version. Now I've got this error, TypeError: register() got an unexpected keyword argument 'base_name' Traceback ... ... ... File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/abu/projects/django-example/django2x/urls.py", ...
From the release notes of Django RestFramework and DRF 3.9 announcement they mentioned that Deprecate the Router.register base_name argument in favor of basename. #5990 Which means, the argument base_name is no longer available from DRF=3.11 onwards and use basename instead So, Change your router config as, router.r...
34
76
59,712,892
2020-1-13
https://stackoverflow.com/questions/59712892/dont-understand-keras-double-parentheses-syntax
Hi I am new to python and keras and looking in some keran example code: model = VGG19(weights='imagenet',include_top=False) model.trainable=False x = Flatten(name='flat')(model) x = Dense(512, activation='relu', name='fc1')(x) x = Dense(512, activation='relu', name='fc2')(x) x = Dense(10, activation='softmax', name='pr...
This might be an easier to understand version of these chained calls: model = VGG19(weights='imagenet',include_top=False) model.trainable=False layer1 = Flatten(name='flat')(model) layer2 = Dense(512, activation='relu', name='fc1')(layer1) layer3 = Dense(512, activation='relu', name='fc2')(layer2) layer4 = Dense(10, ac...
7
5
59,655,537
2020-1-9
https://stackoverflow.com/questions/59655537/property-setter-for-subclass-of-pandas-dataframe
I am trying to set up a subclass of pd.DataFrame that has two required arguments when initializing (group and timestamp_col). I want to run validation on those arguments group and timestamp_col, so I have a setter method for each of the properties. This all works until I try to set_index() and get TypeError: 'NoneType'...
The set_index() method will call self.copy() internally to create a copy of your DataFrame object (see the source code here), inside which it uses your customized constructor method, _internal_ctor(), to create the new object (source). Note that self._constructor() is identical to self._internal_ctor(), which is a comm...
9
4
59,717,828
2020-1-13
https://stackoverflow.com/questions/59717828/copy-type-signature-from-another-function
Imagine I have a set of functions like below. foo has a lot of arguments of various types, and bar passes all its arguments to that other function. Is there any way to make mypy understand that bar has the same type as foo without explicitly copying the whole argument list? def foo(a: int, b: float, c: str, d: bool, *e...
There's been a lot of discussion about adding this feature here. For the straightforward case of passing all arguments you can use the recipe from this comment: F = TypeVar('F', bound=Callable[..., Any]) class copy_signature(Generic[F]): def __init__(self, target: F) -> None: ... def __call__(self, wrapped: Callable[.....
23
18
59,706,137
2020-1-12
https://stackoverflow.com/questions/59706137/what-is-alpha-in-ridge-regression
What is the parameter alpha in ridge regression and how does it influence the trained regression? So examples would be helpful for me :)
Ridge or Lasso regression is basically Shrinkage(regularization) techniques, which uses different parameters and values to shrink or penalize the coefficients. When we fit a model, we are asking it to learn a set of coefficients that best fit over the training distribution as well as hope to generalize on test data poi...
7
11
59,704,538
2020-1-12
https://stackoverflow.com/questions/59704538/what-is-a-dimensional-range-of-1-0-in-pytorch
So I'm struggling to understand some terminology about collections in Pytorch. I keep running into the same kinds of errors about the range of my tensors being incorrect, and when I try to Google for a solution often the explanations are further confusing. Here is an example: m = torch.nn.LogSoftmax(dim=1) input = torc...
When specifying a tensor's dimension as an argument for a function (e.g. m = torch.nn.LogSoftmax(dim=1)) you can either use positive dimension indexing starting with 0 for the first dimension, 1 for the second etc. Alternatively, you can use negative dimension indexing to start from the last dimension to the first: -1 ...
7
6
59,701,981
2020-1-12
https://stackoverflow.com/questions/59701981/bert-tokenizer-model-download
I`m beginner.. I'm working with Bert. However, due to the security of the company network, the following code does not receive the bert model directly. tokenizer = BertTokenizer.from_pretrained('bert-base-multilingual-cased', do_lower_case=False) model = BertForSequenceClassification.from_pretrained("bert-base-multilin...
As described here, what you need to do are download pre_train and configs, then putting them in the same folder. Every model has a pair of links, you might want to take a look at lib code. For instance import torch from transformers import * model = BertModel.from_pretrained('/Users/yourname/workplace/berts/') with /...
9
14
59,702,410
2020-1-12
https://stackoverflow.com/questions/59702410/cython-returns-0-for-expression-that-should-evaluate-to-0-5
For some reason, Cython is returning 0 on a math expression that should evaluate to 0.5: print(2 ** (-1)) # prints 0 Oddly enough, mix variables in and it'll work as expected: i = 1 print(2 ** (-i)) # prints 0.5 Vanilla CPython returns 0.5 for both cases. I'm compiling for 37m-x86_64-linux-gnu, and language_level is ...
It's because it's using C ints rather than Python integers so it matches C behaviour rather than Python behaviour. I'm relatively sure this used to be documented as a limitation somewhere but I can't find it now. If you want to report it as a bug then go to https://github.com/cython/cython/issues, but I suspect this is...
8
4
59,696,421
2020-1-11
https://stackoverflow.com/questions/59696421/why-we-need-asyncio-synchronization-primitives-when-to-use-these
According to asyncio synchronization primitives, there are synchronization methods. I am getting confused about why we need synchronization in asyncio? I mean, asyncio is asynchronous. Is it meaningful to add something synchronous in asynchronization?
Synchronization primitives don't make your code synchronous, they make coroutines in your code synchronized. Few examples: You may want to start/continue some coroutine only when another coroutine allows it (asyncio.Event) You may want some part of your code to be executed only by single coroutine at the same time and...
9
12
59,693,174
2020-1-11
https://stackoverflow.com/questions/59693174/attributeerror-posixpath-object-has-no-attribute-path
I have a python script that I'm trying to execute but i'm not sure how it's meant to be executed. I don't program in Python so i'm unfamiliar with the language. Here is the link to the script i'm trying to use. Also, a link the configuration it's using if you wish to see it. All it seems to do for what's relevant here,...
Going through your code, I think you might mean: self.root = course at that line. Path.cwd() returns: ... the current working directory, that is, the directory from where you run the script. that is, either a WindowsPath() or a PosixPath object. I believe it is PosixPath for you, and you can verify with: import os p...
13
4
59,690,457
2020-1-11
https://stackoverflow.com/questions/59690457/whats-the-difference-between-auto-remove-and-remove-in-docker-sdk-for-python
I'm learning to use docker SDK. I understand that containers need to be removed after run, otherwise requiring pruning later on. I'm see that there are two boolean flags in client.containers.run: auto_remove (bool) – enable auto-removal of the container on daemon side when the container’s process exits. remove (bool)...
It's in fact exactly that: AutoRemove is one of the parameters to the "create a container" Docker API call, but the remove option signals the client library to remove the container after it exits. Setting auto_remove: True is probably more robust (the container will still clean itself up if the coordinator process cras...
11
8
59,689,524
2020-1-10
https://stackoverflow.com/questions/59689524/how-to-add-variable-type-annotation-for-what-goes-into-a-queue
e.g. from queue import Queue q: Queue = Queue() q.put("abc") This is okay. Now I want to specify the types that go into the queue. from queue import Queue q: Queue[str] = Queue() q.put("abc") This gets "TypeError: 'type' object is not subscriptable"
This isn't currently supported by the typing functionality. See this discussion of Python core developers: https://bugs.python.org/issue33315 It also suggests a current workaround, to put the annotation in quotes: q: "Queue[str]" = Queue() The workaround is that an annotation can be any type (no pun intended). A strin...
15
12
59,638,155
2020-1-8
https://stackoverflow.com/questions/59638155/how-to-set-0-to-white-at-an-uneven-colormap
I have an uneven colormap and I want the 0 to be white. All negative colors have to be bluish and all positive colors have to be reddish. My current attempt displays the 0 bluish and the 0.7 white. Is there any way to set the 0 to white? import numpy as np import matplotlib.colors as colors from matplotlib import pyplo...
The other answer makes it a little more complicated than it needs to be. In order to have the middle point of the colormap at 0, use a DivergingNorm with vcenter=0. import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import DivergingNorm x, y = np.meshgrid(np.linspace(0,50,51), np.linspace(0,50,51...
8
12
59,678,780
2020-1-10
https://stackoverflow.com/questions/59678780/show-extra-columns-when-hovering-in-a-scatter-plot-with-hvplot
I'm trying to add a label or hover column to the points in a scatter plot, but to no avail. For use as example data: import pandas as pd import holoviews as hv import hvplot.pandas df = pd.read_csv('http://assets.holoviews.org/macro.csv', '\t') df.query("year == 1966").hvplot.scatter(x="gdp", y="unem") results in the ...
You can use keyword hover_cols to add additional columns to your hover. Documentation: https://hvplot.holoviz.org/user_guide/Customization.html hover_cols (default=[]): list or str Additional columns to add to the hover tool or 'all' which will includes all columns (including indexes if use_index is True). So in yo...
11
16
59,669,715
2020-1-9
https://stackoverflow.com/questions/59669715/fastest-way-to-find-the-rgb-pixel-color-count-of-image
I have a use case where i have to find the consecutive rgb pixel color count of each frame of live video after searching i found a piece of code which does the same thing but performance wise it take around ~ 3 sec to give me output but in my case i have to do this calculation as fast as possible may be 25 frames in 1 ...
You need to use Numpy, or OpenCV, for fast image processing in Python. I made a 9-colour version of Paddington: from PIL import Image import numpy as np # Open Paddington and make sure he is RGB - not palette im = Image.open('paddington.png').convert('RGB') # Make into Numpy array na = np.array(im) # Arrange all pixel...
7
17
59,662,920
2020-1-9
https://stackoverflow.com/questions/59662920/how-to-get-the-mode-of-distribution-in-scipy-stats
The scipy.stats library has functions to find the mean and median of a fitted distribution but not mode. If I have the parameters of a distribution after fitting to data, how can I find the mode of the fitted distribution?
If I don't get your wrong, you want to find the mode of fitted distributions instead of mode of a given data. Basically, we can do it with following 3 steps. Step 1: generate a dataset from a distribution from scipy import stats from scipy.optimize import minimize # generate a norm data with 0 mean and 1 variance data ...
9
7
59,666,138
2020-1-9
https://stackoverflow.com/questions/59666138/sklearn-roc-auc-score-with-multi-class-ovr-should-have-none-average-available
I'm trying to compute the AUC score for a multiclass problem using the sklearn's roc_auc_score() function. I have prediction matrix of shape [n_samples,n_classes] and a ground truth vector of shape [n_samples], named np_pred and np_label respectively. What I'm trying to achieve is the set of AUC scores, one for each cl...
As you already know, right now sklearn multiclass ROC AUC only handles the macro and weighted averages. But it can be implemented as it can then individually return the scores for each class. Theoretically speaking, you could implement OVR and calculate per-class roc_auc_score, as: roc = {label: [] for label in multi_c...
15
7
59,672,062
2020-1-9
https://stackoverflow.com/questions/59672062/elegant-way-in-python-to-make-sure-a-string-is-suitable-as-a-filename
I want to use a user-provided string as a filename for exporting, but have to make sure that the string is permissible on my system as a filename. From my side it would be OK to replace any forbidden character with e.g. '_'. Here I found a list of forbidden characters for filenames. It should be easy enough to use the...
pathvalidate is a Python library to sanitize/validate a string such as filenames/file-paths/etc. This library provides both utilities for validation of paths: import sys from pathvalidate import ValidationError, validate_filename try: validate_filename("fi:l*e/p\"a?t>h|.t<xt") except ValidationError as e: print("{}\n...
10
10
59,669,413
2020-1-9
https://stackoverflow.com/questions/59669413/what-is-the-canonical-way-to-split-tf-dataset-into-test-and-validation-subsets
Problem I was following a Tensorflow 2 tutorial on how to load images with pure Tensorflow, because it is supposed to be faster than with Keras. The tutorial ends before showing how to split the resulting dataset (~tf.Dataset) into a train and validation dataset. I checked the reference for tf.Dataset and it does not ...
I don't think there's a canonical way (typically, data is being split e.g. in separate directories). But here's a recipe that will let you do it dynamically: # Caveat: cache list_ds, otherwise it will perform the directory listing twice. ds = list_ds.cache() # Add some indices. ds = ds.enumerate() # Do a rougly 70-30 s...
8
14
59,662,533
2020-1-9
https://stackoverflow.com/questions/59662533/argparse-append-action-with-default-value-only-if-argument-doesnt-appear
I'm parsing CLI arguments in my program with the argparse library. I would like to parse an argument that can repeat, with the following behaviour: if the argument appears at least once, its values are stored in a list, if the argument doesn't appear, the value is some default list. I have the following code so far: ...
There's a bug/issue discussing this behavior. I wrote several posts to that. https://bugs.python.org/issue16399 argparse: append action with default list adds to list instead of overriding For now the only change is in documentation, not in behavior. All defaults are placed in the namespace at the start of parsing. For...
14
15
59,661,074
2020-1-9
https://stackoverflow.com/questions/59661074/holoviews-charts-sharing-axis-when-combined-and-outputted
I'm using Holoviews to construct a dashboard of charts. Some of these charts have percentages in the y axis where as others have sums/counts etc. When I try to output all the charts I have created to a html file, all the charts change their y axis to match the axis of the first chart of my chart list. For example: Ch...
This happens when the y-axes have the same name. You need to use option axiswise=True if you want every plot to get its own independent x-axis and y-axis. There's a short reference to axiswise in the holoviews FAQ: https://www.holoviews.org/FAQ.html Here's a code example that I've checked and works: # import librarie...
13
10
59,661,904
2020-1-9
https://stackoverflow.com/questions/59661904/what-does-equal-do-in-f-strings-inside-the-expression-curly-brackets
The usage of {} in Python f-strings is well known to execute pieces of code and give the result in string format. However, what does the '=' at the end of the expression mean? log_file = open("log_aug_19.txt", "w") console_error = '...stuff...' # the real code generates it with regex log_file.write(f'{console_error=}')...
This is actually a brand-new feature as of Python 3.8. Added an = specifier to f-strings. An f-string such as f'{expr=}' will expand to the text of the expression, an equal sign, then the representation of the evaluated expression. Essentially, it facilitates the frequent use-case of print-debugging, so, whereas we w...
81
116
59,656,759
2020-1-9
https://stackoverflow.com/questions/59656759/what-is-a-best-way-to-intersect-multiple-arrays-with-numpy-array
Suppose I have an example of numpy array: import numpy as np X = np.array([2,5,0,4,3,1]) And I also have a list of arrays, like: A = [np.array([-2,0,2]), np.array([0,1,2,3,4,5]), np.array([2,5,4,6])] I want to leave only these items of each list that are also in X. I expect also to do it in a most efficient/common wa...
One idea would be less compute and minimal work when looping. So, here's one with those in mind - a = np.concatenate(A) m = np.isin(a,X) l = np.array(list(map(len,A))) a_m = a[m] cut_idx = np.r_[0,l.cumsum()] l_m = np.add.reduceat(m,cut_idx[:-1]) cl_m = np.r_[0,l_m.cumsum()] out = [a_m[i:j] for (i,j) in zip(cl_m[:-1],c...
7
2
59,652,882
2020-1-8
https://stackoverflow.com/questions/59652882/comparing-lists-in-two-columns-row-wise-efficiently
When having a Pandas DataFrame like this: import pandas as pd import numpy as np df = pd.DataFrame({'today': [['a', 'b', 'c'], ['a', 'b'], ['b']], 'yesterday': [['a', 'b'], ['a'], ['a']]}) today yesterday 0 ['a', 'b', 'c'] ['a', 'b'] 1 ['a', 'b'] ['a'] 2 ['b'] ['a'] ... etc But with about 100 000 entries, I am look...
Not sure about performance, but at the lack of a better solution this might apply: temp = df[['today', 'yesterday']].applymap(set) removals = temp.diff(periods=1, axis=1).dropna(axis=1) additions = temp.diff(periods=-1, axis=1).dropna(axis=1) Removals: yesterday 0 {} 1 {} 2 {a} Additions: today 0 {c} 1 {b} 2 {b}
17
15
59,645,496
2020-1-8
https://stackoverflow.com/questions/59645496/how-to-perform-a-join-in-salesforce-soql-simple-salesforce-python-library
I am using simpleSalesforce library for python to query SalesForce. I am looking at two different object in SalesForce: Account and Opportunity (parent-child). There is an accountId inside the opportunity object. I am trying to perform an inner join between the two and select the results (fields from both objects). a n...
Salesforce doesn't allow arbitrary joins. You must write relationship queries to traverse predefined relationships in the Salesforce schema. Here, you'd do something like SELECT Name, (SELECT StageName FROM Opportunities) FROM Account No explicit join logic is required, or indeed permitted. Note too that your return v...
12
7
59,647,765
2020-1-8
https://stackoverflow.com/questions/59647765/how-to-obtain-a-list-of-all-markers-in-matplotlib
The diagrams I am generating have many lines, and I want to automatically use colors and markers to distinguish them. I tried this: for i,studyDframeTuple in enumerate(studyDframeTuples): time = studyDframeTuple[1]['time'] error = studyDframeTuple[1]['Linf velocity error'] caseName = studyDirs[studyDframeTuple[0]] ax...
12 doesn't exist as marker value. You can have a dict of all existing markers using this : from matplotlib.lines import Line2D print(Line2D.markers) Output: {'.': 'point', ',': 'pixel', 'o': 'circle', 'v': 'triangle_down', '^': 'triangle_up', '<': 'triangle_left', '>': 'triangle_right', '1': 'tri_down', '2': 'tri_up',...
10
22
59,643,874
2020-1-8
https://stackoverflow.com/questions/59643874/aws-cdk-error-when-deploying-redis-elasticache-subnet-group-belongs-to-a-diffe
Summary I am trying to deploy a Redis ElastiCache Cluster on AWS using CDK. I want the cluster to be within a VPC for security reasons. My code (see supra) defines a VPC, a security group, a cache subnet group (linked to vpc private subnets) and the cache cluster (linked to both cache subnet group and the security grou...
I can see that CacheSubnetGroupName is missing in the CacheCluster definition in the generated template. That is why the cache is using the default VPC. CDK omits your subnet group definition as you assign it incorrectly. When using a Cfn resource, you should refer to other resources in your code using ref instead of a...
10
23
59,645,179
2020-1-8
https://stackoverflow.com/questions/59645179/update-anaconda-failed-entry-point-not-found
I have just tried to update my anaconda environment to the latest version and I am now receiving errors. I opened the conda environment as an admin, and the commands issued were: conda update conda conda update anaconda First command finished fine. Second command produced error: pythonw.exe - Entry Point Not Found The...
Sorry all - the clue was in the error message. The entry on how to fix entry point led me in the right direction. but it was the pythoncom37.dll file I needed to copy. That's what you get for blindly following instructions. Many thanks.
21
1
59,644,751
2020-1-8
https://stackoverflow.com/questions/59644751/show-both-value-and-percentage-on-a-pie-chart
Here's my current code values = pd.Series([False, False, True, True]) v_counts = values.value_counts() fig = plt.figure() plt.pie(v_counts, labels=v_counts.index, autopct='%.4f', shadow=True); Currently, it shows only the percentage (using autopct) I'd like to present both the percentage and the actual value (I don't ...
Create your own formatting function. Note that you have to recalculate the actual value from the percentage in that function somehow def my_fmt(x): print(x) return '{:.4f}%\n({:.0f})'.format(x, total*x/100) values = pd.Series([False, False, True, True, True, True]) v_counts = values.value_counts() total = len(values) f...
11
17
59,642,338
2020-1-8
https://stackoverflow.com/questions/59642338/creating-new-column-based-on-condition-on-other-column-in-pandas-dataframe
I have this dataframe: +------+--------------+------------+ | ID | Education | Score | +------+--------------+------------+ | 1 | High School | 7.884 | | 2 | Bachelors | 6.952 | | 3 | High School | 8.185 | | 4 | High School | 6.556 | | 5 | Bachelors | 6.347 | | 6 | Master | 6.794 | +------+--------------+------------+ ...
import pandas as pd # initialize list of lists data = [[1,'High School',7.884], [2,'Bachelors',6.952], [3,'High School',8.185], [4,'High School',6.556],[5,'Bachelors',6.347],[6,'Master',6.794]] # Create the pandas DataFrame df = pd.DataFrame(data, columns = ['ID', 'Education', 'Score']) df['Labels'] = ['Bad' if x<7.000...
7
12
59,638,571
2020-1-8
https://stackoverflow.com/questions/59638571/where-to-place-all-in-a-python-file
I am wondering, what the standard placement in a Python file for __all__? My assumption is directly below the import statements. However, I could not find this explicitly stated/asked anywhere. So, in general, where should one place __all__? Where would it be put in the below example file? #!/usr/bin/env python3 """Whe...
Per PEP 8: Module level "dunders" (i.e. names with two leading and two trailing underscores) such as __all__, __author__, __version__, etc. should be placed after the module docstring but before any import statements except from __future__ imports. So if you're following PEP 8 strictly, you were close. In practice, i...
10
21
59,638,035
2020-1-8
https://stackoverflow.com/questions/59638035/using-python-multiprocessing-queue-inside-aws-lambda-function
I have some python that creates multiple processes to complete a task much quicker. When I create these processes I pass in a queue. Inside the processes I use queue.put(data) so I am able to retrieve the data outside of the processes. It works fantastic on my local machine, but when I upload the zip to an AWS Lambda f...
doesn't look like it's supported - https://blog.ruanbekker.com/blog/2019/02/19/parallel-processing-on-aws-lambda-with-python-using-multiprocessing/
8
7
59,637,973
2020-1-8
https://stackoverflow.com/questions/59637973/how-to-run-virtualenv-python-on-mac
I am trying to use virtualenv to create a virtual python environment on my mac. I have downloaded virtualenv however I can't run it because it can't find the path to my installation of python3 even though I am supplying the correct path. Here is the command I have run and the response: virtualenv --python=/usr/local/bi...
Try: python3 -m venv venv source ./venv/bin/activate
20
63
59,586,879
2020-1-4
https://stackoverflow.com/questions/59586879/does-await-in-python-yield-to-the-event-loop
I was wondering what exactly happens when we await a coroutine in async Python code, for example: await send_message(string) (1) send_message is added to the event loop, and the calling coroutine gives up control to the event loop, or (2) We jump directly into send_message Most explanations I read point to (1), as the...
No, await (per se) does not yield to the event loop, yield yields to the event loop, hence for the case given: "(2) We jump directly into send_message". In particular, certain yield expressions are the only points, at bottom, where async tasks can actually be switched out (in terms of nailing down the precise spot wher...
29
60
59,591,969
2020-1-4
https://stackoverflow.com/questions/59591969/python-setuptools-quick-way-to-add-scripts-without-main-function-as-console
My request seems unorthodox, but I would like to quickly package an old repository, consisting mostly of python executable scripts. The problem is that those scripts were not designed as modules, so some of them execute code directly at the module top-level, and some other have the if __name__=='__main__' part. How wou...
There's some design considerations, but I would recommend using a __main__.py for this. it allows all command line invocations to share argument parsing logic you don't have to touch the scripts, at all it is explicit (no do-nothing functions that exist to trigger import) it enables refactoring out any other common st...
9
1
59,610,164
2020-1-6
https://stackoverflow.com/questions/59610164/how-to-evaluate-coroutine-in-pycharms-interactive-debugger
When interrupting execution of python async code with PyCharm's interactive debugger (breakpoints) we can inspect the environment with PyCharm's debugging tools like "evaluate expression" or "Execute Line in Python Console". How can we evaluate coroutines within these debugging tools?
Update from October 2022 Make sure you have the latest version of PyCharm, because they said they added this
10
3
59,579,859
2020-1-3
https://stackoverflow.com/questions/59579859/set-niceness-of-each-process-in-a-multiprocessing-pool
How can I set the niceness for each process in a multiprocessing.Pool? I understand that I can increment niceness with os.nice(), but how do call it in the child process after creating the pool? If I call it in the mapped function it will be called every time the function executes, rather than once when the process is ...
What about using an initializer for that? https://docs.python.org/3.8/library/multiprocessing.html#multiprocessing.pool.Pool The function is called once when the pool is started so the os.nice() call in the initializer sets the niceness for the proces after that. I've added some additional statements to show that it wo...
10
6
59,572,174
2020-1-3
https://stackoverflow.com/questions/59572174/no-module-named-dotenv-python-3-8
EDIT: Solved, if anyone comes across this python3.8 -m pip install python-dotenv worked for me. I've tried reinstalling both dotenv and python-dotenv but I'm still getting the same error. I do have the .env file in the same directory as this script. #bot.py import os import discord from dotenv import load_dotenv load...
in your installation manager if it's Ubuntu or Debian try: apt install python3-dotenv you can also try sudo pip3 install dotenv to install via pip. Whatever you do remember to include explicitly the missing 3 part. Debian/Ubuntu have separate packages and as of the present time python means python2 and python3 means py...
105
38
59,590,993
2020-1-4
https://stackoverflow.com/questions/59590993/where-can-i-download-a-pretrained-word2vec-map
I have been learning about NLP models and came across word embedding, and saw the examples in which it is possible to see relations between words by calculating their dot products and such. What I am looking for is just a dictionary, mapping words to their representative vectors, so I can play around with it. I know th...
You can try out Google's word2vec model trained with about 100 billion words from various news articles. An interesting fact about word vectors, w2v(king) - w2v(man) + w2v(woman) ≈ w2v(queen)
10
9
59,567,226
2020-1-2
https://stackoverflow.com/questions/59567226/how-to-programmatically-determine-available-gpu-memory-with-tensorflow
For a vector quantization (k-means) program I like to know the amount of available memory on the present GPU (if there is one). This is needed to choose an optimal batch size in order to have as few batches as possible to run over the complete data set. I have written the following test program: import tensorflow as tf...
This code will return free GPU memory in MegaBytes for each GPU: import subprocess as sp import os def get_gpu_memory(): command = "nvidia-smi --query-gpu=memory.free --format=csv" memory_free_info = sp.check_output(command.split()).decode('ascii').split('\n')[:-1][1:] memory_free_values = [int(x.split()[0]) for i, x i...
33
49
59,621,736
2020-1-7
https://stackoverflow.com/questions/59621736/despite-installing-the-torch-vision-pytorch-library-i-am-getting-an-error-sayin
The error that I am getting when I use import torchvision is this: Error Message "*Traceback (most recent call last): File "/Users/gokulsrin/Desktop/torch_basics/data.py", line 4, in <module> import torchvision ModuleNotFoundError: No module named 'torchvision'*" I don't know what to do. I have tried changing the vers...
From PyTorch installing Docs you should follow these steps: In Anaconda use this command: conda install pytorch torchvision cpuonly -c pytorch In Pip use this command: pip3 install torch==1.3.1+cpu torchvision==0.4.2+cpu -f https://download.pytorch.org/whl/torch_stable.html Note: If you have an enabled CUDA card yo...
31
18
59,563,498
2020-1-2
https://stackoverflow.com/questions/59563498/systemerror-class-pyodbc-error-returned-a-result-with-an-error-set
def insert(self): conn = pyodbc.connect( 'Driver={SQL Server};' 'Server=DESKTOP-S0VG212\SQLEXPRESS;' 'Database=MovieGuide;' 'Trusted_Connection=yes;' ) cursor = conn.cursor() Error occurs when executing the query but I don't know what's causing it. cursor.execute('insert into Movies(MovieName,Genre,Rating,Username) v...
I know my answer is late, but it can be useful to someone. SystemError: <class 'pyodbc.Error'> returned a result with an error set error appears when the query is wrong, make sure you are executing the correct query using SQL server query window then you can able to identify the problem. In the question, the semicolon ...
11
4
59,615,759
2020-1-6
https://stackoverflow.com/questions/59615759/high-precision-word-alignment-algorithm-in-python
I am working on a project for building a high precision word alignment between sentences and their translations in other languages, for measuring translation quality. I am aware of Giza++ and other word alignment tools that are used as part of the pipeline for Statistical Machine Translation, but this is not what I'm l...
I highly recommend testing Awesome-Align. It relies on multilingual BERT (mBERT) and the results look very promising. I even tested it with Arabic, and it did a great job on a difficult alignment example since Arabic is a morphology-rich language, and I believe it would be more challenging than a Latin-based language s...
8
6
59,620,543
2020-1-7
https://stackoverflow.com/questions/59620543/setup-py-install-running-egg-info-error-errno-13-permission-denied-regarless
I encountered a bug-like feature of setup.py where I am getting the Permission denied error regardless where I want to install the package without root privilege. I have a toy python package with a few tiny files, and there is no problem of building it. There is nothing special in the setup.py file. I will list one or ...
The reason for this particular difficulty is because I run sudo before in the package directory and it created some directories owned by root. Afterwards, I run as a regular user and got permission issues. The fix is ownership change. cd ~/lib/python3.8/site-packages sudo chown -R myuid:mygroup * After the above actio...
7
9
59,637,048
2020-1-7
https://stackoverflow.com/questions/59637048/how-to-find-element-by-part-of-its-id-name-in-selenium-with-python
I'm using selenium with python,now I want to locate an element by part of its id name,what can I do? For example,now I've already located a item by id name coption5 : sixth_item = driver.find_element_by_id("coption5") Is there anyway I can locate this element only by using coption?
To find the element which you have located with: sixth_item = driver.find_element_by_id("coption5") To locate this element only by using coption you can use can use either of the following Locator Strategies: Using XPATH and starts-with(): sixth_item = driver.find_element_by_xpath("//*[starts-with(@id, 'coption')]") ...
10
27
59,622,573
2020-1-7
https://stackoverflow.com/questions/59622573/pyspark-groupby-dataframe-without-aggregation-or-count
Can it iterate through the Pyspark groupBy dataframe without aggregation or count? For example code in Pandas: for i, d in df2: mycode .... ^^ if using pandas ^^ Is there a difference in how to iterate groupby in Pyspark or have to use aggregation and count?
At best you can use .first , .last to get respective values from the groupBy but not all in the way you can get in pandas. ex: from pyspark.sql import functions as f df.groupBy(df['some_col']).agg(f.first(df['col1']), f.first(df['col2'])).show() Since their is a basic difference between the way the data is handled in ...
7
3
59,563,085
2020-1-2
https://stackoverflow.com/questions/59563085/how-to-stop-training-when-it-hits-a-specific-validation-accuracy
I am training a convolutional network and I want to stop training once the validation error hits 90%. I thought about using EarlyStopping and setting baseline to .90 but then it stops training whenever the validation accuracy is below that baseline for given number of epochs(which is just 0 here). So my code is: es=Ear...
Early Stopping Callback will search for a value that stopped increasing (or decreasing) so it's not a good use for your problem. However tf.keras allows you to use custom callbacks. For your example: class MyThresholdCallback(tf.keras.callbacks.Callback): def __init__(self, threshold): super(MyThresholdCallback, self)....
9
10
59,549,829
2020-1-1
https://stackoverflow.com/questions/59549829/how-do-i-downgrade-my-version-of-python-from-3-7-5-to-3-6-5-on-ubuntu
So currently, I have ubuntu 19. And it comes by default with python 3.7.5. I need to downgrade to 3.6.5. EDIT: I am using virtualenv
The following talks about upgrade from 3.6.7 to 3.7.0 but you can use the same process for downgrade. You should not change the system python unless you really know what you're doing First Install Pyenv Installlation Instructions are here Look at Pyenv Options $ pyenv pyenv 1.2.14 Usage: pyenv <command> [<args>] Some ...
9
30
59,618,368
2020-1-6
https://stackoverflow.com/questions/59618368/sklearn-extra-installation-issue
[in]: from sklearn_extra.cluster import KMedoids [out]: ModuleNotFoundError: No module named 'sklearn_extra' Then, I tried installing sklearn_extra via [in]: python -m pip install sklearn_extra [out]: ERROR: Could not find a version that satisfies the requirement sklearn_extra (from versions: none) ERROR: No matchin...
Uninstalling enum34 worked for me and then I was able to install sklearn_extra pip uninstall -y enum34
12
0
59,622,277
2020-1-7
https://stackoverflow.com/questions/59622277/attributeerror-module-object-has-no-attribute-set-random-seed-when-i
The complete set of error messages are shown below: (FYP_v2) sg97-ubuntu@SG97-ubuntu:~/SGSN$ python2 ./train.py Traceback (most recent call last): File "./train.py", line 165, in <module> main() File "./train.py", line 65, in main tf.set_random_seed(args.random_seed) AttributeError: 'module' object has no attribute 'se...
Use tf.random.set_seed() instead of tf.set_random_seed. Link to the tensorflow doc here: https://www.tensorflow.org/api_docs/python/tf/random/set_seed?version=stable
7
31
59,589,647
2020-1-4
https://stackoverflow.com/questions/59589647/what-is-the-most-time-efficient-way-to-remove-unordered-duplicates-in-a-2d-array
I've generated a list of combinations, using itertools and I'm getting a result that looks like this: nums = [-5,5,4,-3,0,0,4,-2] x = [x for x in set(itertools.combinations(nums, 4)) if sum(x)==target] >>> x = [(-5, 5, 0, 4), (-5, 5, 4, 0), (5, 4, -3, -2), (5, -3, 4, -2)] What is the most time-complexity wise efficien...
Since you want to find unordered duplicates the best way to go is by typecasting. Typecast them as set. Since set only contains immutable elements. So, I made a set of tuples. Note: The best way to eliminate duplicates is by making a set of the given elements. >>> set(map(tuple,map(sorted,x))) {(-3, -2, 4, 5), (-5, 0...
7
7
59,580,517
2020-1-3
https://stackoverflow.com/questions/59580517/how-to-document-callable-classes-annotated-with-dataclass-in-sphinx
I researched this topic and cannot see a clear solution. There is a similar SO question My problem is that I have a class with attr.dataclass and typing_extensions.final annotations and I don't want them to be documented but I still want to describe the class from the point of how it would be called. For instance, @fin...
As @mzjn mentioned in comments :exclude-members: dataclass should do the job if automodule configured correctly. I made a dumb mistake that was hard to track. If you write :exclude-members: and <name-of-module> on the separate lines then all classes in the file will be ignored. Another part related to make constructor ...
7
3
59,623,952
2020-1-7
https://stackoverflow.com/questions/59623952/weird-issue-when-using-dataclass-and-property-together
I ran into a strange issue while trying to use a dataclass together with a property. I have it down to a minumum to reproduce it: import dataclasses @dataclasses.dataclass class FileObject: _uploaded_by: str = dataclasses.field(default=None, init=False) uploaded_by: str = None def save(self): print(self.uploaded_by) @p...
So, unfortunately, the @property syntax is always interpreted as an assignment to uploaded_by (since, well, it is). The dataclass machinery is interpreting that as a default value, hence why it is passing the property object! It is equivalent to this: In [11]: import dataclasses ...: ...: @dataclasses.dataclass ...: cl...
8
6
59,594,317
2020-1-4
https://stackoverflow.com/questions/59594317/how-can-i-add-a-python-package-to-a-shell-nix-if-its-not-in-nixpkgs
I have a shell.nix that I use for Python development that looks like this: with import <nixpkgs> {}; (( python37.withPackages (ps: with ps; [ matplotlib spacy pandas spacy_models.en_core_web_lg plotly ])).override({ignoreCollisions=true; })).env It works fine for these packages. The problem is, I also want to use col...
I did solve a similar problem like that: with import <nixpkgs> {}; ( let colormath = pkgs.python37Packages.buildPythonPackage rec { pname = "colormath"; version = "3.0.0"; src = pkgs.python37Packages.fetchPypi{ inherit version; inherit pname; sha256 = "05qjycgxp3p2f9n6lmic68sxmsyvgnnlyl4z9w7dl9s56jphaiix"; }; buildInpu...
7
7
59,633,558
2020-1-7
https://stackoverflow.com/questions/59633558/python-based-dockerfile-throws-locale-error-unsupported-locale-setting
I have a problem with passing the host's (Centos7) locales to the python3 docker image. Only the following locales end up in the image, even though I used the suggestion described in the link below: C C.UTF-8 POSIX Why does locale.getpreferredencoding() return 'ANSI_X3.4-1968' instead of 'UTF-8'? My Dockerfile has: FR...
What I would do for Debian based docker image: FROM python:3.7.5 RUN apt-get update && \ apt-get install -y locales && \ sed -i -e 's/# ru_RU.UTF-8 UTF-8/ru_RU.UTF-8 UTF-8/' /etc/locale.gen && \ dpkg-reconfigure --frontend=noninteractive locales ENV LANG ru_RU.UTF-8 ENV LC_ALL ru_RU.UTF-8 and then in python: import lo...
11
27
59,636,923
2020-1-7
https://stackoverflow.com/questions/59636923/create-a-grid-of-plots-with-holoviews-hvplot-and-set-the-max-number-of-columns
I'd like to plot several data into a grid using holoviews/hvplot, based on one dimension, which contains several unique data points. Considering this example: import seaborn as sns import hvplot.pandas iris = sns.load_dataset('iris') plot = iris.hvplot.scatter(x="sepal_length", y="sepal_width", col="species") hvplot.sh...
In your case I would not create a Gridspace (by using keyword 'row' and 'col') but a Layout. When you have a Layout you can adjust the number of columns easily with .cols(2). Using hvplot you have to use keyword 'by' and 'subplots=True' instead of 'col'. See the code below: iris.hvplot.scatter( x='sepal_length', y='s...
7
3
59,604,595
2020-1-5
https://stackoverflow.com/questions/59604595/how-to-extract-features-from-fft
I am gathering data from X, Y and Z accelerometer sensors sampled at 200 Hz. The 3 axis are combined into a single signal called 'XYZ_Acc'. I followed tutorials on how to transform time domain signal into frequency domain using scipy fftpack library. The code I'm using is the below: from scipy.fftpack import fft # get ...
Since 'XYZ_Acc' is defined as a linear combination of the components of the signal, taking its DFT makes sense. It is equivalent to using a 1D accelometer in direction (1,1,1). But a more physical energy-related viewpoint can be adopted. Computing the DFT is similar to writing the signal as a sum of sines. If the accel...
7
6
59,559,788
2020-1-2
https://stackoverflow.com/questions/59559788/pandas-zigzag-segmentation-of-data-based-on-local-minima-maxima
I have a timeseries data. Generating data date_rng = pd.date_range('2019-01-01', freq='s', periods=400) df = pd.DataFrame(np.random.lognormal(.005, .5,size=(len(date_rng), 3)), columns=['data1', 'data2', 'data3'], index= date_rng) s = df['data1'] I want to create a zig-zag line connecting between the local maxima and ...
I have answered to my best understanding of the question. Yet it is not clear to how the variable K influences the filter. You want to filter the extrema based on a running condition. I assume that you want to mark all extrema whose relative distance to the last marked extremum is larger than p%. I further assume that ...
12
5
59,636,631
2020-1-7
https://stackoverflow.com/questions/59636631/importerror-cannot-import-name-mutablemapping-from-collections
I have installed the AWS CLI using pip on my Python 3.9.0a1 alpine Docker image. Installation went fine. When I run the aws command, I'm getting the following error. aws Traceback (most recent call last): File "/usr/local/bin/aws", line 27, in <module> sys.exit(main()) File "/usr/local/bin/aws", line 23, in main return...
collections.MutableMapping has been deprecated since Python 3.3, and was officially removed since Python 3.9. Excerpt from the documentation: Deprecated since version 3.3, will be removed in version 3.9: Moved Collections Abstract Base Classes to the collections.abc module. You can either wait for a Python 3.9-compat...
14
19
59,636,344
2020-1-7
https://stackoverflow.com/questions/59636344/how-to-remove-extra-whitespace-from-image-in-opencv
I have the following image which is a receipt image and a lot of white space around the receipt in focus. I would like to crop the white space. I can't manually crop it so I'm looking for a way that I could do it. Cropped one: Tried this code from the following post: How to remove whitespace from an image in OpenCV? ...
Here's a simple approach: Obtain binary image. Load the image, convert to grayscale, apply a large Gaussian blur, and then Otsu's threshold Perform morphological operations. We first morph open with a small kernel to remove noise then morph close with a large kernel to combine the contours Find enclosing bounding box ...
7
9
59,635,147
2020-1-7
https://stackoverflow.com/questions/59635147/looping-through-multiple-arrays-concatenating-values-in-pandas
I've a dataframe with list of items separated by , commas as below. +----------------------+ | Items | +----------------------+ | X1,Y1,Z1 | | X2,Z3 | | X3 | | X1,X2 | | Y2,Y4,Z2,Y5,Z3 | | X2,X3,Y1,Y2,Z2,Z4,X1 | +----------------------+ Also I've 3 list of arrays which has all items said above clubbed into specific gr...
Setup df = pd.DataFrame( [['X1,Y1,Z1'], ['X2,Z3'], ['X3'], ['X1,X2'], ['Y2,Y4,Z2,Y5,Z3'], ['X2,X3,Y1,Y2,Z2,Z4,X1']], columns=['Items'] ) X = ['X1', 'X2', 'X3', 'X4', 'X5'] Y = ['Y1', 'Y2', 'Y3', 'Y4', 'Y5'] Z = ['Z1', 'Z2', 'Z3', 'Z4', 'Z5'] Counter from collections import Counter M = {**dict.fromkeys(X, 'X'), **dict...
7
6
59,634,937
2020-1-7
https://stackoverflow.com/questions/59634937/variable-foo-class-is-not-valid-as-type-but-why
I have something similar to this: from typing import Type class Foo: pass def make_a_foobar_class(foo_class: Type[Foo]) -> Type[Foo]: class FooBar(foo_class): # this.py:10: error: Variable "foo_class" is not valid as a type # this.py:10: error: Invalid base class "foo_class" pass return FooBar print(make_a_foobar_class...
Mypy, and the PEP 484 ecosystem in general, does not support creating classes with dynamic base types. This is likely because supporting such a feature is not worth the additional complexity: the type checker would need to implement additional logic/additional passes since it can no longer cleanly determine what exactl...
17
14
59,630,622
2020-1-7
https://stackoverflow.com/questions/59630622/how-to-enable-zoom-in-out-and-zoom-to-percentage-buttons-in-plots-pane-in-spyder
The zoom in, zoom out and zoom to percentage buttons are disabled in Plots pane in Spyder as shown here. Any idea how to enable them? The should be enabled as seen here. Specs Spyder version: 4.0.0 OS: elementary OS Python: 3.7.5 64-bit Kernel: Linux 5.4.7-050407-generic Laptop: Thinkpad E585 Failed attempts Following...
(Spyder maintainer here) To be able to use those buttons you need to deactivate the option called Fit plots to window, present in the Options menu of the Plots pane:
8
9
59,629,795
2020-1-7
https://stackoverflow.com/questions/59629795/how-can-i-split-columns-with-regex-to-move-trailing-caps-into-a-separate-column
I'm trying to split a column using regex, but can't seem to get the split correctly. I'm trying to take all the trailing CAPS and move them into a separate column. So I'm getting all the CAPS that are either 2-4 CAPS in a row. However, it's only leaving the 'Name' column while the 'Team' column is blank. Here's my code...
You may extract the data into two columns by using a regex like ^(.*?)([A-Z]+)$ or ^(.*[^A-Z])([A-Z]+)$: df[['Name','Team']] = df['Name'].str.extract('^(.*?)([A-Z]+)$', expand=True) This will keep all up to the last char that is not an uppercase letter in Group "Name" and the last uppercase letters in Group "Team". Se...
11
9
59,627,976
2020-1-7
https://stackoverflow.com/questions/59627976/integrating-dash-apps-into-flask-minimal-example
I want to create a Flask web-application. I want to integrate several Dash-Apps into this site and display links to each Dash-app on the home page. Here is a minimal example: The home page should look like this: from flask import Flask app = Flask(__name__) @app.route("/") def main(): return "Hello World" if __name__ =...
Combining One or More Dash Apps with Existing WSGI Apps The following example illustrates this approach by combining two Dash apps with a Flask app. flask_app.py from flask import Flask flask_app = Flask(__name__) @flask_app.route('/') def index(): return 'Hello Flask app' app1.py import dash import dash_html_componen...
12
14
59,559,294
2020-1-2
https://stackoverflow.com/questions/59559294/error-in-installing-python-package-flair-about-a-dependent-package-not-hosted-i
I am trying to install flair. It is throwing below error when executing below command: pip install flair ERROR: Packages installed from PyPI cannot depend on packages which are not also hosted on PyPI. tiny-tokenizer depends on SudachiDict_core@ https://object-storage.tyo2.conoha.io/v1/nc_2520839e1f9641b08211a5c8524312...
It is strange running below command solved the problem. pip install flair==0.4.3 I assume that the problem is in a latest version 0.4.4 (and its dependencies). Note: I had torch==1.1.0 package already installed.
7
0
59,624,729
2020-1-7
https://stackoverflow.com/questions/59624729/re-findallabcd-string-vs-re-findallabcd-string
In a Python regular expression, I encounter this singular problem. Could you give instruction on the differences between re.findall('(ab|cd)', string) and re.findall('(ab|cd)+', string)? import re string = 'abcdla' result = re.findall('(ab|cd)', string) result2 = re.findall('(ab|cd)+', string) print(result) print(resul...
I don't know if this will clear things more, but let's try to imagine what happen under the hood in a simple way, we going to sumilate what happen using match # group(0) return the matched string the captured groups are returned in groups or you can access them # using group(1), group(2)....... in your case there is o...
18
6
59,563,746
2020-1-2
https://stackoverflow.com/questions/59563746/how-to-clean-a-tox-environment-after-running
I have the following tox.ini file: [tox] envlist = flake8,py{35,36,37,38}{,-keyring} [testenv] usedevelop = True install_command = pip install -U {opts} {packages} deps = .[test] keyring: .[keyring] setenv = COVERAGE_FILE = .coverage.{envname} commands= pytest {toxinidir}/tests -n 4 {posargs} [testenv:flake8] basepytho...
I found a way by creating a tox hook. This hook runs the shutil.rmtree command after the tests have been run inside the env. In a tox_clean_env.py file: import shutil from tox import hookimpl @hookimpl def tox_runtest_post(venv): try: shutil.rmtree(venv.path) except Exception as e: print("An exception occurred while re...
10
5
59,614,014
2020-1-6
https://stackoverflow.com/questions/59614014/pypdf4-exported-pdf-file-size-too-big
I have a PDF file of around 7000 pages and 479 MB. I have create a python script using PyPDF4 to extract only specific pages if the pages contain specific words. The script works but the new PDF file, even though it has only 650 pages from the original 7000, now has more MB that the original file (498 MB to be exactly)...
After a lot of searching found some solutions. The only problem with the exported PDF file was that it was uncompressed. So I needed a solution to compress a PDF file: PyPDF2 and/or PyPDF4 do not have an option to compress PDFs. PyPDF2 had the compressContentStreams() method, which doesn't work. Found a few other solu...
8
11
59,620,431
2020-1-6
https://stackoverflow.com/questions/59620431/what-is-a-buffer-in-pytorch
I understand what register_buffer does and the difference between register_buffer and register_parameters. But what is the precise definition of a buffer in PyTorch?
This can be answered looking at the implementation: def register_buffer(self, name, tensor): if '_buffers' not in self.__dict__: raise AttributeError( "cannot assign buffer before Module.__init__() call") elif not isinstance(name, torch._six.string_classes): raise TypeError("buffer name should be a string. " "Got {}".f...
11
5
59,612,745
2020-1-6
https://stackoverflow.com/questions/59612745/can-i-set-a-default-value-of-prometheus-labels-in-python
I'm using the official python (2.7) client. I want to define a metric with some labels but I don't always have them all the labels to send. When I send only some of them I get the error: AttributeError: 'Counter' object has no attribute '_value' This is the code I used: c = Counter("counterTest, "explain this counter...
You must always specify all labels, how else would we know which series it is that you want to increment? You can specify an empty string as a label value, though this may cause confusion for your users.
7
4
59,619,940
2020-1-6
https://stackoverflow.com/questions/59619940/what-is-the-point-of-built-distributions-for-pure-python-packages
One can share Python as a source distribution (.tar.gz format) or as a built distribution (wheels format). As I understand it, the point of built distributions is: Save time: Compilation might be pretty time-consuming. We can do this once on the server and share it for many users. Reduce requirements: The user does no...
From pythonwheels.com: Advantages of wheels Faster installation for pure Python and native C extension packages. Avoids arbitrary code execution for installation. (Avoids setup.py) Installation of a C extension does not require a compiler on Linux, Windows or macOS. Allows better caching for testing and continuous in...
7
6
59,580,304
2020-1-3
https://stackoverflow.com/questions/59580304/extract-individual-field-from-table-image-to-excel-with-ocr
I have scanned images which have tables as shown in this image: I am trying to extract each box separately and perform OCR but when I try to detect horizontal and vertical lines and then detect boxes it's returning the following image: And when I try to perform other transformations to detect text (erode and dilate) ...
You're on the right track. Here's a continuation of your approach with slight modifications. The idea is: Obtain binary image. Load image, convert to grayscale, and Otsu's threshold. Remove all character text contours. We create a rectangular kernel and perform opening to only keep the horizontal/vertical lines. This ...
13
7