[{"Question":"I would like to make a PyTorch model that takes the outer product of the input with itself and then does a linear regression on that. As an example, consider the input vector [1,2,3], then I would like to compute w and b to optimize [1*1, 1*2, 1*3, 2*1, 2*2, 2*3, 3*1, 3*2, 3*3] @ w + b.\nFor a batch input with r rows and c columns, I can do this in PyTorch with\n(input.reshape(r,c,1) @ input.reshape(r,1,c)).reshape(r,c**2) @ weigts + b\nMy problem is that it is extraordinarily slow. Like a factor 1000 times slower and more memory consumptious than Adding a fully connected c*c RELU layer, even though it has the same number of weights.\nMy question is why this happens?\nIs reshape a very expensive operation for PyTorch? Could I reformulate it in a different way that would make things more efficient?\nAnother equivalent formulation I know is torch.diag(input @ weights @ input.T) + b, but now we are computing way more values than we need (r*r) just to throw them away again.","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":233,"Q_Id":60025695,"Users Score":1,"Answer":"It turns out that PyTorch has torch.bilinear, which is backed up by CUDA and does exactly what I need. That's neat and very fast. It still leaves the case of higher-order tensorings. I don't see any torch.trilinear and so forth, but for now it's great.","Q_Score":1,"Tags":"python,neural-network,pytorch,linear-algebra,tensor","A_Id":60031030,"CreationDate":"2020-02-02T11:37:00.000","Title":"Computing Linear Layer in Tensor\/Outer-Product space in PyTorch is Very Slow","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am having a problem that I can not use cv2.imshow() because of following error message\n\nqt.qpa.plugin: Could not find the Qt platform plugin \"cocoa\" in \"\"\nThis application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.\n\nLast Macbook I was using initially did not have QT so I have no idea how should I deal with it.\nAny ideas?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":8481,"Q_Id":60032540,"Users Score":43,"Answer":"I had the same issue after updating opencv - python to 4.2.0.32.\nUninstall opencv-python and install the lower version (e.g pip install opencv-python==4.1.0.25) solves this issue.","Q_Score":10,"Tags":"python,python-3.x,qt,opencv","A_Id":60032783,"CreationDate":"2020-02-03T02:50:00.000","Title":"OpenCV cv2.imshow is not working because of the qt","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":1,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am currently , successfully, importing stock information from Yahoo using pandas-datareader. However, before the extracted data, I always get the following message: \n\nFutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead.\n\nWould anyone have an idea of what it means and how to fix it?","AnswerCount":6,"Available Count":3,"Score":-0.0665680765,"is_accepted":false,"ViewCount":7121,"Q_Id":60039161,"Users Score":-2,"Answer":"For mac OS open \/Library\/Frameworks\/Python.framework\/Versions\/3.8\/lib\/python3.8\/site-packages\/pandas_datareader\/compat\/__init__.py\nchange: from pandas.util.testing import assert_frame_equal\nto: from pandas.testing import assert_frame_equal","Q_Score":2,"Tags":"python,pandas-datareader","A_Id":61034041,"CreationDate":"2020-02-03T12:22:00.000","Title":"Getting a \"Future Warning\" when importing for Yahoo with Pandas-Datareader","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am currently , successfully, importing stock information from Yahoo using pandas-datareader. However, before the extracted data, I always get the following message: \n\nFutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead.\n\nWould anyone have an idea of what it means and how to fix it?","AnswerCount":6,"Available Count":3,"Score":0.0,"is_accepted":false,"ViewCount":7121,"Q_Id":60039161,"Users Score":0,"Answer":"Cause: The cause of this warning is that, basically, the pandas_datareader is importing a module from the pandas library that will be deprecated. Specifically, it is importing pandas.util.testing whereas the new preferred module will be pandas.testing.\nSolution: First off this is a warning, and not an outright error, so it won't necessarily break your program. So depending on your exact use case, you may be able to ignore it for now.\nThat being said, there are a few options you can consider:\n\nOption 1: Change the code yourself -- Go into the pandas_datareader module and modify the line of code in compat_init.py that currently says from pandas.util.testing import assert_frame_equal simply to from pandas.testing import assert_frame_equal. This will import the same function from the correct module.\nOption 2: Wait for pandas-datareader to update --You can also wait for the library to be upgraded to import correctly and then run pip3 install --upgrade pandas-datareader. You can go to the Github repo for pandas-datareader and raise an issue.\nOption 3: Ignore it -- Just ignore the warning for now since it doesn't break your program.","Q_Score":2,"Tags":"python,pandas-datareader","A_Id":62805935,"CreationDate":"2020-02-03T12:22:00.000","Title":"Getting a \"Future Warning\" when importing for Yahoo with Pandas-Datareader","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am currently , successfully, importing stock information from Yahoo using pandas-datareader. However, before the extracted data, I always get the following message: \n\nFutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead.\n\nWould anyone have an idea of what it means and how to fix it?","AnswerCount":6,"Available Count":3,"Score":-0.0333209931,"is_accepted":false,"ViewCount":7121,"Q_Id":60039161,"Users Score":-1,"Answer":"You may find the 'util.testing' code in pandas_datareader, which is separate from pandas.","Q_Score":2,"Tags":"python,pandas-datareader","A_Id":60122268,"CreationDate":"2020-02-03T12:22:00.000","Title":"Getting a \"Future Warning\" when importing for Yahoo with Pandas-Datareader","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm training Yolov3 on my dataset. I'm training it on different resolutions of the image, trying to find the best speed\/quality ratio. I started wondering if I can compare the loss function of Yolo between different resolutions. Anchor sizes are proportional to resolution. \nSo does same loss on different resolutions mean I'd get approximately the same results on my test dataset?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":435,"Q_Id":60041695,"Users Score":0,"Answer":"In general input size changes the size of the final grid and so the number of predicted boxes. Depending on the implementation you use this can change the loss. If e.g. the loss values for one parameter are all summed up, more boxes would mean higher loss. If loss values are averaged over all boxes you can probably compare it.\nYou might wanna use some other form of evaluation besides just the loss. Depending on the task have a look at benchmarks and the metrics they are using. For object detection the IoU is often used to assign predictions to ground truth and calculate a precision out of it.","Q_Score":0,"Tags":"python,keras,deep-learning,conv-neural-network,yolo","A_Id":60046061,"CreationDate":"2020-02-03T14:53:00.000","Title":"How does Yolov3 loss function change with resolution of the image?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have unsigned 16-bit grayscale tiff images as numpy arrays. I want to do some image processing on these images using OpenCV. I am converting the numpy array to Mat format using cv2.cvtColor(src, code). As far as the documentation goes, I am having a hard time finding the right code argument to correctly convert 16-bit grayscale images without losing any information.\nPreviously, I read the images directly using cv2.imread(src, cv2.IMREAD_UNCHANGED). However, I don't have the original image files now, only the pickled numpy array. I am looking for the code in cvtColor which does a similar thing as cv2.IMREAD_UNCHANGED","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":318,"Q_Id":60044041,"Users Score":1,"Answer":"Your question is tough to follow. All you appear to have are some files containing pickled Numpy arrays, correct?\nIf so, you don't need any imread(), you just need to unpickle the files and you will have Numpy arrays of the type that OpenCV uses to hold images. Check their dtype is np.uint16 and their shape appears correct.","Q_Score":0,"Tags":"python,python-3.x,opencv,tiff","A_Id":60044639,"CreationDate":"2020-02-03T17:14:00.000","Title":"cvtColor \"code\" for 16-bit grayscale images","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I used a random forest classifier and now I want to see how good my classification was. Maybe even perform a grid search. My test data has no labels, meaning I only have x_train, y_train and x_test. Is there a way to calculate the error rate without having the accuracy?\nThank you in advance!","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":148,"Q_Id":60045062,"Users Score":0,"Answer":"It's not possible since you don't have a ground truth. If you don't know what the test data is labeled, how do you want to know how often you predicted the correct label? \nI would suggest you split your training data set into a training and a test data set and go from there.","Q_Score":0,"Tags":"python,classification","A_Id":60045177,"CreationDate":"2020-02-03T18:26:00.000","Title":"Find error rate of a classifier without having y_test","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I used a random forest classifier and now I want to see how good my classification was. Maybe even perform a grid search. My test data has no labels, meaning I only have x_train, y_train and x_test. Is there a way to calculate the error rate without having the accuracy?\nThank you in advance!","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":148,"Q_Id":60045062,"Users Score":0,"Answer":"unsupervised techniques can work better in this case,and no there is no way to evaluate your algorithm performance unless you cut a part of you training data if it's big enough","Q_Score":0,"Tags":"python,classification","A_Id":60045730,"CreationDate":"2020-02-03T18:26:00.000","Title":"Find error rate of a classifier without having y_test","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"This could be more of a theoretical question than a code-related one. In my current job I find myself estimating\/ predicting (this last is more opportunistic) the water level for a given river in Africa.\nThe point is that I am developing a simplistic multiple regression model that takes more than 15 years of historical water levels and precipitation (from different locations) to generate water level estimates. \nI am not that used to work with Machine Learning or whatever the correct name is. I am more used to model data and generate fittings (the current data can be perfectly defined with asymetric gaussians and sigmoids functions combined with low order polynomials.\nSo the point is; once I have a multiple regression model, my colleagues advised me not to use fitted data for the estimation but all the raw data instead. Since they couldn't explain to me the reason of that, I attempted to use the fitted data as raw inputs (in my defense, a median of all the fitting models has a very low deviation error == nice fittings). But what I don't understand is why should I use just the raw data, which cold be noisy, innacurate, taking into account factors that are not directly related (biasing the regression?). What is the advantage of that?\nMy lack of theoretical knowledge in the field is what makes me wonder about that. Should I always use all the raw data to determine the variables of my multiple regression or can I use the fitted values (i.e. get a median of the different fitting models of each historical year)?\nThanks a lot!","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":30,"Q_Id":60046724,"Users Score":1,"Answer":"here is my 2 cents\nI think your colleagues are saying that because it would be better for the model to learn the correlations between the raw data and the actual rain fall.\nIn the field you will start with the raw data so being able to predict directly from it is very useful. The more work you do after the raw data is work you will have to do every time you want to make a prediction.\nHowever, if a simpler model work perfectly defined with asymetric gaussians and sigmoids functions combined with low order polynomials then I would recommend doing that. As long as your (y_pred - t_true) ** 2 is very small","Q_Score":1,"Tags":"python,machine-learning,linear-regression,data-fitting,model-fitting","A_Id":60046810,"CreationDate":"2020-02-03T20:29:00.000","Title":"Input data necessary for forecasting\/ estimating trends for a given variable","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"As an example, I have a set of records in a 2D numpy.array and I would like to select all records where value in the 3rd column equal 10. Is there a way to do that apart from looping through the array and build a list of the selected records?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":99,"Q_Id":60050503,"Users Score":0,"Answer":"Here I have created a numpy array.\nprint(df)\no\/p is: array([['A', 'car'],['B', 'bike'],['C', 'car'],['D', 'truck']], dtype=object)\nNow to select all rows with car, you can just filter that value from the array\ndf[df == \"car\"] \no\/p is: array(['car', 'car'], dtype=object)\nIf you want it to be converted to python list, wrap the statement in list, i.e \nlist(df[df == \"car])","Q_Score":0,"Tags":"arrays,python-3.x,numpy,select","A_Id":60050625,"CreationDate":"2020-02-04T04:16:00.000","Title":"How to select from a 2D numpy.array where column == condition","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am new to pandas and I was wondering if there was a way I could run formulas on two dataframes. \nI have two dfs that have the same columns and same index. example each df looks like this\nx y z\na 2 4 5\nb 7 9 0\n\nI want to take df1, df2 and find the absolute difference for x ,y, z something like (df1[n]-df2[n] \/ df1[n]) * 100 for each n element of columns, and store the result in a new df.\nNote: I just want the difference to be positive. (Misunderstood the meaning of absolute)","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":2376,"Q_Id":60050512,"Users Score":1,"Answer":"Yes run them as you wrote them\nabsolute\n(df1 - df2).abs()\nor \n(df1 -df2).div(df2) * 100","Q_Score":1,"Tags":"python,pandas,dataframe","A_Id":60050580,"CreationDate":"2020-02-04T04:17:00.000","Title":"Computing absolute difference between two dataframes","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am doing an NLP task, where I have a distribution of word occurrence in the texts grouped by day. I want to find Pearson correlation between a given word and all other words in the database. Is there possibly some algorithmic solution rather than just manually iterating over all other words in database and calculating correlation. May be something to do with graphs?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":36,"Q_Id":60053797,"Users Score":0,"Answer":"You can use numpy or pandas (vectorised version instead of iterating over all records).","Q_Score":0,"Tags":"python,algorithm,graph,nlp","A_Id":60054120,"CreationDate":"2020-02-04T09:00:00.000","Title":"Finding Pearson correlation for millions of records","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using tf.random.set_seed to assure the reproducibility of my experiments but getting different results in terms of loss after training my model multiple times. I am monitoring the learning curve of each experiment using Tensorboard but I am getting different values of Loss and accuracy.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":2511,"Q_Id":60058588,"Users Score":0,"Answer":"for tensorflow 2, use tf.random.set_seed(seed) instead","Q_Score":3,"Tags":"python,tensorflow,keras,tensorflow2.0","A_Id":70132670,"CreationDate":"2020-02-04T13:35:00.000","Title":"Tesnorflow 2.0 tf.random.set_seed not working since I am getting different results","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Brief introduction:\nI'm trying to get certain texts from an image of a lot of texts.\nBy just thinking, there should be at least two ways to handle this problem: \nOne way is first segmenting the images by text areas \u2014 for example, train the neural network with a bunch of sample images that contain the sample texts, and then let the trained model locate corresponding text areas in the real image, then crop that area out from the image, save it \u2014 and secondly use, for instance, pytesseract to convert image to string.\nThe other way is to reverse the processes. First convert the image into strings, then train the neural network with sample real texts, then let the trained model find corresponding texts in texts converted from images.\n\nSo, my questions are listed below:\n\nCan this problem be solved without training a neural network? Will it be more efficient than NN, in terms of time taken to run the program and accuracy of results?\nAmong the two methods above I wrote, which one is better, in terms of time taken to run the program and accuracy of results?\nAny other experienced suggestions?\n\n\nAdditional background information if needed:\nSo, I have a number of groups of screenshots of different web pages, each of which has a lot of texts on it. And I want to extract certain paragraphs from that large volume of texts. The paragraphs I want to extract express similar things but under different contexts.\nFor example, on a large mixed online forum platform, many comments are made on different things, some on landscapes of mountains, some politics, some sciences, etc... As that platform cannot only have one page, there must be hundreds of pages where countless of users make their comments. Now I want to extract the comments on politics specifically from the entire forum, i.e. from all the pages that platform has. So I would use Python + Selenium to scrape the pages and save the screenshots. Now we need to go back to the questions asked above. What to do now? \n\nUpdate:\nJust a thought went by. Probably a NN trained by images that contain texts cannot give a very accurate location of wanted texts, as the NN might be only looking for arrangements of pixels instead of the words, or even meaning, that compose the sentences or paragraphs. So maybe the second method, text processing, may be better in this case? (like NLP?)","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":169,"Q_Id":60058636,"Users Score":0,"Answer":"So, you decided not to parse text, but save it as an image and then detect text from this image. \nText -> Image -> Text\nIt is worst scenario for parsing webpages. \nWhile dealing with OCR you must expect many problems, such as:\n\nHigh CPU consumption;\nDifferent fonts;\nHidden elements (like 'See full text');\nAnd the main one - you can't OCR with 100% accuracy. \n\nIf you try to create common parser, that should crawl only required text from any page given without any \"garbage\" - it is almost utopic idea.\nAs far as i know, something about this is 'HTML Readability' technology (Browsers like Safari and Firefox uses it). But how it will work with forums i can't say. Forums is very special format of pages.","Q_Score":0,"Tags":"python-3.x,image-processing,web-scraping,neural-network,nlp","A_Id":60061871,"CreationDate":"2020-02-04T13:38:00.000","Title":"Text\/Image processing in Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm working on a program that outputs data in several CSV files from Maya 2018. It reads an object name from a setting file, then creates an array of every keyframe that object has, then exports a column of keyframes and a column of values of the different axes associated with the object.\nThis unfortunately causes a problem when using cubic interpolation to connect the dots, so I'm trying to find a better way to collect the data. My current idea is to capture not only the keyframes, but also the frames immediately before and after the keys as well as the midpoints between the keys, but this seems clunky.\nAny recommendations?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":35,"Q_Id":60064675,"Users Score":0,"Answer":"Interpolating maya anim curves is not the easiest task in the world (effectively you need to solve the cubic equation to find the correct 't' value to then pass to the cubic interpolation function. It's probably that first step you're missing).\nMy advice though, would be to simply output samples for the frame values you need from Maya directly, and skip the interpolation entirely (be aware that any transform driven by IK, expressions, etc, will not have anim curves, so you'll get bad data in those cases)","Q_Score":0,"Tags":"python,maya","A_Id":60068296,"CreationDate":"2020-02-04T19:55:00.000","Title":"How can I create a dynamic sample rate for increased accuracy in reading from a Maya animation with Python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"If I'm working with a dataset where I have ~100,000 training images and ~20,000 validation images, each of size 32 x 32 x 3, how does the size and the dimensions of my dataset affect the number of Conv2d layers I have in my CNN? My intuition is to use fewer Conv2d layers, 2-3, because any more than 3 layers will be working with parts of the image that are too small to gain relevant data from. \nIn addition, does it make sense to have layers with a large number of filters, >128? My thought is that when dealing with small images, it doesn't make sense to have a large number of parameters.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":189,"Q_Id":60069035,"Users Score":0,"Answer":"Since you have the exact input size like the images in Cifar10 and Cifar100 just have a look what people tried out.\nIn general you can start with something like a ResNet18. Also I don't quite understand why you say \n\nbecause any more than 3 layers will be working with parts of the image that are too small to gain relevant data from. \n\nAs long as you don't downsample using something like max pooling or a conv with padding 1 and stride 2. The size of 32x32 will be the same and only the number of channels will change depending on the network.\nDesigning networks is almost always at looking what did other people do and what worked for them and starting from there. You almost never want to do it from scratch on your own, since the iteration cycles are just to long and models released by researches from Google, Facebook ... had way more resources then you will ever have to find something good.","Q_Score":4,"Tags":"python,deep-learning,neural-network,pytorch,conv-neural-network","A_Id":60074178,"CreationDate":"2020-02-05T04:27:00.000","Title":"Number of Conv2d Layers and Filters for Small Image Classification Task","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have data in nifti format, these are 3 axial images of an animal\u2019s brain, how to create a dataset for training a convolutional neural network, for segmenting brain regions, by python 3?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":507,"Q_Id":60074950,"Users Score":0,"Answer":"You can use nibabel library for loading nifti files using nibabel.load(path). And from that, you can get numpy array and combine all arrays to form a dataset in numpy arrays or convert it to H5py format as your choice.","Q_Score":1,"Tags":"python-3.x,tensorflow,conv-neural-network,tensorflow-datasets,faster-rcnn","A_Id":62447534,"CreationDate":"2020-02-05T11:37:00.000","Title":"How to create a dataset for CNN from Mri Nifti files?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've been working with facial embeddings but I think Word2Vec is a more common example.\nEach entry in that matrix is a number that came from some prediction program\/algorithm, but what are they? Are they learned features?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":104,"Q_Id":60076497,"Users Score":2,"Answer":"Those numbers are learned vectors that each represents a dimension that best separates each word from each other, given some limiting number of dimensions (normally ~200). So if one group of words tends to appear in the same context, then they'd likely share a similar score on one or more dimensions. \nFor example, words like North, South, East, West are likely to be very close since they are interchangeable in many contexts. \nThe dimensions are chosen by algorithm to maximize the variance they encode, and what they mean is not necessarily something we can talk about in words. But imagine a bag of fridge-magnets each representing a letter of the alphabet - if you shine a light on them so as to cast a shadow, there will be some orientations of the letters that yield more discriminatory information in the shadows than for other orientations. \nThe dimensions in a word-embedding represent the best \"orientations\" that give light to the most discriminatory \"shadows\". Sometimes these dimensions might approximate things we recognise as having direct meaning, but very often, they wont.\nThat being said, if you collect words that do have similar functions, and find the vectors from those words to other words that are the endpoint of some kind of fixed relationship - say England, France, Germany as one set of words consisting of Countries, and London, Paris, Berlin as another set of words consisting of the respective Capital-Cities, you will find that the relative vectors between each country and its capital are often very, very similar in both direction and magnitude. \nThis has an application for search because you can start with a new word location, say \"Argentina\" and by looking in the location arrived at by applying the relative \"has_capital_city\" vector, you should arrive at the word \"Buenos Aires\".\nSo the raw dimensions probably have little meaning of their own, but by performing these A is to B as X is to Y comparisons, it is possible to derive relative vectors that do have a meaning of sorts.","Q_Score":0,"Tags":"python,word2vec,feature-extraction,embedding,word-embedding","A_Id":60076869,"CreationDate":"2020-02-05T13:05:00.000","Title":"What does each element in an embedding mean?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"As I get, tf.layers.conv1d uses pipeline like this: BatchToSpaceND -> conv1d -> SpaceToBatchND. So the question is how to remove (or disable) BatchToSpaceND and SpaceToBatchND from the pipeline?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":56,"Q_Id":60080700,"Users Score":0,"Answer":"As I've investigated it's impossible to remove BatchToSpaceND and SpaceToBatchND from tf.layers.conv1d without changing and rebuilding tensorflow source code. One of the solutions is to replace layers to tf.nn.conv1d, which is low-level representation of convolutional layers (in fact tf.layers.conv1d is a wrapper around tf.nn.conv1d). These low-level implementations doesn't include BatchToSpaceND and SpaceToBatchND.","Q_Score":0,"Tags":"python,tensorflow,conv-neural-network","A_Id":60151192,"CreationDate":"2020-02-05T17:03:00.000","Title":"Is there any way to remove BatchToSpaceND from tf.layers.conv1d?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"So here is the problem, I'm trying to import a DF from a file downloaded from COGNOS. In cognos I select .CSV format but always is downloaded the format is .xls\nIt will be very easy to open the .xls file and save as CVS but the problem with that is that the file has more rows than excel so I will lose a lot of data in the process. Also when I open the file in excel it is a warning that the file could be corrupted.\nWhen I'm trying to open the data with df = pd.read_excel(\"Time Series 2018-1.xls\") it shows the following problem.\nXLRDError: Unsupported format, or corrupt file: Expected BOF record; found b'\\xff\\xfeP\\x00r\\x00o\\x00'\nPlease HELP","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":1157,"Q_Id":60087450,"Users Score":0,"Answer":"I already resolve it. Just open the file in sublime and save with encoding UTF-8. Then just open it with df = pd.read_csv(\"Prueba1.xls\", sep = \"\\t\", encoding = 'utf8') because as @dougp said, is just a csv file save with the extension xls.\nI guess there is a way to change the encoding in PYTHON but that's for another question.","Q_Score":0,"Tags":"python-3.x,pandas,xls,cognos","A_Id":60118432,"CreationDate":"2020-02-06T03:47:00.000","Title":"Open with Pandas in Python a .xls file that is corrupted","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"For the below line of code to get the metrics, I'm getting the ValueError mentioned\nf1_test.append(f1_score(y_test, y_pred_test, pos_label=\"str\"))\nValueError: pos_label='str' is not a valid label: array([' <=50K', ' >50K'], dtype='\nMy data has Income vlaue <=50k or >50k.\nPlease advise.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":349,"Q_Id":60087814,"Users Score":0,"Answer":"The parameter pos_label is used to indicate the positive class. In your data, your labels are string based '<=50K' and '>50K'.\nYou can do one of the following:\n\nLeave pos_label to the default value, set pos_label = 1.\nSet pos_label = '>50K' or '<=50K', based on what your +ve class. The positive class is normally attributed to the best outcome, for example, the income that you are trying to predict, is it better if its more than 50K or less than <=50K?","Q_Score":1,"Tags":"python-3.x,scikit-learn","A_Id":60088681,"CreationDate":"2020-02-06T04:36:00.000","Title":"sklearn metrics f1_score : pos_label valueError","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a relatively small dataset consisting of x, y coordinates and organic matter content. I perform a simple multi-linear regression in Python using statsmodels.api ordinary least square (OLS) with organic matter content being the dependent variable and the others predictors. Firstly, I find the total sum of squares of my model (called mreg) with the built-in method 'mreg.centered_tss'. Now I have to find the sum of squares for my predictors, the x and y variable. Is it possible to do with the statsmodels.api or should I use a for loop instead?\nI have used the .ess and the .centered_tss to determine the sum of squares of the model. I only need to know the sum of squares of my modelled variables x and y coordinates compared to the mean. \nedit: I think what I am asking for is the residual sum of squares of my x coordinates and y coordinates from the model. \nThomas","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":1053,"Q_Id":60091784,"Users Score":2,"Answer":"there should be a .ssr method for the regression sum of squares","Q_Score":1,"Tags":"python,statistics,statsmodels","A_Id":64764107,"CreationDate":"2020-02-06T09:38:00.000","Title":"How do I find the sum of squares of my predicting variables with statsmodels linear model OLS?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Is there a way to get values of a dask dataframe without using compute function as pandas? \n\nPandas: df.values\nDask using compute function: ddf.compute().values\n\nDask using compute function is slow and I have to transform the dask dataframe to json format and to do that I should get the values.","AnswerCount":2,"Available Count":2,"Score":1.2,"is_accepted":true,"ViewCount":877,"Q_Id":60102700,"Users Score":0,"Answer":"I have to transform the dask dataframe to json format and \n\nYou may be interested in the .to_json method of Dask dataframes\n\nand to do that I should get the values.\n\nThis may not be true","Q_Score":0,"Tags":"python,pandas,function,dataframe,dask","A_Id":60243760,"CreationDate":"2020-02-06T20:04:00.000","Title":"Values of a Dask Dataframe","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Is there a way to get values of a dask dataframe without using compute function as pandas? \n\nPandas: df.values\nDask using compute function: ddf.compute().values\n\nDask using compute function is slow and I have to transform the dask dataframe to json format and to do that I should get the values.","AnswerCount":2,"Available Count":2,"Score":0.0996679946,"is_accepted":false,"ViewCount":877,"Q_Id":60102700,"Users Score":1,"Answer":"Because Dask is suited for large datasets, performing compute on the full data source does not make sense.\nI think you should generate your json file by iterating on partitions.\ndf.npartitions gives you the number of partitions.\nYou can get a specific partition (for example n) with df.get_partition(n).","Q_Score":0,"Tags":"python,pandas,function,dataframe,dask","A_Id":60111095,"CreationDate":"2020-02-06T20:04:00.000","Title":"Values of a Dask Dataframe","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I applied a linear regression on some features to predict the target with 10 folds cross validation.\nMinMax scale was applied for both the features and the target.\nThen the features standardized.\nWhen I run the model, the r2 equal to 0.65 and MSE is 0.02.\nBut when I use the target as they are without MinMax scaling, I got r2 same but the MSE increase a lot to 18.\nMy question is, do we have to deal with targets as same we do with features in terms of data preprocessing? and which of the values above is correct? because the mse got quit bigger with out scaling the target.\nSome people say we have to scale the targets too while others say no.\nThanks in advance.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":697,"Q_Id":60111980,"Users Score":2,"Answer":"Whether you scale your target or not will change the 'meaning' of your error. For example, consider 2 different targets, one ranged [0, 100] and another one [0, 10000]. If you run models against them (with no scaling), MSE of 20 would mean different things for the two models. In the former case it will be disastrous, while in the latter case it will be pretty decent.\nSo the fact that you get lower MSE with target range [0, 1] than the original is not surprising.\nAt the same time, r2 value is independent of the range since it is calculated using variances.\nScaling allows you to compare model performance for different targets, among other things.\nAlso for some model types (like NNs) scaling would be more important.\nHope it helps!","Q_Score":0,"Tags":"python,machine-learning,scikit-learn,linear-regression","A_Id":60114625,"CreationDate":"2020-02-07T10:51:00.000","Title":"MinMax scaling the target","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am appending different dataframes to make one set. Occasionally, some values have the same index, so it stores the value as a series. Is there a quick way within Pandas to just overwrite the value instead of storing all the values as a series?","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":245,"Q_Id":60116827,"Users Score":0,"Answer":"You weren't very clear guy. If you want to resolve the duplicated indexes problem, probably the pd.Dataframe.reset_index() method will be enough. But, if you have duplicate rows when you concat the Dataframes, just use the pd.DataFrame.drop_duplicates() method. Else, share a bit of your code with or be clearer.","Q_Score":0,"Tags":"python,pandas","A_Id":60117514,"CreationDate":"2020-02-07T15:51:00.000","Title":"How to append rows to a Pandas dataframe, and have it turn multiple overlapping cells (with the same index) into a single value, instead of a series?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to write a large dask array (46 GB with 124 -- 370 MB chunks) to a zarr file using dask. If my dask array was named dask_data, then a simple dask_data.to_zarr(\"my_zarr.zarr\") would work. But from what I understand, this is a synchronous, CPU bound process.\nWhat I would like to do is to use parallelism with much of the work allocated to a Quadro GV100 GPU. I tried to convert the numpy.ndarray to a cupy.ndarray via dask_data_cupy = dask_data.map_blocks(cupy.asarray) and write this out to a zarr file, but I receive: ValueError: object __array__ method not producing an array (and frankly, I do not see a performance boost either).\nHow could I go about using a GPU to parallelize writing a dask array to a zarr file?\nThanks!","AnswerCount":2,"Available Count":2,"Score":0.0996679946,"is_accepted":false,"ViewCount":634,"Q_Id":60119406,"Users Score":1,"Answer":"I think you would need to add dask_data.map_blocks(cupy.asnumpy) before calling to_zarr.\nCuPy tries to make sure that the user intended to do a device to host transfer (as these can be expensive). So intentionally raises when numpy.asarray is called on a CuPy array (as would happen during this write).","Q_Score":1,"Tags":"python,python-3.x,dask,cupy,zarr","A_Id":60121331,"CreationDate":"2020-02-07T18:49:00.000","Title":"How to write a large dask array (numpy.ndarray) to a Zarr file leveraging GPUs?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to write a large dask array (46 GB with 124 -- 370 MB chunks) to a zarr file using dask. If my dask array was named dask_data, then a simple dask_data.to_zarr(\"my_zarr.zarr\") would work. But from what I understand, this is a synchronous, CPU bound process.\nWhat I would like to do is to use parallelism with much of the work allocated to a Quadro GV100 GPU. I tried to convert the numpy.ndarray to a cupy.ndarray via dask_data_cupy = dask_data.map_blocks(cupy.asarray) and write this out to a zarr file, but I receive: ValueError: object __array__ method not producing an array (and frankly, I do not see a performance boost either).\nHow could I go about using a GPU to parallelize writing a dask array to a zarr file?\nThanks!","AnswerCount":2,"Available Count":2,"Score":0.1973753202,"is_accepted":false,"ViewCount":634,"Q_Id":60119406,"Users Score":2,"Answer":"But from what I understand, this is a synchronous, CPU bound process.\n\nThis is probably not true, your bottleneck is likely the storage device. In any case, each chunk is written to a separate file, and in parallel across threads and\/or processes (depending on your setup). That is the whole point of the design of zarr, that an application can interact with each chunk independently. \nYou may be CPU bound if you choose to use various encodings of compression; however these do not necessarily lend themselves to GPU operation. \nIn short, unless your data is already generated on the GPU, I would be surprised if transferring it to the GPU for processing before writing it to files is worth the while. If there were a function to directly read\/write cupy arrays to zarr, and your were also processing on the GPU, it would be different - but I don't believe there is.","Q_Score":1,"Tags":"python,python-3.x,dask,cupy,zarr","A_Id":60121482,"CreationDate":"2020-02-07T18:49:00.000","Title":"How to write a large dask array (numpy.ndarray) to a Zarr file leveraging GPUs?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a seq2seq neural network which I use for translating text. I need the sentences to remain the same during batches, more exactly, a sentence should be like an inseparable block of tokens. However, it looks like the iterators provided by Torchtext (BucketIterator and Iterator) do not keep the initial order of the tokens. Is there a solution to this, except of writing my own padding and batching functions?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":164,"Q_Id":60127422,"Users Score":0,"Answer":"Both Iterator and BucketIterator should keep the order of tokens and only shuffle the sentences in the dataset.\nYou very likely have your input tensors in an incorrect shape. The default shapes in TorchText are: length \u00d7 batch_size \u00d7 features. If you have the batch first and sequence length the second, your sentences got shuffled.","Q_Score":0,"Tags":"python,deep-learning,dataset,recurrent-neural-network,torchtext","A_Id":60147116,"CreationDate":"2020-02-08T13:50:00.000","Title":"Torchtext keep tokens in the same order","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have tried the following steps after the installation of Anaconda's latest version. I am not able to get the autocomplete feature working...\nAny suggestions on what else I need to try...\nStep 1\n 1) pip install jupyter_contrib_nbextensions\n 2) pip install jupyter_nbextensions_configurator\n 3) jupyter contrib nbextension install --user \n 4) jupyter nbextensions_configurator enable --user\nStep 2: Open jupyter notebook\n - click on nbextensions tab\n - unckeck disable configuration for nbextensions without explicit compatibility\n - put a check on Hinterland","AnswerCount":4,"Available Count":2,"Score":0.049958375,"is_accepted":false,"ViewCount":11450,"Q_Id":60131686,"Users Score":1,"Answer":"Out of frustration,\nI moved to Spyder 4.0.1 and installed Kite.\nBeen quite frustrating...","Q_Score":7,"Tags":"python,jupyter-notebook,anaconda","A_Id":60324373,"CreationDate":"2020-02-08T22:09:00.000","Title":"Autocomplete in Jupyter notebook not working","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have tried the following steps after the installation of Anaconda's latest version. I am not able to get the autocomplete feature working...\nAny suggestions on what else I need to try...\nStep 1\n 1) pip install jupyter_contrib_nbextensions\n 2) pip install jupyter_nbextensions_configurator\n 3) jupyter contrib nbextension install --user \n 4) jupyter nbextensions_configurator enable --user\nStep 2: Open jupyter notebook\n - click on nbextensions tab\n - unckeck disable configuration for nbextensions without explicit compatibility\n - put a check on Hinterland","AnswerCount":4,"Available Count":2,"Score":1.0,"is_accepted":false,"ViewCount":11450,"Q_Id":60131686,"Users Score":6,"Answer":"One of the reasons behind this issue can be the crashes of kernel when you try to use the autocompletion. I faced this issue and by observing the logs generated in the terminal used to open jupyter found that every time I try to use the autocompleter, kernel crashes. with the following solution, I resolved the issue in macOs 11.1 Big Sur.\nYou can just set the Ipython to use something else rather than jedi to do the completion task like pyreadline which can be installed by pip3 install pyreadline . But first you have to disable jedi in the Ipython kernel with the following command:\n\n%config IPCompleter.use_jedi = False\n\nThis command will resolve the issue in the current session and if you want to change this configuration in the config file of Ipython kernel you can use the following commands:\n\nipython profile create\n\nmaking a new config file for the ipython in the following directory:\n\/Users\/zhivarsourati\/.ipython\/profile_default\nand you can append the following line to the file ipython_kernel_config.py generated with the previous command:\n\nc.IPCompleter.use_jedi = False","Q_Score":7,"Tags":"python,jupyter-notebook,anaconda","A_Id":65773234,"CreationDate":"2020-02-08T22:09:00.000","Title":"Autocomplete in Jupyter notebook not working","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a database that is made of (3862900,19), each column is a different parameter and includes outliers, is it possible to detect outliers in each column simultaneously, or do I have to repeat it 19 times for each column?\nThank you","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":74,"Q_Id":60132600,"Users Score":1,"Answer":"Yes, It is possible to detect outliers in each column simultaneously","Q_Score":0,"Tags":"python,pandas,jupyter-notebook,random-forest,outliers","A_Id":60132922,"CreationDate":"2020-02-09T00:48:00.000","Title":"Isolation Forest large dataset","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've been searching for a long time for a method to pull the p-value for LDA and QDA models without success.\nI know I can use the summary function from statsmodel for linear and logistic regression but I think this does not apply to the above regressions.\nWould appreciate your help with this\nThanks!","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":338,"Q_Id":60135064,"Users Score":1,"Answer":"Summary shows how statistically significant the model coefficients are. Actually, LDA and QDA don't estimate any coefficients as logictic regression does. Therefore, it's impossible to measure the coefficients performance of LDA and QDA.","Q_Score":1,"Tags":"python,python-3.x","A_Id":65026134,"CreationDate":"2020-02-09T09:14:00.000","Title":"p-values for Linear Discriminant and Quadratic Discriminant analyses (LDA, QDA)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am training an text generation model with Generative adversarial networks.\nAs a common method, I used tf.clip_by_global_norm() to avoid gradient problems. However, even I used gradient clipping, I am still facing gradient exploding problem with error caused by tf.clip_by_global_norm() function.\nThe document says: If global_norm == infinity then the entries in t_list are all set to NaN to signal that an error occurred.\nI can hardly find the origin of problem with this situation since I believed that tf.clip_by_global_norm definitely avoid the gradient problem.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":47,"Q_Id":60145905,"Users Score":0,"Answer":"Have you tried tf.clip_by_value? You could set clip_value_min to be -1 and the max to be 1.\nIf you're using an embedding matrix for your text, the embedding values shouldn't get larger than 1\nAlso as an aside, people have tried using GAN's for text generation, and the results aren't very good","Q_Score":0,"Tags":"python,tensorflow,deep-learning","A_Id":60146528,"CreationDate":"2020-02-10T07:34:00.000","Title":"Adversarial text generation with gradient clipping, still facing gradient explosion","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working on an intelligent embedded system that implemented with an alexnet (kind of shallow cnn) while training my model on colab, I realized that RAM usage is about 10 GB. Does FPGA Support this? How can I reduce RAM usage?\nThanks","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":45,"Q_Id":60155132,"Users Score":2,"Answer":"There are no FPGAs with 10 GB of RAM built-in, but many of them will let you connect that much RAM externally.","Q_Score":0,"Tags":"python,neural-network,fpga,xilinx","A_Id":60162363,"CreationDate":"2020-02-10T17:09:00.000","Title":"Reduce RAM Usage for AlexNet implementation on FPGA","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Suppose I have a batch with shape [n, h, w, c] as well as a list of n indices in range of 0-9 and 10 Conv2D convs, that I want to apply to the data depending on the index in the list. The indices list changes with every batch.\nEg. with input x, batch size 4 and indices l=[1,5,1,9] I would like to compute [convs[l[0]](x[0]), convs[l[1]](x[1]), convs[l[2]](x[2]), convs[l[3]](x[3])]\nA naive solution would be to compute every combination and gather based on l. However, this requires 10 times the amount of memory. Is there a better solution to this problem?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":126,"Q_Id":60157547,"Users Score":0,"Answer":"One \"hacky\" solution would be to expand the dimension of the input from [n, h, w, c] to [1, n, h, w, c], then use Conv3D instead with kernel shape [1, x, y]\nIf you have the weights defined separately (weights can also be obtained using layer.weights), you could similarly stack them in the 0th dimension and use them through tf.nn.conv3d.","Q_Score":1,"Tags":"python,tensorflow,keras,tf.keras","A_Id":60165121,"CreationDate":"2020-02-10T20:00:00.000","Title":"Tensorflow switch case in batch dimension with Conv2d","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm currently stuyind TensorFlow 2.0 and Keras. I know that the activation functions are used to calculate the output of each layer of a neural network, based on mathematical functions. However, when searching about layers, I can't find synthetic and easy-to-read information for a beginner in deep learning. \nThere's a keras documentation, but I would like to know synthetically:\n\nwhat are the most common layers used to create a model (Dense, Flatten, MaxPooling2D, Dropout, ...).\nIn which case to use each of them? (Classification, regression, other)\nwhat is the appropriate way to use each layer depending on each case?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":112,"Q_Id":60162973,"Users Score":1,"Answer":"Depending on the problem you want to solve, there are different activation functions and loss functions that you can use.\n\nRegression problem: You want to predict the price of a building. You have N features. Of course, the price of the building is a real number, therefore you need to have mean_squared_error as a loss function and a linear activation for your last node. In this case, you can have a couple of Dense() layers with relu activation, while your last layer is a Dense(1,activation='linear').\nIn between the Dense() layers, you can add Dropout() so as to mitigate the overfitting effect(if present).\nClassification problem: You want to detect whether or not someone is diabetic while taking into account several factors\/features. In this case, you can use again stacked Dense() layers but your last layer will be a Dense(1,activation='sigmoid'), since you want to detect whether a patient is or not diabetic. The loss function in this case is 'binary_crossentropy'. In between the Dense() layers, you can add Dropout() so as to mitigate the overfitting effect(if present).\nImage processing problems: Here you surely have stacks of [Conv2D(),MaxPool2D(),Dropout()]. MaxPooling2D is an operation which is typical for image processing and also some natural language processing(not going to expand upon here). Sometimes, in convolutional neural network architectures, the Flatten() layer is used. Its purpose is to reduce the dimensionality of the feature maps into 1D vector whose dimension is equal to the total number of elements within the entire feature map depth. For example, if you had a matrix of [28,28], flattening it would reduce it to (1,784), where 784=28*28.\n\nAlthough the question is quite broad and maybe some people will vote to close it, I tried to provide you a short overview over what you asked. I recommend that your start learning the basics behind neural networks and then delve deeper into using a framework, such as TensorFlow or PyTorch.","Q_Score":0,"Tags":"python,tensorflow,keras,neural-network,tensorflow2.0","A_Id":60164132,"CreationDate":"2020-02-11T06:15:00.000","Title":"Which layer should I use when I build a Neural Network with Tensorflow 2.x?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am new in python and I have a folder with 15 excel files and I am trying to rename a specific column in each file to a standard name, for instance I have a columns named \"name, and server\" on different files but they entail of the same information so I need to rename them to a standard name like \" server name\" and I don't know how to start","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":754,"Q_Id":60164763,"Users Score":0,"Answer":"If the position of the columns are the same across all excel file, you can iterate all the 15 excel files, locate the position of the column and replace the text directly. \nAlternatively, you can iterate all the files via read_xls (or read_csv depending on your context), reading them as dataframe and replace the necessary column name, and overwrite the file. Below is a reference syntax for your reference. \ndf.rename(columns={ df.columns[1]: \"your value\" }, inplace = True)","Q_Score":1,"Tags":"python,python-3.x","A_Id":60165113,"CreationDate":"2020-02-11T08:37:00.000","Title":"Add a new column to multiple .csv and populate with filename","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"If I have a list of files in a directory is it possible to estimate a memory use number that would be taken up by reading or concatenating the files using pd.read_csv(file) or pd.concat([df1, df2])?\nI would like to break these files up into concatenation 'batches' where each batch will not exceed a certain memory usage so I do not run into local memory errors.\nUsing os.path.getsize() will allow me to obtain the file sizes and df.memory_usage() will tell me how much memory the dataframe will use once it's already read in but is there a way to estimate this with just the files themselves?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":45,"Q_Id":60175436,"Users Score":0,"Answer":"You could open each CSV, read first 1000 lines only into DataFrame, and then check memory usage. Then scale estimated memory usage by number of lines in the file.\nNote that memory_usage() isn't accurate with default arguments, because it won't count strings' memory usage. You need memory_usage(deep=True), although that might overestimate memory usage in some cases. But better to overestimate than underestimate.","Q_Score":0,"Tags":"python,python-3.x,pandas,dataframe,operating-system","A_Id":60191632,"CreationDate":"2020-02-11T18:40:00.000","Title":"Estimating Dataframe memory usage from file sizes","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have two different excel files. One of them is including time series data (268943 accident time rows) as below\nThe other file is value of 14 workers measured daily from 8 to 17 and during 4 months(all data merged in one file) \nI am trying to understand correlation between accident times and values (hourly from 8 to 17 per one hour and daily from Monday to Friday and monthly)\nWhich statistical method is fit(Normalized Auto or cross correlation) and how can I do that?\nGenerally, in the questions, the correlation analysis are performed between two time series based values, but I think this is a little bit different. Also, here times are different.\nThank your advance..","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":798,"Q_Id":60182894,"Users Score":2,"Answer":"I think the accident times and the bloodsugar levels are not coming from the same source, and so I think it is not possible to draw a correlation between these two separate datasets. If you would like to assume that the blood sugar levels of all 14 workers reflect that of the workers accident dataset, that is a different story. But what if those who had accidents had a significantly different blood sugar level profile than the rest, and what if your tiny dataset of 14 workers does not comprise such examples? I think the best you may do is to graph the blood sugar level of your 14 worker dataset and also similarly analyze the accident dataset separately, and try to see visually whether there is any correlation here.","Q_Score":2,"Tags":"python,time","A_Id":60760032,"CreationDate":"2020-02-12T07:09:00.000","Title":"How do find correlation between time events and time series data in python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Currently i am working on an object detection problem which involves detecting faces in an images and creating boxes around them.\nTo address this issue , i have created a yolov2 model as described in the paper with loss function as mentioned in the paper itlself. At earlier stages i was facing the issue of Nan losses for localization loss and hence unstable training. Hence found a workaround by making some small changes in loss function. Presently the issue i am facing is with very low object confidence score, as i am dealing with face-no_face dataset ,the class score during inference is 1.0 but the object confidence score is very lesss for many of the instances which contain only one face , let alone multiple faces in an image. Though while training the cummulative loss is saturating around 0.06 , but while inference , there is whole new picture of very less confidence score.\nLoss function : The loss function i am using for calculating confidence score is cummumative loss of two terms : no_object_loss and object_loss and both are MSE losses for grid cells which has object (object_loss) and rest contribute to no_object_loss.\nNote : My dataset contains 4996 instances of multi face images and ONLY 4 INSTANCES OF NO FACE. and so i was wondering if this is the issue as i why i am getting low object confidence scores.","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":885,"Q_Id":60183423,"Users Score":2,"Answer":"i am posting the answer here , in case if someone goes through same issue they can follow the same debugging steps , \nSo first i figured what was the cause of low combined scores , and it turned out that it was the object scores which were very less , \nSo i looked at the distribution of the activations after each loss and also the behaviour of object loss , seemed like it was fluctuating a lot , which suggested that the loss from this particular term was not according to the desired pattern . \nhence i recursed back to the loss function and fortunately the mistake was in the IOU calculation of the loss function . \nThe problem was basically with the bounds of the iou calculation , i.e there was no bounds on what the intersection of two boxes can be , so the range of the intersection can from -inf to +inf. Hence the iou was coming to be huge lot of times , but intuitively iou can be only from 0 to 1 and . \nthe solution to it was to truncate the localisation of predictions from 0 to image height and image width during preprocessing for iou calculation. also, while calculating the iou which is intersection \/ union , i made sure that intersection is greater or equal to 0 (not less than which means that there is not intersection at all).\nDoing this helped the model learn in a lot correct and better way to predict boxes whenever it can .","Q_Score":1,"Tags":"python,deep-learning,computer-vision,object-detection,yolo","A_Id":60207612,"CreationDate":"2020-02-12T07:47:00.000","Title":"low object confidence scores while training yolov2 for face-non face dataset","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I installed tensorflow using sudo pip3.6 install tensorflow==1.7 (I already had tensorflow 1.6 but wanted to upgrade) however I am unable to uninstall it. I tried sudo pip3.6 uninstall tensorflow and it said that tensorflow is successfully uninstalled but I don't think that's true. I get the following error when I try to run a tensorflow python code (which ideally should say import error I guess)\n\nAttributeError: module 'tensorflow.python.training.checkpointable' has no attribute 'CheckpointableBase'\n\nUsing sudo pip3.6 uninstall tensorflow again only shows\n\nSkipping tensorflow as it is not installed.\n\nI looked around a little and found the following folders in usr\/local\/lib\/python3.6\/dist-packages\/\n\ntensorboard\ntensorboard-1.7.0.dist-info\ntensorflow\ntensorflow_datasets\ntensorflow_datasets-1.3.2.dist-info\ntensorflow_estimator\ntensorflow_estimator-1.13.0.dist-info\ntensorflow_metadata\ntensorflow_metadata-0.21.0.dist-info\ntensorflow_tensorboard-0.4.0.dist-info\n\nIt seems to be a mess. Can I go ahead and simply delete these folders? What is the correct way to removing these?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":282,"Q_Id":60189194,"Users Score":0,"Answer":"Yes, you need to delete it manually, you can follow the below steps to do it.\n\nGo to the site-packages directory where pip is installing your packages in your case usr\/local\/lib\/python3.6\/dist-packages\/.\nYou should see the file that corresponds to the package you want to uninstall. Delete the file for your case rm -rf tensor*.\nInstall your required Tensorflow version pip install tensorflow==1.7\n\nI hope this solves your issue.","Q_Score":2,"Tags":"python,tensorflow,ubuntu-16.04,uninstallation,tensorflow-estimator","A_Id":61746088,"CreationDate":"2020-02-12T13:12:00.000","Title":"Unable to uninstall Tensorflow - Folders still remain in dist-packages","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have been working on an algorithm trading project where I used R to fit a random forest using historical data while the real-time trading system is in Python. \nI have fitted a model I'd like to use in R and am now wondering how can I use this model for prediction purposes in the Python system.\nThanks.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":777,"Q_Id":60190695,"Users Score":1,"Answer":"There are several options:\n(1) Random Forest is a well researched algorithm and is available in Python through sci-kit learn. Consider implementing it natively in Python if that is the end goal.\n(2) If that is not an option, you can call R from within Python using the Rpy2 library. There is plenty of online help available for this library, so just do a google search for it.\nHope this helps.","Q_Score":0,"Tags":"python,r,random-forest,modeling","A_Id":60191260,"CreationDate":"2020-02-12T14:33:00.000","Title":"How to use R models in Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"My distributed application consists of many producers that push tasks into several FIFO queues, and multiple consumers for every one of these queues. All these components live on a single node, so no networking involved.\nThis pattern is perfectly supported by Python's built-in multiprocessing.Queue, however when I am scaling up my application the queue implementation seems to be a bottleneck. I am not sending large amounts of data, so memory sharing does not solve the problem. What I need is fast guaranteed delivery of 10^4-10^5 small messages per second. Each message is about 100 bytes.\nI am new to the world of fast distributed computing and I am very confused by the sheer amount of options. There is RabbitMQ, Redis, Kafka, etc.\nZeroMQ is a more focused and compact alternative, which also has successors such as nanomsg and nng. Also, implementing something like a many-to-many queue with a guaranteed delivery seems nontrivial without a broker.\nI would really appreciate if someone could point me to a \"standard\" way of doing something like this with one of the faster frameworks.","AnswerCount":3,"Available Count":2,"Score":1.2,"is_accepted":true,"ViewCount":1950,"Q_Id":60197392,"Users Score":4,"Answer":"I think that a lot of it depends partly on what sort of importance you place on individual messages. \nIf each and every one is vital, and you have to consider what happens to them in the event of some failure somewhere, then frameworks like RabbitMQ can be useful. RabbitMQ has a broker, and it's possible to configure this for some sort of high availability, high reliability mode. With the right queue settings, RabbitMQ will look after your messages up until some part of your system consumes them.\nTo do all this, RabbitMQ needs a broker. This makes it fairly slow. Though at one point there was talk about reimplementing RabbitMQ on top of ZeroMQ's underlying protocols (zmtp) and doing away with the broker, implementing all the functionality in the endpoints instead.\nIn contrast, ZeroMQ does far less to guarantee that, in the event of failures, your messages will actually, eventually, get through to the intended destination. If a process dies, or a network connection fails, then there's a high chance that messages have got lost. More recent versions can be set up to actively monitor connections, so that if a network cable breaks or a process dies somewhere, the endpoints at the other end of the sockets can be informed about this pretty quickly. If one then implements a communicating sequential processes framework on top of ZMQ's actor framework (think: message acknowledgements, etc. This will slow it down) you can end up with a system whereby endpoints can know for sure that messages have been transfered to intended destinations.\nBeing brokerless allows zmq to be pretty fast. And it's efficient across a number of different transports, ranging from inproc to tcp, all of which can be blended together. If you're not worried about processes crashing or network connections failing, ZMQ gives you a guarantee to deliver messages right out of the box.\nSo, deciding what it is that's important in your application helps choose what technology you're doing to use as part of it - RabbitMQ, ZeroMQ, etc. Once you've decided that, then the problem of \"how to get the patterns I need\" is reduced to \"what patterns does that technology support\". RabbitMQ is, AFAIK, purely pub\/sub (there can be a lot of each), whereas ZeroMQ has many more.","Q_Score":5,"Tags":"python,message-queue,zeromq","A_Id":60247531,"CreationDate":"2020-02-12T21:49:00.000","Title":"High-performance replacement for multiprocessing.Queue","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":1,"Web Development":0},{"Question":"My distributed application consists of many producers that push tasks into several FIFO queues, and multiple consumers for every one of these queues. All these components live on a single node, so no networking involved.\nThis pattern is perfectly supported by Python's built-in multiprocessing.Queue, however when I am scaling up my application the queue implementation seems to be a bottleneck. I am not sending large amounts of data, so memory sharing does not solve the problem. What I need is fast guaranteed delivery of 10^4-10^5 small messages per second. Each message is about 100 bytes.\nI am new to the world of fast distributed computing and I am very confused by the sheer amount of options. There is RabbitMQ, Redis, Kafka, etc.\nZeroMQ is a more focused and compact alternative, which also has successors such as nanomsg and nng. Also, implementing something like a many-to-many queue with a guaranteed delivery seems nontrivial without a broker.\nI would really appreciate if someone could point me to a \"standard\" way of doing something like this with one of the faster frameworks.","AnswerCount":3,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":1950,"Q_Id":60197392,"Users Score":0,"Answer":"I have tried Redis Server queuing in order to replace Python standard multiprocessing Queue. It is s NO GO for Redis ! Python is best, fastest and can accept any kind of data type you throw at it, where with Redis and complex datatype such as dict with lot of numpy array etc... you have to pickle or json dumps\/loads which add up overhead to the process.\nCheers,\nSteve","Q_Score":5,"Tags":"python,message-queue,zeromq","A_Id":67898234,"CreationDate":"2020-02-12T21:49:00.000","Title":"High-performance replacement for multiprocessing.Queue","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":1,"Web Development":0},{"Question":"I'm trying to implement Multiclass Perceptron in python. I have fully understood the concept of perceptron algorithm when it comes to multiclassification, but still get puzzled by the feature vectors that we should provide out of training data. \nThe problem is simply a text (document) classification problem. I'm trying to use unigram term frequencies as features for the perceptron in text preprocessing stage. When I'm constructing features for each document based on term (i.e., unigram) frequencies in each training document, the constructed feature happens to be very sparse (term frequencies for each token that occurs in the document, and 0 for those that do not occur). \nMy question is about an alternative schema for this. Is there a better solution for constructing feature vectors? \nThanks!","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":495,"Q_Id":60198443,"Users Score":0,"Answer":"I approached this problem by utilizing ID for each unigram that occurs in the training set; specifically, each instance within the training set. \nAs such, first I create a distinct vocab dictionary by iterating through each document in, giving incremental id to each term that is newly seen. When performing perceptron, I iterate through the vocab ids with their count in the document and multiply them with the associated entry in perceptron weight matrices. In this sense, I would not need to do dot product, ignoring those sparse entries (0 * 0).","Q_Score":0,"Tags":"python,machine-learning,perceptron","A_Id":61425231,"CreationDate":"2020-02-12T23:33:00.000","Title":"Feature vectors for multiclass perceptron","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've been training a model using just tensorflow on my GPU with the help of tf.device(), it was working fine until now. I am making another NN model in Keras and while using model.fit it is giving me OOM error.\nCan anyone guide me how to solve this issue?","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":1046,"Q_Id":60201977,"Users Score":0,"Answer":"It is solved now. I switched to google.colab for a while, but after sometime, i used it on my device and it ran perfectly, i did cleaned up some files in between, and was experimenting with my GPU, i guess something in that triggered the solution. Thank You anyway.","Q_Score":0,"Tags":"python-3.x,tensorflow,keras,out-of-memory,gpu","A_Id":60617770,"CreationDate":"2020-02-13T06:49:00.000","Title":"Out of Memory Error while training model using Keras","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've been training a model using just tensorflow on my GPU with the help of tf.device(), it was working fine until now. I am making another NN model in Keras and while using model.fit it is giving me OOM error.\nCan anyone guide me how to solve this issue?","AnswerCount":2,"Available Count":2,"Score":0.0996679946,"is_accepted":false,"ViewCount":1046,"Q_Id":60201977,"Users Score":1,"Answer":"OOM(Out of memory) error comes when your model want to use more memory then available memory. Check your GPU memory whether memory is occupied by some process before training. In nvidia GPU you can check with memory by command nvidia-smi in cmd before starting the training.\nIf no memory is occupied by any process or model before starting of training and you still getting OOM error then you have to optimize your model by Changing batch size or reducing data size or image size or by reducing trainable parameters of model(number of neurons).","Q_Score":0,"Tags":"python-3.x,tensorflow,keras,out-of-memory,gpu","A_Id":60203364,"CreationDate":"2020-02-13T06:49:00.000","Title":"Out of Memory Error while training model using Keras","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am currently working on a project, where I need to be able to dynamically classify incoming documents. These documents can come in text PDF files as well as scanned PDF files.\nI have the following labels:\n\nInvoice\nPacking list\nCertificate\n\nI am trying to figure out how I should approach this problem. \nMy initial thoughts\nI was thinking the best way to solve this issue would be to perform text classification, based on the document text.\nStep 1 - Train a model\n\nFirst convert the PDF files to text.\nThen label the text content by one of the three labels. (Do this for a large dataset)\n\nStep 2 - Use the model\n\nOnce the model is trained, for new incoming documents, convert it to text.\nRun the text content through the model to get the text classification.\n\nIs there another way to do this? My concerns are that I am not sure if you can perform NLP on entire text documents? Maybe object detection (Computer Vision) is needed instead?","AnswerCount":2,"Available Count":2,"Score":0.0996679946,"is_accepted":false,"ViewCount":351,"Q_Id":60207272,"Users Score":1,"Answer":"Computer vision would be faster and my first choice in your use case. Are the three types of documents visually different when you look at them in terms of layout? Certificates probably have a different \"look\" and \"layout\" but packing lists and invoices may look similar. You would want to convert PDF into page images and train and run an image classification model first. You should use transfer learning on a pre-trained image classification model like ResNet.\nYou can perform NLP on \"entire documents\" but it works best on prose text and not text on invoices or packing list. You can look up sentence embedding models (Infersent, Google USE, BERT) that can actually be used to classify full page text and not just sentences. Although some of them can be computationally expensive.","Q_Score":0,"Tags":"python,machine-learning,nlp,computer-vision","A_Id":60232186,"CreationDate":"2020-02-13T11:55:00.000","Title":"Document classification using machine learning","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am currently working on a project, where I need to be able to dynamically classify incoming documents. These documents can come in text PDF files as well as scanned PDF files.\nI have the following labels:\n\nInvoice\nPacking list\nCertificate\n\nI am trying to figure out how I should approach this problem. \nMy initial thoughts\nI was thinking the best way to solve this issue would be to perform text classification, based on the document text.\nStep 1 - Train a model\n\nFirst convert the PDF files to text.\nThen label the text content by one of the three labels. (Do this for a large dataset)\n\nStep 2 - Use the model\n\nOnce the model is trained, for new incoming documents, convert it to text.\nRun the text content through the model to get the text classification.\n\nIs there another way to do this? My concerns are that I am not sure if you can perform NLP on entire text documents? Maybe object detection (Computer Vision) is needed instead?","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":351,"Q_Id":60207272,"Users Score":0,"Answer":"I understand your problem.\nSome key point about it\na) First do pre-processing of input data. i.e ( for e.g. how many pages have in invoice or Certificate in pdf ). Then, convert pdf into TiFF images.\nb) Trained Model using Image, Visual\\layout and text. You will get good accuracy.\nc) You can used Computer vison and deep learning (Keras and tensorflow)","Q_Score":0,"Tags":"python,machine-learning,nlp,computer-vision","A_Id":68312501,"CreationDate":"2020-02-13T11:55:00.000","Title":"Document classification using machine learning","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"help me please \n\nTraceback (most recent call last): File\n \"E:\/Speaker-Identification-Python-master\/Speaker-Identification-Python-master\/modeltraining.py\", line 49, in cPickle.dump(gmm, open(dest + picklefile, 'w'))\n TypeError: write() argument must be str, not bytes","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":122,"Q_Id":60210030,"Users Score":0,"Answer":"Simple. You are using the wrong file mode for pickling. Pickling converts objects to bytes, not string. The 'w' or 'write' mode will open the file in string mode. Change it to 'wb' to open the file in the 'write-binary' mode. Change cPickle.dump(gmm, open(dest + picklefile, 'w')) to cPickle.dump(gmm, open(dest + picklefile, 'wb'))","Q_Score":0,"Tags":"python","A_Id":60210370,"CreationDate":"2020-02-13T14:23:00.000","Title":"cPickle.dump(gmm, open(dest + picklefile, 'w')) TypeError: write() argument must be str, not bytes","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a program written in python 2.7.5 scipy 0.18.1 that is able to run scipy.interpolate.UnivariateSpline with arrays that are non-sequential. When I try to run the same program in python 2.7.14 \/ scipy 1.0.0 I get the following error:\nFile \"\/usr\/local\/lib\/python2.7\/site-packages\/scipy\/interpolate\/fitpack2.py\", line 176, in init\n raise ValueError('x must be strictly increasing')\nUsually I would just fix the arrays to remove the non-sequential values. But in this case I need to reproduce the exact same solution produced by the earlier version of python\/scipy. Can anyone tell me how the earlier code dealt with the situation where the values were not sequential?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":96,"Q_Id":60218883,"Users Score":1,"Answer":"IIRC this was whatever the FITPACK (the fortran library the univariatespline class wraps) was doing. So the first stop would be to remove the check from your local scipy install and see if this does the trick","Q_Score":0,"Tags":"python,scipy,version,interpolation","A_Id":60234277,"CreationDate":"2020-02-14T01:43:00.000","Title":"How did scipy ver 0.18 scipy.interpolate.UnivariateSpline deal with values not strictly increasing?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have this data set with 78 columns and 5707 rows. Almost every column has missing values and I would like to impute them with IterativeImputer. If I understood it correctly, it will make a \"smarter\" imputation on each column based on the information from other columns.\nHowever, when imputing, I do not want the imputed values to be less than the observed minimum or more than the observed maximum. I realize there are max_value and min_value parameters, but I do not want to impose a \"global\" limit to the imputations, instead, I want each column to have its own max_value and min_value (which is the already observed maximum and minimum values). Because otherwise, the values in the columns do not make sense (negative values for headcounts, negative values for rates, etc.)\nIs there a way to implement that?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":419,"Q_Id":60228714,"Users Score":0,"Answer":"So if you want to set max and min different for each column then you can go in a loop and in each iteration select the column using sklearn.compose.make_column_selector or sklearn.compose.make_column_transformer and then apply iterative imputer to that column giving max and min of that column as parameter.","Q_Score":1,"Tags":"python,pandas,scikit-learn,sklearn-pandas,imputation","A_Id":60229197,"CreationDate":"2020-02-14T14:58:00.000","Title":"max_value and min_value for each column in scikit IterativeImputer","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am having a problem since im new at the opencv python language, any idea when the camera capture the stepper motor will rotate in 90 degrees.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":93,"Q_Id":60237558,"Users Score":1,"Answer":"I guess you are using opencv 4. In opencv 3 in cv2.findContours writting _, contours, hierarchy was correct because three arguments were returned. However, in opencv 4 only two arguments are returned so change your statement to contours, hierarchy","Q_Score":0,"Tags":"python,opencv,raspberry-pi","A_Id":60238535,"CreationDate":"2020-02-15T09:43:00.000","Title":"Camera Capture + Stepper Motor","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working on emulating MATLAB code in Python. The problems is Matlab vpasolve's exact implementation is not available in Python. I have used fsolve to solve the equation but the solution is different in MATLAB and Python.\nI would like to know if there is any other solver available in Python which can work same as vpasolve.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":1266,"Q_Id":60243243,"Users Score":0,"Answer":"vpasolve is not exact, instead it allows you to solve with a higher precision, defined by digits. While MATLAB calls it variable precisions, other areas mostly call it arbitrary precision. You closest equivalent to vpasolve would be using mpmath in python.\nIf you instead aim for an exact solution using symbolic computation, sympy would be your choice.","Q_Score":2,"Tags":"python,matlab,solver","A_Id":60351888,"CreationDate":"2020-02-15T21:21:00.000","Title":"Is there an equaivalent solver like MATLAB's vpasolve in Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've come across this:\n\nThe core information stored by a search engine is a dictionary, called an inverted\n index or inverted file, storing key-value pairs (w,L), where w is a word and L is\n a collection of pages containing word w. The keys (words) in this dictionary are\n called index terms and should be a set of vocabulary entries and proper nouns as\n large as possible. The elements in this dictionary are called occurrence lists and\n should cover as many Web pages as possible.\nWe can efficiently implement an inverted index with a data structure consisting\n of the following:\n\nAn array storing the occurrence lists of the terms (in no particular order).\nA compressed trie for the set of index terms, where each leaf stores the index\n of the occurrence list of the associated term.\n The reason for storing the occurrence lists outside the trie is to keep the size of the\n trie data structure sufficiently small to fit in internal memory. Instead, because of\n their large total size, the occurrence lists have to be stored on disk.\n\n\nand I don't understand it. If a dictionary is used to store occurence lists, what's the purpose of the trie? If I'm going to have to search for the word in the dictionary anyway, why bother with the trie?\nEdit: The quote is from Data Structures and Algorithms in Python by Michael T. Goodrich, Roberto Tamassia, Michael H. Goldwasser","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":764,"Q_Id":60243441,"Users Score":0,"Answer":"Putting each word w into a Trie data structure reduces the memory needed to store the words and speeds up a search for a specific word. At the end of each word in the Trie, you'll find a list of pointers to documents that contain the word for which you searched.","Q_Score":0,"Tags":"python,tree,search-engine,trie,inverted-index","A_Id":62144197,"CreationDate":"2020-02-15T21:50:00.000","Title":"How can a trie be used in a search engine(not for autocomplete)?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"Ubuntu 19.10,\nVScode 1.42.0,\npython 3.7.6,\nanaconda 4.8.2,\nmatplotlib 3.1.3\nIt seems that plt.show() doesn't work, because the current matplotlib backend is agg.\nRunning from the terminal, I can use Qt4Agg, but from the integrated terminal inside VScode I cannot change from agg.\nTried the following:\n\nadd backend: Qt4Agg at matplotlibrc\n__import__(\"matplotlib\").use(\"Qt4Agg\")\n__import__(\"matplotlib\").use(\"Qt4Agg\", warn=False, force=True)\nImportError: Cannot load backend 'Qt4Agg' which requires the 'qt4' interactive framework, as 'headless' is currently running\nplt.switch_backend('Qt4Agg')\nsame ImportError\nexport MPLBACKEND=Qt4Agg before running the command\n\nBut, nothing worked. Any suggestions?\nThank you!","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":864,"Q_Id":60243974,"Users Score":1,"Answer":"Not sure if this is still relevant, but it looks like your integrated terminal is running in headless mode. Changing terminal.integrated.inheritEnv to true in settings should fix it.","Q_Score":3,"Tags":"python,matplotlib,visual-studio-code","A_Id":67500071,"CreationDate":"2020-02-15T23:07:00.000","Title":"How to set matplotlib backend at vscode","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have an custom Python library function that takes a csv flat file as input that is read using data = open('file.csv', 'r').read(). But currently I've the data processed in Python as a Pandas DataFrame. How can I pass this DataFrame as a flat file object that my custom library function accepts? \nAs a work around I'm writing the DataFrame to disk and reading it back using the read function which is causing adding a second or two for each iteration. I want to avoid using this process.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":64,"Q_Id":60256207,"Users Score":0,"Answer":"In the to_csv method of pandas DataFrame, if you don't provide any argument you get the CSV output returned as a string. So you can use the to_csv method on your DataFrame, that produces the same output as you are getting by storing and reading the DataFrame again.","Q_Score":0,"Tags":"python,pandas","A_Id":60256310,"CreationDate":"2020-02-17T05:04:00.000","Title":"Read Pandas DataFrame object like a flatfile","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a Pandas DataFrame with a few columns, but I want to manipulate all of values in a single column (conditionally), like this:\ndf[my_column] = df[my_column].apply(lambda x: -float(x))\nThis works, but Pandas gives me a SettingWithCopyWarning.\n\nSettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.\n Try using .loc[row_indexer,col_indexer] = value instead\n\nIs there a problem with the way I'm going about manipulating this column?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":84,"Q_Id":60270430,"Users Score":1,"Answer":"The problem occurs earlier in your code. df is probably a slice of another dataframe and pandas is warning you not to make a modification of df because it is a copy of that other dataframe.\nThe easiest solution when you want to subset a dataframe and manipulate further is to use the .copy() method.\ndf = df_original.copy()\nnow you can apply code like:\ndf[my_column] = xxx \nwithout a SettingWithCopyWarning.","Q_Score":0,"Tags":"python,pandas,python-3.7","A_Id":60270555,"CreationDate":"2020-02-17T21:10:00.000","Title":"Pandas: SettingWithCopyWarning when calling apply on a slice","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm working on a project which i receive some EMG data from Myo Arm Band\nI need to clasify them, what machine learning algorithm can be good for this?","AnswerCount":1,"Available Count":1,"Score":-0.3799489623,"is_accepted":false,"ViewCount":47,"Q_Id":60285744,"Users Score":-2,"Answer":"you can use svm. kernels can be varied depending on number of movements to classify and it has high accuracy. i would recommend you to read some research paper related to this.","Q_Score":0,"Tags":"python,classification","A_Id":60763352,"CreationDate":"2020-02-18T16:47:00.000","Title":"What machine learning i can use for classifing EMG data from MyoArm Band?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"As my database I have a bunch of images of the same class - which means I do have only one class of images. \nAfter implementing a CBIR (feature extraction by histograms and calculating distance by euclidean - very naive approach, nothing fancy), I get the 25 best matched results. And now I would like to evaluate them. \nAll evaluation metrics like mean average precision and precision recall need ground truth data, which I don't have. Right now I'm just taking one image and calculate the similarity. \nHow can I evaluate without having any ground truth data?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":188,"Q_Id":60304192,"Users Score":0,"Answer":"Late reply, but I am working on a similar project. You can't really evaluate your approach as you don't have ground truth. What you can do is to run it for various images and calculate the mean of how many images you think are relevant each time. Even better would be to use human judges instead of your own judgement since one could say it would be highly biased.","Q_Score":0,"Tags":"python,opencv,evaluation,precision-recall,cbir","A_Id":61664504,"CreationDate":"2020-02-19T15:49:00.000","Title":"How to evaluate CBIR system without having a ground truth?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a saved model with h5 format created using keras with tensorflow v1.x backend. I can no longer load this model in keras with tensorflow v2.x backend using keras.models.load_model. Is there anyway to migrate the saved model to make it compatible with newer keras with tensorflow v2.x backend?\nSo far I have found tools \/ tutorials to migrate the code but I could not find any useful way to upgrade the saved models. I know there is tf.compat.v1.saved_model.load method for tensorflow but I cannot really use that as I saved the model using keras.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":937,"Q_Id":60304558,"Users Score":3,"Answer":"You should be able to load the same model in TensorFlow 1.x and 2.x, but for this you need to use a version of Keras that supports both, for example, Keras 2.3.1","Q_Score":2,"Tags":"python,tensorflow,keras","A_Id":60372531,"CreationDate":"2020-02-19T16:07:00.000","Title":"How to load keras model with tensorflow v1.x backend in keras with tensorflow v2.x backend?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":1},{"Question":"I know how to do a few things already:\n\nSummarise a model with model.summary(). But this actually doesn't print everything about the model, just the coarse details.\nSave model with model.save() and load model with keras.models.load_model()\nGet weights with model.get_weights()\nGet the training history from model.fit()\n\nBut none of these seem to give me a catch all solution for saving everything from end to end so that I can 100% reproduce a model architecture, training setup, and results.\nAny help filling in the gaps would be appreciated.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":81,"Q_Id":60306789,"Users Score":0,"Answer":"model.to_json() can be used to convert model config into json format and save it as a json. \nYou can recreate the model from json using model_from_json found in keras.models\nWeights can be saved separately using model.save_weights.\nUseful in checkpointing your model. Note that model.save saves both of these together. Saving only the weights and loading them back useful when you need to work with the variables used in defining the model. In that case create the model using the code and do model.load_weights.","Q_Score":0,"Tags":"python,tensorflow,keras","A_Id":60307146,"CreationDate":"2020-02-19T18:16:00.000","Title":"What's a good way to save all data related to a training run in Keras?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working with a steadily growing corpus. I train my Document Vector with Doc2Vec which is implemented in Python. \nIs it possible to update a Document Vector?\nI want to use the Document Vector for Document recommendations.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":79,"Q_Id":60307249,"Users Score":0,"Answer":"Individual vectors can be updated, but the gensim Doc2Vec model class doesn't have much support for adding more doc-vectors to itself. \nIt can, however, return individual vectors for new texts that are compatible (comparable) with the existing vectors, via the .infer_vector(words) method. You can retain these vectors in your own data structures for lookup. \nWhen enough new documents have arrived that you think your core model would be better, if trained on all documents, you can re-train the model with all available data, using it as the new base for .infer_vector(). (Note that vectors from the retrained model won't usually be compatible\/comparable with those from the prior model: each training session bootstraps a different self-consistent coordinate space.)","Q_Score":1,"Tags":"python,gensim,doc2vec","A_Id":60309760,"CreationDate":"2020-02-19T18:46:00.000","Title":"Is it possible to update a Doc2Vec Vector?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"My python version = 3.7.4\ncv2 version= 4.2.0\nThese are my version on python and open cv, Im trying to use SIFT function and I got the famous error module cv2.cv2' has no attribute 'SIFT', so I tried pip install opencv-contrib-python and also python -m pip install --user opencv-contrib-python, and I changed detector=cv2.SIFT() to detector=cv2.xfeatures2d.SIFT_create() and the error just changed to AttributeError: module 'cv2.cv2' has no attribute 'xfeatures2d'\nI Tried with similar questions that I found, but are not working for me, I dont find a recent question, thats why Im opening this new because maybe as the version were different it could be the reason doesnt work for me\nWhat else could I do?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":3506,"Q_Id":60323159,"Users Score":1,"Answer":"SIFT and SURF are proprietary, patented algorithms. You'd need to compile OpenCV and OpenCV-contrib from source, with non-free packages enabled, building the python libraries. I wasn't able to get this working so I used pip to find an older version (3.4.2) that did not remove the non-free libraries. I may have had to roll back python but I'm not sure. I am using python 3.6.8","Q_Score":0,"Tags":"python,python-3.x,opencv","A_Id":60329148,"CreationDate":"2020-02-20T15:18:00.000","Title":"module 'cv2.cv2' has no attribute 'xfeatures2d' and module 'cv2.cv2' has no attribute 'SIFT'","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm using Auto-Sklearn and have a dataset with 42 classes that are heavily imbalanced. What is the best way to handle this imbalance? As far as I know, two approaches to handle imbalanced data within machine learning exist. Either using a resampling mechanism such as over- or under-sampling (or a combination of both) or to solve it on an algorithmic-level by choosing an inductive bias that would require in-depth knowledge about the algorithms used within Auto-Sklearn. I'm not quite sure on how to handle this problem. Is it anyhow possible to solve the imbalance directly within Auto-Sklearn or do I need to use resampling strategies as offered by e.g. imbalanced-learn? Which evaluation metric should be used after the models have been computed? The roc_auc_score for multiple classes is available since sklearn==0.22.1. However, Auto-Sklearn only supports sklearn up to version 0.21.3. Thanks in advance!","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":5508,"Q_Id":60327063,"Users Score":0,"Answer":"For those interested and as an addition to the answers given, I can highly recommend the following paper: \nLemnaru, C., & Potolea, R. (2011, June). Imbalanced classification problems: systematic study, issues and best practices. In International Conference on Enterprise Information Systems (pp. 35-50). Springer, Berlin, Heidelberg.\nThe authors argue that: \n\nIn terms of solutions, since the performance is not expected to improve\n significantly with a more sophisticated sampling strategy, more focus should be\n allocated to algorithm related improvements, rather than to data improvements.\n\nAs e.g. the ChaLearn AutoML Challenge 2015 used the balanced accuracy, sklearn argues that it is a fitting metric for imbalanced data and Auto-Sklearn was able to compute well-fitting models, I'm going to have a try. Even without resampling, the results were much \"better\" (in terms of prediction quality) than just using the accuracy.","Q_Score":2,"Tags":"python,machine-learning,scikit-learn,multiclass-classification","A_Id":60352461,"CreationDate":"2020-02-20T19:15:00.000","Title":"Best way to handle imbalanced dataset for multi-class classification in Auto-Sklearn","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to create a health score system for my company\u2019s clients. There is a lot of data that I am pulling from through my API. I was crunching data through g-scripts but it is taking a really long time, so I thought using Numpy's vectorization would make things much faster. I was thinking of creating a new web application using the MERN stack but I would like to crunch the data using python. Any suggestions on what to do?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":456,"Q_Id":60330478,"Users Score":1,"Answer":"A MERN stack is essentially javascript, so there's a ceiling to the amount of calculation you can realistically do on the backend with a vanilla implementation. \nI would build a native daemon that runs your Python code, place it in a docker container, and choosing your favorite messaging\/transportation system to communicate with your backend API. There are plenty of choices there:\n\nWebsockets (raw)\nMessaging Queue Libraries (IE ZeroMQ)\nMongoDB change streams (Since you are using MERN)\n\nSo a classic life cycle would of a data crunch event would be:\n\nIssue a rest-ful command to backend API\nBackend API issues a message to daemon using your messaging system\nDaemon awakes and crunches data\nDaemon sends back result via messaging system to rest-ful api\nBackend API reads the message back and send result to front-end","Q_Score":2,"Tags":"python,amazon-web-services,numpy,data-science,mern","A_Id":60330638,"CreationDate":"2020-02-21T00:21:00.000","Title":"How to crunch data in python but add to MERN Stack Application","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Whether it is dynamic time warping or some sort of Euclidean k-means clustering of a time series, it is (nearly?) always required to consider irregular spacing of data, unequal lengths of data and\/or missing-ness of data.\nWhile realizing that each of these issues have considerations unto themselves, is there a general reason why pre-processing each time series with a spline to interpolate (or very minimally extrapolate) the data to ameliorate these issues cannot be done?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":357,"Q_Id":60343442,"Users Score":1,"Answer":"I don't see why not. I think the main thing to consider is what assumption(s) you are making. The assumptions that come to mind for such a procedure, to me at least, are\n\nThe splines can adequately describe (smooth) each time series, and capture differences between them.\nThe inputs into the clustering procedure describe true differences between the splines, and hence the time series.\n\nThe input into the clustering procedure could be the estimated spline function, or the coefficients of the spline. Certainly, the estimated coefficients would be easier to use, but you'd want to ensure that differences between them truly represent differences in the spline function. This might boil down to orthogonality of the basis function of the splines, but I'm not sure if there is theory existing to back that up or not.","Q_Score":2,"Tags":"python,r,time-series,cluster-analysis,spline","A_Id":60348199,"CreationDate":"2020-02-21T17:14:00.000","Title":"Irregular\/missing data when clustering time series","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a trained model and I need to run inference on a large directory of images. I know I can make a generator using ImageDataGenerator.flow_from_directory but it is not obvious how to associate predicted results with file names. Ideally given a keras model + directory of images i'd like to have an array of file names and predicted probabilities. How do I accomplish this?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":220,"Q_Id":60350353,"Users Score":0,"Answer":"What you need to do is to separate the images into a different folder, corresponding to the class. The name of the folder should be the name of the class, by using the ImageDataGenerator.flow_from_directory() Keras will automatically infer the class names based on the directories. \nAs an example, you should have a folder named \"data\" that contains 2 folders named \"cat\" and \"dog\". \nThen you can call the method ImageDataGenerator.flow_from_directory(\"path\/to\/folder\/data\") and Keras will produce a dataset with the two classes, \"cat\" and \"dog\".\nDepending on the name of the files, the separation might be easy for you with a simple program, If not, I recommend using a program that groups together similar images, and based on that you can manually create the folders.","Q_Score":2,"Tags":"python-3.x,tensorflow,keras","A_Id":60354477,"CreationDate":"2020-02-22T08:29:00.000","Title":"Streaming images from directory and associating prediction with file name in tensorflow","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a dataset which contains english statements. Each statement has been assigned a number of topics that the statement is about. The topics could be economy, sports, politics, business, science, etc. Each statement can have more than 1 topic. Some statements can have 1 topic, some can have 2 topics, so on and so forth. For the statement itself I am using TF-IDF vectors to convert statement into a feature vector. However, I am confused how to convert topics into a feature vector for machine learning training.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":49,"Q_Id":60361601,"Users Score":0,"Answer":"You can create a binary column for each topic which will show whether the statement has this topic.","Q_Score":1,"Tags":"python,machine-learning,feature-extraction,feature-selection,feature-engineering","A_Id":60363881,"CreationDate":"2020-02-23T11:13:00.000","Title":"How do I convert topics for each item in the dataset into a feature vector, considering that each item can have more than 1 topic","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am developing a robot based on StereoPI. I have successfully calibrated the cameras and obtained a fairly accurate depth map. However, I am unable to convert my depth map to point cloud so that I can obtain the actual distance of an object. I have been trying to use cv2.reprojectImageTo3D, but see no success. May I ask if there is a tutorial or guide which teaches how to convert disparity map to point cloud? \nI am trying very hard to learn and find reliable sources but see on avail. So, Thank you very much in advance.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":158,"Q_Id":60364209,"Users Score":0,"Answer":"By calibrating your cameras you compute their interior orientation parameters (IOP - or intrinsic parameters). To compute the XYZ coordinates from the disparity you need also the exterior orientation parameters (EOP).\nIf you want your point cloud relative to the robot position, the EOP can be simplified, otherwise, you need to take into account the robot's position and rotation, which can be retrieved with a GNSS receiver and intertial measurement unit (IMU). Note that is very likely that such data need to be processed with a Kalman filter.\nThen, assuming you got both (i) the IOP and EOP of your cameras, and (ii) the disparity map, you can generate the point cloud by intersection. There are several ways to accomplish this, I suggest using the collinearity equations.","Q_Score":0,"Tags":"python,image-processing,raspberry-pi3,point-clouds,stereo-3d","A_Id":60409243,"CreationDate":"2020-02-23T16:13:00.000","Title":"Converting depth map to pointcloud on Raspberry PI for realtime application","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm fairly new to programming and need help I've installed pip and I have installed NumPy using\npip install numpy\nand when I try to import it in my code I get \nModuleNotFoundError: No module named 'numpy'' (also the same for cv2)\nif this is any help\nI've installed pip, anaconda, and tensor flow 2.0 GPU\nMy os is Windows 10\nany help is good thank you!","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":80,"Q_Id":60368738,"Users Score":0,"Answer":"If you're running through anaconda, you should strictly use conda to install packages instead of pip. Using both will confuse python and give a 'module not found' error.","Q_Score":0,"Tags":"python,numpy,new-operator","A_Id":60368756,"CreationDate":"2020-02-24T02:12:00.000","Title":"Numpy and open cv not importing","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to do MLE regression using AR(p) by importing the module from statsmodels.tsa.ar_model import AutoReg, ar_select_order, but this ImportError keeps coming. How to solve this? Is there any other way I can do Autoregression in Python?","AnswerCount":2,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":9341,"Q_Id":60369122,"Users Score":2,"Answer":"do pip install statsmodels --upgrade and restart the environment.","Q_Score":6,"Tags":"python,time-series,statsmodels,mle,vector-auto-regression","A_Id":67997654,"CreationDate":"2020-02-24T03:19:00.000","Title":"Why ImportError: cannot import name 'AutoReg' from 'statsmodels.tsa.ar_model' occuring?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I built regression data model to predict house price upon several independent variables. And I got regression equation with coefficient. I used StandardScaler()to scale my variables before split the data set. And now I want to predict house price when given new values for independent variables using my regression model for that thing can I directly use values for independent variables and calculate price? or before include values for independent variables should I pass the values through StandardScaler() method??","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":107,"Q_Id":60370388,"Users Score":1,"Answer":"To answer your question, yes you have to process your test input as well but consider the following explanation.\nStandardScaler() standardize features by removing the mean and scaling to unit variance\nIf you fit the scaler on whole dataset and then split, Scaler would consider all values while computing mean and Variance.\nThe test set should ideally not be preprocessed with the training data. This will ensure no 'peeking ahead'. Train data should be preprocessed separately and once the model is created we can apply the same preprocessing parameters used for the train set, onto the test set as though the test set didn't exist before.","Q_Score":0,"Tags":"python,machine-learning,regression,data-science,data-modeling","A_Id":60370498,"CreationDate":"2020-02-24T06:07:00.000","Title":"Predicting price using regression data model","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am relatively new to data science and machine learning and I am currently working on my first project with a very large data set, with over a million rows and 88 columns`.\nI am currently in the process of cleaning the data and trying to use features like data.isnull(), .sum() and data[data.isnull().values.any(axis=1)].head() but my Jupiter notebook file will only show the first ten and last ten columns. \nJust looking for the best way to view the data or to be directed to any resources that may help.","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":718,"Q_Id":60383131,"Users Score":0,"Answer":"You are using .head() in your code,\ndata[data.isnull().values.any(axis=1)].head().\nThis will give you first 10 columns by default. You can specify number of columns you want to see as argument to .head(). \nIf you remove .head() from above line you will see the full dataframe.\nSimilarly, check if you are using .tail() somewhere. That will give you last 10 columns.","Q_Score":0,"Tags":"python,python-3.x,pandas,dataframe,data-cleaning","A_Id":60383203,"CreationDate":"2020-02-24T20:04:00.000","Title":"Python\/Pandas only showing the first 10 and last 10 columns in a data frame","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"It makes sense that pooled output is used for sentence level analysis (e.g classification). I am wondering, is the token level embedding better for named entity recongition? I would've thought so, but am unsure how to take the sequence output and manipulate for NER. Do I just take a slice [:, :, -1] for [batch_size, num_tokens, 768]?","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":669,"Q_Id":60386576,"Users Score":2,"Answer":"If we talk about bert, there we get two output\no1, o2 = self.bert(ids, attention_mask=mask)\n\no1-Sequential output: Each and every token will receive its own embedding (can be used in NER Pooled output.)\no2-Pooled output: Whole Sentence receives an embedding. (can be used in classification problem )\n\nIn the forward pass, you can further modify the bert output according to your use case.","Q_Score":3,"Tags":"python,nlp","A_Id":64402117,"CreationDate":"2020-02-25T02:11:00.000","Title":"pooled output vs sequence output for NER with BERT","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"When the outputs (prediction) are the probabilities coming from a Softmax function, and the training target is one-hot type, how do we compare those two different kinds of data to calculate the accuracy? \n(the number of training data classified correctly) \/ (the number of the total training data) *100%","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":365,"Q_Id":60387266,"Users Score":0,"Answer":"Usually, we assign the class label with highest probability in the output of the soft max function as the label.","Q_Score":1,"Tags":"python,neural-network,multiclass-classification","A_Id":60387487,"CreationDate":"2020-02-25T03:53:00.000","Title":"How do we calculate the accuracy of a multi-class classifier using neural network","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"We know that the default threshold for success in a Binary Classification of the Logistic Regression model is > 0.5.\nI'm curious to know the output of this model if the predicted probability is exactly 0.5 for both Success and Failure. Can someone clarify me?","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":178,"Q_Id":60387801,"Users Score":1,"Answer":"To simply put, the model is not confident in making the decision. You can choose either of the class labels based on your problem -- do you want high precision or high recall ? However a more systematic way is to use ROC curve to find the optimal threshold value.","Q_Score":1,"Tags":"python,machine-learning,data-science,logistic-regression","A_Id":60387875,"CreationDate":"2020-02-25T05:04:00.000","Title":"How a Logistic Regression model reacts if the probability of success and failure are exactly 0.5?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"In the training data, I did feature engineering and clean my data. Is this important to do the same with test data?\nI know some basic modifications like label encoding, dependent\/independent feature split, etc.. are required in test data as well. But do we really need to CLEAN the test data before we do the predictions?","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":1188,"Q_Id":60392255,"Users Score":1,"Answer":"It depends:\nNormalizing the data: If you normalized your training data, then yes, normalize the test data in exactly the way you normalized the training data. But be careful that you do not re-tune any parameters you tuned on the training data.\nFilling missing values: idem. Treat the test data as the training data but do not re-tune any of the parameters.\nRemoving outliers: probably not. The aim of the test set is to make an estimate about how well your model will perform on unseen data. So removing outliers will probably not be a good idea.\nIn general: only do things to your test data that you can\/will also do on unseen data upon applying your model.","Q_Score":0,"Tags":"python,machine-learning,data-science,data-cleaning","A_Id":60392572,"CreationDate":"2020-02-25T10:18:00.000","Title":"Is this important to clean test data?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Is there a way to list the packages for which I specified the version number. For example, if I specified scipy version but not numpy version by installing them like this: conda install scipy=0.15.0 numpy, I would like to be able to know that I specified version 0.15.0 for scipy. Furthermore, how can I unspecify a package version if I do not want to specifically use that version but I would rather like to get the latest possible version?","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":347,"Q_Id":60407724,"Users Score":1,"Answer":"There is no any programmatic way to extract the information you are looking for. The only way I could think of is by extracting the history of the commands you typed while installing your packages through your terminal (in case of mac or linux machines) or command prompt (in case of windows machine).\n\nFor checking the history of typed commands in MAC or LINUX:\nType history in your terminal window\nFor checking the history of typed commands in Windows:\nType doskey \/history or press F7 key inside your command\nprompt\n\nAfter extracting this history of commands you typed, you can create a piece of code to check for commands in which you have specified version numbers. \nHow can I unspecify a package version if I do not want to specifically use that version but I would rather like to get the latest possible version? You can just do pip install [package_name] --upgrade in case of pip or conda update [package_name] in case of conda to upgrade a package to its latest version","Q_Score":2,"Tags":"python,version-control,anaconda","A_Id":60408388,"CreationDate":"2020-02-26T06:05:00.000","Title":"list anaconda packages for which I specified version number","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm working on a supervised multi-label ML model which for now works by predicting a \"tag\" (label) for an input from the user, based on the dataset it was trained with. The training dataset had two columns - posts & tags. \nWhenever I give anything as an input, the prediction is a relevant tag for it. But when the input is something which is not in the dataset, the output is again some random tag. I'm looking for a solution in the context of creating a chatbot, which would return something like \"Sorry, I couldn't understand that\" if the input is something different from what the machine has been trained for. How do I do that? Is there any way to get an \"empty label\" in such a case so that I can simply map my responses accordingly for that condition?\nThanks in advance!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":91,"Q_Id":60412386,"Users Score":0,"Answer":"You can use a softmax in your last layer and create a treshold for your prediction. \nIf the score of your maximum prediction is under the treshold, the chatbot can answer \"Sorry, I couldn't understand that\". \nAs you didn't give any code, I can't show you how yo add a treshold but it is quite easy to find it on Stack Overflow.","Q_Score":0,"Tags":"python,machine-learning,nlp,chatbot,multilabel-classification","A_Id":60412548,"CreationDate":"2020-02-26T10:58:00.000","Title":"How to get \"no label\" from a supervised multi-label machine learning model?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"was just wondering whether anyone had any thoughts on best practices when working in databricks. It is financially costing a lot to develop within databricks, hence would like to know where else it would be best to develop python code in. With thought also to collaborative work, is there a similar set up to databricks for collaborative work that is free or of little cost to use. \nAny suggestions, greatly appreciated!","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":284,"Q_Id":60415762,"Users Score":0,"Answer":"The cost of Databricks is really related to the size of the clusters you are running (1 worker, 1 driver or 1 driver 32 workers?), the spec of the machines in the cluster (low RAM and CPU or high RAM and CPU), and how long you leave them running (always running or short time to live, aka \"Terminate after x minutes of inactivity\". I am also assuming you are not running the always on High Concurrency cluster mode.\nSome general recommendations would be:\n\nwork with smaller datasets in dev, eg representative samples which would enable you to...\nwork with smaller clusters in dev, eg instead of working with large 32 node clusters, work with 2 node small clusters\nset time to live as short eg 15 mins\nwhich together would reduce your cost\n\nObviously there is a trade-off in assembling representative samples and making sure your outputs are still accurate and useful but that's up to you.","Q_Score":2,"Tags":"python,amazon-web-services,azure,databricks,cost-management","A_Id":60417809,"CreationDate":"2020-02-26T14:08:00.000","Title":"How can I reduce the financial cost of working in databricks?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"So as the title suggests, my question is whether feature selection algorithms are independent of the regression\/classification model chosen. Maybe some feature selection algorithms are independent and some are not? If so can you name a few of each kind? Thanks.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":45,"Q_Id":60434250,"Users Score":2,"Answer":"It depends on the algorithm you use to select features. Filter methods that are done prior to modeling are of course agnostic, as they're using statistical methods like chi-squared or correlation coefficient to get rid of unnecessary features.\nIf you use embedded methods where features are selected during model creation, it is possible that different models will find value in different feature sets. Lasso, Elastic Net, Ridge Regression are a few examples of these. \nIt's worth noting that some model types perform well with sparse data or missing values while others do not.","Q_Score":0,"Tags":"python,machine-learning,scikit-learn,regression","A_Id":60434515,"CreationDate":"2020-02-27T13:23:00.000","Title":"Is feature selection agnostic to regression\/classification model chosen?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to train a Masked RCNN neural network to be able to segment different parts of the seedlings. We have images of the seedlings with black and white background, would it be best to train the CNN with only one background or both of them combined, to get good segmentation results?\nWe will only acquire images with black background in the final pipeline.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":38,"Q_Id":60435868,"Users Score":1,"Answer":"It\u2019s best to have your training data match your production inputs. If you are always going to have your seedlings on a black background during inferencing, you don\u2019t need to have them on a white background during training.","Q_Score":0,"Tags":"python,machine-learning,image-processing,deep-learning,faster-rcnn","A_Id":60451748,"CreationDate":"2020-02-27T14:50:00.000","Title":"Training instance segmentation of seedlings. Better results with different backgrounds?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a pandas dataframe and using:\nfiltered = dataframe[dataframe[\"x\"] == \"y\"] returns results. \nHowever, this does not:\nfiltered = dataframe.query('x == \"y\"', inplace=True) does not.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":119,"Q_Id":60440413,"Users Score":0,"Answer":"As ifly6 and Yuca pointed out, removing inplace=True resolved this.","Q_Score":2,"Tags":"python,pandas","A_Id":60440495,"CreationDate":"2020-02-27T19:25:00.000","Title":"Pandas: df.query() method returns 0 results","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using fetch_20newsgroups_vectorized data:\nimport numpy as np\nfrom scipy.sparse import csr_matrix\nfrom sklearn.datasets import fetch_20newsgroups\nfrom sklearn.datasets import fetch_20newsgroups_vectorized\nnewsgroups = fetch_20newsgroups(subset='all')\nlabels = newsgroups.target_names\nnews_data, news_labels = fetch_20newsgroups_vectorized(subset='all', normalize=False, return_X_y=True)\nnews_labels = [labels[i] for i in news_labels] ### converting integer list to str list\nwhen I try to subset matrix news_data based on groups of news_label (exstract all rows that have label i into a new matrix), it returns the same subset for each label level (there are 20 different levels and news_data is csr_matrix):\nfor i in set(news_labels):\n print(i)\n subset = news_data[news_labels == i]\nHow can I subset news_data for every level of news_label?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":279,"Q_Id":60445662,"Users Score":1,"Answer":"I tried: \nfor i in set(news_labels):\n indices = [element for element, x in enumerate(news_labels) if x == i]\n subset = news_data[indices]\nand it worked!","Q_Score":1,"Tags":"python,list,subset,sparse-matrix","A_Id":60446694,"CreationDate":"2020-02-28T05:19:00.000","Title":"How to subset sparse matrix by value of a label list?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using matplotlib.pyplot module imported as plt for plots. \nIn the plt.plot() statement, if I pass the arguments as \"x= array1, \"y= array2\", I get \"TypeError: plot got an unexpected keyword argument 'x' \". \nThe code gets executed correctly if I simple pass \"array1 and array2\", without explicitly saying they correspond to x and y axes. \nWhy is that?","AnswerCount":2,"Available Count":1,"Score":0.2913126125,"is_accepted":false,"ViewCount":7480,"Q_Id":60452488,"Users Score":3,"Answer":"It has to do with the concepts of *args and **kwargs in Python. Both of these let you to use a variable number of parameters within your function, but the difference comes in the fact that while *args takes only the values, **kwargs also takes the keywords as the name \"kw\" implies.\nSince matplotlib.pyplot.plot() function uses *args instead of **kwargs, these functions do not accept keywords within the parameters.","Q_Score":8,"Tags":"python,matplotlib","A_Id":66302239,"CreationDate":"2020-02-28T08:54:00.000","Title":"Why can't arguments be passed explicitly as x and y in pyplot?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to train a custom ner model using spacy. Currently, I have more than 2k records for training and each text consists of more than 100 words, at least more than 2 entities for each record. I running it for 50 iterations.\nIt is taking more than 2 hours to train completely. \nIs there any way to train using multiprocessing? Will it improve the training time?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":1329,"Q_Id":60453073,"Users Score":0,"Answer":"Hi I did same project where I created custom NER Model using spacy3 and extracted 26 entities on large data. See it really depends like how are you passing your data. Follow the steps I am mentioning below might it could work on CPU:\n\nAnnotate your text files and save into JSON\n\nConvert your JSON files into .spacy format because this is the format spacy accepts.\n\nNow, here is the point to be noted that how are you passing and serializing your .spacy format in spacy doc object.\n\n\nPassing all your JSON text will take more time in training. So you can split your data and pass iterating it. Don't pass consolidated data. Split it.","Q_Score":2,"Tags":"python,nlp,python-multiprocessing,spacy,named-entity-recognition","A_Id":72028293,"CreationDate":"2020-02-28T13:47:00.000","Title":"Spacy train ner using multiprocessing","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am publishing same data (Topic, Key & Value) from python confluent_kafka library based Producer v\/s Java apache library based producer but when messages checked on Kafka then they are published to different \nKafka Partition.\nI was expecting by default both these library will use same hash method (murmur2) on Key and will determine same partition when publishing message to Kafka, but looks like that is is not happening.\nIs there flag or option that needs to be set on Python library so that it will use same algorithm and generate same (as Java library) Kafka partition OR is there any other python library that should be used to achieve this?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":218,"Q_Id":60457993,"Users Score":0,"Answer":"I found a way to force confluent_kafka Producer to use murmur2 algorithm to determine partition. You can set below parameter with value:\n'partitioner': 'murmur2_random'","Q_Score":0,"Tags":"python,apache-kafka,confluent-platform","A_Id":60458635,"CreationDate":"2020-02-28T19:18:00.000","Title":"Kafka different partitions are selected python confluent_kafka library v\/s apache kafka Java","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":1,"Web Development":0},{"Question":"I have 20 symbols for which I need to record tick data continuously for 6 hours a day every week.\nSo I want 20 excel files to be created automatically by the module (if files don't exist) and a excel writer which stores tick data (row by row). Then I need to resample the data to 5 minutes timeframe after reading them through dataframe. Dataframe should be able to read the tick data created by the module.\nWhat best excel writer can be used for this function. I want to write to the files when they are closed.\nwhich of them will work better?\n\nIn built open function\nOpenpyxl\nXlwt","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":26,"Q_Id":60462134,"Users Score":0,"Answer":"hello i would recommed you xlwings. as it is the best module to stream the tick data to excel when file is opened.","Q_Score":0,"Tags":"python","A_Id":60650847,"CreationDate":"2020-02-29T05:02:00.000","Title":"How to create excel files and then read the files through dataframe?","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've tried to import opencv to Pycharm, but this error pops up:\nCollecting cv2\nCould not find a version that satisfies the requirement cv2 (from versions: )\nNo matching distribution found for cv2\nCan you please help me?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":238,"Q_Id":60465368,"Users Score":0,"Answer":"Install opencv with:\npip3 install opencv-python\nMake sure you are using the correct interpreter for your project in PyCharm. Go to File\\Settings...\\Project\\Project Interpreter and ensure opencv is listed under the Python interpreter you wish to use.","Q_Score":0,"Tags":"python,opencv,pycharm","A_Id":60465423,"CreationDate":"2020-02-29T12:56:00.000","Title":"can't import opencv in PyCharm","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"With dask dataframe using\ndf = dask.dataframe.from_pandas(df, npartitions=5)\nseries = df.apply(func) \nfuture = client.compute(series)\nprogress(future)\nIn a jupyter notebook I can see progress bar for how many apply() calls completed per partition (e.g 2\/5).\nIs there a way for dask to report progress inside each partition?\nSomething like tqdm progress_apply() for pandas.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":474,"Q_Id":60467807,"Users Score":0,"Answer":"If you mean, how complete each call of func() is, then no, there is no way for Dask to know that. Dask calls python functions which run in their own python thread (python threads cannot be interrupted by another thread), and Dask only knows whether the call is done or not.\nYou could perhaps conceive of calling a function which has some internal callbacks or other reporting system, but I don't think I've seen anything like that.","Q_Score":0,"Tags":"python,pandas,dask,tqdm,dask-dataframe","A_Id":60491327,"CreationDate":"2020-02-29T17:31:00.000","Title":"Dask progress during task","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to process images(most probably in big sizes) on Hadoop platform but I am confused about which one to choose from the aforementioned 2 interfaces, especially for someone who is still a beginner in Hadoop. Considering the need to split the images into blocks to distribute processing among working machines and merge the blocks after processing is completed.\nIt's known that Pydoop has better access to the Hadoop API while mrjob has powerful utilities for executing the jobs, which one is suitable to be used with this kind of work?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":121,"Q_Id":60469567,"Users Score":1,"Answer":"I would actually suggest pyspark because it natively supports binary files.\nFor image processing, you can try TensorFlowOnSpark","Q_Score":0,"Tags":"python,hadoop,image-processing","A_Id":60476719,"CreationDate":"2020-02-29T21:00:00.000","Title":"Pydoop vs Mrjob for image processing on Hadoop","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":1},{"Question":"I am trying to solve a modified version of the TSP. In my version, multiple visits to a city are allowed, as long as the path is the shortest, and also, only subset of the cities are compulsory to visit, as in, you can go through other cities to visit all the subset cities if path is shorter, but if not, the other cities can be ignored. NetworkX has approx. solution for the traditional TSP using the dwave_networkx.algorithms.tsp.traveling_salesperson, but I have trouble solving this one. A naive approach can be to find all possible combinations of the subset cities and check which has the shortest total path length, but that solution will have a n^2 complexity for trying each combination, plus the complexity for finding shortest path for each two cities. So, what should I use to solve this problem using NetworkX.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":706,"Q_Id":60473238,"Users Score":0,"Answer":"You can select a path randomly and optimize the way on it. Basically, randomly assign a way between two nodes. Than on nodes, try to find optimal way for n+2 nodes. A --> B --> C if there is a path between shortest then try A--> D --> C---E if there is path between D and E shortest than D --> K --> E then again iterate A--> D --> F --> E simply that sound to me a good idea. I don't have proof now but it can give you the possible shortest path. I hope that will be helpful. Good luck.","Q_Score":0,"Tags":"python,algorithm,graph,networkx,traveling-salesman","A_Id":60486146,"CreationDate":"2020-03-01T08:18:00.000","Title":"Solving a modified Travelling Salesman Problem(TSP) using networkx","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":1,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am struggling with the basics.\nI have just one column with names in pandas dataframe and I want to compare strings for potential duplicates using 3-4 functions from fuzzywuzzy library. \nSo first name I want to check against the rest of the column content, then 2nd name and so on. Column will have hundreds if not thousands of names.\nI want to create a df with combination of names for which at least one of the values is above 80.\nDo I need to create a list out of that df?\nApologies, I know it is very basic I just can't seem to find a solution myself.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":96,"Q_Id":60475903,"Users Score":0,"Answer":"So in the end I found a different approach to my issue. Instead of doing 80k vs 80k list I have used a function called itertools.combinations which gives you unique combinations which is perfect in this scenario.","Q_Score":2,"Tags":"python,pandas,fuzzywuzzy","A_Id":60828461,"CreationDate":"2020-03-01T14:02:00.000","Title":"Basic question - iterating through pandas dataframe column using a function","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"will it be possible to use CNN weights on an RNN model \nlike can you use the weights of a CNN learning what each letter looks like and using the weights from that CNN to translate a whole sentence?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":31,"Q_Id":60476253,"Users Score":1,"Answer":"It is possible. For an RNN you have to define what is the hidden state so you may set it to be the output of the CNN on the previous element in the sequence. There are several models with state-of-the-art performance on sentence translation. One of them is the Transformer which is makes use of convolutions, as in CNNs, and self-attention. However, it doesn't do so in an RNN scheme, as RNNs are slower to train and evaluate due to their sequential nature. Also note that RNNs are inferior (mainly) due to their problem of short-term memory. You may want to read on LSTMs (that became their successor).","Q_Score":0,"Tags":"python","A_Id":60476585,"CreationDate":"2020-03-01T14:43:00.000","Title":"CNN weights on RNN model","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I know in Numpy, if it is divided by 0, it could become -inf or inf. In DolphinDB, if dividing by 0, it will turn into NULL, it is hard for me to tell if the value is just NULL or caused by 0 division.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":16,"Q_Id":60478113,"Users Score":0,"Answer":"The current version of DolphinDB doesn't support INF.","Q_Score":1,"Tags":"python,database,numpy,time-series,dolphindb","A_Id":62103341,"CreationDate":"2020-03-01T17:59:00.000","Title":"Does DolphinDB support -inf and inf when dividing by 0 like numpy?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"First of all, my apologies if I am not following some of the best practices of this site, as you will see, my home is mostly MSE (math stack exchange).\nI am currently working on a project where I build a vacation recommendation system. The initial idea was somewhat akin to 20 questions: We ask the user certain questions, such as \"Do you like museums?\", \"Do you like architecture\", \"Do you like nightlife\" etc., and then based on these answers decide for the user their best vacation destination. We answer these questions based on keywords scraped from websites, and the decision tree we would implement would allow us to effectively determine the next question to ask a user. However, we are having some difficulties with the implementation. Some examples of our difficulties are as follows:\nThere are issues with granularity of questions. For example, to say that a city is good for \"nature-lovers\" is great, but this does not mean much. Nature could involve say, hot, sunny and wet vacations for some, whereas for others, nature could involve a brisk hike in cool woods. Fortunately, the API we are currently using provides us with a list of attractions in a city, down to a fairly granular level (for example, it distinguishes between different watersport activities such as jet skiing, or white water rafting). My question is: do we need to create some sort of hiearchy like:\n\nnature-> (Ocean,Mountain,Plains) (Mountain->Hiking,Skiing,...)\n\nor would it be best to simply include the bottom level results (the activities themselves) and just ask questions regarding those? I only ask because I am unfamiliar with exactly how the classification is done and the final output produced. Is there a better sort of structure that should be used?\nThank you very much for your help.","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":66,"Q_Id":60481819,"Users Score":0,"Answer":"Bins and sub bins are a good idea, as is the nature, ocean_nature thing.\nI was thinking more about your problem last night, TripAdvisor would be a good idea. What I would do is, take the top 10 items in trip advisor and categorize them by type. \nOr, maybe your tree narrows it down to 10 cities. You would rank those cities according to popularity or distance from the user.\nI\u2019m not sure how to decide which city would be best for watersports, etc. You could even have cities pay to be top of the list.","Q_Score":1,"Tags":"python,machine-learning,decision-tree","A_Id":60517774,"CreationDate":"2020-03-02T02:33:00.000","Title":"Using a Decision Tree to build a Recommendations Application","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"First of all, my apologies if I am not following some of the best practices of this site, as you will see, my home is mostly MSE (math stack exchange).\nI am currently working on a project where I build a vacation recommendation system. The initial idea was somewhat akin to 20 questions: We ask the user certain questions, such as \"Do you like museums?\", \"Do you like architecture\", \"Do you like nightlife\" etc., and then based on these answers decide for the user their best vacation destination. We answer these questions based on keywords scraped from websites, and the decision tree we would implement would allow us to effectively determine the next question to ask a user. However, we are having some difficulties with the implementation. Some examples of our difficulties are as follows:\nThere are issues with granularity of questions. For example, to say that a city is good for \"nature-lovers\" is great, but this does not mean much. Nature could involve say, hot, sunny and wet vacations for some, whereas for others, nature could involve a brisk hike in cool woods. Fortunately, the API we are currently using provides us with a list of attractions in a city, down to a fairly granular level (for example, it distinguishes between different watersport activities such as jet skiing, or white water rafting). My question is: do we need to create some sort of hiearchy like:\n\nnature-> (Ocean,Mountain,Plains) (Mountain->Hiking,Skiing,...)\n\nor would it be best to simply include the bottom level results (the activities themselves) and just ask questions regarding those? I only ask because I am unfamiliar with exactly how the classification is done and the final output produced. Is there a better sort of structure that should be used?\nThank you very much for your help.","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":66,"Q_Id":60481819,"Users Score":0,"Answer":"I think using a decision tree is a great idea for this problem. It might be an idea to group your granular activities, and for the \"nature lovers\" category list a number of different climate types: Dry and sunny, coastal, forests, etc and have subcategories within them.\nFor the activities, you could make a category called watersports, sightseeing, etc. It sounds like your dataset is more granular than you want your decision tree to be, but you can just keep dividing that granularity down into more categories on the tree until you reach a level you're happy with. It might be an idea to include images too, of each place and activity. Maybe even without descriptive text.","Q_Score":1,"Tags":"python,machine-learning,decision-tree","A_Id":60483055,"CreationDate":"2020-03-02T02:33:00.000","Title":"Using a Decision Tree to build a Recommendations Application","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a LSTM Keras Tensorflow model trained and exported in .h5 (HDF5) format. \nMy local machine does not support keras tensorflow. I have tried installing. But does not work.\nTherefore, i used google colabs and exported the model. \nI would like to know, how i can use the exported model in pycharm\nEdit : I just now installed tensorflow on my machine\nThanks in Advance","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":1484,"Q_Id":60482956,"Users Score":0,"Answer":"You still need keras and tensorflow to use the model.","Q_Score":2,"Tags":"python,tensorflow,keras,pycharm,google-colaboratory","A_Id":60483561,"CreationDate":"2020-03-02T05:24:00.000","Title":"How to use an exported model from google colab in Pycharm","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have build a real time face detection using OPENCV in python now i am expanding my project to fyp and making a iot based smart home automation using AI.I am implementing a door lock as a initial state which will be opened if it detect a face which will be in dataset.\nI don't want it to detect or opened if someone show a picture from mobile of same person which is a security concern\nplease Help.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":49,"Q_Id":60485783,"Users Score":1,"Answer":"An idea to improve security is asking people to perform something like: \n\nblink one or both eyes\nopen mouth\nturn left or right... \n\nProbably choose one or two of these randomly... This will improve security, but it is not really safe. It may be useful to overcome some accessibility issues.\nSome other ideas I've read eslewhere:\n\ncheck background of the image (if the camera is fixed) \nuse infrared camera to detect heat patterns\nuse two cameras to get a stereoscopic image","Q_Score":1,"Tags":"python,opencv,security,iot","A_Id":60490783,"CreationDate":"2020-03-02T09:23:00.000","Title":"How to overcome face detection security issues so it cannot detect a face if someone shows a picture?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am quite new to Tensor Flow \/ Edge TPU usage.\nWhile I mange to run an image classification with the classify_image.py script \nit has a very poor performance on the Edge TPU USB module because it always loads the model and kind of reboots the device (you see the Win10 device manager reinstalling it at every run of the script).\nIs there any way to run a python script that classifies an image with the last loaded model in the USB dongle, avoiding the 3-5 seconds of device configuration time ?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":30,"Q_Id":60490009,"Users Score":0,"Answer":"Normally, you should load the model first and store it. Then when you use it for invoking, you just need to allocate tensor, then pass to it the input. You can keep your script in while loop waiting for your input (ie sending through websocket,... or loading a directory). But according to what I see, you will have to self load the image to the model,so there is really hard to self-allocate a fixed part of TPU to your model.","Q_Score":0,"Tags":"python,image,classification,tpu","A_Id":63877839,"CreationDate":"2020-03-02T13:37:00.000","Title":"Running classification inference on EDge TPU USB without reloading model every time","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a little big problem, we created a Jupyter Notebook on windows os, but when I try to run it on a linux server, the following line of code runs without errors: pandas.read_csv(\"file.csv\", encoding='utf-8'), but the NaN values are not replaced like in windows. Do you know any solution to this issue?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":252,"Q_Id":60492332,"Users Score":0,"Answer":"i find the solution on colab:\npandas.read_csv(\"file.csv\", delimiter='\\t', header=None, names=['colNamesHere'])\nthe solution was import like normali CSV file but in the method you need to add: delimiter='\\t'","Q_Score":0,"Tags":"python,pandas","A_Id":60530554,"CreationDate":"2020-03-02T15:48:00.000","Title":"Python Encoding CSV from Windows to linux","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working on a document classification problem using CNN\/LSTM and embeddings generated from universal sentence encoder. I have 10,000 records and each record has about 100~600 sentences. I save all the document matrices into one json file before I feed them into the neural network models. The overall json file is about 20GB which will take too much memory.\nI'm not sure if I should save documents in text format and convert them into sentence embeddings during the training process. What's the potential solution?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":106,"Q_Id":60493576,"Users Score":0,"Answer":"Providing the Solution in this section (even though it is present in Comments section), for the benefit of the Community.\nSaving the Embeddings in a Separate Pickle File has resolved the problem.","Q_Score":0,"Tags":"python,deep-learning,pytorch,tensorflow-hub","A_Id":60633021,"CreationDate":"2020-03-02T17:08:00.000","Title":"Handle large dense vectors generated from universal sentence encoder","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have an array as below.\nX1=np.array([[0,0],[0,0]])\nX1[:,0].shape gives me (2,).\nHow do I convert X1[:,0] to a shape of (2,1).","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":272,"Q_Id":60499238,"Users Score":0,"Answer":"thanks for asking. what you have is a two by two matrix, so turning one part of the array to a two dimensional array will cause an error. I think you should create a new array from the sub array and then reshape it. you can do it like this new_x = X[:,0]\nnew_x.reshape(2,1). I hope this works","Q_Score":0,"Tags":"python-3.x,numpy-ndarray","A_Id":60499587,"CreationDate":"2020-03-03T02:26:00.000","Title":"How to reshape an array of shape (m,) to (m,1)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am following a tutorial in keras but i am getting the error which i could not find the\ndocumentation online \n\nModuleNotFoundError: No module named 'data_engine'\n\nWhat is the problem here does that mean this library is not exist or what?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":502,"Q_Id":60501538,"Users Score":0,"Answer":"It means you didn't include the module named 'data_engine', you need to include it at the header of your python script.","Q_Score":0,"Tags":"python,python-3.x,tensorflow,keras,module","A_Id":60501613,"CreationDate":"2020-03-03T06:48:00.000","Title":"ModuleNotFoundError: No module named 'data_engine'","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I encountered an error when I was importing the module pyttsx. Does anyone have an idea how we can solve this. I have turned on virtuavenv and have pyttsx in my pip, i checked that with pip freeze\nthe error is: Error: No module found","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":32,"Q_Id":60501993,"Users Score":0,"Answer":"You have to install that module firstly and then you can import it successfully.\nTry pip install pyttsx\nNote: before running the above command check that the module name is correct or not? Hopefully this will work for you.","Q_Score":1,"Tags":"python","A_Id":60502406,"CreationDate":"2020-03-03T07:22:00.000","Title":"Why is there an error when I tried to import pyttsx","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've seen 2 ways of installing OpenCV (there might be more ways which I don't know): \n\nInstalling from the source\nInstalling with pip: pip install opencv-python\n\nMy question is, why we need to install OpenCV from the source while we can simply install it using pip? Since people are using both of them, both must be useful. If so, there are any conditions for selecting one of them?","AnswerCount":2,"Available Count":2,"Score":0.2913126125,"is_accepted":false,"ViewCount":1253,"Q_Id":60503042,"Users Score":3,"Answer":"I will list out the differences between both\n1.\nInstallation using pip\nInstallation is done at the default location where all the python packages resides.\nInstallation from Source\nInstallation location is provided by the developer.\n2.\nInstallation using pip\nIn terms of performance, the packages installed might run slower because of the hidden conflicts between features.\nInstallation from Source\nThe developer can select the optimization flags during the compilation of packages which are responsible for the fast performance of library.\n3.\nInstallation using pip\nThe developers can neither add nor remove features provided in the installation done by pip.\nInstallation from Source\nThe developer has all the rights to add or remove the features during the installation of library.\n4.\nInstallation using pip\nThe package manager will do the work on behalf of developer. Package Manager is also responsible for taking care of library updation.\nInstallation from Source\nThe developers are responsible for feature selection and updation of library. They must be aware of new package updates, latest security patches etc, to keep themselves updated about the library.\nHope this helps you!","Q_Score":0,"Tags":"python,opencv,deep-learning,computer-vision","A_Id":60503293,"CreationDate":"2020-03-03T08:32:00.000","Title":"Install OpenCV from source or via Pip?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've seen 2 ways of installing OpenCV (there might be more ways which I don't know): \n\nInstalling from the source\nInstalling with pip: pip install opencv-python\n\nMy question is, why we need to install OpenCV from the source while we can simply install it using pip? Since people are using both of them, both must be useful. If so, there are any conditions for selecting one of them?","AnswerCount":2,"Available Count":2,"Score":0.0996679946,"is_accepted":false,"ViewCount":1253,"Q_Id":60503042,"Users Score":1,"Answer":"OpenCV is always under development, and the thing is some parts of the library is not going to published, due to compatibility and copyright issues, but if you use the source then you can have all the capabilities that you need. SURF & SIFT are examples of this problem.","Q_Score":0,"Tags":"python,opencv,deep-learning,computer-vision","A_Id":60504817,"CreationDate":"2020-03-03T08:32:00.000","Title":"Install OpenCV from source or via Pip?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"When I import Tensorflow, Python crashes with the following output: \n\nC:\\Anaconda\\lib\\site-packages\\tensorflow\\python\\framework\\dtypes.py:516:\n FutureWarning: Passing (type, 1) or '1type' as a synonym of type is\n deprecated; in a future version of numpy, it will be understood as\n (type, (1,)) \/ '(1,)type'. _np_qint8 = np.dtype([(\"qint8\", np.int8,\n 1)])\n C:\\Anaconda\\lib\\site-packages\\tensorflow\\python\\framework\\dtypes.py:517:\n FutureWarning: Passing (type, 1) or '1type' as a synonym of type is\n deprecated; in a future version of numpy, it will be understood as\n (type, (1,)) \/ '(1,)type'. _np_quint8 = np.dtype([(\"quint8\",\n np.uint8, 1)])\n C:\\Anaconda\\lib\\site-packages\\tensorflow\\python\\framework\\dtypes.py:518:\n FutureWarning: Passing (type, 1) or '1type' as a synonym of type is\n deprecated; in a future version of numpy, it will be understood as\n (type, (1,)) \/ '(1,)type'. _np_qint16 = np.dtype([(\"qint16\",\n np.int16, 1)])\n C:\\Anaconda\\lib\\site-packages\\tensorflow\\python\\framework\\dtypes.py:519:\n FutureWarning: Passing (type, 1) or '1type' as a synonym of type is\n deprecated; in a future version of numpy, it will be understood as\n (type, (1,)) \/ '(1,)type'. _np_quint16 = np.dtype([(\"quint16\",\n np.uint16, 1)])\n C:\\Anaconda\\lib\\site-packages\\tensorflow\\python\\framework\\dtypes.py:520:\n FutureWarning: Passing (type, 1) or '1type' as a synonym of type is\n deprecated; in a future version of numpy, it will be understood as\n (type, (1,)) \/ '(1,)type'. _np_qint32 = np.dtype([(\"qint32\",\n np.int32, 1)])\n C:\\Anaconda\\lib\\site-packages\\tensorflow\\python\\framework\\dtypes.py:525:\n FutureWarning: Passing (type, 1) or '1type' as a synonym of type is\n deprecated; in a future version of numpy, it will be understood as\n (type, (1,)) \/ '(1,)type'. np_resource = np.dtype([(\"resource\",\n np.ubyte, 1)])\n\nCan anyone help me ?","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":238,"Q_Id":60511386,"Users Score":0,"Answer":"i solved my problem : \ndon't try uptade , uninstall tensorflow (i tried everything)\ndelete (if u use anaconda ) anaconda and install again , mark \"add Python to my PATH\" during installation.\nhave a nice day.","Q_Score":0,"Tags":"python,tensorflow,machine-learning,jupyter-notebook","A_Id":60527516,"CreationDate":"2020-03-03T16:12:00.000","Title":"Python crashed when I try to import Tensorflow","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"When I import Tensorflow, Python crashes with the following output: \n\nC:\\Anaconda\\lib\\site-packages\\tensorflow\\python\\framework\\dtypes.py:516:\n FutureWarning: Passing (type, 1) or '1type' as a synonym of type is\n deprecated; in a future version of numpy, it will be understood as\n (type, (1,)) \/ '(1,)type'. _np_qint8 = np.dtype([(\"qint8\", np.int8,\n 1)])\n C:\\Anaconda\\lib\\site-packages\\tensorflow\\python\\framework\\dtypes.py:517:\n FutureWarning: Passing (type, 1) or '1type' as a synonym of type is\n deprecated; in a future version of numpy, it will be understood as\n (type, (1,)) \/ '(1,)type'. _np_quint8 = np.dtype([(\"quint8\",\n np.uint8, 1)])\n C:\\Anaconda\\lib\\site-packages\\tensorflow\\python\\framework\\dtypes.py:518:\n FutureWarning: Passing (type, 1) or '1type' as a synonym of type is\n deprecated; in a future version of numpy, it will be understood as\n (type, (1,)) \/ '(1,)type'. _np_qint16 = np.dtype([(\"qint16\",\n np.int16, 1)])\n C:\\Anaconda\\lib\\site-packages\\tensorflow\\python\\framework\\dtypes.py:519:\n FutureWarning: Passing (type, 1) or '1type' as a synonym of type is\n deprecated; in a future version of numpy, it will be understood as\n (type, (1,)) \/ '(1,)type'. _np_quint16 = np.dtype([(\"quint16\",\n np.uint16, 1)])\n C:\\Anaconda\\lib\\site-packages\\tensorflow\\python\\framework\\dtypes.py:520:\n FutureWarning: Passing (type, 1) or '1type' as a synonym of type is\n deprecated; in a future version of numpy, it will be understood as\n (type, (1,)) \/ '(1,)type'. _np_qint32 = np.dtype([(\"qint32\",\n np.int32, 1)])\n C:\\Anaconda\\lib\\site-packages\\tensorflow\\python\\framework\\dtypes.py:525:\n FutureWarning: Passing (type, 1) or '1type' as a synonym of type is\n deprecated; in a future version of numpy, it will be understood as\n (type, (1,)) \/ '(1,)type'. np_resource = np.dtype([(\"resource\",\n np.ubyte, 1)])\n\nCan anyone help me ?","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":238,"Q_Id":60511386,"Users Score":0,"Answer":"FutureWarning= a warning about a future (not currently existing) version of numpy. As tensorflow will definitely address this warning when numpy updates, you can ignore this. It's only a warning, I also get this warning, you can ignore it.","Q_Score":0,"Tags":"python,tensorflow,machine-learning,jupyter-notebook","A_Id":60511446,"CreationDate":"2020-03-03T16:12:00.000","Title":"Python crashed when I try to import Tensorflow","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to get some specific values given a dataframe using pandas and numpy.\nMy process right now is as it follows:\n\nIn[1]: df = pd.read_csv(file)\nIn[2]: a = df[df.columns[1]].values\n\nRight now a has the following shape:\n\nIn[3]: a.shape\nOut[4]: (8640, 1)\n\nWhen I filter it out to get the values that match a given condition I don't get the same shape in the axis 1:\n\nIn[5]: b = a[a>100]\nIn[6]: b.shape\nOut[7]: (3834,)\n\nRight now I'm reshaping the new arrays everytime I filter them, however this is making my code look really messy and uncomfortable: \n\nIn[8]: (b.reshape(b.size,1)).shape\nOut[9]: (3834, 1)\n\nI really need it to have the shape (x, 1) in order to use some other functions, so is it any way of getting that shape everytime I filter out the values without having to reshape it constantly?\nEDIT:\nThe main reason I need to do this reshaping is that I need to get the minimum value in every row for two arrays with the same number of rows. What I use is np.min and np.concatenate.\nFor example:\nav is the mean of 5 different columns in my dataframe:\n\nav = np.mean(myColumns,axis=1)\n\nWhich has shape (8640, )\nmed is the median for the same columns:\n\nmed = np.median(myColumns,axis=1)\n\nAnd when I try to get the minimum values I have the next error:\n\nnp.min(np.concatenate((av,med),axis=1),axis=1) Traceback (most recent\n call last):\nFile \"\", line 1, in \n np.min(np.concatenate((av,med),axis=1),axis=1)\nAxisError: axis 1 is out of bounds for array of dimension 1\n\nHowever, if I reshape av and med it works fine:\n\nnp.min(np.concatenate((av.reshape(av.size,1),med.reshape(av.size,1)),axis=1),axis=1)\n Out[232]: array([0., 0., 0., ..., 0., 0., 0.])","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":385,"Q_Id":60526861,"Users Score":0,"Answer":"you can use np.take(a, np.where(a>100)[0], axis=0) for keeping the same shape as original","Q_Score":0,"Tags":"python,pandas,numpy","A_Id":60527161,"CreationDate":"2020-03-04T13:09:00.000","Title":"Filtering data in arrays and keeping the same shape in axis 1","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to implement Classification algorithm for Iris Dataset (Downloaded from Kaggle). In the Species column the classes (Iris-setosa, Iris-versicolor , Iris-virginica) are in sorted order. How can I stratify the train and test data using Scikit-Learn?","AnswerCount":3,"Available Count":1,"Score":-0.0665680765,"is_accepted":false,"ViewCount":1171,"Q_Id":60530673,"Users Score":-1,"Answer":"use sklearn.model_selection.train_test_split and play around with Shuffle parameter.\nshuffle: boolean, optional (default=True)\nWhether or not to shuffle the data before splitting. If shuffle=False then stratify must be None.","Q_Score":1,"Tags":"python,pandas,machine-learning,scikit-learn,multiclass-classification","A_Id":60530952,"CreationDate":"2020-03-04T16:32:00.000","Title":"How to stratify the training and testing data in Scikit-Learn?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have trained my CNN in Tensorflow using MNIST data set; when I tested it, it worked very well using the test data. Even, to prove my model in a better way, I made another set taking images from train and test set randomly. All the images that I took from those set, at the same time, I deleted and I didn't give them to my model. It worked very well too, but with a dowloaded image from Google, it doesn't classify well, so my question is: should I have to apply any filter to that image before I give it to the prediction part? \nI resized the image and converted it to gray scale before.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":32,"Q_Id":60532922,"Users Score":0,"Answer":"MNIST is an easy dataset. Your model (CNN) structure may do quite well for MNIST, but there is no guarantee that it does well for more complex images too. You can add some more layers and check different activation functions (like Relu, Elu, etc.). Normalizing your image pixel values for small values like between -1 and 1 may help too.","Q_Score":0,"Tags":"python,tensorflow","A_Id":60533907,"CreationDate":"2020-03-04T18:55:00.000","Title":"How do I have to process an image to test it in a CNN?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I had a small question, I have 3 of the same dataset, but one has been filtered assuming 10% outlier fraction, then 15% then 20%. I need to compare the mean squared error for each. I was thinking of building the same keras model 3 times in the same script, and run each individiually. I wanted to do so because I wanted to produce a graph at the end with epochs number on the x-axis, and the mse values of each dataset on y-axis, all in the same figure. is that possible?\nThank you","AnswerCount":1,"Available Count":1,"Score":0.537049567,"is_accepted":false,"ViewCount":31,"Q_Id":60538166,"Users Score":3,"Answer":"Yes, this is absolutely possible, just name your models accordingly i.e. instead of model.fit() use model_1.fit() for dataset 1, model_2.fit() for dataset 2 etc","Q_Score":0,"Tags":"python,keras","A_Id":60538314,"CreationDate":"2020-03-05T04:21:00.000","Title":"Can i build three keras models in same script?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm training an LSTM model on GPU using Tensorflow Keras. Before training starts when calling model.fit() it takes about 30 minutes to start training process. I think in this period its preparing data using one core of CPU. Am I correct? and if yes how can I parallelize this data preparation process, using multiple cores?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":140,"Q_Id":60539413,"Users Score":3,"Answer":"If you use tf.data.Dataset() for preparing your data, you can exploit some parameters while preparing the dataset.\n\nFor example, in your .map() function, set the num_parallel_calls parameter to num_parallel_calls=tf.data.experimental.AUTOTUNE; in this way it will allow your program to automatically choose the number of CPU cores for the dataset preparation.\nThe speed can also be improved if you use the .batch().shuffle()\nin this order, rather than shuffle().batch() in this order. In the first situation, you take a batch of your dataset and shuffle the elements inside it; in the second case, you batch() on your dataset after the entire dataset is shuffled. One can easily see that shuffling an enormous dataset would lead to much more time spent rather than batching and shuffling in this order. \nLet us see another case(related to the actual training process)(not your case as the dataset preparation is\nvery time-consuming in your situation): the prefetch() operation.\nIn this case, the GPU is not idling while waiting for the CPU to\nfetch another batch of data. Practically, when the backpropagation\nhas finished updating the weights after a batch, the GPU immediately\nconsumes another batch of data. For simplicity purposes, also set its value to tf.data.experimental.AUTOTUNE.","Q_Score":0,"Tags":"python-3.x,tensorflow,keras,training-data,tensorflow2.x","A_Id":60539743,"CreationDate":"2020-03-05T06:32:00.000","Title":"Parallelize data preparation with tensorflow and keras","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to use RUN conda install -c conda-forge tesseract in my dockerfile to install the tesseract-ocr package. All my other conda install packages have worked fine using that method. I've looked at the GIT for tesseractocr https:\/\/github.com\/sirfz\/tesserocr\/blob\/master\/Dockerfile and it seems that the references they have in their docker example are out of date since the links to some of the dependencies return 'not found'. \nMy base image is continuumio\/anaconda3\nHow can I get this library to install in this docker container?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":334,"Q_Id":60547269,"Users Score":0,"Answer":"Just wanted to close this out. I used conda install -y -c conda-forge tesseract\nwith the -y being the operative function that allowed the process to complete.","Q_Score":0,"Tags":"python,docker,tesseract,anaconda3","A_Id":60554895,"CreationDate":"2020-03-05T14:10:00.000","Title":"I can't Conda install Tesseract in a continuumio\/anaconda3 Docker container","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":1,"Web Development":0},{"Question":"Whats the difference between two LSTM models A and B that are trained on same data, but the batches are shuffled randomly for each epoch, that A has 14 steps per epoch and B has 132 steps per epoch?\nWhich one will perform better in validation?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":1345,"Q_Id":60553285,"Users Score":0,"Answer":"An epoch consists of going through all your training samples once. And one step\/iteration refers to training over a single minibatch. So if you have 1,000,000 training samples and use a batch size of 100, one epoch will be equivalent to 10,000 steps, with 100 samples per step.\nA high-level neural network framework may let you set either the number of epochs or total number of training steps. But you can't set them both since one directly determines the value of the other.\nEffect of Batch Size on Model Behavior: Small batch results generally in rapid learning but a volatile learning process with higher variance. Larger batch sizes slow down the learning process but the final stages result in a convergence to a more stable model exemplified by lower variance.","Q_Score":1,"Tags":"python,tensorflow,machine-learning,keras,deep-learning","A_Id":60565279,"CreationDate":"2020-03-05T20:15:00.000","Title":"Importance of number of steps in an epoch for LSTM model training in Keras","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to calculate a simple linear regression where I need to force a particular value for one point. Namely, I have x and y arrays, and I want my regression f(x) to force f(x[-1]) == y[-1] - that is, the prediction over the last element of x should be equal to the last element of y.\nIs there a way to do it using Python and scikit-learn?","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":1297,"Q_Id":60553680,"Users Score":2,"Answer":"Here's a slightly roundabout trick that will do it.\nTry re-centering your data, i.e. subtract x[-1], y[-1] from all datapoints so that x[-1], y[-1] is now the origin.\nNow fit your data using sklearn.linear_model.LinearRegression with fit_intercept set to False. This way, the data is fit so that the line is forced to pass through the origin. Because we've re-centered the data, the origin corresponds to x[-1], y[-1].\nWhen you use the model to make predictions, subtract x[-1] from any datapoint for which you are making a prediction, then add y[-1] to the resulting prediction, and this will give you the same results as forcing your model to pass through x[-1], y[-1].\nThis is a little roundabout but it's the simplest way that occurs to me to do it using the sklearn linear regression function (without writing your own).","Q_Score":0,"Tags":"python,scikit-learn,conditional-statements,regression","A_Id":60553912,"CreationDate":"2020-03-05T20:45:00.000","Title":"Linear regression forcing one specific value","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using Word2vec model to extract similar words, but I want to know if it is possible to get words while using unseen words for input. \nFor example, I have a model trained with a corpus [melon, vehicle, giraffe, apple, frog, banana]. \"orange\" is unseen word in this corpus, but when I put it as input, I want [melon, apple, banana] for result. \nIs this a possible situation?","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":208,"Q_Id":60556328,"Users Score":2,"Answer":"The original word2vec algorithm can offer nothing for words that weren't in its training data.\nFacebook's 'FastText' descendent of the word2vec algorithm can offer better-than-random vectors for unseen words \u2013 but it builds such vectors from word fragments (character n-gram vectors), so it does best where shared word roots exist, or where the out-of-vocabulary word is just a typo of a trained word.\nThat is, it won't help in your example, if no other words morphologically similar to 'orange' (like 'orangey', 'orangade', 'orangish', etc) were present. \nThe only way to learn or guess a vector for 'orange' is to have some training examples with it or related words. (If all else failed, you could scrape some examples from other large corpora or the web to mix with your other training data.)","Q_Score":0,"Tags":"python,word2vec","A_Id":60556657,"CreationDate":"2020-03-06T01:25:00.000","Title":"While using Word2vec, how can I get a result from unseen words corpus?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to solve a problem with SVM and my X_train features are 2D with shapes of (256,1).\nIs there any way to train a SVM model on a dataset with such features?\nThese features are histograms of gray-scale images.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":125,"Q_Id":60561895,"Users Score":1,"Answer":"Yes, its possible to train a SVM with histograms of gray-scale images but you need to transform them into representations with numerical values.\nI would suggest to reshape the 2D array into a 1D array\/list with 256 entries, so that the SVM can use it as a feature vector with 256 different numerical features, each representing a value of your histogram.","Q_Score":0,"Tags":"python,machine-learning,scikit-learn,histogram,svm","A_Id":60565738,"CreationDate":"2020-03-06T10:13:00.000","Title":"Does Support Vector Machine takes vectors as features?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a problem with the Spyder software of Python(version 4.0.1) regarding the running kernels in the IPython Console. Accordingly, I have tried many ways to resolve the issue like running some commands in Anaconda prompt or set the settings to the default mode. I even updated the version of my anaconda and the spyder. Nevertheless, nothing has been changed and the issue still exists. \nThis is the error I am receiving:\n\nTraceback (most recent call last): File\n \"C:\\ProgramData\\Anaconda3\\lib\\runpy.py\", line 193, in\n _run_module_as_main \"main\", mod_spec) File \"C:\\ProgramData\\Anaconda3\\lib\\runpy.py\", line 85, in _run_code\n exec(code, run_globals) File\n \"C:\\ProgramData\\Anaconda3\\lib\\site\u2011packages\\spyder_kernels\\console__main__.py\",\n line 11, in start.main() File\n \"C:\\ProgramData\\Anaconda3\\lib\\site\u2011packages\\spyder_kernels\\console\\start.py\",\n line 287, in main import_spydercustomize() File\n \"C:\\ProgramData\\Anaconda3\\lib\\site\u2011packages\\spyder_kernels\\console\\start.py\",\n line 39, in import_spydercustomize import spydercustomize File\n \"C:\\ProgramData\\Anaconda3\\lib\\site\u2011packages\\spyder_kernels\\customize\\spydercustomize.py\",\n line 24, in from IPython.core.getipython import get_ipython File\n \"C:\\ProgramData\\Anaconda3\\lib\\site\u2011packages\\IPython__init__.py\", line\n 56, in from .terminal.embed import embed File\n \"C:\\ProgramData\\Anaconda3\\lib\\site\u2011packages\\IPython\\terminal\\embed.py\",\n line 14, in from IPython.core.magic import Magics, magics_class,\n line_magic File\n \"C:\\ProgramData\\Anaconda3\\lib\\site\u2011packages\\IPython\\core\\magic.py\",\n line 20, in from . import oinspect File\n \"C:\\ProgramData\\Anaconda3\\lib\\site\u2011packages\\IPython\\core\\oinspect.py\",\n line 30, in from IPython.lib.pretty import pretty File\n \"C:\\ProgramData\\Anaconda3\\lib\\site\u2011packages\\IPython\\lib\\pretty.py\",\n line 82, in import datetime File \"C:\\Users\\mahkam\\datetime.py\", line\n 4 ^ SyntaxError: EOF while scanning triple\u2011quoted string literal","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":1231,"Q_Id":60568931,"Users Score":0,"Answer":"(Spyder maintainer here) You need to rename or remove this file\nC:\\Users\\mahkam\\datetime.py\nThat's because that file is using the same name of Python internal module and that confuses other modules that depend on it.","Q_Score":0,"Tags":"python,ipython,spyder","A_Id":60570084,"CreationDate":"2020-03-06T17:28:00.000","Title":"Problem with running Kernel in IPython console","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"Recently I was trying to test my model which i already trained. Initially I was using Google colab notebook to write code because of it's interactive features, once I was done writing code and I was getting satisfactory results, it took around 2.5 hr to give final output. After that what I wanted was to transfer the notebook code to .py script, I did that with little bit of modification, saved it in gdrive, and then used command !python test.py. now it took me more than 4.5 hr to get the final output, can any one explain why does colab take so much time when trying to run the python script from gdrive while compared to the same code as used in notebook","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":270,"Q_Id":60572161,"Users Score":0,"Answer":"Well it can be because of the fact that colab is retrieving the data from gdrive and then might be again writing in gdrive which will of ofcourse take time i guess","Q_Score":0,"Tags":"python-3.x,google-colaboratory","A_Id":61006480,"CreationDate":"2020-03-06T21:59:00.000","Title":"Running python script in colab very slow as compared to same code run on directly colab in notebook","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"For instance,\nI have 1000 rows and 10 columns,\nbatch size is 25,\nsteps per epoch =1000\/25 ==> 40\nepoch = 10\nEpoch 1:\n|----------------------|40 iterations # so in this only 40 samples are propagated right? or wrong?\nso , 10* 40 = 400 so 400 values are only propagated ?","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":246,"Q_Id":60576323,"Users Score":0,"Answer":"With a batch size of 25 and steps per epoch=40 you will go through 1000 samples. It works like this. For EACH step 25 samples are provided. So after 40 steps you have gone through 25 X 40 samples. If you run for 10 epochs the total training samples processed will be 10 X 1000=10,000. I haven't tried it but I think if you set the steps per epoch say to 50 it will run 25 X 50 samples. I get this from the Keras documentation from model.fit.\n\nsteps_per_epoch: Integer or None. Total number of steps (batches of samples) before declaring one epoch finished and starting the next epoch. When training with input tensors such as TensorFlow data tensors, the default None is equal to the number of samples in your dataset divided by the batch size, or 1 if that cannot be determined.\n\nSo I believe this leads to the definition of an epoch as being completed when samples of batch_size X steps per epoch is completed. The generator will just keep cycling as more batches are called for.","Q_Score":0,"Tags":"python,tensorflow,keras,deep-learning,neural-network","A_Id":60579866,"CreationDate":"2020-03-07T09:53:00.000","Title":"what is really happening in the single epoch forward or backward pass or both?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"For instance,\nI have 1000 rows and 10 columns,\nbatch size is 25,\nsteps per epoch =1000\/25 ==> 40\nepoch = 10\nEpoch 1:\n|----------------------|40 iterations # so in this only 40 samples are propagated right? or wrong?\nso , 10* 40 = 400 so 400 values are only propagated ?","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":246,"Q_Id":60576323,"Users Score":0,"Answer":"25 steps_per_epoch means that there are 25 iterations to be completed during your epoch.\nOne iteration implies both a forward and a backward pass.\nIf you have 1000 elements, a batch_size of 10, you have 100 steps_per_epoch(1000\/10),i.e. 100 iterations.\nThis means that after each batch of 10 elements, a forward and a backward pass are performed.","Q_Score":0,"Tags":"python,tensorflow,keras,deep-learning,neural-network","A_Id":60576359,"CreationDate":"2020-03-07T09:53:00.000","Title":"what is really happening in the single epoch forward or backward pass or both?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a large input file of numerical data (22000) columns and at the moment when I use\ndf = pd.read_csv(path_to_file), it uses the first line of numbers as the column values. \nIs there any way to replace the column value with random variables or load the data in a way that the first line is not used as a column name?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":112,"Q_Id":60577051,"Users Score":0,"Answer":"Use pd.read_csv(\"path_to_file\", header=0).\nIf you also want to assign names to the columns you can pass a list in the names parameter of pd.read_csv.","Q_Score":1,"Tags":"python,python-3.x,pandas,dataframe","A_Id":60577094,"CreationDate":"2020-03-07T11:28:00.000","Title":"Replace column values in large Pandas dataframe","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Currently, I have a class which stores a dictionary of Card elements, each of which is unique. The class can also generate these cards and append them to the dictionary or remove a card from a dictionary. However, I am not sure how to best allow for this action through a callback function since the ID for a card doesn't exist until the card is made, and the functionality isn't directly within the Dash framework since a dictionary object acts as an intermediary where the objects are stored.\nBasically, I am wondering what the best way to dynamically create and destroy objects with a callback is?\nThank you!","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":433,"Q_Id":60583933,"Users Score":0,"Answer":"Just on the basis of your question, I have some immediate suggestions (since there is no working code that you have posted). \n1. Generate all card elements by default. They can be generated, but not 'displayed'\n2. Add your callbacks to toggle the display\/rendering of the cards dynamically based on the use case. That way you will have card element ids to play around with in the callbacks. \nHope this helps.","Q_Score":0,"Tags":"python,flask,callback,dashboard,plotly-dash","A_Id":60595465,"CreationDate":"2020-03-08T02:12:00.000","Title":"What is the best way for allowing for dynamic object creation and removal in a Plotly Dash dashboard?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a dataset with an upper numerical limit of 50, none of the samples go above this figure or below zero. \nAfter running a deepAREstimator in GluonTS I get predictions way above 50 and also in the minuses. How can\/could I fix this?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":70,"Q_Id":60590137,"Users Score":0,"Answer":"I would probably try to train the model slightly longer, and if possible on a larger dataset.\nTo prevent getting negative values just try a different distribution:\ndistr_output=gluonts.distribution.NegativeBinomial\nBut other than that its hard to tell without additional information what the problem is.","Q_Score":0,"Tags":"python,tensorflow,mxnet,gluon,probability-distribution","A_Id":61350714,"CreationDate":"2020-03-08T17:25:00.000","Title":"Probabilistic time series returning results above thresholds (GluonTS)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to read txt file containing the table with pandas.read_table by executing the following code.\nI added import pandas as pd and the problematic code is pstttable=read_table(\"pstttable.txt\").\nObviously, the location of the txt file is correct and the same code works when working with Jupyter notebook from Windows.\nHowever, I want to compile the code with .py file edited by vi editor from Linux terminal and the following error will occur.\nFile \"Global_Repeater_Search.py\", line 22\n pstttable=pd.read_table(\"\/Users\/sgtsnu02\/2019-2020_Intern\/EQcorrscan\/pstttable.txt\")\n ^\nSyntaxError: invalid syntax\nI have no idea why this kind of error occurs. Is this problem inherent to pandas when working in Linux terminal?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":103,"Q_Id":60594897,"Users Score":0,"Answer":"This was really stupid question.\nI forgot to close parentheses of the line before pstttable=pd.read_table(\"\/Users\/sgtsnu02\/2019-2020_Intern\/EQcorrscan\/pstttable.txt\").\nThis caused SyntaxError: invalid syntax.\nNothing is wrong with vi nor pandas.read_table.","Q_Score":0,"Tags":"python,pandas,jupyter-notebook,text-files,vi","A_Id":60666086,"CreationDate":"2020-03-09T04:54:00.000","Title":"pandas.read_table working in Jupyter notebook but would not work in vi editor","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I applied batch normalization technique to increase the accuracy of my cnn model.The accuracy of model without batch Normalization was only 46 % but after applying batch normalization it crossed 83% but a here arisen a bif overfitting problem that the model was giving validation Accuracy only 15%. Also please tell me how to decide no of filters strides in convolution layer and no of units in dence layer","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":50,"Q_Id":60595671,"Users Score":0,"Answer":"Batch normalization has been shown to help in many cases but is not always optimal. I found that it depends where it resides in your model architecture and what you are trying to achieve. I have done a lot with different GAN CNNs and found that often BN is not needed and can even degrade performance. It's purpose is to help the model generalize faster but sometimes it increases training times. If I am trying to replicate images, I skip BN entirely. I don't understand what you mean with regards to the accuracy. Do you mean it achieved 83% accuracy with the training data but dropped to 15% accuracy on the validation data? What was the validation accuracy without the BN? In general, the validation accuracy is the more important metric. If you have a high training accuracy and a low validation accuracy, you are indeed overfitting. If you have several convolution layers, you may want to apply BN after each. If you still over-fit, try increasing your strides and kernel size. If that doesn't work you might need to look at the data again and make sure you have enough and that it is somewhat diverse. Assuming you are working with image data, are you creating samples where you rotate your images, crop them, etc. Consider synthetic data to augment your real data to help combat overfiiting.","Q_Score":1,"Tags":"python-3.x,deep-learning,conv-neural-network","A_Id":60716359,"CreationDate":"2020-03-09T06:36:00.000","Title":"Overfitting problem in convolutional neural Network and deciding the parameters of convolution and dence layer","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"In my company, I have got task to create dash board using python whose complete look and feel should be like qlicksense. I am fresher in data science field I don't know how to do this. I did lots of R & D and plotly and dash is the best option as much according to R & D on internet dash table is also a good option but I am not able to create the things what it should look like. If any one know how to start plz help me ..","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":247,"Q_Id":60597337,"Users Score":0,"Answer":"you can use django or other web framework to develop the solution, \nkeep in mind that you probably will need to handle lots of front end stuff like builiding the UI of the system, \nFlask also is very lightweight option, but it needs lots of customization.\nDjango comes with pretty much everything you might need out of the box.","Q_Score":0,"Tags":"python,python-requests,python-3.6,shinydashboard,flexdashboard","A_Id":60649474,"CreationDate":"2020-03-09T09:01:00.000","Title":"How to create Dashboard using Python or R","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Suppose I have created a speech to text model 'A' which recognizes 20 speech commands and model 'B' which recognizes other 20 commands .Is there a way so that i can join both models so that it recognizes total 40 words.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":164,"Q_Id":60598788,"Users Score":1,"Answer":"I think it depends on your model. If you are using a deep learning model like and LSTM or RNN, and depending on what libraries you use, it might be possible. Many people use pre-trained CNNs to then train their image recognition and generation models. I am not sure how you would join the weights of the two already trained models. Starting from scratch, and using Keras I would train one model, save the weights, load the weights into the other model (assuming they have the same architecture and parameters, and then train the second model on the other 20 words. Also, it might be worth looking into some of the distributed learning solutions out there. I only know of vendor with products (no open source that I have heard of) that offer products that centralize model weights and allow you train data on different data in different locations and then merge those weights centrally. For instance, different hospitals can share model training without sharing data, which is very beneficial when you think about privacy.","Q_Score":2,"Tags":"python,tensorflow,speech-recognition,conv-neural-network","A_Id":60716288,"CreationDate":"2020-03-09T10:37:00.000","Title":"Tensorflow joining two models","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a text file . I need to identify specific paragraph headings and if true i need to extract relevant tables and paragraph wrt that heading using python. can we do this by nlp or machine learning?. if so please help me out in gathering basics as i am new to this field.I was thinking of using a rule like:\nif (capitalized) and heading_length <50:\n return heading_text\nhow do i parse through the entire document and pick only the header names ? this is like automating human intervention of clicking document,scrolling to relevant subject and picking it up.\nplease help me out in this","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":467,"Q_Id":60605461,"Users Score":0,"Answer":"I agree with lorg. Although you could use NLP, but that might just complicate the problem. This problem could be an optimization problem if performance is a concern.","Q_Score":0,"Tags":"python,machine-learning,nlp,data-science,information-extraction","A_Id":60607335,"CreationDate":"2020-03-09T17:18:00.000","Title":"is there any function or module in nlp that would find a specific paragraph headings","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a text file . I need to identify specific paragraph headings and if true i need to extract relevant tables and paragraph wrt that heading using python. can we do this by nlp or machine learning?. if so please help me out in gathering basics as i am new to this field.I was thinking of using a rule like:\nif (capitalized) and heading_length <50:\n return heading_text\nhow do i parse through the entire document and pick only the header names ? this is like automating human intervention of clicking document,scrolling to relevant subject and picking it up.\nplease help me out in this","AnswerCount":2,"Available Count":2,"Score":0.0996679946,"is_accepted":false,"ViewCount":467,"Q_Id":60605461,"Users Score":1,"Answer":"You probably don't need NLP or machine learning to detect these headings. Figure out the rule you actually want and if indeed it is such a simple rule as the one you wrote, a regexp will be sufficient. If your text is formatted (e.g. using HTML) it might be even simpler.\nIf however, you can't find a rule, and your text isn't really formatted consistently, your problem will be hard to solve.","Q_Score":0,"Tags":"python,machine-learning,nlp,data-science,information-extraction","A_Id":60606666,"CreationDate":"2020-03-09T17:18:00.000","Title":"is there any function or module in nlp that would find a specific paragraph headings","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to be sure that my model is not overfitting. I checked the overfitting using cross validation. Results of all folds are close.But at the same time I checked the train and test predictions. Test size is 0.25. And train and test predictions are so different. It shows that my model is overfitting. Which result should I believe? Cross validation or test\/train prediction.Is my model overfitting?\nNote:I used python. Sklearn for cross validation, train test split and modelling","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":187,"Q_Id":60606697,"Users Score":0,"Answer":"From the accuracies you've given, both methods say you have overfitting. Cross validation is just a more accurate way to test how well the model generalises, so don't compare folds, compare the average cross validation accuracy with the training accuracy, since these are very different you have overfitting","Q_Score":0,"Tags":"python,scikit-learn,data-science,cross-validation,training-data","A_Id":60607530,"CreationDate":"2020-03-09T18:53:00.000","Title":"Checking Overfitting","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I initialize a list of length n using df_list = [None] * n. Then I have a for loop where I fill each element of df_list with a dataframe. Then, when I concat all these dataframes together using df = pd.concat(df_list, axis=0) I end up with fewer rows than expected, and upon further inspection I find that some elements of df_list are None type while others are dataframes. This is strange to me because in my for loop, I print the type of each value before filling it into df_list and they are all dataframes of the desired shape and columns as well. \nWondering how, after running the loop, I can have None values in df_list when each value I filled in is a dataframe and not None. \nAny help here is appreciated - quite puzzled by this!","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":187,"Q_Id":60612985,"Users Score":1,"Answer":"Why do you even need to initialize the list with None values. Just create empty list and append your dataframes to it.","Q_Score":2,"Tags":"python,pandas,dataframe,concat,nonetype","A_Id":60613053,"CreationDate":"2020-03-10T07:16:00.000","Title":"Python list has none type elements even though filled with dataframe elements","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am struggling on a simple problem where i need to check whether customer location has effect on number of defects.\nDataset is like. Location has 50 values and categorical in nature and defects is continuous.\n\nlocation defects\na 20\nb 30\nc 40\nd 50\ne 60\nf 70\ng 80","AnswerCount":2,"Available Count":1,"Score":-0.1973753202,"is_accepted":false,"ViewCount":558,"Q_Id":60614236,"Users Score":-2,"Answer":"So you basically wanna calculate (ratio_for_location) = (number_of_defects_for_location) \/ (total_number_of_whatever_for_location) and check for outliers \/ find the function defect_ratio(location)?","Q_Score":1,"Tags":"python,anova","A_Id":60614285,"CreationDate":"2020-03-10T08:56:00.000","Title":"correlation between two variables(categorical and continuous) in python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Which unit of measurement has the accuracy, mean absolut error and mean squared error of the sklearn metrics? and are they used for regression problems? \nFor example i have a regressor.score(X_test,y_test)) of about 0.99469. So the tested Model is 0.99469 in comparison to the real data? or do you say percent of 99%? \nThe same with the MAE and MSE. \nThe other question is, i red about the confusion matrix for classification problems and the accuracy is the value calculated out of the confusion matrix. I use a multiple linear regression, so can i use these metrics for my regression?","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":752,"Q_Id":60627942,"Users Score":0,"Answer":"To answer your first question, the metric such as accuracy can't be used for regression problems. And yes, you are right. The accuracy is calculated using the confusion matrix, but since you have a regression problem, you can't get the confusion matrix as it is an output of the classification problem but you have a regression problem in place.\nMoreover, the right metrics for the regression problem are mean squared error, mean absolute error and the R squared value. By default the regressor.score(X_test,y_test)) function gives out the R squared value.\nTo make it easy, the closer the value is to 1 (0.99469 in your case), the better is your model. And it seems like your model is performing really well.","Q_Score":0,"Tags":"python,machine-learning,scikit-learn,metrics,confusion-matrix","A_Id":60629372,"CreationDate":"2020-03-11T01:03:00.000","Title":"sklearn metrics units of Measurement of accuracy, mean absolut error, mean squared error for regression problems?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to find out if there is an easy way or like a one line code to plot the basic statistics (like mean, std dev, min, max etc) of any dataframe in python using plotly or any such graphing library. Right now I made a few functions to manipulate the dataframe, to transform it into a desired form containing basic stats so I can plot it using cufflinks. And I get the basic stats of all columns in a dataframe, in one place.","AnswerCount":2,"Available Count":1,"Score":-0.0996679946,"is_accepted":false,"ViewCount":66,"Q_Id":60629052,"Users Score":-1,"Answer":"You should be able to use the .plot() method on a dataframe you're working with and be returned a collection of different types of graphs.","Q_Score":0,"Tags":"python,dataframe,plot,jupyter-notebook,plotly","A_Id":60629097,"CreationDate":"2020-03-11T03:54:00.000","Title":"Is there an easy\/shortcut way to obtain visualizations of basic stats of any dataframe in python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have image-like data. And I wont to perform Image cropping, squishing and zooming, on one or both axis. The problem is that the data is not in between 0-255, and normalizing it to 0-255, would mean loosing a lot of the information I want to preserve. So unfortunately I can\u2019t use PIL or cv2. Is there a easy way to do it with numpy or scipy?\nThanks for the help","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":82,"Q_Id":60636391,"Users Score":0,"Answer":"Check ImageChops function of Image Librart","Q_Score":0,"Tags":"python,image,numpy,scikit-learn,scipy","A_Id":60640599,"CreationDate":"2020-03-11T12:46:00.000","Title":"perform Image cropping on Image like data using Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"It works for the huber and log, however only the logarithm has a predict_proba? How it works? I used roc_auc_score.","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":105,"Q_Id":60649581,"Users Score":1,"Answer":"Grid Search CV has both the predict and the predict_proba functions.\nIf you consider a binary classification problem, predict will have the values of 0 or 1. While, Predict_proba will have the probability values of it being 0 or 1.\npredict_proba will have an array output like [0.23 0.77]","Q_Score":0,"Tags":"python-3.x,machine-learning,scikit-learn,gridsearchcv","A_Id":63290682,"CreationDate":"2020-03-12T07:44:00.000","Title":"GridSearchCV uses predict or predict_proba?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have checked five different methods for face detection.\n 1. Haar cascade \n 2. Dlib HOG \n 3. Python face_recognition module \n 4. DLib_CNN \n 5. OpenCV CNN \nAll these methods have some advantages and disadvantages and i found out that openCV_CNN works better out of these five algorithm. But for my application i need to detect faces from people on far distance and for this purpose even OpenCV_CNN is not working well (it detects faces of people closer to camera and not the people on far distance). Is there any other algorithm which detects faces of people on far distance?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":90,"Q_Id":60651983,"Users Score":1,"Answer":"One of the ways is to do instance segmentation in order to get all the classes in the environment including distant objects. \nOnce you get all the classes, you can draw a bounding box around the required far off face class, upsample it and send it to your face detection NN. suppose your image is of 54x54x3, it will be upsampled to 224x224x3 and sent to your trained NN.","Q_Score":0,"Tags":"python-3.x,machine-learning,deep-learning,computer-vision,data-science","A_Id":61311705,"CreationDate":"2020-03-12T10:20:00.000","Title":"Which face detection method suitable for detecting faces of people at a long distance?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am new to data science\/Machine Learning.\nI have to write a web crawler and extract features out of each blog. These features in the form of Tags tell about the industry, specific products, tools, and similar things like these.\nI have done part of scraping but now I am stuck with entities identification. \nI did Data processing (Tokenization, data cleaning, removing stop words\/punctuation, stemming\/lemmatization).\nfor now, what I have to do for feature extractions?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":19,"Q_Id":60653333,"Users Score":0,"Answer":"Ok so what you need to do is set up a pandas dataframe.\nIn the first column, you need to have the entire text of the website or blog, processes as you mentioned. In the following columns, you need to have one column for each tag you want to apply to the dataset, one-hot encoded.\nThen you will need to fill out the rows by labeling, by hand, several thousand of the website or blog posts using that one-hot encoding.\nWhen you are done, you can train your machine. Then any new article you put into it, the machine will output a probability for the tags belonging to that article. There are probably a lot of repositories on github with pretrained models you can use.","Q_Score":0,"Tags":"python,machine-learning,deep-learning,web-crawler,data-science","A_Id":60655309,"CreationDate":"2020-03-12T11:35:00.000","Title":"Features Extraction from News Blog","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I read a lot of tutorial about BPE but I am still confuse how it works.\nfor example.\nIn a tutorial online, they said the folowing : \nAlgorithm\nPrepare a large enough training data (i.e. corpus)\nDefine a desired subword vocabulary size\nSplit word to sequence of characters and appending suffix \u201c\u201d to end of\nword with word frequency. So the basic unit is character in this stage. For example, the frequency of \u201clow\u201d is 5, then we rephrase it to \u201cl o w \u201d: 5\n Generating a new subword according to the high frequency occurrence.\n Repeating step 4 until reaching subword vocabulary size which is defined in step 2 or the next highest frequency pair is 1.\nTaking \u201clow: 5\u201d, \u201clower: 2\u201d, \u201cnewest: 6\u201d and \u201cwidest: 3\u201d as an example, the highest frequency subword pair is e and s. It is because we get 6 count from newest and 3 count from widest. Then new subword (es) is formed and it will become a candidate in next iteration.\nIn the second iteration, the next high frequency subword pair is es (generated from previous iteration )and t. It is because we get 6count \nfrom newest and 3 count from widest.\nI do not understand why low is 5 and lower is 2:\ndoes this meand l , o, w , lo, ow + = 6 and then lower equal two but why is not e, r, er which gives three ?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":1056,"Q_Id":60659868,"Users Score":0,"Answer":"The numbers you are asking about are the frequencies of the words in the corpus. The word \"low\" was seen in the corpus 5 times and the word \"lower\" 2 times (they just assume this for the example).\nIn the first iteration we see that the character pair \"es\" is the most frequent one because it appears 6 times in the 6 occurrences of \"newest\" and 3 times in the 3 occurrences of the word \"widest\".\nIn the second iteration we have \"es\" as a unit in our vocabulary the same way we have single characters. Then we see that \"est\" is the most common character combination (\"newest\" and \"widest\").","Q_Score":4,"Tags":"python,scikit-learn,nlp,vectorization","A_Id":60804237,"CreationDate":"2020-03-12T18:21:00.000","Title":"How to understand byte pair encoding?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm working on simple machine learning problems and I trying to build a classifier that can differentiate between spam and non-spam SMS. I'm confused as to whether I need to generate the document-term matrix before splitting into test and train sets or should I generate the document-term matrix after splitting into test and train? \nI tried it both ways and found that the accuracy is slightly higher when the I split the data before generating the document-term matrix. But to me, this makes no sense. Shouldn't the accuracy be the same? Does the order of these operations make any difference?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":356,"Q_Id":60661508,"Users Score":2,"Answer":"Qualitatively, you don't need to do it either way. However, proper procedure requires that you keep your training and test data entirely separate. The overall concept is that the test data are not directly represented in the training; this helps reduce over-fitting. The test data (and later validation data) are samples that the trained model has never encountered during training.\nTherefore, the test data should not be included in your pre-processing -- the document-term matrix. This breaks the separation, in that the model has, in one respect, \"seen\" the test data during training.\nQuantitatively, you need to do the split first, because that matrix is to be used for training the model against only the training set. When you included the test data in the matrix, you obtained a matrix that is slightly inaccurate in representing the training data: it no longer properly represents the data you're actually training against. This is why your model isn't quite as good as the one that followed proper separation procedures.\nIt's a subtle difference, most of all because the training and test sets are supposed to be random samples of the same population of possible inputs. Random differences provide the small surprise you encountered.","Q_Score":2,"Tags":"python,machine-learning,nlp,data-science","A_Id":60662708,"CreationDate":"2020-03-12T20:33:00.000","Title":"Split into test and train set before or after generating document term matrix?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a data set of 1500 records with two classes which are imbalanced. Class 0 is 1300 records while Class 1 is 200 records, hence a ratio of ard 6.5:1.\nI built a random forest with this data set for classification. I know from past experience, if I use the whole data set, the recall is pretty low, which is probably due to the imbalanced class.\nSo I decided to undersample Class 0. My steps are as follows:\n\nRandomly split the data set into train & test set of ratio 7:3 (hence 1050 for training and 450 for test.)\nNow the train set has ~900 data of Class 0 ~100 for Class 1. I clustered ~900 data of Class 0, and undersample it (proportionally) to ~100 records.\n\nSo now train set ~100 Class 0 + ~100 Class 1 = ~200 records in total while the test set is 70 Class 0 + 380 Class 1 = 450 records in total.\nHere comes my questions:\n1) Are my steps valid? I split the train\/test first and then undersample the majority class of the train set.\n2) Now my train set (~200) < test set (450). Does it make sense?\n3) The performance is still not very good. Precision is 0.34, recall is 0.72 and the f1 score is 0.46. Is there any way to improve? Should I use CV?\nMany thanks for helping!","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":243,"Q_Id":60667970,"Users Score":0,"Answer":"1) Are my steps valid? I split the train\/test first and then\n undersample the majority class of the train set.\n\nYou should split train and test so the class balance is preserved in both. If in your whole dataset ratio is 6.5:1 it should be the same both in train and test. \nYes, you should split it before undersampling (no need to undersample test cases), just remember to monitor multiple metrics (e.g. f1 score, recall, precision were already mentioned and you should be fine with those) as you are training on different distribution than test.\n\n2) Now my train set (~200) < test set (450). Does it make sense?\n\nYes it does. You may also go for oversampling on training dataset (e.g. minority class is repeated at random to match the number of examples from majority). In this case you have to split before as well otherwise you may spoil your test set with training samples which is even more disastrous.\n\n3) The performance is still not very good. Precision is 0.34, recall is 0.72 and the f1 score is 0.46. Is there any way to improve? Should I use CV?\n\nIt depends on specific problem, what I would do:\n\noversampling instead of undersampling - neural networks need a lot of data, you don't have many samples right now\ntry other non-DL algorithms (maybe SVM if you have a lot of features? RandomForest otherwise might be a good bet as well)\notherwise fine tune your neural network (focus especially on learning rate, use CV or related methods if you got the time) \ntry to use some pretrained neural networks if available for the task at hand","Q_Score":1,"Tags":"python,tensorflow,machine-learning,data-science,imbalanced-data","A_Id":60670419,"CreationDate":"2020-03-13T09:33:00.000","Title":"Is it feasible to have the training set < the test set after undersampling the majority class?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have 1 dimensions scatter plot that marks the value of my data. How should I find the centroid from my graph","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":26,"Q_Id":60669901,"Users Score":0,"Answer":"If it's one dimension then just take the average.","Q_Score":0,"Tags":"python-3.x,data-analysis","A_Id":60669917,"CreationDate":"2020-03-13T11:45:00.000","Title":"How do find the centroid from the 1 dimension scatter plot graph","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have an AttributeError: module 'tensorflow_core.python.keras.api._v2.keras.losses' has no attribute 'softmax_cross_entropy' error when using tf.losses.softmax_cross_entropy. Could someone help me?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":5641,"Q_Id":60670924,"Users Score":0,"Answer":"The tf.losses now point to tf.keras.losses. You can get identical behavior by using\ntf.losses.categorical_crossentropy with from_logits set to True","Q_Score":1,"Tags":"python,tensorflow,keras,cross-entropy","A_Id":60676246,"CreationDate":"2020-03-13T12:58:00.000","Title":"AttributeError: module 'tensorflow_core.python.keras.api._v2.keras.losses' has no attribute 'softmax_cross_entropy'","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have an image of shape (32, 3, 32, 32). I know it's of the form (batch_size, Channel, Height, Width).\nQ. How do I convert it to be (32, 32, 32) overriding the Channel?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":142,"Q_Id":60671971,"Users Score":0,"Answer":"If you want to convert to grayscale you could do this:\nimage.mean(dim=1)","Q_Score":0,"Tags":"python,image-processing,dataset,pytorch","A_Id":60672798,"CreationDate":"2020-03-13T14:09:00.000","Title":"How to reshape an Image in pytorch","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a Gated Reccurent unit (GRU) model and I made two versions of it each are slightly different. When I ran both, Version 1 gave me a validation mean squared error (MSE) of 0.0013, while Version 2 gave me 0.0015. This means Version 1 is a better model. But when I ran model.evaluate(X_test,y_test) with the test dataframe, Version gave me an MSE value of 0.0027 while Version 2 gave me 0.0018.\nMy question is which version is considered better, the version which gives a better Validation MSE or the model that gave a lower MSE when using the Test dataframe for predicting\nThank you.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":58,"Q_Id":60679791,"Users Score":1,"Answer":"First of all, you can not cheat on the test set, and choose the model so that it gives the best results on the test. Validation is meant to be used for that intention, and the test is only there to check validation and test are getting along each other.\nYou did not mention the size of the training, validation, and test. The size of the data you use is very important to be as big enough to represent the real distribution of the data, in training, validation, and the test.\nOn the other hand, the way you sample the data should be done in a way, that three sets have the same distribution. \nLast, by not least, you are comparing two results which differ about 0.0002 in MSE. I do not believe it gives you good judgment on which one is better.","Q_Score":0,"Tags":"python,tensorflow,machine-learning,keras","A_Id":60680248,"CreationDate":"2020-03-14T04:40:00.000","Title":"Validation loss or model evaluate","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to plot a graph for the data set which has only categorical data(no numeric data) so what library I can use to plot the graph for categorical data on both axes. I have used seaborn.stripplot() but it also requires one numeric data for an axis.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":729,"Q_Id":60690585,"Users Score":0,"Answer":"I have not tried it - but could you create a Enum with the Categorical data for 1 of the axis's. Obviously it can not be dynamic values.\nYou may be able get that to work.\nJust a thought however - I HAVE NOT tried this.","Q_Score":0,"Tags":"python,data-science,data-analysis","A_Id":60690847,"CreationDate":"2020-03-15T07:19:00.000","Title":"Is there a graph to plot non numeric data (categorical data) on both axes in Jupyter Notebook(Python)?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"When I was training my neural network there is a sudden drop in validation accuracy during the 8th epoch what does this mean?\nTrain for 281 steps, validate for 24 steps\nEpoch 1\/10\n281\/281 [==============================] - 106s 378ms\/step - loss: 1.5758 - accuracy: 0.8089 - val_loss: 1.8909 - val_accuracy: 0.4766\nEpoch 2\/10\n281\/281 [==============================] - 99s 353ms\/step - loss: 1.5057 - accuracy: 0.8715 - val_loss: 1.7364 - val_accuracy: 0.6276\nEpoch 3\/10\n281\/281 [==============================] - 99s 353ms\/step - loss: 1.4829 - accuracy: 0.8929 - val_loss: 1.5347 - val_accuracy: 0.8398\nEpoch 4\/10\n281\/281 [==============================] - 99s 353ms\/step - loss: 1.4445 - accuracy: 0.9301 - val_loss: 1.5551 - val_accuracy: 0.8047\nEpoch 5\/10\n281\/281 [==============================] - 99s 353ms\/step - loss: 1.4331 - accuracy: 0.9412 - val_loss: 1.5043 - val_accuracy: 0.8659\nEpoch 6\/10\n281\/281 [==============================] - 97s 344ms\/step - loss: 1.4100 - accuracy: 0.9639 - val_loss: 1.5562 - val_accuracy: 0.8151\nEpoch 7\/10\n281\/281 [==============================] - 96s 342ms\/step - loss: 1.4140 - accuracy: 0.9585 - val_loss: 1.4935 - val_accuracy: 0.8737\nEpoch 8\/10\n281\/281 [==============================] - 96s 341ms\/step - loss: 1.4173 - accuracy: 0.9567 - val_loss: 1.7569 - val_accuracy: 0.6055\nEpoch 9\/10\n281\/281 [==============================] - 96s 340ms\/step - loss: 1.4241 - accuracy: 0.9490 - val_loss: 1.4756 - val_accuracy: 0.9023\nEpoch 10\/10\n281\/281 [==============================] - 96s 340ms\/step - loss: 1.4067 - accuracy: 0.9662 - val_loss: 1.4167 - val_accuracy: 0.9648","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":1163,"Q_Id":60691599,"Users Score":3,"Answer":"Sudden drops in validation loss and training loss occur due to the batch training; in essence, the convergence would be smooth only if we trained with the entire dataset, not with batches. Therefore, it is normal to see such drops (both for training and for validation).\n\nval_loss: 1.4935 - val_accuracy: 0.8737 (Previous epoch)\nval_loss: 1.7569 - val_accuracy: 0.6055 (Epoch with drop)\nval_loss: 1.4756 - val_accuracy: 0.9023 (Next epoch)\n\nIf you take a look at the validation loss, it merely increased with 0.26; however, this resulted in a 27% decrease in your accuracy. In this case, it is due to the fact that your model is not certain when it makes a prediction (at least at this stage of training).\nImagine that you have a binary classification model(between apples and oranges). At each prediction, when the ground truth is an apple, the network is 51% confident that the image is of an apple. We have the ground_truth apple, and as Keras does behind the curtains, the default confidence threshold is 50%. Then all the predictions are good and you have a good accuracy.\nHowever, now comes the 'problematic' epoch. Due to the changed values of the weights of your neural network after another epoch of training, when you predict on your validation dataset, you get a confidence of 48-49% for each ground_truth apple, and again, since the threshold is 50%, you get much poorer accuracy than the previous epoch.\nThis particular case that you are experiencing, as you can now infer from the previous explanation, does not affect the loss so much, but the accuracy. It does not affect the loss that much during backpropagation, because a difference in the confidence prediction between 49% and 51% when computing the loss is not a very significant difference in the overall loss(as you see in your case, only a 0.26%). In the end, even at the 'previous epoch', when the model predicted correctly an apple, the neural network was not that extremely confident, by yielding only 51% confidence for an apple, not 95% for instance.","Q_Score":2,"Tags":"python,tensorflow,machine-learning,keras,neural-network","A_Id":60691955,"CreationDate":"2020-03-15T09:50:00.000","Title":"Sudden drop in validation accuracy during training","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm new to google colab.\nI'm trying to do deep learning there.\nI have written a class to create and train a LSTM net using just python - not any specific deep learning library as tensorflow, pytorch, etc.\nI thought I was using a gpu because I had chosen the runtime type properly in colab.\nDuring the code execution, however, I was sometimes getting the message to quit gpu mode because I was not making use of it.\nSo, my question: how can one use google colab gpu, using just plain python, without special ai libraries? Is there something like \"decorator code\" to put in my original code so that the gpu get activated?","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":1746,"Q_Id":60696987,"Users Score":1,"Answer":"It's just easier to use frameworks like PyTorch or Tensorflow.\nIf not, you can try pycuda or numba, which are closer to \"pure\" GPU programming. That's even harder than just using PyTorch.","Q_Score":4,"Tags":"python,deep-learning,gpu,google-colaboratory","A_Id":60701833,"CreationDate":"2020-03-15T19:50:00.000","Title":"How to activate google colab gpu using just plain python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a dataset of 1.2mil single sentence descriptions (5-50 words) and I want to cluster these into n clusters. For vector conversion, I want to use doc2vec to get 1.2mil equal size vectors. However, I'm not sure what should be the size parameter. I've read, it should be between 100-300 however since each document, in this case, has fewer tokens (words) should the vector be small?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":286,"Q_Id":60704127,"Users Score":0,"Answer":"Your data \u2013 over a million texts, and perhaps tens-of-millions of words \u2013 is certainly large enough to try a default vector-size of 100 dimensions. \nPeople with smaller datasets may need to try even smaller vector-sizes, but that's getting far from the cases where Doc2Vec ('Paragraph Vectors') works well. \nBut the actual best size for your dataset & goals is something you have to find out via experimentation. (If your dataset is dominated by 5-word texts, and if your vocabulary of unique words is quite small, maybe you'll need to try lower sizes, too.) \nThere's no one answer \u2013 the variety of your texts\/vocabulary, & the patterns in your data, will affect the best choice. Only having your own project-specific repeatable evaluation, which you can use to compare alternate choices, can guid you to what's best.","Q_Score":0,"Tags":"python,cluster-analysis,gensim,doc2vec","A_Id":60709966,"CreationDate":"2020-03-16T10:21:00.000","Title":"tuning size parameter for doc2vec","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to write a function in python that takes as input two matrices X and Y and computes for every pair of rows x in X and y in Y, the norm ||x - y|| . I would like to do it without using for loops.\nDo you have an idea about how to do it ?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":117,"Q_Id":60723670,"Users Score":0,"Answer":"I just solve it :D\ninstead of len(np.trnspose(y)) i had to do len(y) and it perfectly worked with a for loop.","Q_Score":0,"Tags":"python,numpy","A_Id":60727470,"CreationDate":"2020-03-17T13:45:00.000","Title":"how to compute the sum for each pair of rows x in matrice X and y in matrice Y?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a dataset like\n\n+--------------------------------------------------\n| |entity |individual_name |investor_name |\n---------------------------------------------------\n| 0 |Null |Null | Mark Wurtzel |\n| 1 |entity |Al Ihne | Ihne LLC |\n| 2 |entity |Al Ihne | Ihne LLC |\n| 3 |entity |Myles Lewis | JMFM INC |\n| 4 |entity |Myles Lewis | JMFM INC |\n| 4 |entity |Myles Lewis | JMFM INC |\n+--------------------------------------------------\n\nIf my individual_name and investor_name same then first take investor_name and split into first_name and last_name and isSelf is 1 and then take individual_name and split into first_name and last_name and isSelf is would be 0.\nand my dataframe look like\n\n+------------------------------------------------------------------------------------------+\n| |entity |individual_name |investor_name | first_name | last_name | isSelf |\n--------------------------------------------------------------------------------------------\n| 0 |Null |Null | Mark Wurtzel | Mark | Wurtzel | 1 |\n| 1 |entity |Al Ihne | Ihne LLC | Ihne | LLC | 1 |\n| 2 |entity |Al Ihne | Ihne LLC | AL | Ihne | 0 |\n| 3 |entity |Myles Lewis | JMFM INC | JMFM | INC | 1 |\n| 4 |entity |Myles Lewis | JMFM INC | Myles | Lewis | 0 |\n| 5 |entity |Myles Lewis | JMFM INC | Myles | Lewis | 0 |\n+------------------------------------------------------------------------------------------+\n\nThanks in advance","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":30,"Q_Id":60727673,"Users Score":0,"Answer":"Filter your database based on your condition using loops, if condition and group_by method that is available in pandas library this will create you a new object that contains only the filtered values.\nFrom this, you can easily split up the names using regex or using some string functions.","Q_Score":0,"Tags":"python,pandas,dataframe","A_Id":60728176,"CreationDate":"2020-03-17T17:49:00.000","Title":"Split first name and last name if there is common matching in another column","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have different shape files which contain polygons on a different coordinate system. When I merge them into a GeoDataFrame the crs attribute is not set. It is a way to set for each row in my GeoDataFrame a different crs? \nI have found a postgis way SRID=312;POINTM(-126.4 45.32 15) but I'm not sure if it works on GeoPandas","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":105,"Q_Id":60728875,"Users Score":1,"Answer":"GeoPandas does not support different CRS for different rows. The geometry column of a GeoDataFrame can only have a single CRS.","Q_Score":0,"Tags":"python,geopandas","A_Id":60729068,"CreationDate":"2020-03-17T19:15:00.000","Title":"Geopandas each row different crs?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"When loading the output of query into a DataFrame using pandas, the standard behavior was to convert integer fields containing NULLs to float so that NULLs would became NaN. \nStarting with pandas 1.0.0, they included a new type called pandas.NA to deal with integer columns having NULLs. However, when using pandas.read_sql(), the integer columns are still being transformed in float instead of integer when NULLs are present. Added to that, the read_sql() method doesn't support the dtype parameter to coerce fields, like read_csv().\nIs there a way to load integer columns from a query directly into a Int64 dtype instead of first coercing it first to float and then having to manually covert it to Int64?","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":284,"Q_Id":60731612,"Users Score":1,"Answer":"Have you tried using \nselect isnull(col_name,0) from table_name. This converts all null values to 0.\nIntegers are automatically cast to float values just as boolean values are cast to objects when some values are n\/a.","Q_Score":2,"Tags":"python,pandas","A_Id":60731768,"CreationDate":"2020-03-17T23:29:00.000","Title":"Is there a way to load a sql query in a pandas >= 1.0.0 dataframe using Int64 instead of float?","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"recently doing a course on numpy, I encountered this problem and am finding difficulty understanding some concepts therefore if someone could help me.Some websites state that it interchanges the axis but what does that actually mean?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":78,"Q_Id":60734756,"Users Score":0,"Answer":"If you have two 2D np.arrays - A and B - where B was created by transposing A, then for every i, j being legal indices for A: A[i][j] == B[j][i] does holds True.","Q_Score":0,"Tags":"python,arrays,numpy,axis","A_Id":60735079,"CreationDate":"2020-03-18T06:57:00.000","Title":"what does the np.transpose function do?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've tried to run this code on Jupyter notebook python 3:\nclass CSRNet(nn.Module):\n def __init__(self, load_weights=False):\n super(CSRNet, self).__init__()\n self.frontend_feat = [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512]\n self.backend_feat = [512, 512, 512,256,128,64]\n self.frontend = make_layers(self.frontend_feat)\n self.backend = make_layers(self.backend_feat,in_channels = 512,dilation = True)\n self.output_layer = nn.Conv2d(64, 1, kernel_size=1)\n if not load_weights:\n mod = models.vgg16(pretrained = True)\n self._initialize_weights()\n for i in range(len(self.frontend.state_dict().items())):\n self.frontend.state_dict().items()[i][1].data[:] = mod.state_dict().items()[i][1].data[:]\nit displays 'odict_items' object is not subscriptable as an error in the last line of code!!how to deal with this?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":1196,"Q_Id":60740451,"Users Score":1,"Answer":"In python3, items() returns a dict_keys object, you should try to convert it to a list:\n\nlist(self.frontend.state_dict().items())[i][1].data[:] =\nlist(mod.state_dict().items())[i][1].data[:]","Q_Score":1,"Tags":"python-3.x,conv-neural-network","A_Id":67223193,"CreationDate":"2020-03-18T13:18:00.000","Title":"'odict_items' object is not subscriptable how to deal with this?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have 2 dataframes: \nFinalFrame:\nTime | Monday | Tuesday | Wednesday | ...\nand df (Where weekday is the current day, whether it be monday tuesday etc):\nWEEKDAY\nI want to append the weekday's data to the correct column. I will need to constantly keep appending weekdays data as weeks go by. Any ideas on how to tackle this?","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":28,"Q_Id":60749292,"Users Score":0,"Answer":"You can add index of week days instead of their name. For example, \nweekdays = ['Mon', Tue', 'Wed', 'Thu', 'Fri','Sat', 'Sun']\nTime | 0 | 1 | 2 ....","Q_Score":0,"Tags":"python,pandas","A_Id":60749473,"CreationDate":"2020-03-19T00:25:00.000","Title":"How to append data to specific column Pandas?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have 2 dataframes: \nFinalFrame:\nTime | Monday | Tuesday | Wednesday | ...\nand df (Where weekday is the current day, whether it be monday tuesday etc):\nWEEKDAY\nI want to append the weekday's data to the correct column. I will need to constantly keep appending weekdays data as weeks go by. Any ideas on how to tackle this?","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":28,"Q_Id":60749292,"Users Score":0,"Answer":"So the way you could do it isolates the series by saying weekday[whatever day you are looking at .append.","Q_Score":0,"Tags":"python,pandas","A_Id":60749625,"CreationDate":"2020-03-19T00:25:00.000","Title":"How to append data to specific column Pandas?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm starting a project on a dataset that contains over 5k unique values for a category. \nMy question is, after using label encoder, to \"enumerate\" the categories, does it make sense to use Standard Scaler to make the data a little more \"manageable\" for my Machine Learning model? \nKeep in mind I have over 500k entries in total and 5k unique categories for this particular column.\nThis is more about the intuition behind it rather than how to code it, but I figured this should be the place to ask.","AnswerCount":3,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":1168,"Q_Id":60750375,"Users Score":0,"Answer":"If you use LabelEncoder for a category, you need to make sure that your category can be comparable. For example, for category ['high', 'med', 'low'], items are comparable, so it makes sense to LabelEncoding it and standard scaling it.\nHowever, when your category cannot be compared to each other, label encoding it would not make any sense. For example, you cannot compare 'Monday' to 'Tuesday'.\nTL;DR \nIf your category is comparable (ordinal), it makes sense. If not, try to find ways to reduce your category, there are a lot of methods to do so.","Q_Score":0,"Tags":"python,machine-learning,label-encoding","A_Id":60750707,"CreationDate":"2020-03-19T03:07:00.000","Title":"Does it make sense to user Standard Scaler after applying Label Encoder?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm starting a project on a dataset that contains over 5k unique values for a category. \nMy question is, after using label encoder, to \"enumerate\" the categories, does it make sense to use Standard Scaler to make the data a little more \"manageable\" for my Machine Learning model? \nKeep in mind I have over 500k entries in total and 5k unique categories for this particular column.\nThis is more about the intuition behind it rather than how to code it, but I figured this should be the place to ask.","AnswerCount":3,"Available Count":2,"Score":1.2,"is_accepted":true,"ViewCount":1168,"Q_Id":60750375,"Users Score":0,"Answer":"LabelEncoder should be used for the labels, in order to have labels for n categories replaced with integers from 1 to n. You should do this if it is not already done.\nStandardScaler is meant to be used, eventually, for the training and test data but nor for the labels. It outputs positive or negative float.\nYou should certainly not apply this to the label column, as the label column must be a positive Integer.","Q_Score":0,"Tags":"python,machine-learning,label-encoding","A_Id":60769398,"CreationDate":"2020-03-19T03:07:00.000","Title":"Does it make sense to user Standard Scaler after applying Label Encoder?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"After i did a lot of research about AI and sentiment analysis i found 2 ways to do text analysis.\nAfter the pre-processing for text is done we must create a classification in order to get the positive and negative, so my question is it better to have example:\nfirst way:\n\n100 records of text to train that includes 2 fields text &\nstatus filed that indicate if its positive 1 or negative 0.\n\nsecond way:\n100 records of text to train and make a vocabulary for bag of word in order to train and compare the tested records based on this bag of word.\nif i am mistaking in my question please tel me and correct my question.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":53,"Q_Id":60752016,"Users Score":0,"Answer":"I think you might miss something here, so to train a sentiment analysis model, you will have a train data which every row has label (positive or negative) and a raw text. In order to make computer can understand or \"see\" the text is by representing the text as number (since computer cannot understand text), so one of the way to represent text as number is by using bag of words (there are other methods to represent text like TF\/IDF, WORD2VEC, etc.). So when you train the model using data train, the program should preprocess the raw text, then it should make (in this case) a bag of words map where every element position represent one vocabulary, and it will become 1 or more if the word exist in the text and 0 if it doesn't exist.\nNow suppose the training has finished, then the program produce a model, this model is what you save, so whenever you want to test a data, you don't need to re-train the program again. Now when you want to test, yes, you will use the bag of words mapping of the train data, suppose there is a word in the test dataset that never occurred in train dataset, then just map it as 0.\nin short:\nwhen you want to test, you have to use the bag of words mapping from the data train","Q_Score":0,"Tags":"python,nltk,sentiment-analysis","A_Id":60752756,"CreationDate":"2020-03-19T06:35:00.000","Title":"best practice to start a sentiment analysis project?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a folder containing a lot of files with similar names and I want to open two of them with xarray so I get one array (with the time axis consistent).\nI know that I can open multiple files with the *\nExample:\nxarray.open_mfdataset('folder\/*.nc') would open all netcdf files in the folder.\nNow, say I have file_01, file_02 and file_03 in folder.\nHow can I open file_01 & file_02, but not file_03 ?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":474,"Q_Id":60758026,"Users Score":3,"Answer":"xr.open_mfdataset() can accept wildcards, as you said, but it can also accept an explicit list of files if you want to specify them. \nSo in your case, you could use:\nxr.open_mfdataset(['folder\/file1.nc','folder\/file2.nc'])","Q_Score":2,"Tags":"python,python-xarray","A_Id":60758940,"CreationDate":"2020-03-19T13:16:00.000","Title":"Open selected files with open_mfdataset","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to create a speaker recognition machine learning. \nCurrently i'm using the following scheme:\n\ntaking my audio files data set and computing for each 0.15 seconds of the audio file 13 mel freaquency coeffs \neach 13 coeffs I input to a neural network that based on 3 blocks of [conv, pool, norm]\nfor the test files i use a majority over all the outpus for each 13 coeffs vector\n\nI usually get about 85% recognition rate for 3 speakers which is not amazing and therefore I decided that I want to add some features, but I don't know what to add...\nSomeone has a recommendations to what feature should I add\/ what should I do in order to increase my precentage?\nI tried to use a module that call - \"pitch\" which give me the pitch of a wav file but it gave me very randomic values ( for example for the same speaker it gave me 360, 80, 440 for the 3 first audios ) \nThanks alot for any help","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":86,"Q_Id":60774064,"Users Score":0,"Answer":"You should be processing longer chunks at once, in 0.15 seconds is almost impossible identify speaker identity.\nThe general rule is the longer audio you process, the more accurate recognition you will have. Something like 1-3 seconds is good and you need to input them to neural network as a whole.\nYou can google for x-vector on github, there are many implementation, you can find one in kaldi for example.","Q_Score":1,"Tags":"python,neural-network,voice-recognition,mfcc,pitch","A_Id":60786263,"CreationDate":"2020-03-20T12:22:00.000","Title":"Features for speaker recognition that can be added to mfcc features\/ Things that I can do in order to improve my speaker recognition neural network","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am writing 6 datasets to a new hdf5 with h5py. 3 of them are of one format and 3 of the other. For 3 of the first set, I use dt=\"s103\" which perfectly captures the datatype. For the other set of 3, I need the datatype to be H5T_STD_U8LE to match what another hdf5 file on disc has. How would I accomplish this when creating a dataset to write out?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":43,"Q_Id":60774568,"Users Score":0,"Answer":"In my situation it was dt='uint8'. This would give me the above type","Q_Score":0,"Tags":"python,hdf5,h5py","A_Id":60774693,"CreationDate":"2020-03-20T12:52:00.000","Title":"In H5PY, what would be the equivalent of datatype H5T_STD_U8LE?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Suppose I have trained the doc2vec model with 50000 documents and I want to infer vectors for a separate dataset containing 36000 documents. In this case will the inferred vectors be effective for the downstream task of classification, becasue my assumption is that the inferred vectors depend on the size of documents with which the model is trained. \nNote: Both dataset i.e one used for training doc2vec and other for inferring vectors are unique but from the same domain of US supreme court.\nPlease correct me if I am wrong with valid reason.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":135,"Q_Id":60774762,"Users Score":1,"Answer":"With such a tiny dataset, no answer I can give will be as useful as just trying it to see if it works. \n50000 is smallish for a training set, but some useful Doc2Vec results have been based on similar corpuses. \nVector inference, like training, reduces documents of any length to a fixed-size vector. (But note: gensim silently limits any text fed to a 2Vec model to 10000 tokens.) \nBut, if you've trained a model on documents that are all about 1000 words, then try inference on 10-word fragments, those doc-vectors might not be as useful, or useful in the same way, as inferred vectors on documents more similar to the training set. But you'd still need to try it to find out. (Also note: words not learned during training are completely ignored during inference, so later inferences on docs with many\/all unknown words will be weak or meaningless.)\nIs that the the case with your inference docs \u2013 they are very different from training docs in size & vocabulary? And if so, why? (Can you train with more representative documents?)\nIf the set of 36000 documents is fixed before training begins, it may also be valid\/defensible to include them in the unsupervised Doc2Vec training. They're data, they help learn the domain lingo, and they don't have in them any form of the \"right\" answers for classification.","Q_Score":0,"Tags":"python,nlp,word-embedding,doc2vec,pre-trained-model","A_Id":60778723,"CreationDate":"2020-03-20T13:04:00.000","Title":"Doc2Vec Pre training and Inferring vectors","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying the typical hololens tutorial to use Tensorflow, Keras, and ImageAI to be able to train a new custom object detection.\nThe training is running, but it is always returning something like: \nloss: 0.0000e+00 - yolo_layer_1_loss: 0.0000e+00 - yolo_layer_2_loss: 0.0000e+00 \nAnd when I try to use the outcome of the model, it fails.\nI am using Python 3.7.7\ntensorflow 1.14.0\nimageai 2.1.5\nKeras 2.3.1","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":97,"Q_Id":60776218,"Users Score":1,"Answer":"For me, what solved the issue was using batch size > 1.","Q_Score":1,"Tags":"python,tensorflow,keras,imageai","A_Id":60804572,"CreationDate":"2020-03-20T14:36:00.000","Title":"Running an ImageAI training returns always 0 loss","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have my university project and i'm given a dataset which almost all features have a very weak (only 1 feature has moderate correlation with the target) correlation with the target. It's distribution is not normal too. I already tried to apply simple model linear regression it caused underfitting, then i applied simple random forest regressor but it caused overfitting but when i applied random forest regressor with optimization with randomsearchcv it took time so long. Is there any way to get decent model with not-so-good dataset without underfitting or overfitting? or it's just not possible at all?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":207,"Q_Id":60776759,"Users Score":3,"Answer":"Well, to be blunt, if you could fit a model without underfitting or overfitting you would have solved AI completely.\nSome suggestions, though:\nOverfitting on random forests\n\nPersonally, I'd try to hack this route since you mention that your data is not strongly correlated. It's typically easier to fix overfitting than underfitting so that helps, too.\nTry looking at your tree outputs. If you are using python, sci-kit learn's export_graphviz can be helpful. \nTry reducing the maximum depth of the trees. \nTry increasing the maximum number of a samples a tree must have in order to split (or similarly, the minimum number of samples a leaf should have). \nTry increasing the number of trees in the RF.\n\nUnderfitting on linear regression\n\nAdd more parameters. If you have variables a, b, ... etc. adding their polynomial features, i.e. a^2, a^3 ... b^2, b^3 ... etc. may help. If you add enough polynomial features you should be able to overfit -- although that doesn't necessarily mean it will have a good fit on the train set (RMSE value).\nTry plotting some of the variables against the value to predict (y). Perhaps you may be able to see a non-linear pattern (i.e. a logarithmic relationship). \nDo you know anything about the data? Perhaps a variable that is the multiple, or the division between two variables may be a good indicator. \nIf you are regularizing (or if the software is automatically applying) your regression, try reducing the regularization parameter.","Q_Score":0,"Tags":"python,machine-learning,data-science","A_Id":60777051,"CreationDate":"2020-03-20T15:09:00.000","Title":"How to achieve regression model without underfitting or overfitting","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Lets say I have a training sample (with their corresponding training labels) for a defined neural network (the architecture of the neural network does not matter for answering this question). Lets call the neural network 'model'.\nIn order to not create any missunderstandings, lets say that I introduce the initial weights and biases for 'model'.\nExperiment 1.\nI use the training sample and the training labels to train the 'model' for 40 epochs. After the training, the neural network will have a specific set of weights and biases for the entire neural network, lets call it WB_Final_experiment1.\nExperiment 2\nI use the training sample and the training labels to train 'model' for 20 epochs. After the training, the neural network will have a specific set of weights and biases for the entire neural network, lets call it WB_Intermediate.\nNow I introduce WB_Intermediate in 'model' and train for another 20 epochs. After the training, the neural network will have a specific set of weights and biases for the entire neural network, lets call it WB__Final_experiment2.\nConsiderations. Every single parameter, hyperparameter, activation functions, loss functions....is exactly the same for both experiments, except the epochs.\nQuestion: Are WB_Final_experiment1 and WB__Final_experiment2 exactly the same?","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":153,"Q_Id":60780523,"Users Score":0,"Answer":"If the operations you are doing are entirely deterministic, then yes. Epochs are implemented as an iteration number for a for loop around your training algorithm. You can see this in implementations in PyTorch.","Q_Score":3,"Tags":"python,machine-learning,keras,neural-network,epoch","A_Id":60780565,"CreationDate":"2020-03-20T19:31:00.000","Title":"I am trying to understand 'epochs' in neural network training. Are the next experiments equivalent?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to import an excel and create a dataframe using pandas read_excel function.\nThe thing is I only need to use columns C to F and rows 17 onward from the excel. How can I select only that part of the excel file and transform it to a dataframe in pandas???\nThank you!!!!!","AnswerCount":1,"Available Count":1,"Score":0.537049567,"is_accepted":false,"ViewCount":37,"Q_Id":60783110,"Users Score":3,"Answer":"You can use the usecols parameter to select the columns of interest in your spreadsheet, and skiprows to select everything below row 17. \nimport pandas as pd\n pd.read_excel('my_spreadsheet.xlsx', usecols='C:F', skiprows=16)","Q_Score":0,"Tags":"python,pandas","A_Id":60783157,"CreationDate":"2020-03-20T23:58:00.000","Title":"Creating a Dataframe from an excel","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm using windows 10\n\npython version: 3.7.1 \nktrain version: 0.11.3\ntensorflow downgrade to 2.0\n\nerror log::\n\nTraceback (most recent call last):\n File \"text_classifier.py\", line 3, in \n import ktrain\n File \"C:\\Users\\user\\PycharmProjects\\ai\\env\\lib\\site-packages\\ktrain__init__.py\", line 2, in \n from .imports import *\n File \"C:\\Users\\user\\PycharmProjects\\ai\\env\\lib\\site-packages\\ktrain\\imports.py\", line 209, in \n import cchardet as chardet\n File \"C:\\Users\\user\\PycharmProjects\\ai\\env\\lib\\site-packages\\cchardet__init__.py\", line 1, in \n from cchardet import _cchardet\n ImportError: DLL load failed: The specified module could not be found.","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":1408,"Q_Id":60784527,"Users Score":2,"Answer":"I was working on virtualenv\n\nI moved to conda env\npip install ktrain\npip install tensorflow=2.0\npip uninstall h5py\npip install h5py\n\nNow it's working fine, thanks for the idea conda install -c conda-forge cchardet","Q_Score":0,"Tags":"python,windows,tensorflow,dll","A_Id":60861776,"CreationDate":"2020-03-21T04:40:00.000","Title":"ktrain ImportError: DLL load failed: The specified module could not be found","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"If got the following problem:\nGiven a series of rectangles defined by {x_min, height and x_max}, I want to efficiently compute their intersection and union, creating a new series.\nFor instance, if I got S1 = [{1,3,3}] and S2 = [{2,3,5}], the union would result in S3 = [{1,3,5}] and intersection in S3 = [{2,3,3}]. This would be a fairly simple case, but when S1 and S2 are a list of rectangles (unordered) It get's a little bit tricky.\nMy idea is trying some divide and conquer strategy, like using a modificated mergesort, and in the merge phase try to also merge those buildings. But I'm a little bit unsure about how to express this.\nBasically I can't write down how to compare two rectangles with those coordinates and decide if they have to be in S3, or if I have to create a new one (for the intersection).\nFor the union I think the idea has to be fairly similar, but the negation (i.e. if they don't interesct).\nThis has to be O(nlogn) for sure, given this is in a 2D plane I surely have to sort it. Currently my first approach is O(n^2).\nAny help how to reduce the complexity?\nPD: The implementation I'm doing is in Python","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":48,"Q_Id":60791535,"Users Score":0,"Answer":"I tried to write the whole thing out in psudo-code, and found that it was too psudo-y to be useful and too code-y to be readable. Here's the basic idea:\nYou can sort each of your input lists in O(n*log(n)). \nBecause we assume there's no overlap within each series, we can now replace each of those lists with lists of the form {start, height}. We can drop the \"end\" attribute by having a height-0 element start where the last element should have ended. (or not, if two elements were already abutting.) \nNow you can walk\/recurse\/pop your way through both lists in a single pass, building a new list of {start, height} outputs as you go. I see no reason you couldn't be building both your union and intersection lists at the same time.\nCleanup (conversion to a minimal representation in the original format) will be another pass, but still O(n).\nSo the problem is O(n*log(n)), and could be O(n) if you could finagle a way to get your input pre-sorted.","Q_Score":0,"Tags":"python,algorithm","A_Id":60795389,"CreationDate":"2020-03-21T18:13:00.000","Title":"Efficient unions and intersections in 2D plane when y_min = 0","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I need a suggestion in unsupervised training of Doc2Vec for the 2 options I have. The scenario is I have N documents each of size greater than 3000 tokens. So now for training which alternative is better:\n\nTraining with whole document as such.\nBreaking the documents into chunks of 1000 tokens and then training it.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":60,"Q_Id":60792362,"Users Score":1,"Answer":"You should watch out for docs with more than 10000 tokens \u2013 that's an internal implementation limit of gensim, and tokens beyond the 10000th position in a single document will be ignored.\nBut whether you should split documents into 1000-token chunks is entirely dependent on what works best for your specific data and goals. If you have reason to consider it \u2013 perhaps you want to get back results of subdocument ranges? \u2013 then you should try it, compare the results to the alternative, and use whichever works better. There is no general answer.","Q_Score":0,"Tags":"python,gensim,doc2vec","A_Id":60796323,"CreationDate":"2020-03-21T19:29:00.000","Title":"Doc2Vec Unsupervised training","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to create a document term matrix. In my case it is not like documents x words but it is sentences x words so the sentences will act as the documents. I am using 'l2' normalization post doc-term matrix creation.\nThe term count is important for me to create summarization using SVD in further steps.\nMy query is which axis will be appropriate to apply 'l2' normalization. With sufficient research I understood:\n\nAxis=1 : Will give me the importance of the word in a sentence (column wise normalization)\nAxis=0 : Importance of the word in a document (row wise normalization).\n\nEven after knowing the theory I am not able to decide which alternative to choose because the choice will greatly affect my summarization results. So kindly guide me a solution along with a reason for the same.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":45,"Q_Id":60793533,"Users Score":1,"Answer":"By L2 normalization, do you mean division by the total count?\nIf you normalize along axis=0, then the value of x_{i,j} is the probability of the word j over all sentences i (division by the global word count), which is dependent on the length of the sentence, as longer ones can repeat some words over and over again and will have a much higher probability for this word, as they contribute a lot to the global word count.\nIf you normalize along axis=1, then you're asking whether sentences have the same composition of words, as you normalize along the lenght of the sentence.","Q_Score":1,"Tags":"python,normalization,countvectorizer,lsa","A_Id":60798114,"CreationDate":"2020-03-21T21:35:00.000","Title":"In count vectorizer which axis to use?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am going to save a list of arrays into a file that can be read in Matlab. The arrays in the list are of 3-dimensional but varied shapes, so I cannot put them into a single large array. \nOriginally I thought I could save the list in to a pickle file and then read the file in Matlab. Later I found Matlab does not support reading the pickle file. I also tried using scipy.io.savemat to save the list to a mat file. The inconsistencies of array dimensions causes saving problems. \nAnyone has ideas of how to solve the problem? It should be noted that the list file is very large in memory (>4 G).","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":567,"Q_Id":60794727,"Users Score":1,"Answer":"If you don't need a single file, you can iterate through the list and savemat each entry into a separate file. Then iterate through that directory and load each file into a cell array element. \nYou can also zip the directory you store these in, to get one file to pass around.","Q_Score":0,"Tags":"python,matlab,numpy,scipy","A_Id":60795163,"CreationDate":"2020-03-22T00:26:00.000","Title":"How to save a Python list of arrays of varied dimensions to mat file","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm currently trying to light up a 32x60 led matrix made of single WS2812B led strips. With the node-red-node-pi-neopixel node, i have to write 10 different msgs if I want to light up 10 leds that are not next to each other. Since the node uses a csv, it there another way to pass a more complex csv that uses ';' to light up more than one array?\nLike '1,255,255,0;5;2550,255'.\nOr if there are other ways, I'm more than happy to here from you!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":62,"Q_Id":60802661,"Users Score":0,"Answer":"The node can't take an array, but you can achieve the same thing using a split node.\nIf you create and array of values representing the whole string of LEDS using n,r,g,b for each element in the array then pass this to the split node and then on to the neopixel node, it will break the array up into individual messages and send them in sequence.\nYou can use n,0,0,0 for any LEDs you want to be off.","Q_Score":0,"Tags":"python,node-red,led,neopixel","A_Id":60803822,"CreationDate":"2020-03-22T17:30:00.000","Title":"How to pass a csv to light more single leds in one msg payload with node-red-node-pi-neopixel library","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I updated Anaconda-Navigator to 1.9.12 on ubuntu and now my environments dont work. \nI can still start a jupyter notebook from the environment but all my installed packages are not available even though they are displayed in the anaconda-navigator gui under installed packages for this env. \nbut when I import a package in a notebook : ModuleNotFoundError: No module named ....\nThe standard packages like numpy are available though...\nPlease help me... why did I update!!!!????\nmaybe a path problem? Please help me in simple terms \nThanks","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":348,"Q_Id":60805199,"Users Score":0,"Answer":"I think this is a bug. My experiance is that when you upgrade to Navigator to 1.9.12.\nthe enviroment variables in GUI(Navigator UI), are taken from base enviroment not from second enviroment and if you work from console it work, so it looks like it not executes conda activate new_environment in gui. When you work from terminal everythings works fine.\nTo be honest it has the same behaviour if fresh install last anaconda too. This was the reason i have downgraded conda isntallation, and than i found out that last version of navigator was making the issues . Or you can downgrade:\nconda install anaconda-navigator=1.9.7.","Q_Score":0,"Tags":"python,anaconda,conda","A_Id":61206708,"CreationDate":"2020-03-22T21:31:00.000","Title":"After updating Anaconda-Navigator environments dont work","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"How to delete drawn objects with OpenCV in Python ?\n\nI draw objects on click (cv2.rectangle, cv2.circle) ...\nThen I would like to delete only drawn objects.\nI know that i need to make a layer in behind of the real image and to draw on another one.\nBut I do not know how to implement this in code.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":1279,"Q_Id":60823140,"Users Score":0,"Answer":"Have a method or something that when it's executed, will replace the image with stuff drawn on it with an original unaltered image. It's best to create a clone of your original image to draw on.","Q_Score":0,"Tags":"python,opencv,computer-vision","A_Id":60823211,"CreationDate":"2020-03-23T23:50:00.000","Title":"How to delete drawn objects with OpenCV in Python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I was wondering if there is any way to use selection_glyph as the renderer of HoverTool in bokeh, i am using python and tried to add a name label to the selected glyph and then using plot.hover.names, but it does not work. \nBasically i have a plot with many glyphs and i want the tooltip to appear when a glyph is selected (single click), and not when a mouse is just hovered over it? is it possible at all? thanks in advance","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":79,"Q_Id":60828308,"Users Score":0,"Answer":"I'm afraid that's not possible with the vanilla HoverTool and without creating additional renderers.\nThe tool works with renderers, not with glyphs, and it doesn't know anything about selection. So you can either create a glyph that's rendered only when something is selected (which is finicky at best), or you can create a custom version of HoverTool.","Q_Score":0,"Tags":"python-3.x,bokeh","A_Id":60829103,"CreationDate":"2020-03-24T09:35:00.000","Title":"Using selection_glyph as renderer for hovertool","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":1,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"My problem: I am composing a data source that I pass to the constControl(..., ds=ds, ...) that will be updated iteratively. It is the result of a series of calculations at every timestep coming from a model that I built. After passing the results of my model (loads) at every timestep, I want to call run_timeseries and store the results before going to the next iteration.\nTrying to store some results (e.g. net.res_bus.vm_pu, ...) into a list fails to update the values after every iteration as if the data source object had constant values throughout the iterations, which it doesn't.\nMy solution: I found that calling OutputWriter() before the run_timeseries() and letting it output an excel file at every iteration successfully updates the results I am simultaneously storing in that empty list. So it works now!\nMy question: I don't want to be forced to output excel files every time I run_timeseries() in order for the results to be stored and\/or successfully updated in the next iteration. I do not even need excel files at the moment. Is there any way to not having to call OutputWriter() but store net's result values in an empty list?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":163,"Q_Id":60838667,"Users Score":0,"Answer":"You don't neet to use OutputWriter(). It depends in what you're trying to do, if you create a loop that make the same as run_timeseries() that might work.\nIn my case I wanted to change the load and make a new power flow calculation every time the change was made.\nA overview of the steps taken:\n\nCreate a loop\n\nEach step change the load using map to go through all item in net.load.p_mw for example.\n\nCall the run_control(net) to make the new power flow calculation.\n\n\nThen you can create a list to collect the data and convert it in JSON.\n\ndata = all bus data\njson = { dataBuses: data }\n\nOnce it's in JSON format you can even send to a database by a post request or whatever you desire.","Q_Score":0,"Tags":"python,iteration,pandapower","A_Id":62493799,"CreationDate":"2020-03-24T20:18:00.000","Title":"pandapower python: need OutputWriter before run_timeseries for updating net result","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"is there something i can do to use NumPy in IBM quantum experience? I have searched on google but i couldn't find anything. I thought about coping the source code, any suggestion?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":43,"Q_Id":60839687,"Users Score":0,"Answer":"NumPy is one of the pre-installed packages (it's a pre-requisite for Qiskit, for one thing). You should be able to just do import numpy from your Jupyter notebook.","Q_Score":0,"Tags":"python,quantum-computing","A_Id":60848813,"CreationDate":"2020-03-24T21:34:00.000","Title":"using third part modules in IBM quantum experience","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have been unable to find any way to add a box annotation to a bokeh plot between the same set of hours for each day on a graph. For example, if I had a line graph of hourly data for an entire month, is it possible to add a box annotation between the hours of 5 and 10 each day without explicitly coding the left\/right bounds of the box for each day in the dataset?\nDoes anyone know of any other solution in order to highlight on the graph the same time frame each day?\nX-axis is in datetime format","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":159,"Q_Id":60839898,"Users Score":1,"Answer":"Box annotations don't accept neither a data source nor an array of values.\nYou have 3 options:\n\nJust as you said, explicitly specify the bounds\nIf it's possible, replace them with rect glyphs that accept data sources and\/or arrays\nCreate a custom annotation class that renders multiple boxes","Q_Score":1,"Tags":"python,pandas,bokeh,pandas-bokeh","A_Id":60840033,"CreationDate":"2020-03-24T21:51:00.000","Title":"Is there a way to use bokeh box annotation to highlight the same time frame each day?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Let's assume there are two networks called A and B.\nI want to train the network A to get the output which is also the input of network B. \nNetwork B can be considered as a trained network by other people. My work is to train the network A and the weights of network B would be fixed.\nCan it work?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":21,"Q_Id":60844997,"Users Score":0,"Answer":"It surely works, you just don't apply backpropagation to the weights of B.","Q_Score":0,"Tags":"python,tensorflow","A_Id":60848964,"CreationDate":"2020-03-25T08:14:00.000","Title":"Can I train a network to get the output for the other network?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to evaluate a home-made topic model. For this, I'm using the list of topics (represented by keywords), and want to use a gensim.models.coherencemodel.CoherenceModel, and call it on a corpus, which is a list of strings (each one being a document).\nThe CoherenceModel requires a Dictionary, but I don't understand what this corresponds to, and how I can get it.\nI'm using the TfidfVectorizer from sklearn to vectorize the text, and glove embeddings from gensim to compute similarities within my model.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":47,"Q_Id":60850956,"Users Score":0,"Answer":"From the docs, a Dictionary can be created from a corpus where the corpus is a list of lists of str. This same corpus should be passed in the text argument of the CoherenceModel.","Q_Score":0,"Tags":"python,gensim","A_Id":60852969,"CreationDate":"2020-03-25T14:31:00.000","Title":"Topic Coherence with Dictionary from Glove (gensim)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to implement a data structure that would make it easy to build a questionnaire. What I mean is the following:\nLet's say the first question is \"Which country are you from?\" You answer \"United States\" and thus, the next question is \"Which state are you from?\" \nIf you were to answer, say, \"China\" for the first question, it might ask a different question next. What kind of data structure would I need to implement to do something like this?","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":266,"Q_Id":60855230,"Users Score":1,"Answer":"I believe an tree with any natural number n nodes from every node, with each node representing a question, would work. Use a function ask to get the answer, and decide which node to go to next. This would be a long process for you to code, but it's good enough. You can create this tree by a list of lists of lists, etc. or a dictionary of dictionaries of dictionaries (in this case I would choose the dictionaries).\nExample:\ntree = {\"United States\": {\"Pizza\": {}, \"Taco\": {}}, \"China\": {\"Books\": {}, \"Movies\", {}}}, and so on until the end.\nEach \"layer\" of dictionaries represents the answers to one question.","Q_Score":1,"Tags":"python,data-structures","A_Id":60855445,"CreationDate":"2020-03-25T18:35:00.000","Title":"Questionnaire Data Structure","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"To perform a binary prediction, I have 5 features which I want to use for my random forest classifier and two are them are not being utilized at all. I understand that this is the whole point of Machine Learning to select the useful features only, but the other three features might have biased data and I want to make sure that all my features are being used at equal weightage to run my classifier. I can't find a straight forward answer to this question. I use sklearn in python for this work. Any comments\/suggestions would be greatly appreciated.","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":605,"Q_Id":60856374,"Users Score":1,"Answer":"What it can help you is setting the parameter max_feature = 1, so each node will take a (uniform distributed) random feature, and it will be forced to use it. Nevertheless, you need to set the depth of the tree too, because it will be infinitely adding nods till receiving one of the main features.","Q_Score":0,"Tags":"python,machine-learning,scikit-learn,classification,random-forest","A_Id":63169771,"CreationDate":"2020-03-25T19:51:00.000","Title":"Force the random forest classifier to use all the input features?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"origin2 = pd.to_datetime([1,2,3],unit='D',origin='julian')\norigin2\non the above command getting the following issue :\nOutOfBoundsDatetime Traceback (most recent call last)\n in \n----> 1 origin2 = pd.to_datetime([1,2,3],unit='D',origin='julian')\n 2 origin2\n~\\AppData\\Local\\Continuum\\anaconda3\\lib\\site-packages\\pandas\\util_decorators.py in wrapper(*args, **kwargs)\n 206 else:\n 207 kwargs[new_arg_name] = new_arg_value\n--> 208 return func(*args, **kwargs)\n 209 \n 210 return wrapper\n~\\AppData\\Local\\Continuum\\anaconda3\\lib\\site-packages\\pandas\\core\\tools\\datetimes.py in to_datetime(arg, errors, dayfirst, yearfirst, utc, box, format, exact, unit, infer_datetime_format, origin, cache)\n 750 \n 751 if origin != \"unix\":\n--> 752 arg = _adjust_to_origin(arg, origin, unit)\n 753 \n 754 tz = \"utc\" if utc else None\n~\\AppData\\Local\\Continuum\\anaconda3\\lib\\site-packages\\pandas\\core\\tools\\datetimes.py in _adjust_to_origin(arg, origin, unit)\n 515 raise tslibs.OutOfBoundsDatetime(\n.......\nOutOfBoundsDatetime: [1, 2, 3] is Out of Bounds for origin='julian'","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":125,"Q_Id":60859244,"Users Score":0,"Answer":"The range for Julian calendar is from 2333836 to 2547339 (from Timestamp('1677-09-21 12:00:00') to Timestamp('2262-04-11 12:00:00')), so [1, 2, 3] are OutOfBoundsDatetime, like error said.","Q_Score":0,"Tags":"python,pandas,datetime,python-datetime","A_Id":63436649,"CreationDate":"2020-03-26T00:12:00.000","Title":"Getting OutofBoundSDateTime on pandas to_datetime origin Parameter when origin='julian'","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I learned that if one needs to implement dct on a image of size (H, W), one needs a matrix A that is of size (8, 8), and one needs to use this A to compute with a (8, 8) region F on the image. That means if the image array is m, one needs to compute m[:8, :8] first, and then m[8:16, 8:16], and so on. \nHow could I implement this dct when input image size is not a scale of 8. For example, when image size is (12, 12) that cannot hold two (8, 8) windows, how could I implement dct ? I tried opencv and found that opencv can cope with this scenario, but I do not know how it implemented it.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":62,"Q_Id":60863664,"Users Score":1,"Answer":"The 8x8 is called a \"Minimum Coded Unit\" (MCU) in the specification, though video enthusiasts call them \"macroblocks\".\nPoorer implementations will pad to fill with zeroes - which can cause nasty effects.\nBetter implementations pad to fill by repeating the previous pixel from the left if padding to the right, or from above if padding downwards.\nNote that only the right side and bottom of an image can be padded.","Q_Score":2,"Tags":"python,opencv,image-processing,dct","A_Id":60864848,"CreationDate":"2020-03-26T08:51:00.000","Title":"How to implement dct when the input image size is not a scale of 8?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have fetched data from a CSV file, and it is held and manipulated in my Dask dataframe. From there I need to write the data into a data table. I have not really come across any solutions for this. Pandas have built-in functionality for this with its to_sql function, so I am unsure whether I need to convert to Pandas first? I currently think that converting the Dask dataframe to Pandas will cause it to be loaded fully into memory, which may defeat the purpose of using Dask in the first place. \nWhat would the best and fastest approach be to write a Dask dataframe to a datatable?","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":1297,"Q_Id":60871938,"Users Score":0,"Answer":"I have no problem with @kfk's answer, as I also investigated that, but my solution was as follows.\nI drop the DASK dataframe to a csv, and from there pick the CSV up with a Golang application that shoves the data into Mongo using multi-threading. For 4.5 million rows, the speed went from 38 minutes using \"load local infile\" to 2 minutes using a multi-threaded app.","Q_Score":1,"Tags":"python,dask,dask-dataframe","A_Id":61123236,"CreationDate":"2020-03-26T16:37:00.000","Title":"How do I get a DASK dataframe into a MySQL datatable?","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've been working on PyTorch and wanted to use Cuda tensors but I've been having trouble getting it to work.\nWhen I use the line torch.cuda.is_available(), it returns false.\nBut when I use the same line on the anaconda command prompt, it returns true. What gives? Do I need to set the device somehow? Or maybe have the interpreter include my GPU? All I want is my GPU to be recognized as CUDA usable and can use in code.\nI use:\npython 3.7\nCUDA 10.1\nGPU: GTX 1070","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":33,"Q_Id":60877680,"Users Score":0,"Answer":"I found the issue, My interpreter was wrong and I changed it to match my anaconda prompt interpreter. Works like a charm","Q_Score":0,"Tags":"python-3.x,pytorch","A_Id":60877942,"CreationDate":"2020-03-26T23:20:00.000","Title":"Trying to use Cuda in pyTorch","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have an autoencoder model using keras, input and output shape is (BATCH_SIZE, 20). In the middle there is a Lambda layer that filters the data. In other words, if the batch size is 1000, there might be only 700 that comes out from the Lambda layer. Then I want to update the weights based on just these 700 samples. Is there any way to tackle this in Keras?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":144,"Q_Id":60878915,"Users Score":0,"Answer":"I recently dealt with such a situation and the way I handled was by keeping the batch dimension flexible. For example: if you are using TensorFlow define the placeholder as [None, w, h, 3] (in case of image) and develop your model. The weights have nothing to do with the batch dimensions. So, when you decrease the size of the computations on axis = 0, the rest of the change will happen accordingly. Basically don't define any concrete batch size, keep it flexible.","Q_Score":0,"Tags":"python,tensorflow,keras,lambda,model","A_Id":60879155,"CreationDate":"2020-03-27T01:58:00.000","Title":"Update weights of keras model only based on samples that meet a condition while training","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I recently convert my model to tensorflow lite but I only got the .tflite file and not a labels.txt for my Android project. So is it possible to create my own labels.txt using the classes that I used to classify? If not, then how to generate labels.txt?","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":4062,"Q_Id":60880310,"Users Score":2,"Answer":"You should be able to generate and use your own labels.txt. The file needs to include the label names in the order you provided them in training, with one name per line.","Q_Score":1,"Tags":"python,tensorflow,model,tensorflow2.0,tensorflow-lite","A_Id":60896637,"CreationDate":"2020-03-27T05:09:00.000","Title":"Is it possible to create labels.txt manually?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to understand how the learning algorithms used by TensorFlow work.\nI have read papers on these methods in the past (a few years ago now, so apologies for my poor terminology) and they seem to claim to be able to differentiate the loss function with respect to each value within the AI's weights and biases. This would tell the learning algorithm which direction to move the AI's parameters in to reduce the loss. \nTo differentiate the AI's parameters with respect to the loss function, the learning algorithm would first need to generate an equation describing this relationship. My question is: how is this equation generated?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":36,"Q_Id":60895421,"Users Score":0,"Answer":"When training a dense network with a single hidden layer (with $m$ hidden nodes) to do binary classification, we minimize the cost function \n$$L(W_1,W_2) = \\sum_{i=1}^N \\ell(y_i, \\sigma(W_2 a(W_1 \\hat x_i)),$$ \nwhere $x_i \\in \\mathbb R^d$ is the $i$th feature vector in the training dataset, $\\hat x_i \\in \\mathbb R^{d+1}$ is the augmented feature vector obtained by prepending a $1$ to $x_i$, $W_1$ is an $m \\times (d+1)$ matrix containing the weights and biases for the hidden layer, $a$ is a function that applies the ReLU activation function to each of its inputs (and also has an additional output which is equal to $1$), and $W_2$ is a $1 \\times m$ matrix containing the weights and bias of the output layer. Here $\\sigma$ is the logistic function and $\\ell$ is the binary cross-entropy loss function.\nEdit: Does mathjax not work on this website?","Q_Score":0,"Tags":"python,tensorflow,machine-learning,artificial-intelligence","A_Id":60896964,"CreationDate":"2020-03-27T23:20:00.000","Title":"How do TensorFlow learning algorithms work?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to do a topic labeling problem on a large dataset of research papers. The idea is that I can give each paper a few relevant labels.\nI have 2 questions.\nI know you can do topic modeling in a variety of ways like using LDA and NMF, but what can you do to later extract possible labels from those topics?\nAlso, assuming I have extracted a bunch of labels, how can I mathematically estimate their accuracy? Is there some kind of metric available that can determine say, the variance of the information explained by a label in a document, or something along those lines? How would I evaluate my labels without a large group of humans doing qualitative analysis?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":423,"Q_Id":60895874,"Users Score":1,"Answer":"The most simple way is to use the top k words as the labels. More complicated methods include candidate label generation and candidate label ranking. Many related papers talking about this topic: \n\nAletras, Nikolaos, and Mark Stevenson. \"Labelling topics using unsupervised graph-based methods.\" ACL. 2014\nBhatia, Shraey, Jey Han Lau, and Timothy Baldwin. \"Automatic labelling of topics with neural embeddings.\"\u00a0COLING\u00a0(2016).\nHingmire, Swapnil, et al. \"Document classification by topic labeling.\"\u00a0SIGIR. 2013\n\nAll the above papers have sections discussing how to evaluate the labels.","Q_Score":2,"Tags":"python,nlp,topic-modeling","A_Id":61099208,"CreationDate":"2020-03-28T00:25:00.000","Title":"Automatic Topic Labeling Evaluation metric","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"For a school project I need to evaluate a neural network with different learning rates. I chose sklearn to implement the neural network (using the MLPRegressor class). Since the training data is pretty small (20 instances, 2 inputs and 1 output each) I decided to use the lbfgs solver, since stochastic solvers like sgd and adam for this size of data don't make sense.\nThe project mandates testing the neural network with different learning rates. That, however, is not possible with the lbfgs solver according to the documentation:\n\nlearning_rate_init double, default=0.001\n The initial learning rate used. It controls the step-size in updating the weights. Only used when solver=\u2019sgd\u2019 or \u2018adam\u2019.\n\nIs there a way I can access the learning rate of the lbfgs solver somehow and modify it or that question doesn't even make sense?","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":1876,"Q_Id":60902315,"Users Score":4,"Answer":"LBFGS is an optimization algorithm that simply does not use a learning rate. For the purpose of your school project, you should use either sgd or adam. Regarding whether it makes more sense or not, I would say that training a neural network on 20 data points doesn't make a lot of sense anyway, except for learning the basics.\nLBFGS is a quasi-newton optimization method. It is based on the hypothesis that the function you seek to optimize can be approximated locally by a second order Taylor development. It roughly proceeds like this:\n\nStart from an initial guess\nUse the Jacobian matrix to compute the direction of steepest descent\nUse the Hessian matrix to compute the descent step and reach the next point\nrepeat until convergence\n\nThe difference with Newton methods is that quasi Newton methods use approximates for the Jacobian and\/or Hessian matrices.\nNewton and quasi-newton methods requires more smoothness from the function to optimize than the gradient descent, but converge faster. Indeed, computing the descent step with the Hessian matrix is more efficient because it can foresee the distance to the local optimum, thus not ending up oscillating around it or converging very slowly. On the other side, the gradient descent only use the Jacobian matrix (first order derivatives) to compute the direction of steepest descent and use the learning rate as the descent step.\nPractically the gradient descent is used in deep learning because computing the Hessian matrix would be too expensive.\nHere it makes no sense to talk about a learning rate for Newton methods (or Quasi-Newton methods), it is just not applicable.","Q_Score":1,"Tags":"python,scikit-learn,neural-network","A_Id":61059397,"CreationDate":"2020-03-28T14:58:00.000","Title":"MLPRegressor learning_rate_init for lbfgs solver in sklearn","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"So, i had a working report, using bokeh and some Select buttons with callbacks using CustomJS.\n(if its important, I have a simple DataTable, which I change the data according to the selected value in the Select button)\nMy bokeh version was 0.12.5 and everything worked ok.\nSince upgrading to 1.3.0, the report is broken.\nLooking at the source, this is the error I'm seeing:\nbokeh-tables-1.3.0.min.js:86 Uncaught Error: SlickGrid's 'enableColumnReorder = true' option requires jquery-ui.sortable module to be loaded\nTried looking for solutions online, couldn't find anything.\nAnyone have any idea? Do I need to load sortable module somehow?\nthanks!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":384,"Q_Id":60912991,"Users Score":0,"Answer":"In the JavaScript console, you should've received this warning: jquery-ui is required to enable DataTable.reorderable. So yes, you have to load jquery-ui yourself.","Q_Score":0,"Tags":"javascript,python,bokeh","A_Id":60913577,"CreationDate":"2020-03-29T10:38:00.000","Title":"bokeh issue - Uncaught Error: SlickGrid's 'enableColumnReorder = true' option requires jquery-ui.sortable module to be loaded","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":1},{"Question":"i have the following error when i run the command java -mx4g -cp \"*\" edu.stanford.nlp.pipeline.StanfordCoreNLPServer -port 9000 -timeout 15000 in folder of stanford core nlp\ni have installed java runtime environment:\nInvalid maximum heap size: -Xmx4g\nThe specified size exceeds the maximum representable size.\nError: Could not create the Java Virtual Machine.\nError: A fatal exception has occurred. Program will exit.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":78,"Q_Id":60913934,"Users Score":0,"Answer":"Do you use 64-bit Java? \nIt depends on the OS you are using, but with 32-bit Java, you can't usually give all 4g for the heap.","Q_Score":0,"Tags":"java,python,nlp,heap-size","A_Id":60927341,"CreationDate":"2020-03-29T12:00:00.000","Title":"Stanfordcore Nlp invalid maximum heap size error","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Do you know if it's possible to use a very small subset of my training data (100 or 500 instances only for example), to train very rough CNN network quickly in order to compare different architectures, then select the best performing one ?\nWhen I say \"possible\", I mean is there evidence that applying that kind of selection strategy works, and that the selected network will consistently outperform the other to for this specific task. \nThank you,\nFor information, the project in question would constist of two stages CNNs to classify multichannel timeseries. The first CNN would forecast the inputs data over the next period of time, then the second CNN would use this forecast and classify the results in two categories.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":109,"Q_Id":60931794,"Users Score":1,"Answer":"The procedure you are talking about is actually used in practice. When tuning hyperparameters, a lot of people select a subset of the whole dataset to do this.\nIs the best architecture on the subset necessarily the best on the full dataset? NO! However, it's the best guess you have and that's why it's useful.\n\nA couple of things to note on your question:\n\n100-500 instances is extremely low! The CNN still needs to be trained. When we say subset we usually mean tens of thousands of images (out of the millions of the dataset). If your dataset is under 50000 images then why do you need a subset? Train on the whole dataset.\nContrary to what a lot of people believe, the details of the architecture are of little importance to the classification performance. Some of the hyperparameters you mention (e.g. kernel size) are of secondary importance. The key things you should focus on is depth, size of layers, use of pooling\/skip connections\/batch norm\/dropout, etc.","Q_Score":0,"Tags":"python,tensorflow,deep-learning,conv-neural-network","A_Id":60931976,"CreationDate":"2020-03-30T13:37:00.000","Title":"Training CNN on small subsets to select architecture","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to delete a particular row from a given user input that matches with a column.\nLet's say I get an employee ID and delete all it's corresponding values in the row. \nNot sure how to approach this problem and other sources suggest using a temporary csv file to copy all values and re-iterate.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":70,"Q_Id":60933352,"Users Score":0,"Answer":"Since these are very primitive requirements, I would just do it manually.\nRead it line by line - if you want to delete the current line, just don't write it back.\nIf you want to delete a column, for each line, parse it as csv (using the module csv - do not use .split(',')!) and discard the correct column.\nThe upside of these solutions is that it's very light on the memory and as fast as it can be runtime-wise.","Q_Score":0,"Tags":"python-3.x,csv","A_Id":60933565,"CreationDate":"2020-03-30T14:57:00.000","Title":"Deleting a particular column\/row from a CSV file using python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using tensorflow-2 gpu with tf.data.Dataset.\nTraining on small models works.\nWhen training a bigger model, everything works at first : gpu is used, the first epoch works with no trouble (but I am using most of my gpu memory).\nAt validation time, I run into a CUDA_ERROR_OUT_OF_MEMORY with various allocation with a smaller and smaller amount of bytes that could not be allocated (ranging from 922Mb to 337Mb).\nI currently have no metrics and no callbacks and am using tf.keras.Model.fit.\nIf I remove the validation data, the training continues.\nWhat is my issue ? how can I debug this ?\nIn tf1, I could use RunOptions(report_tensor_allocations_upon_oom=True), does any equivalent exist in tf2 ? \nThis occurs with tensorflow==2.1.0 .","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":509,"Q_Id":60933768,"Users Score":0,"Answer":"These did not occur in \n2.0 alpha TensorFlow but in 2.0. \nPip installs tensorflow-gpu==2.0.0: has \nleaked memory!\nPip install tensorflow-gpu==2.0.0-alpha: \nit's all right!\nTry it out","Q_Score":5,"Tags":"python,gpu,tensorflow2.x","A_Id":60934498,"CreationDate":"2020-03-30T15:19:00.000","Title":"How to debug out of memory in tensorflow2-gpu","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Does sample= 0 in Gensim word2vec mean that no downsampling is being used during my training? The documentation says just that \n\n\"useful range is (0, 1e-5)\"\n\nHowever putting the threshold to 0 would cause P(wi) to be equal to 1, meaning that no word would be discarded, am I understanding it right or not? \nI'm working on a relatively small dataset of 7597 Facebook posts (18945 words) and my embeddings perform far better using sample= 0rather than anything else within the recommended range. Is there any particular reason? Text size?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":653,"Q_Id":60938299,"Users Score":2,"Answer":"That seems an incredibly tiny dataset for Word2Vec training. (Is that only 18945 unique words, or 18945 words total, so hardly more than 2 words per post?) \nSampling is most useful on larger datasets - where there are so many examples of common words, more training examples of them aren't adding much \u2013 but they are stealing time from, and overwieghting those words' examples compared to, other less-frequent words. \nYes, sample=0 means no down-sampling.","Q_Score":0,"Tags":"python,math,gensim,word-embedding,subsampling","A_Id":60940902,"CreationDate":"2020-03-30T19:42:00.000","Title":"Gensim word2vec downsampling sample=0","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I was reading about different techniques to load large data efficiently. The tf.data seems to perform well as compared to tf.keras.preprocessing.imageImageDataGenerator. \nTo what I know is, tf.data uses CPU pipelining to efficiently load the data and process it so that model training is continuous and fast. But I did not understand how these two techniques are different and in what way. If anybody can explain this I would highly appreciate it.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":180,"Q_Id":60946027,"Users Score":0,"Answer":"the main difference is that ImageDataGenerator uses Pillow library for loading and preprocessing image and tf.data uses tf.image pre-processing technique. ImageDataGenerator returns a batches of tensor Images.Also tf.data uses functions like prefetch,cache to improve the efficiency of preparing the dataset.","Q_Score":3,"Tags":"python,tensorflow,keras,distributed-computing,distributed-training","A_Id":69767805,"CreationDate":"2020-03-31T08:11:00.000","Title":"tf.data vs tf.keras.preprocessing.image.ImageDataGenerator","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to write a program for Windows using python and python frameworks (pandas, numpy etc.), which I want to use to replace several engineering excel spreadsheets (which are repetitive). Please point me in the right direction regarding which python frameworks to use.\nThe program should contain and be able to do the following:\n- Have a GUI to input variables\n- Compute excel formulas using said variables\n- Create graphs\n- Export information to excel spreadsheets\n- Create PDFs\nI know I can set up a single excel spreadsheet to do the above, but I'm using this as a way to learn programming...","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":22,"Q_Id":60946507,"Users Score":0,"Answer":"A good way to learn, maybe a less good way to solve the said problem.\nGUI - ?\nMatplotlib can be used for the graphs.\nExporting to excel can be done easily in pandas with df.to_excel()\nweasyprint library can be used to export to pdf.","Q_Score":0,"Tags":"python,excel,frameworks","A_Id":60947622,"CreationDate":"2020-03-31T08:41:00.000","Title":"Writing a Windows program to replace several engineering excel spreadsheets","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to resize images from 28*28 to 32*32,used tf.image.resize_images(x_train, (32, 32)).It returns AttributeError: module 'tensorflow_core._api.v2.image' has no attribute 'resize_images'.The version of tersorflow is 2.0.0. How can I fix it?","AnswerCount":5,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":15405,"Q_Id":60948568,"Users Score":0,"Answer":"The function has been renamed into resize.\nThe code can be changed as follows;\nimport tensorflow as tf\nimg_A=tf.image.resize(................)","Q_Score":5,"Tags":"python,tensorflow2.0","A_Id":71160984,"CreationDate":"2020-03-31T10:35:00.000","Title":"AttributeError: module 'tensorflow_core._api.v2.image' has no attribute 'resize_images'","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to resize images from 28*28 to 32*32,used tf.image.resize_images(x_train, (32, 32)).It returns AttributeError: module 'tensorflow_core._api.v2.image' has no attribute 'resize_images'.The version of tersorflow is 2.0.0. How can I fix it?","AnswerCount":5,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":15405,"Q_Id":60948568,"Users Score":0,"Answer":"The function has been renamed to resize. You should change your code like it was done below. It worked for me.\nimport tensorflow as tf\nimg_final = tf.image.resize(img_tensor, [192, 192])","Q_Score":5,"Tags":"python,tensorflow2.0","A_Id":71145565,"CreationDate":"2020-03-31T10:35:00.000","Title":"AttributeError: module 'tensorflow_core._api.v2.image' has no attribute 'resize_images'","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have list of RGB images I would like to take each channel from a image in the list and reshape it.\nHowever, I am having an issue extracting the channels from the list of arrays.\nPlease refer the below code;\ndifference[0].shape\nOutput;\n(1280,720,3)\nTo get the first channel width and height in the first image in the list I tried;\ndifference[0][0].shape\nBut I get the answer; (720,3) which is the width and the number of channels. What I want is to get is (1280,720) as the output.\nWould anyone be able to help me regarding this.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":139,"Q_Id":60948836,"Users Score":2,"Answer":"Assuming difference[0] is a numpy array of shape (1280,720,3), you can use difference[0][:,:,0] to access all the data for the first dimension.\ndifference[0][:,:,0].shape will give you (1280, 720).\ndifference[0][:,:,0].shape will give you the red data.\n\ndifference[0][:,:,1].shape will give you the green data.\n\ndifference[0][:,:,2].shape will give you the blue data.","Q_Score":0,"Tags":"python,arrays,python-3.x,list,numpy","A_Id":60949046,"CreationDate":"2020-03-31T10:51:00.000","Title":"Get RGB channels from a list of arrays","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working on building a UNET semantic segmentation network, to detect the iris in eye images we are using DICE loss function and we achieved over 90% train mean IOU and around 87% on validation data but the validation loss and mean IOU showed fluctuation during the 200 epochs, and when we tested our network it showed really poor results, the output image was nothing close to the ground truth even when we used images from the training set it still performed poorly, any suggestions on what we can do to overcome this.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":258,"Q_Id":60959200,"Users Score":0,"Answer":"Is the dataset public? You can find some good resources and guidance here: https:\/\/github.com\/NVIDIA\/DeepLearningExamples\/tree\/master\/TensorFlow2\/Segmentation\/UNet_Medical you will find also benchmark results. I think they are usinf ADAM optimizer with 0.0001 learning rate. More details in the training process section.","Q_Score":0,"Tags":"python,keras,computer-vision","A_Id":60959502,"CreationDate":"2020-03-31T20:19:00.000","Title":"CNN Semantic segmentation network (UNET) performing poorly when tested with images","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to import a lower triangular matrix into pandas (or numpy) in Python in order to convert it into a symmetrical square matrix but I am stuck at the import step.\nThe matrix has the first column with names but the rest of the columns are numbers in a tab delimited format like this:\n\n A\n B 1 \n C 10 20\n D 21 25 45\n\nI get error when I try to import it using numpy:\n\nmyfile = np.genfromtxt(\"trimatrix.txt\", delimiter=\"\\t\")\n\nand also when I use pandas:\n\nmyfile = pd.read_table(\"trimatrix.txt\")\n\nIn both cases, the errors are because there is only one column after reading the first row but the other rows have more columns.\nThank you for your time and help!","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":196,"Q_Id":60961957,"Users Score":1,"Answer":"The straightforward answer is that you don't simply import the triangle: its shape is, by definition, incompatible with the rectangular format required by the built-in readers of NumPy and PANDAS. You have to write your own code to read the input file, stuff the values into the corresponding rows of your chosen data structure, and fill the missing columns with your default value: zeroes, I assume. This needs only a simple loop.\nGiven that what you want is not a built-in method, can you handle the coding from here?","Q_Score":1,"Tags":"python,python-3.x,pandas,numpy","A_Id":60962111,"CreationDate":"2020-04-01T00:33:00.000","Title":"How do I import a lower triangular matrix using pandas?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Once you run the regression model with the module 'statsmodels' in Python, you can get the prediction with these confidence intervals:\nmean_ci_lower mean_ci_upper obs_ci_lower obs_ci_upper\nI know what mean_ci means but I have no idea what obs stands for.","AnswerCount":1,"Available Count":1,"Score":0.537049567,"is_accepted":false,"ViewCount":1606,"Q_Id":60963178,"Users Score":3,"Answer":"obs_ci is the prediction interval, i.e. a confidence interval for a new observation. \nIt combines the uncertainty about the mean estimate with the randomness of a new observation for given mean. It assumes that residuals are distributed close to normal distribution, uses either normal or t distribution for the prediction interval and is therefore only approximate.","Q_Score":4,"Tags":"python","A_Id":60974902,"CreationDate":"2020-04-01T03:21:00.000","Title":"What does obs confidence interval in statsmodels linear regression in Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to process an excel file with ~600k rows and ~10 columns.\nI want to execute some program line by line (or row by row) as if it is an iterator (like txt\/csv files). However, if I use xlrd or pandas to read the excel file, it takes ~2-3min for opening the file.\nI wonder if it is possible to read the excel file line by line efficiently so that, for example, I can verify my program with the first 10 rows without waiting for a long time for every trial.\nEdit: Thank you for suggesting to convert the excel file to a csv before processing. However, I have to create an one-click program to the user. So, I still hope to find out a way to directly read the excel file efficiently, if possible.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":943,"Q_Id":60966543,"Users Score":0,"Answer":"Excel files are zip folder with xml file for each worksheet, maybe it's more efficient to open this file has a zip and read your line with a xml library ?","Q_Score":3,"Tags":"python,pandas","A_Id":60966649,"CreationDate":"2020-04-01T08:27:00.000","Title":"Read Excel file line by line efficiently","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have trained a spacy textcat model but then I realized that there were some incorrect training data: data from one category happened to be labeled with another category. My question is: is it possible to remove these training examples from the model without retraining it? Something like nlp.update() but in reverse? Would appreciate any help!","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":162,"Q_Id":60970109,"Users Score":1,"Answer":"You mean to revert specific cases? As far as I know, that's not currently possible in spaCy. \nI would suggest to either retrain from scratch with the corrected annotations, or continue training with the updated annotations. If you continue training, make sure that you keep feeding a representative set to your model, so that it doesn't \"forget\" cases it was already predicting correctly before.","Q_Score":1,"Tags":"python,spacy,text-classification","A_Id":60970636,"CreationDate":"2020-04-01T11:44:00.000","Title":"Remove training data from spacy model","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working on wind power and speed\nu and vare zonal and meridional wind. (I have the values of these 2 vectors)\nThe wind speed is calculated by V = np.sqrt(u2*v2)\nWind direction is given by \u03b1 between 0 and 360 degree \nI know this relation holds - u \/ V = sin( abs(\u03b1)) and - v \/ V = cos( abs(\u03b1)) \nIn python I am using np.arccos and np.arcsin to try to find \u03b1 between 0 and 360 with the 2 equation above. For the first one, it returns the radian so I convert with np.rad2deg(...) but it gives me a value between 0 and 180 degree for the second one, I also try to convert but it returns me a valus between 0 and 90. \nAnyone knows how to code it? I am lost :(","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":453,"Q_Id":60973244,"Users Score":1,"Answer":"The underlying problem is mathematics: cos(-x) == cos(x), so the function acos has only values in the [0,pi] interval. And for equivalent reasons asin has values in [-pi\/2,pi\/2] one.\nBut trigonometric library designers know about that, and provide a special function (atan2) which uses both coordinates (and not a ratio) to give a value in the [-pi, pi] interval.\nThat being said, be careful when processing wind values. A 360 wind is a wind coming from the North, and 90 is a wind coming from the East. Which is not the way mathematicians count angles...","Q_Score":0,"Tags":"python,degrees,radians","A_Id":60973486,"CreationDate":"2020-04-01T14:28:00.000","Title":"Python Arcsin Arccos radian and degree","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a column named timestamp in dataframe which extends for 30000 rows\nI want to change the unit value of the column to time and date.\nThe first value is 1590000000000 and is going down with same or different values. I want to have the new df to have the timestamp depicted as time and date.\nHow do we do this this in python?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":28,"Q_Id":60984977,"Users Score":0,"Answer":"You could try using pd.to_datetime(df['mydates']).apply(lambda x: x.date())","Q_Score":0,"Tags":"python,datetime,timestamp","A_Id":60985010,"CreationDate":"2020-04-02T05:50:00.000","Title":"chnage a unix base timestamp column into time","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"In the process of writing code using python and pandas, I have opened many dataframes to inspect their contents by double clicking on their object names in the variable explorer. I was wondering if there is an option to \"Close all\", instead of \"X\"-ing out of each one individually.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":31,"Q_Id":60997610,"Users Score":1,"Answer":"(Spyder maintainer here) Unfortunately this is not possible at the moment, sorry.","Q_Score":0,"Tags":"python,spyder","A_Id":61031282,"CreationDate":"2020-04-02T17:34:00.000","Title":"How can I close all dataframes that I've opened using the variable explorer?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a 3D grid for representing shapes\/meshes which is represented in python using an ndarray(20,20,20) of type bool. Each element in the grid represents the presence or absence of material. I want to be able to check if a given grid represents a shape that is connected all the way from the top of the grid to the bottom. I want to be able to discard those that are either disconnected or not occupying continuous series of cells from top of the grid to the bottom. \nAt a later stage I convert the grids into meshes using trimesh. Is there any way to identify the above either directly in python or through trimesh?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":75,"Q_Id":61002532,"Users Score":0,"Answer":"I'd first write a helper function bucket_fill_2d() that takes a slice with material info and, given a starting index (i,j), bucket fills the material like in any old drawing program.\n\nIntroduce an empty Boolean array connected of the shape. \nSet the bottom slice True wherever the material array's bottom slice is True.\nThen go up one step up and bucket_fill_2d(), starting with every connected (i,j) from the previous step.\nRepeat (3) until you reach the top.\nCheck if anything is connected at the top slice.\n\nNote that trimesh, as the name suggests, only supports triangular cells.","Q_Score":0,"Tags":"python,mesh,voxel,trimesh","A_Id":61014997,"CreationDate":"2020-04-02T23:00:00.000","Title":"Check if 3D grid is filled from top to bottom","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"df=pd.read_excel(filename)\nWhat attributes should I add to exclude header and footer?","AnswerCount":3,"Available Count":2,"Score":1.0,"is_accepted":false,"ViewCount":7545,"Q_Id":61004648,"Users Score":7,"Answer":"Head over here: https:\/\/pandas.pydata.org\/pandas-docs\/stable\/reference\/api\/pandas.read_excel.html\nyou will find\npandas.read_excel(io, sheet_name=0, header=0, names=None, index_col=None, usecols=None, squeeze=False, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skiprows=None, nrows=None, na_values=None, keep_default_na=True, verbose=False, parse_dates=False, date_parser=None, thousands=None, comment=None, skipfooter=0, convert_float=True, mangle_dupe_cols=True, **kwds)\nOut of which ones which are useful to you are:\npandas.read_excel(skiprows=None, skipfooter=0)\nyou can specify the value in integer to skiprows=1 to skip header and skipfooter=1 to skip footer you can add as many rows are you want to skip\nHope it helps","Q_Score":2,"Tags":"python-3.x,pandas","A_Id":61005552,"CreationDate":"2020-04-03T03:25:00.000","Title":"How do I exclude header and footer from an excel file in pandas","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"df=pd.read_excel(filename)\nWhat attributes should I add to exclude header and footer?","AnswerCount":3,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":7545,"Q_Id":61004648,"Users Score":0,"Answer":"you should create a sun dataframe from previous data frame which doesn't contain the header and footer attribute.\nfor example,\nif you excel file contains 500 rows, in which first three rows are header and last 10 rows are footers then you can do as below:\ndf = df[4:491]","Q_Score":2,"Tags":"python-3.x,pandas","A_Id":63516219,"CreationDate":"2020-04-03T03:25:00.000","Title":"How do I exclude header and footer from an excel file in pandas","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am new to using CloudFormation \/ CDK and am having trouble figuring out to deploy my stacks without error. Currently I am using the python CDK to create a bucket. This bucket will hold model files and I need to ensure that the bucket deployed in this stack retains data over time \/ new deployments. From my initial tests, it seems that if bucket_name is not specified, the CDK will randomly generate a new bucket name on deployment, which is not ideal. \nHere is the snippet used to create the bucket:\nbucket = aws_s3.Bucket(self, \"smartsearch-bucket\", bucket_name= 'mybucketname')\nThe first time I run cdk deploy, there are no problems and the bucket is created. The second time I run cdk deploy, I get an error stating that my S3 bucket already exists. What else is needed so that I can redeploy my stack using a predetermined S3 bucket name?","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":4090,"Q_Id":61021252,"Users Score":1,"Answer":"The S3 bucket names are global, it means that if someone else on a different account has chosen this name, it wont work, you should provide a very unique name for your bucket.","Q_Score":4,"Tags":"python,amazon-web-services,amazon-s3,amazon-cloudformation,aws-cdk","A_Id":70900366,"CreationDate":"2020-04-03T22:18:00.000","Title":"AWS CDK S3 Bucket Creation Error - Bucket_Name already exisits","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Please consider a matrix \nA= torch.tensor([[1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2,3,4]] \nand vectors of indexes \nind_1= [0,1] and ind_2= [2,3]. \nIs it possible to access the top-right sub-matrix of the matrix A ([[3,4], [3,4]]) without using any for loops? Naively using A[ind_1, ind_2] merely returns the elements 3 and 4 (the diagonal of the required sub-matrix).","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":897,"Q_Id":61022347,"Users Score":0,"Answer":"PyTorch tensors support python slicing so you can use A[:2, 2:] to access the first two rows and the last two columns as a 2x2 tensor.","Q_Score":0,"Tags":"python-3.x,pytorch","A_Id":61022568,"CreationDate":"2020-04-04T00:31:00.000","Title":"How can I access a submatrix specified by row and column index vectors from a matrix (2D tensor) in pytorch?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Please consider a matrix \nA= torch.tensor([[1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2,3,4]] \nand vectors of indexes \nind_1= [0,1] and ind_2= [2,3]. \nIs it possible to access the top-right sub-matrix of the matrix A ([[3,4], [3,4]]) without using any for loops? Naively using A[ind_1, ind_2] merely returns the elements 3 and 4 (the diagonal of the required sub-matrix).","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":897,"Q_Id":61022347,"Users Score":0,"Answer":"WithA[ind_1,:][:,ind_2] you can slice first on the rows, then on the columns. This allows accessing also sub-matrices with non-consecutive indices.","Q_Score":0,"Tags":"python-3.x,pytorch","A_Id":72249080,"CreationDate":"2020-04-04T00:31:00.000","Title":"How can I access a submatrix specified by row and column index vectors from a matrix (2D tensor) in pytorch?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have 120,000 csv inside my AWS EC2 instance, each containing 120,000 rows. I can't insert each of them as is into my AWS RDS postgresql DB, that will be 120,000^2 = 14,400,000,000 records. Each csv is about 2 MB.\nMy approach is:\n\nPython script that converts 120,000 records into just 1 record (list of dictionary) for each csv (now 5 MB after condensing the data) with the help of pandas library\nThe python script then insert each csv's 1 record into AWS postgresql database via pandas.to_sql (which uses sqlalchemy\nI use python multiprocessing module to fully utilize my AWS EC2 to speed up data insertion\nI did not create additional indexes in order to speed up my data insertion\nI use AWS EC2 instance with up to 25GB of network connection\n\nMy observation is:\n\nAt the beginning, my code will insert 50 csv per min, which is decent speed\nHowever, right now, with 50k csv being inserted, it only insert 1k csv in 5 hours, about 3.33 csv per min\nI tried using psql \\copy and realized that it takes between 30-50 sec to insert 1 csv, that's slower than my script that converts the data and insert into the DB directly\n\nI am not sure how I can speed up things up.","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":180,"Q_Id":61028971,"Users Score":2,"Answer":"The reason the database performance drop from 50 to 3.33 csv per min is because of the AWS RDS instance class.\nI am using db.t2.micro class, which I just learnt that it's limited by CPU credits. After I change the instance class to t3, my code is back to 50 csv per min.\n\nAmazon RDS T3 DB instances run in Unlimited mode, which means that you will be charged if your average CPU utilization over a rolling 24-hour period exceeds the baseline of the instance. CPU Credits are charged at $0.075 per vCPU-Hour. The CPU Credit pricing is the same for all T3 instance sizes across all regions and is not covered by Reserved Instances.\n\nConsidering that my code takes <1 sec to execute, and only 1 record to insert each time. pandas.to_sql shouldn't be the bottleneck. Though I do believe using SQLAlchemy will perform better than pandas.to_sql. For the same reason psycopg2 performs better than SQLAlchemy.\nIn short, this is an issue due to hardware rather than software. Fix it by upgrading to a more powerful instance. Thanks.","Q_Score":1,"Tags":"python,database,postgresql,amazon-web-services,multiprocessing","A_Id":61039956,"CreationDate":"2020-04-04T13:40:00.000","Title":"Speed up AWS PostgreSQL insertion via Python script","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I recently created an environment in PyCharm using anaconda and i'm using Python version 3.6. I want to import tensorflow but unfortunately i keep getting the error message \"ModuleNotFoundError: No module named 'tensorflow'\". I installed tensorflow versions (1.20 & 1.15) on my environment with no major issues, i also tried and added both in the Project Interpreter window successfully but when i run my program i keep getting that error. Anyone know a good way to fix this?","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":325,"Q_Id":61030730,"Users Score":2,"Answer":"If you get this error, you have installed everything in one environment but you work in another. \nTry installing tensorflow from another command line (in another shell).","Q_Score":0,"Tags":"python,tensorflow,pycharm","A_Id":61030822,"CreationDate":"2020-04-04T15:54:00.000","Title":"Installed tensorflow in an anaconda env but cannot import (Tensorflow 1.15, Python 3.6, PyCharm)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working on a project, which requires me to build a UI for a search engine. Elasticsearch is my choice. After indexing data and doing search queries, I also implement a function so that, if the user ticks on a result that is not relevant, I will reduce the score of that specific data in elasticsearch. However, when doing the second search with the same query, the order of search results remained the same. The reason is that even though the score is updated, the order of the data in elasticsearch index remained unchanged.\nHow do I reflect the score changes without having to reindex the whole thing again?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":162,"Q_Id":61036904,"Users Score":0,"Answer":"You could add a bool \/ should query. There you perform a term query with a boosting.\nThis is how you change the order depending on the search.","Q_Score":1,"Tags":"python,elasticsearch,scoring,relevance","A_Id":61065640,"CreationDate":"2020-04-05T01:21:00.000","Title":"Update Score based on interactive feedback for Elasticsearch","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"As raw data we have measurements m_{i,j}, measured every 30 seconds (i=0, 30, 60, 90,...720,..) for every subject j in the dataset.\nI wish use TSFRESH (package) to extract time-series features, such that for a point of interest at time i, features are calculated based on symmetric rolling window. \nWe wish to calculate the feature vector of time point i,j based on measurements of 3 hours of context before i and 3 hours after i. \nThus, the 721-dim feature vector represents a point of interest surrounded by 6 hours \u201ccontext\u201d, i.e. 360 measurements before and 360 measurements after the point of interest.\nFor every point of interest, features should be extracted based on 721 measurements of m_{i,j}.\nI've tried using rolling_direction param in roll_time_series(), but the only options are either roll backwards or forwards in \u201ctime\u201d - I'm looking for a way to include both \"past\" and \"future\" data in features calculation.","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":995,"Q_Id":61041024,"Users Score":1,"Answer":"If I understand your idea correctly, it is even possible to do this with only one-sided rolling. Let's try with one example:\nYou want to predict for the time 8:00 - and you need for this the data from 5:00 until 11:00.\n If you roll through the data with a size of 6h and positive rolling direction, you will end up with a dataset, which also includes exactly this part of the data (5:00 to 11:00). Normally, it would be used to train for the value at 11:00 (or 12:00) - but nothing prevents you to use it for predicting the value at 8:00.\nBasically, it is just a matter of re-indexing.\n(Same is actually true for negative rolling direction)","Q_Score":0,"Tags":"python,pandas,time-series,feature-extraction,tsfresh","A_Id":61195646,"CreationDate":"2020-04-05T10:15:00.000","Title":"TSFRESH - features extracted by a symmetric sliding window","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a question related to the data.describe() method in pandas. It gives you the relevant descriptive statistics of your dataset such as standard deviation. How does it tell if your data is from a population or a sample?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":49,"Q_Id":61043180,"Users Score":0,"Answer":"As far as I know, the .describe() method gives you always the stats for your specific sample (drawn in the dataframe). It doesn't make inference about the population","Q_Score":0,"Tags":"python,pandas,python-2.7,dataframe,statistics","A_Id":61043236,"CreationDate":"2020-04-05T13:14:00.000","Title":"How does the data.describe() method in pandas differentiate between population and sample data?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to understand what kind of image preprocessing is required when using one of the base networks provided by keras.application whith tensorflow compat.v1 module\nIn particular, I'm interested about the functions that converts each pixel channel value in the range [-1,1] or similar. I have digged in the code and it seems Tensorflow relies on Keras which, on other hand, should have 3 differents functions: one for tf, one for caffe and the last for torch, meaning not specific ones for each base network\nUp until now I have just re-implemented the function for tensorflow (value = value\/127.5 - 1) but I also read about others discussing something else (e.g. value = value\/255), nothing \"official\" tho. I have started to have some doubts regarding what I'm doing because, after switching to ResNet50, I can't seem to obtain decent results in contrast to several papers I'm following. I would like to have a definitive idea about the topic, any help would be much appreciated","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":30,"Q_Id":61047716,"Users Score":0,"Answer":"Tensorflow provides the preprocessing function for models in keras.applications, called preprocess_input. For example, an image can be preprocessed for InceptionV3 using tf.keras.applications.inception_v3.preprocess_input.","Q_Score":0,"Tags":"python,tensorflow,tf.keras","A_Id":61049604,"CreationDate":"2020-04-05T18:46:00.000","Title":"Does Tensorflow use specific image preprocessing normalization for each keras.application network?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"is there any pretrained vector for particular topic only? for example \"java\", so i want vectors related java in file. mean if i give input inheritance then cosine similarity show me polymorphism and other related stuff only! \ni am using corpus as GoogleNews-vectors-negative300.bin and Glove vectors. still not getting related words.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":320,"Q_Id":61048035,"Users Score":0,"Answer":"Yes, you can occasionally find other groups' pre-trained vectors for download, which may have better coverage of whatever problem domains they've been trained on: both more specialized words, and word-vectors matching the word sense in that domain. \nFor example, the GoogleNews word-vectors were trained on news articles circa 2012, so its vector for 'Java' may be dominated by stories of the Java island of Indosnesia as much as the programming language. And many other vector-sets are trained on Wikipedia text, which will be dominated by usages in that particular reference-style of writing. But there could be other sets that better emphasize the word-senses you need. \nHowever, the best approach is often to train your own word-vectors, from a training corpus that closely matches the topics\/documents you are concerned about. Then, the word-vectors are well-tuned to your domain-of-concern. As long as you have \"enough\" varied examples of a word used in context, the resulting vector will likely be better than generic vectors from someone else's corpus. (\"Enough\" has no firm definition, but is usually at least 5, and ideally dozens to hundreds, of representative, diverse uses.)\nLet's consider your example goal \u2013 showing some similarity between the ideas of 'polymorphism' and 'input inheritance'. For that, you'd need a training corpus that discusses those concepts, ideally many times, from many authors, in many problem-contexts. (Textbooks, online articles, and Stack Overflow pages might be possible sources.) \nYou'd further need a tokenization strategy that manages to create a single word-token for the two-word concept 'input_inheritance' - which is a separate challenge, and might be tackled via (1) a hand-crafted glossary of multi-word-phrases that should be combined; (2) statistical analysis of word-pairs that seem to occur so often together, they should be combined; (3) more sophisticated grammar-aware phrase- and entity-detection preprocessing. \n(The multiword phrases in the GoogleNews set were created via a statistical algorithm which is also available in the gensim Python library as the Phrases class. But, the exact parameters Google used have not, as far as I know, been revealed.And, good results from this algorithm can require a lot of data and tuning, and still result in some combinations that a person would consider nonsense, and missing others that a person would consider natural.)","Q_Score":0,"Tags":"java,python,nlp,word2vec,glove","A_Id":61065738,"CreationDate":"2020-04-05T19:09:00.000","Title":"Pre trained vectors, nlp, word2vec, word embedding for particular topic?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I run two line code, can you let me know what is the issue in importing the scipy in jupyter notebook\nPython Version is 3.7.7\n! pip install scipy\nRequirement already satisfied: scipy in c:\\users\\user\\appdata\\local\\programs\\python\\python37\\lib\\site-packages (1.4.1)\nRequirement already satisfied: numpy>=1.13.3 in c:\\users\\user\\appdata\\local\\programs\\python\\python37\\lib\\site-packages (from scipy) (1.18.2)\nimport scipy\nImportError Traceback (most recent call last)\n in \n----> 1 import scipy\nc:\\users\\user\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\scipy__init__.py in \n 154 # This makes \"from scipy import fft\" return scipy.fft, not np.fft\n 155 del fft\n--> 156 from . import fft\nc:\\users\\user\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\scipy\\fft__init__.py in \n 74 from future import division, print_function, absolute_import\n 75 \n---> 76 from ._basic import (\n 77 fft, ifft, fft2, ifft2, fftn, ifftn,\n 78 rfft, irfft, rfft2, irfft2, rfftn, irfftn,\nc:\\users\\user\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\scipy\\fft_basic.py in \n----> 1 from scipy._lib.uarray import generate_multimethod, Dispatchable\n 2 import numpy as np\n 3 \n 4 \n 5 def _x_replacer(args, kwargs, dispatchables):\nc:\\users\\user\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\scipy_lib\\uarray.py in \n 25 from uarray import _Function\n 26 else:\n---> 27 from ._uarray import *\n 28 from ._uarray import _Function\n 29 \nc:\\users\\user\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\scipy_lib_uarray__init__.py in \n 112 \"\"\"\n 113 \n--> 114 from ._backend import *\n 115 \n 116 version = '0.5.1+5.ga864a57.scipy'\nc:\\users\\user\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\scipy_lib_uarray_backend.py in \n 13 import inspect\n 14 import functools\n---> 15 from . import _uarray # type: ignore\n 16 import copyreg # type: ignore\n 17 import atexit\nImportError: DLL load failed: The specified module could not be found.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":702,"Q_Id":61049268,"Users Score":0,"Answer":"check to see if you are pip installing it with the right version and distribution of python that Jupiter is using.\nVisual Studio Code, Anaconda\/Jupyter, etc sometimes has their own installation of python that is not the one you might have downloaded at some point from the python website.\nIf you are using pip to install things, pip might be installed for another version you are using and adding it to the package list of another python installation.","Q_Score":0,"Tags":"python,scipy,jupyter-notebook","A_Id":61049319,"CreationDate":"2020-04-05T20:45:00.000","Title":"Cannot Import scipy in Jupyter Notebook","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working on a credit card fraud detection model and have labeled data containing orders for an online store. The columns I am working with is: Customer Full Name, Shipping Address and Billing Address (city, state, zip, street), Order \nQuantity, Total Cost, and an indicator on whether or not the order was discovered to be fraud. \nThe problem is the fact that 98%+ of the transactions are not fraudulent- the data set is highly imbalanced. I understand this is a classification problem, however I am unsure where to start with the columns I am working with and the imbalance of the data. \nI would appreciate any suggestions of appropriate classification algorithms for this use case and how to deal with the imbalanced data. There are several articles I found when searching for how to solve this, however most are working with a Kaggle dataset that has very different columns (due to security reasons for not allowing the information to be public). \nThanks!","AnswerCount":2,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":519,"Q_Id":61052293,"Users Score":2,"Answer":"In my mind, there are 2 directions for deal with the imbalanced dataset for anti-fraud cases:\n\nUsing Supervised ML algorithms for Fraud prediction: try to predict a class (fraud\/not fraud) of sample\nUsing Unsupervised ML algorithms Anomaly detection: try to detect unusual customer\/merchant behavior or payments activity.\n\nSupervised Learning (SL) approach\nIf you use Supervised ML algorithms (e.g. Logistic regression, Random forest, Gradient Boosted Trees) then you need to apply one or more tricks:\n\nBefore training ML model:\n\nOversampling - adding more samples of the minority class: RandomOverSampler, SMOTE (generate synthetic samples) methods in imblearn package\nUndersampling - removing some observations of the majority class:\nRandomUnderSampler method in imblearn package\nCombine Oversampling and Undersampling methods.\n\n\nWhile training ML model:\n\nPass weights parameter in the train model method (set higher weights to minor class samples).\n\n\nAfter training ML model:\n\nDo not use accuracy to estimate the trained model\nUse recall, precision, F1 score, or\/and AUC PR (precision-recall curve ) to robust model evaluation.\n\n\n\nUnsupervised Learning (UL) approach\nUnsupervised algorithms don't require the label in dataset. That's a reason why there is no imbalanced classes problem.\nBut unlike the SL-based models, UL-based models haven't prediction as output. You need additional actions to interpret output of UL-based models.\nThe following algorithms most probably will be useful:\n\nAnomaly detection methods:\n\nOne-class SVM\nIsolation forest or iForest\nLocal Outlier Factor\n\n\nNeural Networks methods:\n\nAutoencoder-based networks, e.g. AE, VAE\nDBN or Deep Belief Network,\nGAN or Generative Adversarial Networks\nSelf-organized Maps.","Q_Score":1,"Tags":"python,machine-learning,classification,data-science,fraud-prevention","A_Id":68881403,"CreationDate":"2020-04-06T02:54:00.000","Title":"Python Fraud Detection Classification Algorithms","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm in the middle of a school project on computer vision that consists on two parts. The first part is the semantic segmentation of a ground picture (small picture) and the second part consists in being able to locate that small picture in a pre-loaded and pre-segmented map (big picture) with the output being the coordinates and the orientation of the small picture inside the big one.\nThe first part is already done and working fine, but I have no idea how to approach the second part of the project. When the small picture's orientation is the same as in the original map, I can easily find it using brute force, but problems start when the small image is rotated respect to the original map.\nI have no idea how to approach this problem, any word, topic or algorithms I could use to look for more information online would be appreciated :)\nI'm working on Matlab with the Deep learning and computer vision toolboxes, but I could easily change to Python if needed or if it could be substantially easier.\nThanks to everyone reading this!","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":271,"Q_Id":61067512,"Users Score":1,"Answer":"By the word \"brute force\", I don't understand what you mean. If you provide more detail may be I be able to provide more details or more alogrithms. However if you want to find search image in side same or another image you can use these algorithms: \n- SIFT \n- SURF \n- ORB \n- BRISK \n- FREAK \n- Siamese networks \nMost of these algorithms (expect last one) try to find some key points that are robust against rotations, noise, brightness variations, blur, ... and finally match them using distance measurement such as hamming, euclidean, manhatan, .... \nI my self the prefer last one in terms of accuracy and not needing playing with too many hyper-parameters. For Siamese networks you need training. It means labeling and GPU. SIFT and SURF are famous for image matching. For more details you can read their main articles. I wrote a paper on copy-move forgery that finds copy-pasting an part of image for fraud\/forgery purpose. You can find a lot of approaches for your purpose from papers of this field.","Q_Score":0,"Tags":"python,matlab,computer-vision,slam","A_Id":61110494,"CreationDate":"2020-04-06T19:29:00.000","Title":"locating a picture inside a bigger picture","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"After we have converted our categorical variables to dummy variables for training the model. We tend to find feature importance. But sklearn's model.feature_importance_ object returns feature impotance for every dummy variable, rather than the original categorical variable. How to fix this?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":35,"Q_Id":61072251,"Users Score":0,"Answer":"Because the dummy variables are used to train the model, you cannot find the importance of the original categorical variable. It is mathematically impossible thing.","Q_Score":0,"Tags":"python,pandas,machine-learning,scikit-learn,data-science","A_Id":61072337,"CreationDate":"2020-04-07T03:16:00.000","Title":"How can I find Feature importance from sklearn api, after I have converted my categorical variables into dummy variables?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I currently have installed Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32. I also have Anaconda installed with its own python version.\nI am trying to install tensorflow with below code (also tried pip install tensorflow). I have successfully installed nltk, numpy and tflearn. I am now trying to install tensorflow and the following message is what I get. I have trying several times over the past hour but I keep getting the same error at different points (percentage completed).\nC:\\Windows\\system32>pip3 install --upgrade tensorflow\nCollecting tensorflow\nDownloading tensorflow-2.1.0-cp36-cp36m-win_amd64.whl (355.9 MB)\n|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 | 336.2 MB 251 kB\/s eta 0:01:19\nERROR: Exception:\nTraceback (most recent call last):\nFile.....\n....\nsocket.timeout: The read operation timed out\nDuring handling of the above exception, another exception occurred:\n....\nraise ReadTimeoutError(self._pool, None, \"Read timed out.\") \npip._vendor.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='files.pythonhosted.org', \nport=443): Read timed out.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":248,"Q_Id":61086647,"Users Score":0,"Answer":"I discovered that issue was indeed the speed of my internet. I downloaded it when the internet was much faster and it downloaded completely.","Q_Score":2,"Tags":"python,tensorflow,pip,installation,command-prompt","A_Id":61092921,"CreationDate":"2020-04-07T18:12:00.000","Title":"How can I resolve Time Out Error when installing Tensorflow in Command Prompt","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Someone can help me\nimpossible to catch csv in my PyCharm \nit tells me :\"an error occured: could not a find a version that satisfies the requirement csv (from version:none)\ni succeed to get numpy matplotlib pandas but no csv.\nit warns me about \"to use the correct version of 'pip' installed for my Python interpreter located.\"\nIf someone can help me, bless him(her)\nthks :)\nVersions installed:\npython 3 8 1 \/\npycharm 11 0 5 + 10 b520 38 \/\npandas 1 0 3 \/\npip 20 0 2","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":130,"Q_Id":61087407,"Users Score":0,"Answer":"Hi guys first thank you for your answer :)\nI am using Pycharm\nI do this to install csv:\nFile>Settings>MyProject>Project Interpreter>Clic Add + Enter 'csv'> Install Packages\nand it tells me: an Error Occured \nImportError: cannot import name 'SourceDistribution' from 'pip._internal.distributions.source' (C:\\Users\\admin\\AppData\\Roaming\\Python\\Python38\\site-packages\\pip_internal\\distributions\\source__init__.py)","Q_Score":0,"Tags":"python,csv","A_Id":61118207,"CreationDate":"2020-04-07T18:57:00.000","Title":"I can't get (install\/import) csv from my Pycharm Setting Packages","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"Is it possible to disable MLFlow temporarily for debugging code or adding new features? If it is not disabled it saves a bunch of executions not actually usefull or unfinished executions.\nOr is the best strategy to use similar code that doesn't call mlflow.start_run()?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":496,"Q_Id":61088651,"Users Score":1,"Answer":"Not sure if there is an explicit way to disable mlflow_start_run() but one strategy is to use a debug flag that only calls part of that starts an mlflow_startu_run().","Q_Score":1,"Tags":"python,machine-learning,mlflow","A_Id":61128368,"CreationDate":"2020-04-07T20:14:00.000","Title":"How to disable MLFlow temporarily?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"So working on some research on nursing homes which are often owned by a chain. We have a list of 9,000 + nursing homes corporate ownership. Now, if I was MERGING this data into anything I think this would not be too much of a challenge, but I am being asked to group the facilities that are associated with each other for another analysis. \nFor example:\nABCM\nABCM CORP\nABCM CORPORATION\nABCM CORPORATE\nI have already removed all the extra spaces, non-alphanumeric, and upcased everything. Just trying to think of a way within like a 90% accuracy I can do this. The within the same variable is the part that is throwing me off. I do have some other details such as ownership, state, zip, etc. I use STATA, SAS, and Python if that helps!","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":56,"Q_Id":61090085,"Users Score":1,"Answer":"welcome to SO. \nString matching is - broadly speaking - a pain, whatever the software you are using, and in most cases need a human intervention to yield satisfactory results. \nIn Stata you may want to try matchit (ssc install matchit) for fuzzy string merge. I won't go into the details (I suggest you to look at the helpfile, which is pretty well-outlined), but the command returns each string matched with multiple similar entries - where \"similar\" depends on the chosen method, and you can specify a threshold for the level of similarities kept or discarded. \nEven with all the above options, though, the final step is up to you: my personal experience tells me that no matter how restrictive you are, you'll always end up with several \"false positives\" that you'll have to work yourself!\nGood luck!","Q_Score":1,"Tags":"python,sas,stata","A_Id":61097693,"CreationDate":"2020-04-07T22:02:00.000","Title":"Data Cleanse: Grouping within variable company names","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have huge array objects that are pickled with the python pickler.\nI am trying to unpickle them and reading out the data in a for loop.\nEvery time I am done reading and assesing, I delete all the references to those objects.\nAfter deletion, I even call gc.collect() along with time.sleep() to see if the heap memory reduces.\nThe heap memory doesn't reduce pointing to the fact that, the data is still referenced somewhere within the pickle loading. After 15 datafiles(I got 250+ files to process, 1.6GB each) I hit the memory error.\nI have seen many other questions here, pointing out a memory leak issue which was supposedly solved.\nI don't understand what is exactly happening in my case.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":103,"Q_Id":61091634,"Users Score":0,"Answer":"Python memory management does not free memory to OS till the process is running.\nRunning the for loop with a subprocess to call the script helped me solved the issue.\nThanks for the feedbacks.","Q_Score":0,"Tags":"python,memory-leaks,garbage-collection,pickle,heap-memory","A_Id":61114512,"CreationDate":"2020-04-08T00:45:00.000","Title":"Memory leak on pickle inside a for loop forcing a memory error","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am analyzing histology tissue images stained with a specific protein marker which I would like to identify the positive pixels for that marker. My problem is that thresholding on the image gives too much false positives which I'd like to exclude.\nI am using color deconvolution (separate_stains from skimage.color) to get the AEC channel (corresponding to the red marker), separating it from the background (Hematoxylin blue color) and applying cv2 Otsu thresholding to identify the positive pixels using cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU), but it is also picking up the tissue boundaries (see white lines in the example picture, sometimes it even has random colors other than white) and sometimes even non positive cells (blue regions in the example picture). It's also missing some faint positive pixels which I'd like to capture.\nOverall: (1) how do I filter the false positive tissue boundaries and blue pixels? and (2) how do I adjust the Otsu thresholding to capture the faint red positives?\nAdding a revised example image -\n\ntop left the original image after using HistoQC to identify tissue regions and apply the mask it identified on the tissue such that all of the non-tissue regions are black. I should tru to adjust its parameters to exclude the folded tissue regions which appear more dark (towards the bottom left of this image). Suggestions for other tools to identify tissue regions are welcome.\ntop right hematoxylin after the deconvolution\nbottom left AEC after the deconvolution\nbottom right Otsu thresholding applied not the original RGB image trying to capture only the AEC positives pixels but showing also false positives and false negatives\n\nThanks","AnswerCount":4,"Available Count":1,"Score":0.049958375,"is_accepted":false,"ViewCount":499,"Q_Id":61092050,"Users Score":1,"Answer":"I ended up incorporating some of the feedback given above by Chris into the following possible unconventional solution for which I would appreciate getting feedback (to the specific questions below but also general suggestions for improvement or more effective\/accurate tools or strategy):\n\nDefine (but not apply yet) tissue mask (HistoQC) after optimizing HistoQC script to remove as much of the tissue folds as possible without removing normal tissue area\nApply deconvolution on the original RGB image using hax_from_rgb\nUsing the second channel which should correspond to the red stain pixels, and subtract from it the third channel which as far as I see corresponds to the background non-red\/blue pixels of the image. This step removes the high values in the second channel that which up because of tissue folds or other artifacts that weren't removed in the first step (what does the third channel correspond to? The Green element of RGB?)\nBlur the adjusted image and threshold based on the median of the image plus 20 (Semi-arbitrary but it works. Are there better alternatives? Otsu doesn't work here at all)\nApply the tissue regions mask on the thresholded image yielding only positive red\/red-ish pixels without the non-tissue areas\nCount the % of positive pixels relative to the tissue mask area\n\nI have been trying to apply, as suggested above, the tissue mask on the deconvolution red channel output and then use Otsu thresholding. But it failed since the black background generated by the applying the tissue regions mask makes the Otsu threshold detect the entire tissue as positive. So I have proceeded instead to apply the threshold on the adjusted red channel and then apply the tissue mask before counting positive pixels. I am interested in learning what am I doing wrong here.\nOther than that, the LoG transformation didn't seem to work well because it produced a lot of stretched bright segments rather than just circular blobs where cells are located. I'm not sure why this is happening.","Q_Score":2,"Tags":"python,opencv,image-processing,computer-vision,scikit-image","A_Id":61293526,"CreationDate":"2020-04-08T01:37:00.000","Title":"Identifying positive pixels after color deconvolution ignoring boundaries","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have legacy code which uses tensorflow 1.0.1 version in my ipython notebook.\nI have a requirements.txt file to install dependencies.\nSo I run the cell -!pip3 install -r requirements.txt in my Colab notebook to run this legacy code.\nrequirements.txt has following dependencies,\n\ntensorflow-gpu==1.0.1\nnltk==3.2.5\nmatplotlib==2.0.2\nscipy==0.19.1\nscikit-learn==0.19.0\njupyter==1.0.0\n\nAfter running the above cell in my notebook I get a message to restart the runtime to setup the environment for TensorFlow 1.0.1. \nAfter restarting the kernel I always get the runtime in the \"Busy\" state.\nEven though I tried terminating the session to start again. It does not help because I have to restart the kernel in new session too.\nCan anyone clarify what should I do to avoid \"staying Busy state\" after kernel restart?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":1742,"Q_Id":61093037,"Users Score":1,"Answer":"Try dropping the jupyter install. It's likely that's installing deps that are incompatible with Colab, which results in your backend becoming wedged.\nWhen in this state, you can reset your runtime using the Runtime -> Factory reset runtime menu.","Q_Score":0,"Tags":"python,tensorflow,google-colaboratory","A_Id":61093101,"CreationDate":"2020-04-08T03:50:00.000","Title":"Colab run time stays \"Busy\" state after restarting the run time","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"When using dask.to_parquet(df, filename) a subfolder filename is created and several files are written to that folder, whereas pandas.to_parquet(df, filename) writes exactly one file.\nCan I use dask's to_parquet (without using compute() to create a pandas df) to just write a single file?","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":3082,"Q_Id":61108376,"Users Score":2,"Answer":"Writing to a single file is very hard within a parallelism system. Sorry, such an option is not offered by Dask (nor probably any other parallel processing library).\nYou could in theory perform the operation with a non-trivial amount of work on your part: you would need to iterate through the partitions of your dataframe, write to the target file (which you keep open) and accumulate the output row-groups into the final metadata footer of the file. I would know how to go about this with fastparquet, but that library is not being much developed any more.","Q_Score":4,"Tags":"python,pandas,dask,parquet","A_Id":61109619,"CreationDate":"2020-04-08T19:19:00.000","Title":"Force dask to_parquet to write single file","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to pass the entire dataset to Keras fit function using batch_size parameter equals to length of the dataset, but it seems that process only 1 sample because under the Epoch 1\/50 print of the fit function I see 1\/1 and not, for example, 500\/500, where 500 is the dataset length. How could I do?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":28,"Q_Id":61111263,"Users Score":0,"Answer":"The progress displayed in the terminal output is for batches, so what you see is expected: in that epoch you are processing batch 1 of 1, where that batch has 500 samples in it. You can of course recover the number of samples processed by multiplying by your batch size.","Q_Score":0,"Tags":"python,keras","A_Id":61114180,"CreationDate":"2020-04-08T22:48:00.000","Title":"Pass entire dataset to Keras fit","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"This question has been asked in different ways many times, many people approach this problem in different ways. Which is why I am unsure of my methodology, it would be good if someone could tell me if I am doing things correctly.\nThe steps that I follow are -\n\nSet up stereo camera pair.\nCalibrate both the cameras individually to get their camera\nmatrices, distortion coefficients, using calibrateCamera\nThen we calculate R, T, E, F\n using stereoCalibrate\nCalculate R1,R2,P1,P2 and Q using stereoRectify\nSince I want to find the 3D coordinates of a specific point in my\nscene, I extract the coordinates of that point in both the images,\nand after that I use triangulatePoints to get the 3D points in\nhomogenous coordinates.\n\nAre the steps that I'm following correct? I've been having problems with the OpenCV documentation so it took me a while to formulate the steps, digging through the documentation. People have approached this problem in OpenCV in different ways, some have even constructed the Fundamental and Essential Matrices using some of the helper functions in the OpenCV documentation, but I think the stereoCalibrate and stereoRectify use these helper functions themselves.","AnswerCount":2,"Available Count":2,"Score":0.0996679946,"is_accepted":false,"ViewCount":233,"Q_Id":61111435,"Users Score":1,"Answer":"The steps are theoretically correct. You won't get any good results using them.\nMy advice would be to get a ready-made stereo camera (ZED or RealSense comes to mind), it already has everything you need, so you don't have to calibrate or calculate, just use their libraries and get some results. Which won't be perfect, but it will give you a good start.\nOnce you played enough with the stereo camera, you'll have a better understanding where the most problems are, and how to approach them.","Q_Score":0,"Tags":"python,opencv,computer-vision,stereo-3d","A_Id":61112081,"CreationDate":"2020-04-08T23:07:00.000","Title":"Steps for 3D Reconstruction?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"This question has been asked in different ways many times, many people approach this problem in different ways. Which is why I am unsure of my methodology, it would be good if someone could tell me if I am doing things correctly.\nThe steps that I follow are -\n\nSet up stereo camera pair.\nCalibrate both the cameras individually to get their camera\nmatrices, distortion coefficients, using calibrateCamera\nThen we calculate R, T, E, F\n using stereoCalibrate\nCalculate R1,R2,P1,P2 and Q using stereoRectify\nSince I want to find the 3D coordinates of a specific point in my\nscene, I extract the coordinates of that point in both the images,\nand after that I use triangulatePoints to get the 3D points in\nhomogenous coordinates.\n\nAre the steps that I'm following correct? I've been having problems with the OpenCV documentation so it took me a while to formulate the steps, digging through the documentation. People have approached this problem in OpenCV in different ways, some have even constructed the Fundamental and Essential Matrices using some of the helper functions in the OpenCV documentation, but I think the stereoCalibrate and stereoRectify use these helper functions themselves.","AnswerCount":2,"Available Count":2,"Score":1.2,"is_accepted":true,"ViewCount":233,"Q_Id":61111435,"Users Score":1,"Answer":"As you said, everyone has their own way. The way I tried is, the first 4 steps were the same, but for calculating the 3d point I used the stereo matching algorithms that are present in OpenCV. Algorithms like StereoBM, StereoSGBM are implemented in OpenCV and it has provided an easy to use APIs. \nSo Once we get the disparity map from the stereo matching funciton, we can get the 3d coordinates by using reprojectImageTo3D API. It requires disparity map and Q matrix as inputs.","Q_Score":0,"Tags":"python,opencv,computer-vision,stereo-3d","A_Id":61368544,"CreationDate":"2020-04-08T23:07:00.000","Title":"Steps for 3D Reconstruction?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have trained the model and save this model to a file [ cats_and_dogs_small_1.h5 ]. How can I apply this model to a separate test data (Own created picture from my mobile phone)?\nCan you please help me with this?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":77,"Q_Id":61113360,"Users Score":0,"Answer":"Please provide more info. e.g Which framework are you using? Also, what do you mean by \"apply\" ? Do you wish to evaluate a new image using the trained model?","Q_Score":0,"Tags":"python,deep-learning,computer-vision,conv-neural-network","A_Id":61113468,"CreationDate":"2020-04-09T03:12:00.000","Title":"apply a CNN .h5 format model on the new data set","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am converting a dictionary to pandas object with to_csv. I have both way of doing this \n1 - by writing file in disk(with open statement)\n2 - by writing in memory (StringIO,BytesIO) \nI have used it in both way creating file in disk and using StringIO to convert to pandas object. I tried to read comparisons between these three, but bit confused which one is faster so i can use it in production to process tons of data.","AnswerCount":2,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":453,"Q_Id":61114188,"Users Score":2,"Answer":"Writing and reading from memory is fast. But keep in mind that you have tons of data. So storing all that in-memory might take up all your memory and might make the system slow or might throw errors due to Out of Memory. So, analyze and understand which all data to be put in memory and which all to be written to files.","Q_Score":0,"Tags":"python,python-3.x","A_Id":61114220,"CreationDate":"2020-04-09T04:49:00.000","Title":"Which one is faster in production? file on disk vs file in memory(StringIO,BytesIO)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working on logistic regression project where I have 850 observations and 8 variables and in this, I found 150 missing values and I have decided to use these values as test data. How can I take only missing values as test data in python?\nI am still learning data science if there's a mistake in this approach please let me know.\nThank you :)","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":46,"Q_Id":61119977,"Users Score":0,"Answer":"You could use the pd.isna() from pandas library.\nIt will return a boolean array that you can use for filtering your data.","Q_Score":0,"Tags":"python,regression,logistic-regression","A_Id":61120126,"CreationDate":"2020-04-09T11:20:00.000","Title":"How to select only missing values for testing the model?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I need to fit a horizontal line into my matplotlib plot in python, couldn't find any simple method. so, was wondering if there is any simple way to fit a line of specific slope in matplotlib.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":92,"Q_Id":61122713,"Users Score":1,"Answer":"horizontal line: plt.axhline(.5)\nTo fit a scatter plot, you can use seaborn.regplot","Q_Score":1,"Tags":"python,matplotlib,curve-fitting,data-fitting","A_Id":61122915,"CreationDate":"2020-04-09T13:50:00.000","Title":"Fitting a line of specific slope in matplotlib","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have prepared a time series model using FB Prophet for making forecasts. The model forecasts for the coming 30 days and my data ranges from Jan 2019 until Mar 2020 both months inclusive with all the dates filled in. The model has been built specifically for the UK market\nI have already taken care of the following:\n\nSeasonality\nHolidaying Effect\n\nMy question is, that how do I take care of the current COVID-19 situation into the same model? The cases that I am trying to forecast are also dependent on the previous data at least from Jan 2020. So in order to forecast I need to take into account the current coronavirus situation as well that would impact my forecasts apart from seasonality and holidaying effect.\nHow should I achieve this?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":1115,"Q_Id":61125123,"Users Score":0,"Answer":"I have had the same issue with COVID at my work with sales forecasting. The easy solution for me was to make an additional regressor which indicates the COVID period, and use that in my model. Then my future is not affected by COVID, unless I tell it that it should be.","Q_Score":1,"Tags":"python-3.x,prediction,forecasting,facebook-prophet","A_Id":68980927,"CreationDate":"2020-04-09T15:52:00.000","Title":"Python time series using FB Prophet with covid-19","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am new to ML and currently using Python. If I am testing a set of interventions on a certain outcome . What kind of tools\/Python programs should I start learning to begin to determine which intervention (or combination of interventions) is most likely to predict a certain outcome. \nHere is an example: I want to test which interventions promote recycling behavior most effectively (outcome is 'yes' or 'no' recycling)...different combinations of interventions will be used (i.e phone call, email reminder, text prompt, etc). I want to determine which of these interventions (or which combination of interventions) was most successful at promoting recycling \nThanks everyone and stay healthy!","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":31,"Q_Id":61125226,"Users Score":1,"Answer":"\"Dimensionality reduction\" is the ML topic of reducing the number of features used to predict a response.\nFinding correlation with pandas.DataFrame.corr helps.","Q_Score":0,"Tags":"python,modeling,predictive","A_Id":61125414,"CreationDate":"2020-04-09T15:57:00.000","Title":"Determining which intervention is most predictive of outcome in python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I know I can output the contents of the sklearn classification_report as a dict and extract micro\/macro averaged scores along with scores for individual labels. \nHow can I get the counts for the associated confusion matrix inputs, specifically, TP, FN, and FP that go into the computations for the macro averaged measures? I have my vectors for y_pred and y_true, so I assume there is a way to get the desired parameters I want.\nThis is for a binary classification problem, but I will also need it for a multiclass task, as well.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":181,"Q_Id":61130759,"Users Score":0,"Answer":"Got it: \ntn, fp, fn, tp = confusion_matrix([0, 1, 0, 1], [1, 1, 1, 0]).ravel()\nand sklearn.metrics.multilabel_confusion_matrix","Q_Score":0,"Tags":"python,scikit-learn,confusion-matrix","A_Id":61131420,"CreationDate":"2020-04-09T21:49:00.000","Title":"How can I extract TP, FN, FP from classification_report","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to find all the possible unique combinations out of n elements, taken m at a time. I have used itertools.combinations for the same and I have n=85.\nSo when I'm finding combinations for m=5, the number of combinations produced are about 3 cr and it is taking a lot of time, since as of now, the elements are a list of strings, or more precisely, they're columns in the alphabetical fashion, not numerical indices. I am currently working with pandas and itertools.combinations, would like to know if the process of finding combinations could be parallelised, to give same results every time upon further calculations that I perform on the columns further, or whether GPU dataframes, like cuDF might optimise this, although it doesn't look like it. Also, could converting the column names into numbers and then converting it into a numpy array to work on while finding combinations work faster? \nPlease also suggest solutions where this could be done faster in some other programming language as well. \nNot a very good programmer. Would love to see some mathematical and programmatic solutions with a complexity analysis.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":147,"Q_Id":61134347,"Users Score":1,"Answer":"This is exactly a complexity analysis problem, and there's no way to parallelize it in a way that will be satisfying. With n=85 and m=5, there are 85^5 = 4437053125 possible combinations, including reversals and duplicates.\nThe fastest way that I know of using a GPU to explore this space is with cuGraph. Exploring all 4437053125 combinations is simply a breadth first search, though even with a GPU I expect it to take a very long time. \nArtificial Intelligence is the study of methods of finding useful solutions inside of problem spaces that are too big to fully explore. A* or greedy search could give you a good solution, quickly, assuming that there is some metric that you are trying to optimize among the 85^5 total combinations.","Q_Score":0,"Tags":"python,parallel-processing,multiprocessing,combinations,cudf","A_Id":61236526,"CreationDate":"2020-04-10T05:05:00.000","Title":"Is there a faster\/optimisable way to find unique combinations from a set\/list of unique elements in python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a binary image containing a single contiguous blob, with no holes. I would like create a polygon object based on the exterior edges of the edge pixels. I know how to get the edge pixels themselves, but I want the actual coordinates of the pixel boundaries, sorted clockwise or counter-clockwise. All of the pixels have integer coordinates. \nFor example, say I have a single pixel at (2,2). The vertices of the polygon would be:\n(2.5, 2.5)\n(2.5, 1.5)\n(1.5, 1.5)\n(1.5, 2.5)\n(2.5, 2.5)\nIs there an exact, non-approximate way to do this? Preferably in Python?","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":2436,"Q_Id":61149402,"Users Score":0,"Answer":"Based on the comments, here is the approach that I implemented:\n\nmultiply all pixel coordinates by 10, so that we'll only deal with integers.\n\nFor each pixel, generate the 4 corners by adding +\/- 5. For example, for (20,20), the corners are (25, 25) (25, 15) (15, 15) (15, 25) (25, 25). And store all the corners in a list.\n\nCount the occurrences of each corner. If the count is odd, it is a corner to the blob. Making the coordinates integers makes this step easy. Counting floats has issues.\n\nDivide the blob corner coordinates by 10, getting back the original resolution.\n\nSort the corners clockwise using a standard algorithm.","Q_Score":1,"Tags":"python,image,image-processing,polygon,scikit-image","A_Id":63367126,"CreationDate":"2020-04-10T22:10:00.000","Title":"Get pixel boundary coordinates from binary image in Python (not edges)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I installed opencv 4.3.0 from the source. It was installed sucessfully. \npkg-config --modversion opencv4 gives the output 4.3.0 . But when i try to import cv2 module in pythone it says cv2 module not found. I have Linux(Debian) in my system with python 3.8.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":187,"Q_Id":61152549,"Users Score":0,"Answer":"Likely has to do with where the package was installed. If you used apt-get, I would recommend removing and trying with pip install opencv-python. Aside from that, you can also try running sudo python3 and then importing.\nhope that helps!","Q_Score":0,"Tags":"python,linux,opencv","A_Id":61152598,"CreationDate":"2020-04-11T05:34:00.000","Title":"Python could not detect OpenCv installed in my system","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":1,"Web Development":0},{"Question":"I'm looking for a command to pick the last element of my matrix that is nonzero. Not the index of the value, but the actual value.\nIt's a (1001,50001) matrix where the last value of each column isn't the same.\nIt is not a dataframe, so preferably a numpy command.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":43,"Q_Id":61153359,"Users Score":0,"Answer":"I have a suggestion for that. Replace all non-zero values of your column with 1. Then find the last element that is equal to 1. That would be easy even using Unix using grep '1' file | tail -1 , etc. If however you are not allowed to modify the matrix values then you need to just extract this column and run the scripts for this column only. Good luck.","Q_Score":2,"Tags":"python,numpy","A_Id":61153604,"CreationDate":"2020-04-11T07:23:00.000","Title":"Python: Select last value of each column that is nonzero in a matrix","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a CSV file containing multiple columns(almost 100). How can I filter multiple columns at once using certain criteria in Python? To be more precise, many of the columns are of no use to me. How can the file be filtered?\nPS: I am a beginner user.","AnswerCount":4,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":1168,"Q_Id":61156308,"Users Score":0,"Answer":"You can parse the csv file as pandas dataframe and then play around. Please have a look at the pandas documentation on how to read csv files. You can extract the column you want based on their header names. Also you can apply mathematical operations in a fast way. Though, for large scale calculations, note that python is not suitable since each time you import your libraries.","Q_Score":1,"Tags":"python,pandas,dataframe","A_Id":61156355,"CreationDate":"2020-04-11T11:49:00.000","Title":"Deleting multiple columns of CSV files based on certain conditions on Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've a dataframe in-memory which has certain identifiers, using those identifiers i want to fetch only relevant data from a very large(500M rows) table persisted in a RDBMS(Sql server).\nWhat's the best way to do this? Definitely don't want to bring the entire table in-memory. And can't loop through either. If it was single column key to lookup, I could still think of building a comma-separated string and doing IN clause against that list but I've multiple fields that are identifiers.\nOnly option I see is saving dataframe into db, doing join on db server and bringing in data back. But seems so clunky. \nI've read about dask as an option, but not really sure about that one because bringing entire table in-memory\/disk still doesnt seem like an efficient technique to me","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":85,"Q_Id":61157467,"Users Score":1,"Answer":"Only option I see is saving dataframe into db, doing join on db server and bringing in data back. But seems so clunky.\n\nThis sounds like the most efficient option in terms of compute time.\n\nI've read about dask as an option, but not really sure about that one because bringing entire table in-memory\/disk still doesnt seem like an efficient technique to me\n\nIf your dataframe with the entries that you care about is small then Dask Dataframe probably won't read everything into memory at once. It will likely scan through your database intelligently in small space. The real cost of using Dask here is that you need to move data in and out of the database, which will be slow or fast depending on your database connector.\nI would try it out, and see how it performs.","Q_Score":0,"Tags":"python,sql,sql-server,pandas,dask","A_Id":61164672,"CreationDate":"2020-04-11T13:23:00.000","Title":"Joining in-memory dataframe with very large persisted table in a db?","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am learning object detection using R-CNN...\nI have the images and the annotation file which gives the bounding box for the object\nI understand these steps in R-CNN,\nUsing selective search to get the proposed regions\nMake all the region same size\nFeed those images in CNN \nSave the feature maps and feed to SVM for classification\n\nIn training, I took all the objects (only the objects from images not the background) and feed to the CNN and then train the feature maps in SVM for classification.\nIn every blogs, all are saying in R-CNN, there are three parts, \n1st -selective search\n2nd -CNN\n3rd -BBox Regression\nBut, I don't get the deep explanation of the BBox Regression.\nI understand the IOU(Intercept over Union) to check the BBox accuracy.\nCould you please help me to learn how this BBox Regression is used to get the coordinates of the object.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":93,"Q_Id":61161451,"Users Score":0,"Answer":"To explain about the BBox regression working which is as mentioned below. \nLike you mentioned it happens in multiple stages.\n\nSelective Search:\n\nGenerate initial sub-segmentation, we generate many candidates or part regions.\nUse greedy algorithm to recursively combine similar regions into larger ones.\nUse the generated regions to produce the final candidate region proposals. \n\nCNN and BBox Regression: \nThe regressor is a CNN with convolutional layers, and fully connected layers, but in the last fully connected layer, it does not apply sigmoid or softmax, which is what is typically used in classification, as the values correspond to probabilities. Instead, what this CNN outputs are four values (,,\u210e,), where (,) specify the values of the position of the left corner and (\u210e,) the height and width of the window. In order to train this NN, the loss function will penalize when the outputs of the NN are very different from the labelled (,,\u210e,) in the training set.","Q_Score":0,"Tags":"python,tensorflow,keras,conv-neural-network","A_Id":61714240,"CreationDate":"2020-04-11T18:04:00.000","Title":"Clarification in R-CNN","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I was just wondering how to go from mvnrnd([4 3], [.4 1.2], 300); in MATLAB code to np.random.multivariate_normal([4,3], [[x_1 x_2],[x_3 x_4]], 300) in Python. \nMy doubt namely lays on the sigma parameter, since, in MATLAB, a 2D vector is used to specify the covariance; whereas, in Python, a matrix must be used. \nWhat is the theoretical meaning on that and what is the practical approach to go from one to another, for instance, in this case? Also, is there a rapid, mechanical way?\nThanks for reading.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":1622,"Q_Id":61163753,"Users Score":0,"Answer":"Although python expects a matrix, it is essentially a symmetric covariance matrix. So it has to be a square matrix. \nIn 2x2 case, a symmetric matrix will have mirrored non diagonal elements.\nI believe in python, it should look like [[.4 1.2],[1.2 .4]]","Q_Score":1,"Tags":"python,matlab,covariance,normal-distribution","A_Id":61163964,"CreationDate":"2020-04-11T21:09:00.000","Title":"python equivalent to matlab mvnrnd?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"So I did the pip install through the terminal but when I import TensorFlow in IDLE or any .py file It can't find the tf module.. How do I download TF such that I can use it in IDLE to code?\nIf it makes a difference I'm using a MacBook Air","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":30,"Q_Id":61168042,"Users Score":0,"Answer":"I am assuming IDLE means IDE here.\nGenerally you should able to use teansorflow as soon as you have executed pip install tensorflow.\nCan you provide detail of IDE, and what error you are getting while importing tensorflow in IDE.\nPlease check below:\n-> Have you run command pip install tensorflow and it was executed successfully.\n-> Have you imported tensorflow in .py file with import tensorflow as tf.","Q_Score":0,"Tags":"python,tensorflow","A_Id":63203006,"CreationDate":"2020-04-12T07:18:00.000","Title":"Unable to use TensorFlow in python IDE","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to use Keras EarlyStopping however whenever I try to use restore_best_weights it comes up with an error:\n_init_() got an unexpected keyword argument 'restore_best_weights'\nI am using the most up to date Keras so I'm really unsure why this is happening.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":93,"Q_Id":61174910,"Users Score":0,"Answer":"What version of Keras are you using?\nIf you still do use Keras 2.3.1, please do ensure that your are not mixing keras and tensorflow versions.\nMore precisely, avoid using imports like from keras.layers import Conv2D and from tensorflow.keras.layers import MaxPool2D.\nIf the problem still persists after this issue, please use all the imports from tensorflow, i.e. from tensorflow.keras import .....\nAvoid using the plain Keras package, as it will become obsolete in the foreseeable future; the additional problem is that is nowhere near as well maintained as keras inside tensorflow.\nYou can uninstall it altogether from your environment.","Q_Score":0,"Tags":"python,tensorflow,machine-learning,keras,early-stopping","A_Id":61184943,"CreationDate":"2020-04-12T16:46:00.000","Title":"restore_best_weights issue Keras EarlyStopping","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"The main question is to find which leaf node each sample is classified. There are thousands of posts on using tree.apply. I am well aware of this function, which returns the index of the leaf node.\nNow, I would like to add the leaf index in the nodes of the graph (which I generate by using Graphviz).\nDrawing the enumeration technique used for the indexes won't work. The decision tree that I am developing is quite big. Therefore, I need to be able to print the leaf index in the graph.\nAnother option that I am open to is to generate an array with all the leaf indexes (in the same order) of the leaf nodes of the decision tree. Any hint on how to do this?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":455,"Q_Id":61175533,"Users Score":0,"Answer":"There is a parameter node_ids of the command export_graphviz. When this parameter is set to True, then the indexes are added on the label of the decision tree.","Q_Score":0,"Tags":"python,scikit-learn,decision-tree","A_Id":61177431,"CreationDate":"2020-04-12T17:33:00.000","Title":"How to find the index of each leaf or node in a Decision Tree?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to generate a connected, undirected graph that contains n vertices and m edges. In particular, I want to generate a graph with nodes that contain exactly one of each integer from 0 to n - 1.\nI've looked somewhat deeply on this site and could not find what I was looking for. I will appreciate any help offered. Thanks!","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":116,"Q_Id":61181627,"Users Score":2,"Answer":"I don't know about existing libraries but this is a solution from scratch. Suppose you have n nodes and m edges. To generate a simple (no duplicate edge), connected graph, m, n must satisfy this condition: \nn - 1 <= m <= n * (n - 1) \/ 2\nProcess (nodes are indexed from 0 to n - 1):\n\nGenerate a spanning tree to make sure the graph is connected. There are many ways (for example, Prufer sequence), but here is a simple way:\n\nfor i = 1 to n - 1:\n add_edge(i, randint(0, i - 1))\n\nTo make it look more random, you can shuffle the order of nodes first.\n\nAdd more edges until you have m edges.\n\nwhile there are less than m edges:\n a, b = randint(0, n - 1), randint(0, n - 1)\n if (a != b and edge(a, b) has not existed):\n add_edge(a, b)\n\nNote: randint(a, b) = a random integer in range [a, b].\nThe codes look simple but work very fast in practice. You can calculate expected number of iterations to see why.","Q_Score":0,"Tags":"python,algorithm,graph-algorithm","A_Id":61198390,"CreationDate":"2020-04-13T04:40:00.000","Title":"How do I make a function that accepts numVertices and numEdges then ALWAYS generates a connected graph?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have some text data for which I need to do sentiment classification. I don't have positive or negative labels on this data (unlabelled). I want to use the Gensim word2vec model for sentiment classification.\nIs it possible to do this? Because till now I couldn't find anything which does that?\nEvery blog and article are using some kind of labelled dataset (such as imdb dataset)to train and test the word2vec model. No one going further and predicting their own unlabelled data.\nCan someone tell me the possibility of this (at least theoretically)?\nThanks in Advance!","AnswerCount":4,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":6071,"Q_Id":61185290,"Users Score":0,"Answer":"as Lahiru mention if we downloaded any data, it dont have labelled data. so we need to label it. Either manually one by one by a person and than verify it else use some other library like sentiwordnet or textblob to level it.","Q_Score":6,"Tags":"python-3.7,gensim,word2vec,sentiment-analysis","A_Id":63155902,"CreationDate":"2020-04-13T09:52:00.000","Title":"Is it possible to do sentiment analysis of unlabelled text using word2vec model?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"working on self driving car cnn model to compute the steer with the speed by taking the pervous speed sequences.when we implemented the model the first loss is huge but it decreases.So does matter the start of the loss is huge.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":34,"Q_Id":61187990,"Users Score":0,"Answer":"It does not. If you are starting training your net from scratch then the network will predict pretty poorly so it's normal that the loss will be very high.","Q_Score":1,"Tags":"python,keras,carla","A_Id":61188055,"CreationDate":"2020-04-13T12:33:00.000","Title":"Does it matter if i started training of my keras model with a big value of the loss function","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to install OpenCV into my python environment (Windows), and I'm almost all of the way there, but still having some issues with autocomplete and Pycharm itself importing the library. I've been through countless other related threads, but it seems like most of them are either outdated, for prebuilt versions, or unanswered.\nI'm using Anaconda and have several environments, and unfortunately installing it through pip install opencv-contrib-python doesn't include everything I need. So, I've built it from source, and the library itself seem to be working fine. The build process installed some things into .\/Anaconda3\/envs\/cv\/Lib\/site-packages\/cv2\/: __init__.py, some config py files, and ...\/cv2\/python-3.8\/cv2.cp38-win_amd64.pyd. I'm not sure if it did anything else.\nBut here's where I'm at:\n\nIn a separate environment, a pip install opencv-contrib-python both runs and has autocomplete working\nIn this environment, OpenCV actually runs just fine, but the autocomplete doesn't work and Pycharm complains about everything, eg: Cannot find reference 'imread' in '__init__.py'\nInvalidate Caches \/ Restart doesn't help\nRemoving and re-adding the environment doesn't help\nDeleting the user preferences folder for Pycharm doesn't help\nRebuilding\/Installing OpenCV doesn't help\nFile->Settings->Project->Project Interpreter is set correctly\nRun->Edit Configuration->Python Interpreter is set correctly\n\nSo my question is: how does Pycharm get or generate that autocomplete information? It looks like the pyd file is just a dll in disguise, and looking through the other environment's site-packages\/cv2 folder, I don't see anything interesting. I've read that __init__.py has something to do with it, but again the pip version doesn't contain anything (except there's a from .cv2 import *, but I'm not sure how that factors in). The .whl file you can download is a zip that only contains the same as what 'pip install' gets.\nWhere does the autocomplete information get stored? Maybe there's some way to copy it from one environment to another? It would get me almost all the way there, which at this point would be good enough I think. Maybe I need to rebuild it with another flag I missed?","AnswerCount":2,"Available Count":2,"Score":0.3799489623,"is_accepted":false,"ViewCount":835,"Q_Id":61190224,"Users Score":4,"Answer":"Alternatively add the directory containing the .pyd file to the interpreter paths.\nI had exactly this problem with OpenCV 4.2.0 compiled from sources, installed in my Conda environment and PyCharm 2020.1.\nI solved this way:\n\nSelect project interpreter\nClick on the settings button next to it and then clicking on the Show paths for selected interpreter\nadding the directory containing the cv2 library (in my case in the Conda Python library path - e.g. miniconda3\/lib\/python3.7\/site-packages\/cv2\/python-3.7). In general check the site-packages\/cv2\/python-X.X directory)","Q_Score":1,"Tags":"python,opencv,pycharm,anaconda,conda","A_Id":61281004,"CreationDate":"2020-04-13T14:37:00.000","Title":"OpenCV built from source: Pycharm doesn't get autocomplete information","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to install OpenCV into my python environment (Windows), and I'm almost all of the way there, but still having some issues with autocomplete and Pycharm itself importing the library. I've been through countless other related threads, but it seems like most of them are either outdated, for prebuilt versions, or unanswered.\nI'm using Anaconda and have several environments, and unfortunately installing it through pip install opencv-contrib-python doesn't include everything I need. So, I've built it from source, and the library itself seem to be working fine. The build process installed some things into .\/Anaconda3\/envs\/cv\/Lib\/site-packages\/cv2\/: __init__.py, some config py files, and ...\/cv2\/python-3.8\/cv2.cp38-win_amd64.pyd. I'm not sure if it did anything else.\nBut here's where I'm at:\n\nIn a separate environment, a pip install opencv-contrib-python both runs and has autocomplete working\nIn this environment, OpenCV actually runs just fine, but the autocomplete doesn't work and Pycharm complains about everything, eg: Cannot find reference 'imread' in '__init__.py'\nInvalidate Caches \/ Restart doesn't help\nRemoving and re-adding the environment doesn't help\nDeleting the user preferences folder for Pycharm doesn't help\nRebuilding\/Installing OpenCV doesn't help\nFile->Settings->Project->Project Interpreter is set correctly\nRun->Edit Configuration->Python Interpreter is set correctly\n\nSo my question is: how does Pycharm get or generate that autocomplete information? It looks like the pyd file is just a dll in disguise, and looking through the other environment's site-packages\/cv2 folder, I don't see anything interesting. I've read that __init__.py has something to do with it, but again the pip version doesn't contain anything (except there's a from .cv2 import *, but I'm not sure how that factors in). The .whl file you can download is a zip that only contains the same as what 'pip install' gets.\nWhere does the autocomplete information get stored? Maybe there's some way to copy it from one environment to another? It would get me almost all the way there, which at this point would be good enough I think. Maybe I need to rebuild it with another flag I missed?","AnswerCount":2,"Available Count":2,"Score":0.3799489623,"is_accepted":false,"ViewCount":835,"Q_Id":61190224,"Users Score":4,"Answer":"Got it finally! Figures that would happen just after posting the question...\nTurns out ...\/envs\/cv\/site-packages\/cv2\/python-3.8\/cv2.cp38-win_amd64.pyd needed to be copied to ...\/envs\/cv\/DLLs\/. Then PyCharm did it's magic and is now all good.","Q_Score":1,"Tags":"python,opencv,pycharm,anaconda,conda","A_Id":61192749,"CreationDate":"2020-04-13T14:37:00.000","Title":"OpenCV built from source: Pycharm doesn't get autocomplete information","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I built a CNN audio classifier with 3 classes. My problem is that their are more than 3 classes, e.g. a fourth could be \"noise\". \nSo when I call be prediction the sum of these 3 classes is always 1.\nprediction = model.predict([X])\nIs it somehow possible to extract the accuracy of each class so the sum of these accuracies is less then 1?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":36,"Q_Id":61196194,"Users Score":1,"Answer":"If you use a softmax activation function you are forcing the outputs to sum to 1, thereby making a relative confidence score between your classes. Perhaps, without knowing more about your data and application, a \"1 vs all\" type scheme would work better for your purposes. For example, each class could have a sigmoid activation function and you could pick the highest prediction but if that prediction doesn't score high enough on a sensitivity threshold then none of the classes are predicted and as such is empty or implicitly \"noise.\"","Q_Score":1,"Tags":"python,keras,classification,conv-neural-network","A_Id":61196438,"CreationDate":"2020-04-13T20:28:00.000","Title":"CNN audio classifier trained with 3 classes and the sum of the prediction should be less than one","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Someone was reviewing my code and told me to use the .copy() function when copying a pandas dataframe into another variable. My code was like this:\ndata1 = pd.DataFrame()\ndata1[['Country\/Region','Province\/State','Lat','Long']]=confirmed[['Country\/Region','Province\/State','Lat','Long']]\nI copied the dataframe into another dataframe like this:\ndata2 = data1 and was working alright. Alright means, data1 is not being changed when I work on the data2. So, I am guessing it is ok. I am using Jupyter Notebook.\nShould I stick to using it in the future or use .copy()?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":970,"Q_Id":61199216,"Users Score":0,"Answer":"toking, normally if you say data2=data1 it passes to data2 the reference (a pointer) to data1. Thus when you make changes to data2 you really making them on data1. In your case, however, you already allocated memory to your data2, thus data1[['Country\/Region','Province\/State','Lat','Long']]=confirmed[['Country\/Region','Province\/State','Lat','Long']] code copies the content to the allocated memory. But it is generally a good practice to use .copy(deep=True) if you want to avoid confusion. Cheers","Q_Score":0,"Tags":"python,pandas","A_Id":61199445,"CreationDate":"2020-04-14T01:08:00.000","Title":"How to properly copy a pandas dataframe into another variable?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I was wondering if there was an algorithm I could find or a data structure that I could use that would enable me to efficiently randomly pair two sets of data with each other. \nInitially, I searched for an algorithm\/data structure that would do this for me, but it was to no avail, most likely because I do not know the exact terms to search for. Currently, I'm using the randint() function from the random library in python to implement my own type of algorithm, however, I'm worried if there may be issues with it not being random enough.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":130,"Q_Id":61200425,"Users Score":0,"Answer":"With the information you have provided in the question, my approaches would be as follows:\nApproach 1:\nLets say you have 2 datasets A and B and an indexing operator [], you could use randint to generate 2 random numbers a and b and pair A[a] with B[b]. Here the advantage is you can bootstrap as many times you want to generate a dataset as big as you want.\nApproach 2:\nAs @Mark Meyer suggested in the comments, shuffle the 2 datasets separately, and then pair each data point.","Q_Score":0,"Tags":"python,random","A_Id":61200595,"CreationDate":"2020-04-14T03:49:00.000","Title":"Randomly match items in Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"There is 5000 vectors in 1x721 dimension. These vectors are transformed by wavelet transformation to 5000 images with 9x721 dimension in MATLAB. The question is in which format these images should be saved in MATLAB to be used in Keras Python (Spyder) as a two dimension CNN?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":29,"Q_Id":61209722,"Users Score":0,"Answer":"PNG is a lossless image format so it would be perfect for storing your data in images, which can then be read into Python and used by Keras for your CNN","Q_Score":0,"Tags":"python,image,matlab,keras,format","A_Id":61229943,"CreationDate":"2020-04-14T14:09:00.000","Title":"Which format should I use to save my images in MATLAB?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am building an ensemble of models and need to do hyperparameter selection on 126 different models ranging from linear models to keras model with each taking 4-18 hours to run.\nI plan to do that on google colab as i do not have enough computing resources. \nShould i open 126 google accounts and train all of the models in parallel using 126 colab CPUs \/ GPUs. Or should i open 126 colab notebooks on the same account and run the models there. Will the 126 notebooks share the same resources or will each notebook have access to separate CPUs.","AnswerCount":3,"Available Count":2,"Score":0.1325487884,"is_accepted":false,"ViewCount":2805,"Q_Id":61211864,"Users Score":2,"Answer":"The amount of usable GPU and RAM on Colab is limited on Colab. You can try out how many scripts you can run at the same time and could start using other accounts after that. Note that inactive sessions in Colab will be closed.\nI personally would try to find a way involving less computational power. Google Colab has got a limited amount of hardware available, and using it too much might result in other users not being able to use a GPU. Also, abusing its capacities could result in a ban for you.","Q_Score":2,"Tags":"python,google-colaboratory","A_Id":61212062,"CreationDate":"2020-04-14T15:52:00.000","Title":"Training Multiple Models in Google Colab","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am building an ensemble of models and need to do hyperparameter selection on 126 different models ranging from linear models to keras model with each taking 4-18 hours to run.\nI plan to do that on google colab as i do not have enough computing resources. \nShould i open 126 google accounts and train all of the models in parallel using 126 colab CPUs \/ GPUs. Or should i open 126 colab notebooks on the same account and run the models there. Will the 126 notebooks share the same resources or will each notebook have access to separate CPUs.","AnswerCount":3,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":2805,"Q_Id":61211864,"Users Score":0,"Answer":"Please note that even if Google Colab is free to use it does not provide you full access to resources with the base plan. For this reason, the second approach would not work since you got just a single high-end GPU and a single CPU-core.\nYou could try creating multiple Google accounts but pay attention that according to Colab's policy, they encourage interactive sessions over batch ones, so you could end up with your training stopped after a few hours.\nI personally suggest you try a different approach, maybe trying to use less computational power changing the model or introducing new factors (in this case I suspect that weight decay should help you to merge similar models into single ones).","Q_Score":2,"Tags":"python,google-colaboratory","A_Id":61212108,"CreationDate":"2020-04-14T15:52:00.000","Title":"Training Multiple Models in Google Colab","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am currently working on computer vision program that will stitch images together. I use KAZE algorithm for finding keypoints and describe them. Than I use Brute-force matcher to match them. From this stage I am ready to stitch them I think because I know which point belongs where right? Because I am studing some literature etc. I see they always match keypoints and then use RANSAC which is random? Why use Ransac when I already know which keypoint belong to which done through brute-force matching?\nThank you for answers and have a nice day","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":368,"Q_Id":61214309,"Users Score":0,"Answer":"RANSAC (and variants) is an algorithm used to robustly fit to the matched keypoints to a mathematical model of the transformation (\"warp\") from one image to the other, for example, a homography. The keyword here is \"robustly\": the algorithm tries really hard to identify a large (ideally, the largest) set of matching keypoints that are acceptable, in the sense they agree with each other on supporting a particular value of the model. \nThis is done because matched pair of keypoints may be \"wrong\", either because the matching algorithm screws up (think left eye matched to right eye), or because the matching is correct, but it does not conform to the model (think matches on the same point of a moving car when the two images are taken some time apart). These wrong matches, or \"outliers\", can (and usually do) throw off the model estimate when the estimation procedure is not robust.","Q_Score":0,"Tags":"python,computer-vision,image-stitching,keypoint,ransac","A_Id":61236312,"CreationDate":"2020-04-14T18:06:00.000","Title":"Why we need to use RANSAC when we already match keypoints?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"My objective is to produce a Sankey diagram in plotly (in Python) that does not have all terminal nodes justified on the right. My data is such that certain flows have only one or two intermediate nodes and others have many intermediate nodes. I would like for short flows to be highlighted by visibly terminating before reaching the right edge of the graph. As far as I can tell, there is not currently a way to do this. \nHowever, I thought that a workaround might be to just include dummy nodes and links in my data as needed and either set their visibility to False or make them completely transparent. But so far I have only found visibility and transparency\/opacity approaches that apply to the entire graph.\nSo, is there any way to do any of the following:\n\nleft-justify a Sankey diagram (best option)\nchange visibility of individual nodes\/links (good enough)\nchange transparency of individual nodes\/links (also good enough)","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":564,"Q_Id":61217749,"Users Score":0,"Answer":"For any nodes that you want to be \"left-aligned\" (i.e. end before reaching the farthest left of the page)....\nGive these nodes a path to the most \"right-aligned\" terminal node, but set the color of the path to fully transparent #00000000. This should do the trick.","Q_Score":0,"Tags":"python,graph,plotly,data-visualization,sankey-diagram","A_Id":63867476,"CreationDate":"2020-04-14T21:43:00.000","Title":"Possible to hide specific nodes in plotly Sankey diagram?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"So I have a CSV file of weather stations that have a class (class 1 being the most reliable data to class 3 being the worst). I then have distances from the closest weather station to each county. I am attempting to eliminate station-county relationships that might have unreliable data i.e(class 3 station far from a county). \nI am struggling to come up with a very general way to do this. \nI tried assigned weight to the classes i.e (class 1 = 1, class 2 = .5, class 3 = .1) and then multiplying by distance but that then brings the issue of a close station to a low class give an unreliable read.\nIf anyone has any thoughts or suggestions on this it would be much appreciated!","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":29,"Q_Id":61220291,"Users Score":0,"Answer":"I don\u2019t think you want to use weights here. Unless you have a robust statistic for reliability that applies to all stations, just assigning arbitrary weightings based on class does not sound reasonable.\nHow about using a simpler approach? Break the distances from the counties to their weather stations into three categories:\n\nNear, say < 50 mi \/ 80 km\nMedium distance, say 50 mi to 100 mi\nFar, say > 100 mi\n\n(Note, these distances are most likely not right for your data set. You\u2019ll have to play around with them to get something appropriate.)\nThen, have a matrix of class x distance and discard whichever combinations make sense. It might be that Medium x Class 3 is bad but Far x Class 2 is okay.","Q_Score":0,"Tags":"python,algorithm","A_Id":61220514,"CreationDate":"2020-04-15T02:23:00.000","Title":"How to weight a piece of data?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"So I have a CSV file of weather stations that have a class (class 1 being the most reliable data to class 3 being the worst). I then have distances from the closest weather station to each county. I am attempting to eliminate station-county relationships that might have unreliable data i.e(class 3 station far from a county). \nI am struggling to come up with a very general way to do this. \nI tried assigned weight to the classes i.e (class 1 = 1, class 2 = .5, class 3 = .1) and then multiplying by distance but that then brings the issue of a close station to a low class give an unreliable read.\nIf anyone has any thoughts or suggestions on this it would be much appreciated!","AnswerCount":2,"Available Count":2,"Score":0.0996679946,"is_accepted":false,"ViewCount":29,"Q_Id":61220291,"Users Score":1,"Answer":"If you want higher weights to have higher significance, and you want longer distance to be associated with a lower weight you should use a decreasing function of the distance as a weight, not an increasing one, as you indicated.\nIn Physics, a fair share of quantities decreases with the inverse of the squared distance, so I would recommend you use that as a weighting: divide by the distance squared instead of multiplying by the distance.\nThe decreasing weighting for decreasing class of reliability is just fine.\nOf course, the actual scaling and the choice of the weighting function could be investigated further. For example, would: dividing by the cube of the distance, using different values for weighting the classe, etc. be better for your problem? This is something that we cannot easily investigate without further information.","Q_Score":0,"Tags":"python,algorithm","A_Id":61220419,"CreationDate":"2020-04-15T02:23:00.000","Title":"How to weight a piece of data?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am currently working on an SGE cluster and have code which submits many jobs, written in python, in parallel. \nThe output at the end of my code is a set of files containing numerical data. Each python job performs some calculation and then outputs to each file in turn. To output to a file, my code reads in the data in the file, adds what it has computed to the data, and then outputs back to the file.\nMy problem is this; as all of the jobs are run in parallel, and all of the jobs contribute to each of the output files; my jobs are conflicting with one another. I am often getting errors concerning incompatible file sizes and such. The cause I believe is that sometimes two jobs will try and read in the file around the same time and conflict.\nMy question is this: When running (potentially many) multiple jobs in parallel that are each contributing to the same file multiple times, is there a good practice way of ensuring that they don't try to write to the file concurrently? Are there any pythonic or SGE solutions to this problem?\nMy niave idea was to have a txt file, which contains a 1 or 0 indicating whether a file is currently being accessed, and that a job will only write to a file when the value is set to 0, and will change the value to 1 whilst it is outputting. Is this a bad practice?\/dumb idea?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":549,"Q_Id":61231805,"Users Score":0,"Answer":"You can keep the design simple by having each parallel process write to a separate file. Then when all the processes are finished, have a final process gather all the results and combine them into a single output file. This is a common pattern for HPC processing pipelines.","Q_Score":0,"Tags":"python,file,file-io,sungridengine","A_Id":61250389,"CreationDate":"2020-04-15T14:52:00.000","Title":"Multiple parallel processes writing to the same file on SGE cluster","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I cannot get a satisfying answer to this question. As I understand it, TensorFlow is a library for numerical computations, often used in deep learning applications, and Scikit-learn is a framework for general machine learning. \nBut what is the exact difference between them, what is the purpose and function of TensorFlow? Can I use them together, and does it make any sense?","AnswerCount":3,"Available Count":1,"Score":0.1325487884,"is_accepted":false,"ViewCount":33511,"Q_Id":61233004,"Users Score":2,"Answer":"Both are 3rd party machine learning modules, and both are good at it.\nTensorflow is the more popular of the two.\nTensorflow is typically used more in Deep Learning and Neural Networks.\nSciKit learn is more general Machine Learning.\nAnd although I don't think I've come across anyone using both simultaneously, no one is saying you can't.","Q_Score":47,"Tags":"python,tensorflow,machine-learning,scikit-learn","A_Id":61233138,"CreationDate":"2020-04-15T15:50:00.000","Title":"What's the difference between scikit-learn and tensorflow? Is it possible to use them together?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a mix of labeled and unlabeled data, this last one I would like to classify it by using semi-supervised learning. Suppose I have already an algorithm that gives me the best accuracy at predicting the labels of the training subsample. I want to use that algorithm to predict the labels of the unlabeled subsample. In semi-supervised learning, the pseudo-labeled data is added to the labeled (training) one. I would like to select from the pseudo-labeled data only those points that the probability of being well classified is higher than, let's say, 0.8, and repeat the procedure till all the unlabeled data is pseudo-labeled with high probability.\nHow could I achieve this? Is there a code or built-in function that helps me to compute such a probability?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":31,"Q_Id":61235951,"Users Score":0,"Answer":"All these algorithms \nAdaBoostClassifier, BaggingClassifier, BayesianGaussianMixture, BernoulliNB, CalibratedClassifierCV, ComplementNB, DecisionTreeClassifier, ExtraTreeClassifier, ExtraTreesClassifier, GaussianMixture, GaussianNB, GaussianProcessClassifier,\nGradientBoostingClassifier, KNeighborsClassifier, LabelPropagation, LabelSpreading, LinearDiscriminantAnalysis, LogisticRegression, LogisticRegressionCV, MLPClassifier, MultinomialNB, NuSVC, QuadraticDiscriminantAnalysis, RandomForestClassifier, SGDClassifier, SVC, _BinaryGaussianProcessClassifierLaplace, _ConstantPredictor\nsupport a method called predict_proba(self, X), that doest precisely that.","Q_Score":0,"Tags":"python,sklearn-pandas,unsupervised-learning,supervised-learning","A_Id":61239576,"CreationDate":"2020-04-15T18:26:00.000","Title":"Probability of a data point being well classified","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am reading in a csv in batches and each batch has nulls in various place. I dont want to use tensorflow transform as it requires loading the entire data in memory. Currently i cannot ignore the NaNs present in each column while computing means if i am to try to do it for the entire batch at once. I can loop through each column and then find the mean per columns that way but that seems to be an inelegant solution. \nCan somebody help in finding the right way to compute the mean per column of a csv batch that has NaNs present in multiple columns. Also, [1,2,np.nan] should produce 1.5 not 1.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":116,"Q_Id":61239100,"Users Score":1,"Answer":"I am currently doing this: given tensor a of rank 2 tf.math.divide_no_nan(tf.reduce_sum(tf.where(tf.math.is_finite(a),a,0.),axis=0),tf.reduce_sum(tf.cast(tf.math.is_finite(a),tf.float32),axis=0))\nLet me know somebody has a better option","Q_Score":1,"Tags":"python-3.x,tensorflow,tensorflow2.0,tensorflow-datasets","A_Id":61244390,"CreationDate":"2020-04-15T21:40:00.000","Title":"In tensorflow, How to compute mean for each columns of a batch generated from a csv that has NaNs in multiple columns?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm new to python and I'm using PyCharm as my IDE. I've been able to successfully install other packages like numpy, pandas etc. However, when I'm installing matplotlib, I keep getting the error:\nsrc\/checkdep_freetype2.c(5): fatal error C1189: #error: \"FreeType version 2.3 or higher is required. You may set the MPLLOCALFREETYPE environment variable to 1 to let Matplotlib download it.\"\nI installed it through the command prompt and it installed correctly but (I believe) PyCharm creates it's own environment and does not recognize packages installed through command prompt even though I tried to install them in the same path as other packages in PyCharm. Can you please help?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":918,"Q_Id":61239246,"Users Score":0,"Answer":"I had to run the command \"pip install updates\" and after that I could install the matplotlib package. It turns out that my pip wasn't of the latest version.","Q_Score":0,"Tags":"python,matplotlib,pycharm","A_Id":61239625,"CreationDate":"2020-04-15T21:50:00.000","Title":"How do I install matplotlib on pyCharm","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm having the following numerical issue while using SCIP solver as a callable library via PySCIPOpt:\n\ntwo equivalent and almost identical models for the same problem yield different optimal\n values and optimal solutions, with optimal values having a relative difference of order 1e-6\n\nAn independent piece of software verified that the solutions yielded by both models are feasible for the original problem and that their true values agree with the optimal values reported by SCIP for each model. Until the appearance of this instance a bunch of instances of the same problem had been solved, with both models always agreeing on their optimal solutions and values.\nIs it possible to modify the numerical precision of SCIP for comparing the values of primal solutions among them and against dual bounds? Which parameters should be modified to overcome this numerical difficulty?\nWhat I tried\nI've tried the following things and the problem persisted:\n\nTurning presolving off with model.setPresolve(SCIP_PARAMSETTING.OFF).\nSetting model.setParam('numerics\/feastol', epsilon) with different values of epsilon.\n\nSince feasible sets and objective functions agree (see description below), I've checked that the actual coefficients of the objective functions agree by calling model.getObjective() and comparing coefficients for equality for each variable appearing in the objective function.\nThe only thing that seemed to help was to add some noise (multiplying by numbers of the form 1+eps with small eps) to the coefficients in the objective function of the model yielding the worst solution. This makes SCIP to yield the same (and the better) solution for both models if eps is within certain range.\nJust in case, this is what I get with scip -v in the terminal:\n\nSCIP version 6.0.2 [precision: 8 byte] [memory: block] [mode:\n optimized] [LP solver: SoPlex 4.0.2] [GitHash: e639a0059d]\n\nDescription of the models\nModel (I) has approximately 30K binary variables, say X[i] for i in some index set I. It's feasible and not a hard MIP.\nModel (II) is has the same variables of model (I) plus ~100 continuous variables, say Y[j] for j in some index set J. Also model (II) has some constraints like this X[i_1] + X[i_2] + ... + X[i_n] <= Y[j].\nBoth objective functions agree and depend only on X[i] variables, the sense is minimization. Note that variables Y[j] are essentially free in model (II), since they are continuous and they do not appear in the objective function. Obviously, there is no point in including the Y[j] variables, but the optimal values shouldn't be different.\nModel (II) is the one yielding the better (i.e. smaller) value.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":148,"Q_Id":61241817,"Users Score":0,"Answer":"sorry for the late answer.\nSo, in general, it can definitely happen that any MIP solver reports different optimal solutions for formulations that are slightly perturbed (even if they are mathematically the same), due to the use of floating-point arithmetic.\nYour problem does seem a bit weird though. You say the Y-variables are free, i.e. they do not have any variable bounds attached to them? If this is the case, I would be very surprised if they don't get presolved away.\nIf you are still interested in this problem, could you provide your instance files to me and I will look at them?","Q_Score":0,"Tags":"python,precision,solver,scip","A_Id":62596604,"CreationDate":"2020-04-16T02:40:00.000","Title":"Numerical issue with SCIP: same problem, different optimal values","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I tried to use bert-tensorflow in Google Colab, but I got the following error:\n\n--------------------------------------------------------------------------- AttributeError Traceback (most recent call\n last) in ()\n 1 import bert\n ----> 2 from bert import run_classifier_with_tfhub # run_classifier\n 3 from bert import optimization\n 4 from bert import tokenization\n1 frames \/usr\/local\/lib\/python3.6\/dist-packages\/bert\/optimization.py\n in ()\n 85 \n 86 \n ---> 87 class AdamWeightDecayOptimizer(tf.train.Optimizer):\n 88 \"\"\"A basic Adam optimizer that includes \"correct\" L2 weight decay.\"\"\"\n 89 \nAttributeError: module 'tensorflow._api.v2.train' has no attribute\n 'Optimizer'\n\nHere is the code I tried:\n\nInstall the libraries:\n\n!pip install --upgrade --force-reinstall tensorflow\n!pip install --upgrade --force-reinstall tensorflow-gpu\n!pip install tensorflow_hub\n!pip install sentencepiece\n!pip install bert-tensorflow\n\nRun this code:\n\nfrom sklearn.model_selection import train_test_split\nimport pandas as pd\nfrom datetime import datetime\nfrom tensorflow.keras import optimizers\nimport bert\nfrom bert import run_classifier\nfrom bert import optimization\nfrom bert import tokenization\n\nI've also tried \nimport tensorflow.compat.v1 as tf\ntf.disable_v2_behavior()\nBut got the same error.","AnswerCount":4,"Available Count":1,"Score":0.1488850336,"is_accepted":false,"ViewCount":9846,"Q_Id":61250311,"Users Score":3,"Answer":"import tensorflow as tf\nprint(tf.__version__)\n!pip uninstall tensorflow==2.2.0\n!pip install tensorflow==1.15.0\n!pip install bert-tensorflow\ntry this. it worked for me for the same issue","Q_Score":5,"Tags":"python,tensorflow,classification,bert-language-model","A_Id":61692936,"CreationDate":"2020-04-16T12:30:00.000","Title":"Error importing BERT: module 'tensorflow._api.v2.train' has no attribute 'Optimizer'","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am kinda new to TensorFlow world but have written some programs in Keras. Since TensorFlow 2 is officially similar to Keras, I am quite confused about what is the difference between tf.keras.callbacks.ModelCheckpoint and tf.train.Checkpoint. If anybody can shed light on this, I would appreciate it.","AnswerCount":3,"Available Count":1,"Score":0.2605204458,"is_accepted":false,"ViewCount":1916,"Q_Id":61250353,"Users Score":4,"Answer":"It depends on whether a custom training loop is required. In most cases, it's not and you can just call model.fit() and pass tf.keras.callbacks.ModelCheckpoint. If you do need to write your custom training loop, then you have to use tf.train.Checkpoint (and tf.train.CheckpointManager) since there's no callback mechanism.","Q_Score":2,"Tags":"python,tensorflow,keras,checkpoint","A_Id":63366977,"CreationDate":"2020-04-16T12:33:00.000","Title":"tf.keras.callbacks.ModelCheckpoint vs tf.train.Checkpoint","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a python face recognition where I am using open-face model and SVM to detect and recognize faces. The general steps I am following to recognize image is below:\n\nDetect face using face detection model: Reason for using open face model instead of HAAR cascase is that cascade is not able to detect side face\nExtracting face embedding: Extracting the 128 d face embedding using open face model\nTraining: Using SVM I am training the face embedding with appropriate label like below:\nparams = {\"C\": [0.001, 0.01, 0.1, 1.0, 10.0, 100.0, 1000.0], \"gamma\": [1e-1, 1e-2, 1e-3, 1e-4, 1e-5]}\nmodel = GridSearchCV(SVC(kernel=\"rbf\", gamma=\"auto\", probability=True), params, cv=3, n_jobs=-1)\nmodel.fit(data[\"embeddings\"], labels)\nTesting: Extracting the face embedding of the test image, and predicting the results like below:\n\nmodel.predict_proba()\nI have unknown random face dataset and known person face dataset. The problem here is that if I add around 30 known person image and if I have around 10 unknown person image, it is recognizing the known person fine but if any unknown person comes in, it is also recognizing that unknown person as known person with high confidence which in actual should be unknown.\nIf I add more random person in unknown data set lets say around 50 images and if I have 30 known person image. It is recognizing known person image fine but confidence is low and if any unknown person comes in, it is now recognized as unknown\nIt looks like for good face recognition results we need to have appox same number of known and unknown person image which is practically not possible as known person images can increase to 100 or more than that for each known person we add. I am very confused here and not sure what to do. Is there any other way of recognizing known\/unknown persons. Please help. Thanks","AnswerCount":2,"Available Count":2,"Score":0.0996679946,"is_accepted":false,"ViewCount":1477,"Q_Id":61253604,"Users Score":1,"Answer":"I don't think svm will work well here. It is binary classifier by native. It will try to compute the border between two 128D points sets (known and unknown classes), but these classes are not internally connected with any relations. Known may be similar to unknown more than to another known in embedding space. That will be a problem for generalization for SVM. SVM may be used on closed sets, but you have open set for unknown faces.\nIt is more practical to use non-parametric methods, and use Bayesian approach, computing likelihoods as function of distance for known data in embedding space. Like in your previous question.","Q_Score":1,"Tags":"python,opencv,face-recognition","A_Id":61254102,"CreationDate":"2020-04-16T15:06:00.000","Title":"How to create unknown face dataset for face recognition python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a python face recognition where I am using open-face model and SVM to detect and recognize faces. The general steps I am following to recognize image is below:\n\nDetect face using face detection model: Reason for using open face model instead of HAAR cascase is that cascade is not able to detect side face\nExtracting face embedding: Extracting the 128 d face embedding using open face model\nTraining: Using SVM I am training the face embedding with appropriate label like below:\nparams = {\"C\": [0.001, 0.01, 0.1, 1.0, 10.0, 100.0, 1000.0], \"gamma\": [1e-1, 1e-2, 1e-3, 1e-4, 1e-5]}\nmodel = GridSearchCV(SVC(kernel=\"rbf\", gamma=\"auto\", probability=True), params, cv=3, n_jobs=-1)\nmodel.fit(data[\"embeddings\"], labels)\nTesting: Extracting the face embedding of the test image, and predicting the results like below:\n\nmodel.predict_proba()\nI have unknown random face dataset and known person face dataset. The problem here is that if I add around 30 known person image and if I have around 10 unknown person image, it is recognizing the known person fine but if any unknown person comes in, it is also recognizing that unknown person as known person with high confidence which in actual should be unknown.\nIf I add more random person in unknown data set lets say around 50 images and if I have 30 known person image. It is recognizing known person image fine but confidence is low and if any unknown person comes in, it is now recognized as unknown\nIt looks like for good face recognition results we need to have appox same number of known and unknown person image which is practically not possible as known person images can increase to 100 or more than that for each known person we add. I am very confused here and not sure what to do. Is there any other way of recognizing known\/unknown persons. Please help. Thanks","AnswerCount":2,"Available Count":2,"Score":0.0996679946,"is_accepted":false,"ViewCount":1477,"Q_Id":61253604,"Users Score":1,"Answer":"It is normal that confidence decreases as the number of possible persons (number of labels) increases, as there are more possibilities. I'm trying to understand what you meant: you have a label for each person and then an additional label for unknown? That is not the way to go, as unknown is treated as any other person embedding. You should use a cutoff probability, and everything that falls below that is considered unknown. \nRemember that there is a trade-off between the size of your prediction (more persons, more possibilities) and accuracy","Q_Score":1,"Tags":"python,opencv,face-recognition","A_Id":61253938,"CreationDate":"2020-04-16T15:06:00.000","Title":"How to create unknown face dataset for face recognition python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm quite new to colab. I run my notebook for few hours. I mounted the google drive and I upload data directly there, but the colab disk space is decreasing even though I am not saving anything there, I move it to google drive where I have much bigger space. Does anyone know why is the disk space filling up?","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":445,"Q_Id":61257625,"Users Score":1,"Answer":"Colab gives you the illusion of having your Google Drive mounted to it as a filesystem. But behind the scenes, it is really a remote disk that is mounted as a virtual filesystem.\nSo, when you upload the data through your Colab instance, it first gets uploaded to Colab. Then it starts transferring the data to Drive. This causes the Colab space to be used, until the data is completely uploaded to the Drive. Also, Colab might take some time to refelct the changes.","Q_Score":0,"Tags":"python,google-colaboratory","A_Id":61271125,"CreationDate":"2020-04-16T18:39:00.000","Title":"Google colab drive space decreasing even I save data on google drive","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I periodically receive data (every 15 minutes) and have them in an array (numpy array to be precise) in python, that is roughly 50 columns, the number of rows varies, usually is somewhere around 100-200.\nBefore, I only analyzed this data and tossed it, but now I'd like to start saving it, so that I can create statistics later.\nI have considered saving it in a csv file, but it did not seem right to me to save high amounts of such big 2D arrays to a csv file.\nI've looked at serialization options, particularly pickle and numpy's .tobytes(), but in both cases I run into an issue - I have to track the amount of arrays stored. I've seen people write the number as the first thing in the file, but I don't know how I would be able to keep incrementing the number while having the file still opened (the program that gathers the data runs practically non-stop). Constantly opening the file, reading the number, rewriting it, seeking to the end to write new data and closing the file again doesn't seem very efficient.\nI feel like I'm missing some vital information and have not been able to find it. I'd love it if someone could show me something I can not see and help me solve the problem.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":96,"Q_Id":61261541,"Users Score":1,"Answer":"Saving on a csv file might not be a good idea in this case, think about the accessibility and availability of your data. Using a database will be better, you can easily update your data and control the size amount of data you store.","Q_Score":1,"Tags":"python,numpy,csv,serialization,pickle","A_Id":61261755,"CreationDate":"2020-04-16T23:05:00.000","Title":"Save periodically gathered data with python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"This is probably a really dumb question.\nI have a dataframe that has a column containing scores of a soccer game (e.g. 1-2). When I save the dataframe using df.to_csv, and open the .csv file in Excel afterwards, the scores are given as date (e.g. 1-2 is now 1st Feb).\nI realize this is an issue within Excel probably, since when I open the file in Notepad, the scores are as they should be.\nSo my question is, how best to handle it? Is there an option in Python where I can save the .csv in such a format that the score isn't converted to a date? Or is it something to be tackled in Excel?\nThanks!","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":57,"Q_Id":61270822,"Users Score":0,"Answer":"If you save your file as text (.txt) instead of .csv, Excel shouldn't re-format it. \nThis might go against your specific needs, if .csv is necessary. But if not, you can achieve the same result (in the sense of delimitation and headers) by opening the text file from Excel's File Menu, selecting 'Delimited'. \nThen, if in python you are saving your .txt file with a comma delimitation, de-select the 'Tab' option and select 'Comma'..","Q_Score":0,"Tags":"python,excel","A_Id":61271239,"CreationDate":"2020-04-17T11:43:00.000","Title":"Saving pandas dataframe as .csv, converts score to date","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm working for the first time with a relatively large dataset (50gb). \nThere are 30,000 classes, and 100,000 labels (skewed data).\nI'm trying to train my CNN model on 10% of the data for testing. \nI have a problem for one hot encoding the labels.\nThe labels go from 0 to 29,999 (integers), so in my 10% dataset, I have an array of 10,000 labels with random values from 0 to 29,999. \nWhat happens is that keras to categorical creates a matrix of vectors with length = max(labels). \nFor example, if in my 10% dataset, the largest label is 25,000 then the one encoding will result in a shape (10000, 250000) which is wrong. Because I only have 20 labels in this sub dataset.\nHow can I do to one hot encode this labels ?\nI'm not sure if I was clear enough, first time working on large data got me a bit confused.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":33,"Q_Id":61271987,"Users Score":1,"Answer":"You should definitely one-hot encode the target before you take a smaller sample. Then it won't be a problem.","Q_Score":0,"Tags":"python,keras,data-science,one-hot-encoding","A_Id":61272254,"CreationDate":"2020-04-17T12:43:00.000","Title":"One-hot encode before or after taking a small sample?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"When I use yolov3 to train my dataset and there are more than 60 objects in a picture,and these objects are very dense, the final train-loss is 16.4,do I need to change yolov3.cfg or other parameters?or what can I do to reduce the train-loss?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":417,"Q_Id":61276651,"Users Score":0,"Answer":"From your question I understand that there are many small objects in your images. You could do a few things to improve your training-loss:\n\nset flag random=1 in your .cfg-file - it will increase precision by training Yolo for different resolutions.\nincrease network resolution in your .cfg-file (height=608, width=608 or any value multiple of 32) - it will increase precision.\n\nAlso I'd suggest you to have some test images and check your mAP while training to if the model's detection accuracy is increasing as the loss goes down.","Q_Score":0,"Tags":"python,tensorflow,computer-vision,yolo,darknet","A_Id":61335793,"CreationDate":"2020-04-17T16:48:00.000","Title":"When I use yolov3 to train my dataset and there are more than 60 objects in a picture,do I need to change yolov3.cfg or other parameters?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a pyspark dataframe that I want to write to HDFS. I am using the following command:\ndf.write.mode(\"overwrite\").option(\"header\", \"true\").option(\"sep\", \"|\").csv(outfile, compression=\"bzip2\")\nI am observing a weird thing. The dataframe has 366,000 rows which I obtained using the df.count() function. However, the output of the write command only has 72, 557 lines (wc -l command). Ideally each row should have a corresponding line in the output. Is there anything wrong with the write command I have been using?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":159,"Q_Id":61283147,"Users Score":0,"Answer":"It turns out that there were some rows with all elements as null. And this led to the discrepancy in the line count. \nAnd the rows were null because while reading the dataframe, I was passing a manually-defined schema. The rows that did not follow the schema got inserted as null rows in the dataframe.","Q_Score":0,"Tags":"python,apache-spark,pyspark,hdfs","A_Id":61807348,"CreationDate":"2020-04-18T01:21:00.000","Title":"Line count discrepancy in pyspark write csv","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"How to create json schema required for spark structured streaming? \nTried to generate using \"from_json\" But it's not compatible with pyspark. \nI'm using spark version 2.3.0","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":113,"Q_Id":61284624,"Users Score":0,"Answer":"the method from_json requires that you provide the schema as StructType([StructField(...)]) as its second argument. For your data-stream create a StructType schema and pass it to the function as from_json(datastream,your_msg_schema) and you should be golden.\nIf you need any specific help on the above case, please share the code that you have tried.","Q_Score":0,"Tags":"python-2.7,pyspark,pyspark-sql,jsonschema,pyspark-dataframes","A_Id":63539795,"CreationDate":"2020-04-18T05:29:00.000","Title":"Pyspark Structured Streaming Json Schema","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am creating a Neural Network from scratch for MNIST data, so I have 10 classes in the output layer. I need to perform backpropagation and for that, I need to calculate dA*dZ for the last layer where dA is the derivative of the loss function L wrt the softmax activation function A and dZ is the derivative of the softmax activation functionA wrt to z where z=wx+b. The size obtained for dA is 10*1 whereas the size obtained for dZ is 10*10. \nIs it correct? If yes, who do I multiply dA*dZ as they have different dimension.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":174,"Q_Id":61287179,"Users Score":2,"Answer":"You are almost there. However, you need to transpose dA, e.g. with numpy.transpose(dA).\nThen you will have the right dimensions of dA and dZ to perform matrix multiplication.","Q_Score":1,"Tags":"python,python-3.x,math,neural-network,backpropagation","A_Id":61288488,"CreationDate":"2020-04-18T09:51:00.000","Title":"Working with backpropagation algorithm using softmax function in the neural network","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am looking for a library which i can use for faster way to calculate implied volatility in python. I have options data about 1+ million rows for which i want to calculate implied volatility. what would be the fastest way i can calculate IV's. I have tried using py_vollib but it doesnt support vectorization. It takes about 5 mins approx. to calculate. Are there any other libraries which can help in faster calculation. What do people use in real time volatility calculations where there are millions of rows coming in every second?","AnswerCount":6,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":17709,"Q_Id":61289020,"Users Score":0,"Answer":"please use py_vollib.black_scholes.greeks.numerical instead of analytical for back testing purpose. Analytical throwing errors when option strike prices are deep out or in the money as well as illiquid contract, for this case use historical volatility instead of implied volatility to calculate option greeks. try: with iv and except: with hv","Q_Score":7,"Tags":"python,pandas,quantitative-finance,quantlib,volatility","A_Id":72374537,"CreationDate":"2020-04-18T12:23:00.000","Title":"Fast Implied Volatility Calculation in Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a pointcloud of which I have calculated all present planes. I have the mathematical formula that best describes the planes that contain the points in the point cloud like this: ax+by+cz+d=0. In this formula, a, b, c describe the normal vector of those planes. I know that all planes that I have calculated are either perpendicular to each other or parallel to each other. But due to noise in the point cloud, the resulting normal vectors are not perfectly parallel and perpendicular.\nHow would I calculate the best normal vectors for these planes so they still fit the points as best as possible, but that they are also perfectly perpendicular or parallel to each other? I have some ideas for this that would provide a suboptimal solution, however, I was wondering if there is a method to find the best possible solution to this problem.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":37,"Q_Id":61289573,"Users Score":1,"Answer":"I suggest to distribute the error between normals.\nYou have to types of normals: to one group of planes (parallel) or to the other group (perpendicular to the first group).\nNormals can be weighted-averaged by the number of points in each plane and\/or by the error you get for each plane.\nNow you have only two \"main\" normals, 'A' and 'B'. After normalizing them (divide by its length) their dot product allows to know the angle between both.\nThe difference between the result of the dot product and a 90-degrees angle can be distributed, again with some number-of-points or total-error criteria.\n The two normals form a plane and the difference is applied in this plane, you end rotating the normals a bit around the normal to this plane, each normal with its distributed angle.","Q_Score":1,"Tags":"python,numpy,geometry,plane","A_Id":61294670,"CreationDate":"2020-04-18T13:04:00.000","Title":"Straightening perpendicular planes","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a pandas MultiIndexed pandas dataframe. I would like to find the maximum value of one of the (numerical, integer) indices. \nThat is, the index runs from 1 to 5844. I want to be able to find the scalar value 5844. \nI realize that I could just set the scalar variable as I know the values which the index takes, but I'd like to be able to find the maximum value in the case when I don't know it.","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":66,"Q_Id":61290514,"Users Score":0,"Answer":"If you know that indices go from 1 to 5844 with none missing, df.shape[0] works.","Q_Score":0,"Tags":"python,pandas,multi-index","A_Id":61290688,"CreationDate":"2020-04-18T14:11:00.000","Title":"find the maximum value of a pandas dataframe index","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a numpy array of size (100, 2, 15, 27) (these are 100 images, with 2 channels of size 15x27). I want to separate the 2 channels in order to get 2 separate arrays of size (100, 1, 15, 27) (I do need that 1 there). How can I do that? I usually pick column using a[:,i], but this higher dimensionality confuses me. Thank you!","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":38,"Q_Id":61298595,"Users Score":0,"Answer":"a[:,i] works again. If you need to, you can add dimensions with .reshape(100,1,15,27) or a nicer way, np.expand_dims(a, axis=1).","Q_Score":0,"Tags":"python,numpy","A_Id":61298642,"CreationDate":"2020-04-19T01:52:00.000","Title":"Pick a certain axis from a numpy array","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working on dataset in which almost every feature has missiong values. I want to impute missing values with KNN method. But as KNN works on distance metrics so it is advised to perform normalization of dataset before its use. Iam using scikit-learn library for this.\nBut how can I perform normalization with missing values.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":769,"Q_Id":61301834,"Users Score":1,"Answer":"For classification algorithms like KNN, we measure the distances between pairs of samples and these distances are influenced by the measurement units also. \nFor example: Let\u2019s say, we are applying KNN on a data set having 3 features. \n1st feature : Range from 1 to 100\n2nd feature : Range from 1 to 200\n3rd feature : Range from 1 to 10000\nThis will led to generated clusters based on 3rd feature. Since, the difference between 1st and 2nd are smaller as compared to 3rd one. To avoid this wrong clustering, we need to have normalization in place.","Q_Score":0,"Tags":"python,scikit-learn,normalization,knn","A_Id":61301846,"CreationDate":"2020-04-19T09:01:00.000","Title":"Why perform normalization of data before KNN Imputation?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to take an excel file, which contains different cell types like dates, currency ETC and parse it with Python including the cell types.\nI have tried using Pandas, but when I open it with Python using pd.read_excel, all of these cell types are disappearing.\nFor Example - a cell containing '50 USD' (Cell containing currency type) will be shown as '50'.\nIs there a method in Python that is able to read these cells with their cell types saved?\nThanks","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":26,"Q_Id":61302777,"Users Score":0,"Answer":"I think you may be confusing cell values and cell formatting. For example, with 50 USD, Excel stores the numeric value and then applies a currency format for display. So it is correct to read it into pandas as an integer if you want to sum, average, or otherwise analyze that column. \nDates should be automatically parsed and, if they aren't, read_excel has a parse_dates parameter that allows you to do so.\nNow, depending on how you want to output the data after you've manipulated it in pandas, you could have a function that outputs a new dataframe that converts all values to string and applies formats to different columns. Or, if you are working in a notebook, you can use the pandas styling API. You could also write the file back to excel with pandas and then apply styles programatically with openpyxl.","Q_Score":0,"Tags":"python-3.x,excel,pandas","A_Id":61309931,"CreationDate":"2020-04-19T10:21:00.000","Title":"Save Excel values while parsing in Python","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a very limited dataset having variety of columns having missing values. I can not prune the rows having missing values as it will reduce the size drastically. Can anyone suggest, standard procedure for it ?","AnswerCount":3,"Available Count":1,"Score":0.0665680765,"is_accepted":false,"ViewCount":112,"Q_Id":61303255,"Users Score":1,"Answer":"To fill the missing values, you can do one of the following:\n1) Compute the mean of the feature using the available values and then fill the missing values with the mean. If the values are discrete (categorical), then use the most frequent value (mode) to fill the missing ones.\n2) Find the most similar example(s) to the one that has a missing value given that these examples have a value for the particular feature. Then use their mean\/mode along the feature you\u2019re interested in to fill the missing values.","Q_Score":0,"Tags":"python,missing-data","A_Id":61303391,"CreationDate":"2020-04-19T11:03:00.000","Title":"What are the standard ways of filling missing values in python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"How to run keras.model.fit() in graph not with eager execution...??\nI tried to run my model in graph by using tf.compat.v1.disable_eager_execution(), but the code return error: numpy must be run with eager execution \nThe error appear after checkpoint model\nI\u2019m using tensorflow GpU 2.1.0 and keras 2.3.1","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":1203,"Q_Id":61309661,"Users Score":1,"Answer":"In tensorflow2.x, model.fit() runs in graph mode by default, you can control this behavior by using the run_eagerly argument in the model.compile(...) method, which defaults to False.","Q_Score":2,"Tags":"python-3.x,tensorflow,keras","A_Id":61310421,"CreationDate":"2020-04-19T18:37:00.000","Title":"Run keras.Models.fit() in graph","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using the sklearn.impute.IterativeImputer with extra tree regressor and it is taking too much time, it's almost been an hour and it is still running. Is there a way I can check how much has been executed and estimated time left?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":885,"Q_Id":61314216,"Users Score":1,"Answer":"I don't you can tell estimated time as a direct measure or so. But use verbose=2 as a paramter to sklearn.impute.IterativeImputer. That will give you some idea about how what it is doing and every step. So You can estimate may be rough estimated time, if you have knowledge on algorithm.","Q_Score":0,"Tags":"python,scikit-learn,iteration,imputation","A_Id":61314263,"CreationDate":"2020-04-20T02:25:00.000","Title":"Execution time for sklearn.impute.IterativeImputer","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"My model aims to predict radio listening in hours (on a given day at a given time for 1 specific radio station. Each row of my training set represents 1 hour blocks for each day of the year and has a little under 30,000 records going back 3.5 years. My features include parametric information such as date, station, day of week, start time as well as weather information. \nRecently I added 2 binary features which I expected would help the accuracy of the model but they don't. They are whether a station is running a contest at a given time (contests help to pull more audiences) and if the station is playing Christmas music or not (X-Mas music tends to also pull audiences). When I run a Pearson correlation of all my features vs. my dependent variable (amount of listening hours), these 2 features are in the top 4 of the most correlated features (0.16 for X-Mas music and 0.20 for contests) with the highest correlated feature sitting at 0.31. When there is a contest listening hours tend to double and when X_mas music is playing, hours tend to increase by about 50%. Interestingly, my predictions are also proportionately higher when these 2 features are True (1's).\nThe way I know that these features are not adding predictive value is that when I remove them from my dataset to train the model and make predictions, the model accuracy does not improve. I am measuring Mean Absolute Error, MSE and R2 to evaluate the model performance.\nAny ideas as to why important features to the dependant variable, not very correlated with other features, are not helping to reduce errors?\nI am running a RF with 100 trees. The issue is there if I only run a single tree as well.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":44,"Q_Id":61314925,"Users Score":0,"Answer":"It could be that the other features that you are using as input are already enough to give accurate predictions. Thus including the two binary features does not improve the model accuracy. Id estimate variable importance to see how important the two binary features are relevant to overall predictions.","Q_Score":0,"Tags":"python-3.x,random-forest,feature-selection","A_Id":61361896,"CreationDate":"2020-04-20T04:01:00.000","Title":"Correlated features to the dependent variable don't improve the accuracy of a Random Forest regression model","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a function change_weight() that modifies weights in any given model. This function resides in a different python file.\nSo if I have a simple neural network that classifies MNIST images, I test the accuracy before and after calling this function and I see that it works. This was easy to do in TensorFlow v1, as I just had to pass the Session sess object in the function call, and I could get the weights of this session in the other file.\nWith eager execution in TensorFlow v2, how do I do this? I don't have a Session object anymore. What do I pass?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":66,"Q_Id":61315403,"Users Score":0,"Answer":"I was able to do this by passing the Model object instead and getting the weights by model.trainable_variables in the other function.","Q_Score":0,"Tags":"python,tensorflow,tensorflow2.0,eager-execution","A_Id":61327591,"CreationDate":"2020-04-20T05:00:00.000","Title":"How do you pass session object in TensorFlow v2?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I would want to implement the following logic in pandas:\nif df['xxx'] <= 0 then df['xyz']== 'a'\nif df['xxx'] between 0.5 and 10.97 then df['xyz']== 'b'\nif df['xxx'] between 11 and 89.57 then df['xyz']== 'c'\nif df['xxx'] > 100 then df['xyz']== 'd'\nHow can I do this in the simplest way?\nMuch thanks.","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":84,"Q_Id":61328489,"Users Score":1,"Answer":"df['xyz'] = df.apply(lambda x: 'a' if x['xxx'] <=0 else ('b' if x['xxx'] < 1000 else 'c' ))\nthere might be syntax errors","Q_Score":0,"Tags":"python,pandas","A_Id":61328786,"CreationDate":"2020-04-20T17:32:00.000","Title":"Assigning values based on existing numeric values in a column in pandas","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am exploring the Jupiter notebook for Python. While calling this method \"Access OutbreakLocation data\" I get this exception in Python 3.6:\ngetting AttributeError: module 'pandas' has no attribute 'json_normalize'\nAny ideas how can we fix this issue?","AnswerCount":3,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":28052,"Q_Id":61336238,"Users Score":15,"Answer":"Make sure to update to Pandas 1.0.3. Pandas prior to version 1 doesn't have json_normalize.","Q_Score":16,"Tags":"python","A_Id":61347947,"CreationDate":"2020-04-21T04:58:00.000","Title":"Getting AttributeError: module 'pandas' has no attribute 'json_normalize' while calling method \"Access OutbreakLocation data\"","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"When we visualize the LDA using pyLDAvis, we can see topic overlap. I want know the word that is causing this topic overlap. Or I want to know the words that are at the intersection of the topic bubbles. Any guidance is appreciated.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":407,"Q_Id":61337315,"Users Score":0,"Answer":"Select topic 2\nCopy a list of words from the right (the ones with bars)\nSelect topic 5\nCopy the list as in 2.\nCompare the copied lists on your own.\n\nI am not sure there is any better method there...","Q_Score":0,"Tags":"python-3.x,gensim,lda,topic-modeling,pyldavis","A_Id":61344214,"CreationDate":"2020-04-21T06:34:00.000","Title":"Common words that cause topic overlap in gensim LDA","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"So I want to convert this list:\n[[[1,2]],[[1,2],[3,4]]]\nto a numpy array. \nHowever it gives me:\n[list([[1,2]]),list([[1,2],[3,4]])]","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":27,"Q_Id":61341079,"Users Score":0,"Answer":"The list is not rectangular, it wont work","Q_Score":0,"Tags":"python,numpy","A_Id":61341156,"CreationDate":"2020-04-21T10:15:00.000","Title":"3D list to Numpy array conversion not working, it gives me list object instead","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have 9 boxplots organized in 3 groups: \n\nA1,B1,C1 \nA2,B2,C2\nA3,B3,C3\n\nHow is it possible with seaborn to plot all A in red, all B in green, and all C in blue? \nI create boxplots with bplot = sns.boxplot(data=[d for d in data], width=0.5) and am aware of the existence of bplot.artists. Could anyone provide a hint on this?","AnswerCount":2,"Available Count":1,"Score":-0.0996679946,"is_accepted":false,"ViewCount":96,"Q_Id":61352900,"Users Score":-1,"Answer":"color is an optional parameter that gets passed into the underlying matplotlib object so just specify it in the initialization parameters: sns.boxplot(data, color='blue') and use a for loop to hit A, B, and C","Q_Score":1,"Tags":"python,seaborn,boxplot","A_Id":61352967,"CreationDate":"2020-04-21T20:43:00.000","Title":"Boxplot color grouping in seaborn","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am having major trouble right now trying to use numpy in my jupyter notebook.\nWhen I first tried to simply \"import numpy\", it came back with the error: \"ModuleNotFoundError: No module named 'numpy'\"\nI then read somewhere that I probably needed to install numpy. \nSo I did this: \"import sys\n!conda install --yes --prefix {sys.prefix} numpy\"\nto which it came back saying: \"EnvironmentLocationNotFound: Not a conda environment\"\nNow when it comes to understanding environments or packages or ANYTHING along those lines, I just have no idea what I'm doing. I am in a very beginner course and just following along. \nI wish I could understand all of this environment and versioning stuff. \nI have no idea where to go from here.\nAny insight here would be GREATLY appreciated!!\nEdit: I am in fact using Anaconda to launch Jupyter Notebook. Not sure if that means anything to your understanding of my problem or a potential solution.\nMark","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":2804,"Q_Id":61353010,"Users Score":0,"Answer":"In my case, inside Jupyter notebook, you need to change Kernel (Anaconda environment). I thought you changed environment using conda activate myEnv, but when launching Jupyter, it defaults to the root environment.\nI hope this is in fact true- I am a noob in Anaconda.","Q_Score":1,"Tags":"python,numpy,jupyter-notebook","A_Id":70735920,"CreationDate":"2020-04-21T20:51:00.000","Title":"Problem importing (and installing) NumPy in Jupyter Notebook","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to write Python code that takes a word as an input (e.g. book), and outputs the most similar word with similarity score. \nI have tried different off-the-shelf edit-distance algorithms like cosine, Levenshtein and others, but these cannot tell the degree of differences. For example, (book, bouk) and (book,bo0k). I am looking for an algorithm that can gives different scores for these two examples. I am thinking about using fastText or BPE, however they use cosine distance. \nIs there any algorithm that can solve this?","AnswerCount":3,"Available Count":1,"Score":0.0665680765,"is_accepted":false,"ViewCount":281,"Q_Id":61364975,"Users Score":1,"Answer":"The problem is that both \"bo0k\" and \"bouk\" are one character different from \"book\", and no other metric will give you a way to distinguish between them.\nWhat you will need to do is change the scoring: Instead of counting a different character as an edit distance of 1, you could give it a higher score if it's a different character class (ie a digit instead of a letter). That way you will get a different score for your examples.\nYou might have to adapt the other scores as well, though, so that replacement \/ insertion \/ deletion are still consistent.","Q_Score":1,"Tags":"python-3.x,nlp,text-classification,fasttext,edit-distance","A_Id":61365061,"CreationDate":"2020-04-22T12:20:00.000","Title":"An algorithm for computing the edit-distance between two words","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"How can you prevent the agent from non-stop repeating the same action circle?\nOf course, somehow with changes in the reward system. But are there general rules you could follow or try to include in your code to prevent such a problem?\n\nTo be more precise, my actual problem is this one:\nI'm trying to teach an ANN to learn Doodle Jump using Q-Learning. After only a few generations the agent keeps jumping on one and the same platform\/stone over and over again, non-stop. It doesn't help to increase the length of the random-exploration-time. \nMy reward system is the following:\n\n+1 when the agent is living\n+2 when the agent jumps on a platform\n-1000 when it dies\n\nAn idea would be to reward it negative or at least with 0 when the agent hits the same platform as it did before. But to do so, I'd have to pass a lot of new input-parameters to the ANN: x,y coordinates of the agent and x,y coordinates of the last visited platform.\nFurthermore, the ANN then would also have to learn that a platform is 4 blocks thick, and so on. \nTherefore, I'm sure that this idea I just mentioned wouldn't solve the problem, contrarily I believe that the ANN would in general simply not learn well anymore, because there are too many unuseful and complex-to-understand inputs.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":417,"Q_Id":61367054,"Users Score":0,"Answer":"This is not a direct answer to the very generally asked question.\n\nI found a workaround for my particular DoodleJump example, probably someone does something similar and needs help:\n\nWhile training: Let every platform the agent jumped on disappear after that, and spawn a new one somewhere else.\nWhile testing\/presenting: You can disable the new \"disappear-feature\" (so that it's like it was before again) and the player will play well and won't hop on one and the same platform all the time.","Q_Score":1,"Tags":"python,tensorflow,reinforcement-learning,q-learning","A_Id":61428048,"CreationDate":"2020-04-22T14:02:00.000","Title":"Agent repeats the same action circle non stop, Q learning","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I don't understand how what each value represents, would someone be able to explain?\nimg_left[:,0:150,:] = np.clip(img_left[:,:150,:]*1.5,0, 255)","AnswerCount":2,"Available Count":2,"Score":0.0996679946,"is_accepted":false,"ViewCount":55,"Q_Id":61367541,"Users Score":1,"Answer":"It takes the first 150 columns of image (first dimension in image being rows, second being columns, and third usually RGB). when you call a dimension by : you are selecting all elements along that axis. And calling a dimension by i:j select all the elements between i-th and j-th (including i and excluding j) along that dimension. It then multiplies all those selected values to 1.5 and clips the values to be between 0 and 255.","Q_Score":0,"Tags":"python,numpy,vision","A_Id":61367630,"CreationDate":"2020-04-22T14:24:00.000","Title":"Can someone explain how they are splitting the image here?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I don't understand how what each value represents, would someone be able to explain?\nimg_left[:,0:150,:] = np.clip(img_left[:,:150,:]*1.5,0, 255)","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":55,"Q_Id":61367541,"Users Score":0,"Answer":"I'm assuming this is using open-cv, but either way the numpy array is being indexed by [:,0:150:,:], where : means to take all values when by itself, and x:y is all values from x to y. So that'd mean that all of the y values (open-cv works with y first, then x), the x values from 0 to 149, and all 3 color channels.","Q_Score":0,"Tags":"python,numpy,vision","A_Id":61367657,"CreationDate":"2020-04-22T14:24:00.000","Title":"Can someone explain how they are splitting the image here?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to wrap my head around vectorization (for numerical computing), and I'm coming across seemingly contradictory explanations:\n\nMy understanding is that it is a feature built into low-level libraries that takes advantage of parallel processing capabilities of a given processor to perform operations against multiple data points simultaneously.\nBut several tutorials seem to be describing it as a coding practice that one incorporates into their code for more efficiency. How is it a coding practice, if it is also a feature you have or you don't have in the framework you are using. \n\nA more concrete explanation of my dilemma: \n\nLet's say I have a loop to calculate an operation on a list of numbers in Python. To vectorize it, I just import Numpy and then use an array function to do the calculation in one step instead of having to write a time consuming loop. The low level C routines used by Numpy will do all the heavy lifting on my behalf. \n\nKnowing about Numpy and how to import it and use it is not a coding practice, as far as I can tell. It's just good knowledge of tools and frameworks, that's all. \nSo why do people keep referring to vectorization as a coding practice that good coders leverage in their code?","AnswerCount":3,"Available Count":2,"Score":0.3215127375,"is_accepted":false,"ViewCount":123,"Q_Id":61373860,"Users Score":5,"Answer":"Vectorization can mean different things in different contexts. In numpy we usually mean using the compiled numpy methods to work on whole arrays. In effect it means moving any loops out of interpreted Python and into compiled code. It's very specific to numpy.\nI came to numpy from MATLAB years ago, and APL before that (and physics\/math as a student). Thus I've been used to thinking in terms of whole arrays\/vectors\/matrices for a long time.\nMATLAB now has a lot just-in-time compiling, so programmers can write iterative code without a performance penalty. numba (and cython) lets numpy users do some of the same, though there are still a lot of rough edges - as can be seen in numpa tagged questions.\nParallelization and other means of taking advantage of modern multi-core computers is a different topic. That usually requires using additional packages.\nI took issue with a comment that loops are not Pythonic. I should qualify that a bit. Python does have tools for avoiding large, hard to read loops, things like list comprehensions, generators and other comprehensions. Performing a complex task by stringing together comprehensions and generators is good Python practice, but that's not 'vectorization' (in the numpy sense).","Q_Score":1,"Tags":"python,performance,numpy,parallel-processing,vectorization","A_Id":61374101,"CreationDate":"2020-04-22T19:47:00.000","Title":"Is vectorization a hardware\/framework specific feature or is it a good coding practice?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to wrap my head around vectorization (for numerical computing), and I'm coming across seemingly contradictory explanations:\n\nMy understanding is that it is a feature built into low-level libraries that takes advantage of parallel processing capabilities of a given processor to perform operations against multiple data points simultaneously.\nBut several tutorials seem to be describing it as a coding practice that one incorporates into their code for more efficiency. How is it a coding practice, if it is also a feature you have or you don't have in the framework you are using. \n\nA more concrete explanation of my dilemma: \n\nLet's say I have a loop to calculate an operation on a list of numbers in Python. To vectorize it, I just import Numpy and then use an array function to do the calculation in one step instead of having to write a time consuming loop. The low level C routines used by Numpy will do all the heavy lifting on my behalf. \n\nKnowing about Numpy and how to import it and use it is not a coding practice, as far as I can tell. It's just good knowledge of tools and frameworks, that's all. \nSo why do people keep referring to vectorization as a coding practice that good coders leverage in their code?","AnswerCount":3,"Available Count":2,"Score":0.1325487884,"is_accepted":false,"ViewCount":123,"Q_Id":61373860,"Users Score":2,"Answer":"Vectorization leverage the SIMD (Single Instruction Multiple Data) instruction set of modern processors. For example, assume your data is 32 bits, back in the old days one addition would cost one instruction (say 4 clock cycles depending on the architecture). Intel's latest SIMD instructions now process 512 bits of data all at once with one instruction, enabling you to make 16 additions in parallel.\nUnless you are writing assembly code, you better make sure that your code is efficiently compiled to leverage the SIMD instruction set. This is being taking care of with the standard packages. \nYour next speed up opportunities are in writing code to leverage multicore processors and to move your loops out of the interpreted python. Again, this is being taking care of with libraries and frameworks.\nIf you are a data scientist, you should only care about calling the right packages\/frameworks, avoid reimplementing logic already offered by the libraries (with loops being a major example) and just focus on your application. If you are a framework\/low-level code developer, you better learn the good coding practices or your package will never fly.","Q_Score":1,"Tags":"python,performance,numpy,parallel-processing,vectorization","A_Id":61375476,"CreationDate":"2020-04-22T19:47:00.000","Title":"Is vectorization a hardware\/framework specific feature or is it a good coding practice?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have some data concerning the 2020 Australian bush fires I'm trying to work with.\nI have some data in numpy arrays: lat (for latitude), lon (for longitude), and time.\nThe array size of lat is: 350 with the shape: (350,)\nThe array size of lon is: 500 with the shape: (500,)\nThe array size of time is: 31 with the shape: (31,) - this makes sense as it's days of the month in Jan 2020.\nI have another array, total_combustion_rate:\nThe array size of total_combustion_rate is: 5425000 with the shape: (31, 350, 500) - so it's made up of days in the month, lat and lon values.\nI have a final array called area_array:\nThe array size of area_array is: 175000 with the shape: (350, 500). It contains the area of each grid square in km2.\nI have been asked to work out what percentage of Australia experienced fire during January 2020.\nI'm unsure how to go about this problem though.\nThere are a lot of values in total_combustion_rate that are zero. Getting rid of them should just leave me with entries that mean there is a fire of some description burning in each grid square. I can see that I need to then sum the same lon and lat values in area_array that have a value that isn't zero in total_combustion_rate and that should give me the total area of grid squares that were on fire.\nConverting to a percentage should then just be: (total on fire \/ total area contained in area_array) * 100.\nI'm totally lost on how I'd go about doing this though as I get a bit confused with 3D numpy arrays. Can anyone help?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":23,"Q_Id":61377584,"Users Score":0,"Answer":"I am assuming numpy is imported under the name np, and all arrays are numpy arrays.\nYou have to start by summing total_combustion_rate along the time dimension. This way, you will get a 2-D array for which each entry represents an integrated value over time for each location of your dataset.\ntotal_combustion_rate.sum(axis=0)\nNow, this array is the exact place where you can look for 0 values. The idea is to determine where the non-zero entries are so that you can use their index to probe into area_array and get the relevant areas you need. A masked array makes the task extremely easy as it will \"hide\" these entries you do not want, meaning the ones that sum up to 0.\nnp.ma.MaskedArray(area_array, total_combustion_rate.sum(axis=0) == 0)\nWhen you have the masked array, all you need to do is to compare the sum of the un-masked areas to the sum of all areas. Again, this is achieved effortlessly.\n(np.ma.MaskedArray(area_array, total_combustion_rate.sum(axis=0) == 0).sum()\n \/ area_array.sum())\nAll in one (long) line. :)","Q_Score":0,"Tags":"python,arrays,numpy,multidimensional-array,data-science","A_Id":61377805,"CreationDate":"2020-04-23T00:58:00.000","Title":"3D numpy array woes and extracting data","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am fairly new in Python. I have two pandas data frames ak12_01 and T01\nak12_01\n objectid, coordID, year, doy\n0 495395 5497 2001 120\nand\nT01\n coordID, year, 1, 2, 3, ...\n0 5497 2001 249 251 231 ...\n1 5498 2001 239 231 251 ...\nI want to add a given value from T01 to ak12_01 on two conditions:\n1) if T01['coordID'] == ak12_01['coordID']\n2) if T01(column name) == ak12_01['doy'].\nIn the T01 dataset, the column names represent the doy (day of the year)\nI get an error when comparing the 'coordID' from the two dataset as they are not equally long (Can only compare identically-labeled Series objects). Is there a smart way of adding the given value from T01 to ak_12_01 based on these to conditions?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":34,"Q_Id":61384849,"Users Score":1,"Answer":"I found out that it is possible to do by doing the following merge.\n\nI transposed the doy data, so it is all in 1 column.\nmerge_ID_doy = ak2012_1.merge(T01, how='inner', left_on=['coordID', 'doy'], right_on=['coordID', 'doy']).\n\nThen it merges all the data with similar doy and coordID with each other.","Q_Score":1,"Tags":"python-3.x,pandas,if-statement","A_Id":61524106,"CreationDate":"2020-04-23T10:22:00.000","Title":"Conditional appending of data to a pandas dataframe","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm using GaussianNB for classification problem\nall the features are numerical and they represent marks about something (every mark is between 1 and 8 and they are results to exams)\n\nThe algorithm seems to work enough well in my case: I got 0,85 as an accuracy score.\nBut I read that Gaussian should have mean 0 and variance 1 but they don't.\nShould I use a scaler such as Standard Scaler before?\nIs it compulsory in my case?\nI tried it but performances didn't go up","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":127,"Q_Id":61387135,"Users Score":0,"Answer":"The 'standard Gaussian'- which is the basic\/hypothetical Gaussian distribution - has its mean at 0 and its variance at 1. For example people's height around the world has mean of 175cm and variance of 10cm, yet it is still Gaussian (bell shaped).","Q_Score":0,"Tags":"python,machine-learning,scikit-learn,naivebayes","A_Id":65453710,"CreationDate":"2020-04-23T12:23:00.000","Title":"preprocessing data before GaussianNB for categorical for numerical features","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a dataset of face images which were captured with a uniform gray background. Because of the lighting variations during collection, the images no longer have same color tone. The backgrounds color looks different for all the images.\nI want to find the exact skin color and wanted to implement color correction using the fact that all images had uniform gray background. How can I implement this using python?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":93,"Q_Id":61395195,"Users Score":0,"Answer":"Assuming your pixels are converted to floats in the range 0,0,0 (black) to 1,1,1 (white). You have a vector in 3D (RGB) space from the picture background to the known value. To correct, calculate a correction by multiplying each component by the magnitude of the correction needed. So if you have dR, dG, dB as the differences, all between 0.0 and 1.0, and R,G,B is a pixel, Rnew = R * (1.0 + dR) clipping max at 1.0. This will keep black pixels black.","Q_Score":0,"Tags":"python,algorithm,opencv,image-processing","A_Id":61395865,"CreationDate":"2020-04-23T19:12:00.000","Title":"How to implement color correction based on known background color?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"The background for this question is that I am trying to debug a TensorFlow pipeline. I manually computed the loss for each example based on the network's current prediction and averaged the error terms. The number I get is different from what Keras is reporting, so the question is if I found my bug, or if I am computing the wrong thing to compare to the value reported as \"loss\".\nWhat exactly is Keras computing here?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":298,"Q_Id":61395449,"Users Score":2,"Answer":"The training loss is a running mean of the loss values across batches, during training, after each batch update. The weights are changing during training so you cannot compare this loss to to making predictions with fixed weights and then computing a loss.\nThis means that if you compute the average (or even running mean) over batches, you will get a different result.","Q_Score":1,"Tags":"python,tensorflow,keras","A_Id":61397113,"CreationDate":"2020-04-23T19:30:00.000","Title":"In keras, is the loss value of model.fit the average over batches or over samples?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Is there any different between Nearest Neighbor and KNN or both of them are refereing to the same algorithm?\nIf both of them are in a different type. what is the different use cases to use n_neighbor to find a correlation using nearest neighbor .","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":22,"Q_Id":61400713,"Users Score":0,"Answer":"They're the same thing. If I want to refer to it as an abbreviation I use KNN. If I want to say it, I just say nearest neighbor.\nKNN is used in supervised machine learning, like classification. Using the common Iris example, I would show you a flower, and you would say \"This is an Iris\" or \"This is not an Iris\". We repeat that to build a model, then throw a whole bunch at the model, and we get our results.","Q_Score":0,"Tags":"python","A_Id":61400891,"CreationDate":"2020-04-24T03:39:00.000","Title":"Difference between NearestNeighbours and KNearestNeighbour","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to convert a column in my python dataframe. The column is of type object.\nFrom\nDec-21-20 09:20PM\nto This\n2020-12-21 21:20:00:00.000","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":48,"Q_Id":61400779,"Users Score":0,"Answer":"df[\"column\"] = pd.to_datetime(df[\"column\"])\nIf you need more specific formatting, edit your question and comment back so I can adjust my answer accordingly.","Q_Score":0,"Tags":"python,datetime,date-conversion","A_Id":61400821,"CreationDate":"2020-04-24T03:46:00.000","Title":"Python convert datetime to another format","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm using Linear Regression in scikit-learn and my dataset contains some cateogorical but numerical features.\nI mean that there are features such as the value of the district where the house is that are expressed by an integer number between 1 and 7: the more this number is high, the more the house is of value.\nShould I preprocess a feature that expresses a category (the district of the city) using numbers before Linear Regression with encoders such as OneHotEncoder? Or is it compulsory only when the category is expressed by characters?\nThank you in advance..","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":107,"Q_Id":61410222,"Users Score":0,"Answer":"If I understand correctly, you don't need to one hot encode these since they are ordinal, i.e. there is meaning in the order. If the numbers were product codes, for example, and there was no sense of 7 being \"better than\" or \"more than\" 4, then you would want to one-hot encode those variables, but in this case you would be losing information by one-hot encoding.","Q_Score":0,"Tags":"python,machine-learning,scikit-learn,linear-regression","A_Id":61410477,"CreationDate":"2020-04-24T14:03:00.000","Title":"scikit-learn, categorical (but numerical) features in Linear Regression","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"For context, I trained two separate autoencoders in Keras: one with a standard MSE loss function and one with a customized MSE loss function. When evaluating both models at a given point in training, they have very similar performance but the losses are very different.\nMy metric for performance is mean percent error. Both models are recreating the original image with mean error on the order of 3%. However, when these models were saved, the standard Keras MSE model had a loss less than 1.0 while the model with the customized MSE cost function had a loss on the order of 30.\nIf they perform on such a consistent level, why are the losses so drastically different?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":148,"Q_Id":61410625,"Users Score":1,"Answer":"Loss is just a scalar that says to model train which direction take to adjust weights. If you multiply a loss by a scalar, the result will be almost the same. \nIm not saying that the absolute value doesnt matter, it matters. But it's not the central point.\nProbably the difference in your case happens because Keras MSE do some normalizations that you dont.","Q_Score":0,"Tags":"python,tensorflow,keras,loss-function","A_Id":61411830,"CreationDate":"2020-04-24T14:23:00.000","Title":"What does it mean for the loss in Keras to be different by orders of magnitude between models?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a numpy array X with shape (100,3) and a numpy array sub_res with shape (100,). How can I multiply sub_res element-wise with X so that I can get the resultant shape (100,3)? I want to avoid loop usage.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":1013,"Q_Id":61414152,"Users Score":0,"Answer":"You can transpose X and then multiply it by sub_res using numpy.dot and finally transpose the final result.","Q_Score":0,"Tags":"python,numpy,numpy-ndarray,array-broadcasting","A_Id":61414263,"CreationDate":"2020-04-24T17:33:00.000","Title":"How can I multiply a column vector with a matrix element wise in Numpy","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have been trying the past 40 minutes to delete a specific column (Name) from my data frame but no method seems to work. I am using jupyter notebook by the way, not sure if that may be an issue. I am also 100% sure that the column name is named Name and that it is not the index of the data frame -- I am using the Titanic data set. \n\nWhat I have tried:\n\ndel df['Name']\ndf.drop('Name', axis=1, inplace=True)\ndf = df.drop('Name', 1)\n\nAll the above seem to delete the column, but when re-reading the csv the column appears back. Any clue on why this is happening?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":44,"Q_Id":61414234,"Users Score":0,"Answer":"With reading a csv file and loading its content in a dataframe, you create a python object called df.\nThen, with the three methods you showed us, you only delete some content of this object, not the csv's content.\nI would recommend you to use the first method, del, keep working with the dataframe and not reading the csv again.\nLet me know if anything is unclear, please.","Q_Score":0,"Tags":"python,pandas","A_Id":61414340,"CreationDate":"2020-04-24T17:38:00.000","Title":"Deleting a column in a pandas frame","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Is there an easy way to extract a list of all variables with start attribute from a Modelica model? The ultimate goal is to run a simulation until it reaches steady-state, then run a python script that compares the values of start attribute against the steady-state value, so that I can identify start values that were chosen badly. \nIn the Dymola Python interface I could not find such a functionality. Another approach could be to generate the modelDescription.xml and parse it, I assume the information is available somewhere in there, but for that approach I also feel I need help to get started.","AnswerCount":3,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":303,"Q_Id":61423053,"Users Score":3,"Answer":"The files dsin.txt and dsfinal.txt might help you around with this. They have the same structure, with values at the start and at the end of the simulation; by renaming dsfinal.txt to dsin.txt you can start your simulation from the (e.g. steady-state) values you computed in a previous run. \n\nIt might be worthy working with these two files if you have in mind already to use such values for running other simulations.\nThey give you information about solvers\/simulation settings, that you won't find in the .mat result files (if they're of any interest for your case)\n\nHowever, if it is only a comparison between start and final values of variables that are present in the result files anyway, a better choice might be to use python and a library to read the result.mat file (dymat, modelicares, etc). It is then a matter of comparing start-end values of the signals of interest.","Q_Score":2,"Tags":"python,attributes,modelica","A_Id":61455275,"CreationDate":"2020-04-25T08:38:00.000","Title":"Extract list of variables with start attribute from Modelica model","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"what does, train_data = scaled_data[0:training_data_len , : ] in python\ndoes it mean from 0 to training data length and then up to end\nI tried to use it on Jupiter notebook\nit is a code from machine learning problem","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":327,"Q_Id":61430560,"Users Score":1,"Answer":"you need to select rows starting from zero till training_data_len and all the columns from your scaled_data.","Q_Score":0,"Tags":"python","A_Id":61430649,"CreationDate":"2020-04-25T18:28:00.000","Title":"what does [ 0 : training_data_len , : ] meant here","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"So my questions is, are there functions within basic python libaries(such as pandas, numpy, matplotlib) to backtest without using backtesting liabries(such as pyalgotrade, backtesting.py and zipline). So could you backtest by just using basic libraries or do you have to use the backtesting liabries if you already had the historical data? Thanks","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":200,"Q_Id":61446028,"Users Score":5,"Answer":"There is no magic in programming. If a library implements it, you can do it as well.\nThe question is whether it is worth the amount of effort to re-do someone else's efforts, and whether you can do it better or not.","Q_Score":2,"Tags":"python,pandas,numpy,trading,back-testing","A_Id":61446088,"CreationDate":"2020-04-26T18:33:00.000","Title":"Is it possible to backtest trading algorithms without using backtesting libaries?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Can you suggest a module function from numpy\/scipy that can find local maxima\/minima in a text file? I was trying to use the nearest neighbours approach, but the data fluctuations cause false identification. Is it possible to use the neighbour's approach but use 20 data points as the sample_len.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":167,"Q_Id":61448975,"Users Score":0,"Answer":"scipy.signal.argrelmax looks for relative maxima in an array (there is also argrelmin for minima). It has the order keyword argument which allows you to compare eg. 20 neighbours.","Q_Score":0,"Tags":"python,python-3.x","A_Id":61457159,"CreationDate":"2020-04-26T22:32:00.000","Title":"Finding Local Minimum In 1d array","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a network which takes in an input image and outputs 37 values that are essentially the features. For e.g. the entire output class is a series of questions whose values are the percentage of people who agreed upon the said feature. 0.60 for class1 and 0.4 for class12. \nNow, there are some conditions such that the output of the model can't have one class that is higher than the other. E.g. class1.1 must be higher than class3.2 as it is a higher question in the decision tree. \nIs there any way we can implement this?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":20,"Q_Id":61460373,"Users Score":1,"Answer":"Instead of directly outputting a, b from your neural network you can output a, a + ReLU(b) which ensures the second output is higher than or equal to the first.","Q_Score":0,"Tags":"python,tensorflow,keras,conv-neural-network","A_Id":61460629,"CreationDate":"2020-04-27T13:46:00.000","Title":"Is there any way to ensure that your CNN model predicts outputs following certain thresholds?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a neural network which classify 3 output.My dataset is very small, I have 340 images for train, and 60 images for test. I build a model and when I compile at my result is this:\nEpoch 97\/100\n306\/306 [==============================] - 46s 151ms\/step - loss: 0.2453 - accuracy: 0.8824 - val_loss: 0.3557 - val_accuracy: 0.8922\nEpoch 98\/100\n306\/306 [==============================] - 47s 152ms\/step - loss: 0.2096 - accuracy: 0.9031 - val_loss: 0.3795 - val_accuracy: 0.8824\nEpoch 99\/100\n306\/306 [==============================] - 47s 153ms\/step - loss: 0.2885 - accuracy: 0.8627 - val_loss: 0.4501 - val_accuracy: 0.7745\nEpoch 100\/100\n306\/306 [==============================] - 46s 152ms\/step - loss: 0.1998 - accuracy: 0.9150 - val_loss: 0.4586 - val_accuracy: 0.8627\nwhen I predict the test images, test accuracy is poor.\nWhat should I do ? I also use ImageDatagenerator for data augmentation but the result is same.Is it because I have small dataset.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":89,"Q_Id":61464796,"Users Score":0,"Answer":"You can use Regularization on fully connected layers. But the fact that you already have high validation accuracy it's probably your data. your train data might not fully represent your test data. try to analyze that and make sure you do all the pre processing on the test data before testing as you did for the train data.","Q_Score":1,"Tags":"python,conv-neural-network","A_Id":61478761,"CreationDate":"2020-04-27T17:31:00.000","Title":"High train accuracy poor test accuracy","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have an encoder decoder network with : 3 BLSTMs in the encoder and 2 vanilla LSTMs in the decoder connected with a mutli head attention with 4 nodes. Latent dimension is 32 and my total sample looks like (10000,400,128). The encoder network has a dropout of 0.2 and the decoder has a dropout of 0.3. I'm using an adam optimizer with a learning rate of 0.001 and Mean Squared error loss. Finally I have a validation split of 0.3. I rented an Nvidia Titan V (with Core\u2122 i9-9820X, 5.0\/20 cores and 16\/64 GB total effective shared RAM) on Vast.ai and it takes ~6 minutes for each epoch when I train it all together (7000 train and 3000 validation samples).\nI was hoping to find ways of reducing the total train timing. Any suggestions would be great.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":689,"Q_Id":61474472,"Users Score":1,"Answer":"The first things that pop into mind are early stopping callbacks and change the batch size.\nAlthough I haven't tried that on my own, batch normalization is considered to also make the training more efficient.\nIn my (not so relevant) case, I saw a great improvement in training speed and quality after normalizing the data. So, maybe data normalization\/standardization could help a bit.\nLast but not least, GRU networks tend to train faster, but in some cases they under-perform in relation to LSTM networks. I don't know if you are willing to change your model, but I thought I should mention this.","Q_Score":0,"Tags":"python,tensorflow,keras,lstm,encoder-decoder","A_Id":61476847,"CreationDate":"2020-04-28T07:03:00.000","Title":"Strategies to speed up LSTM training","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Can i directly use the command numpy.ndarray.ndim(arr) to get the no. of dimensions for an array ?? without importing numpy. Is it possible ??","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":60,"Q_Id":61478187,"Users Score":0,"Answer":"No, without importing a module you can't use anything defined in that module.","Q_Score":0,"Tags":"python,arrays,numpy","A_Id":61478558,"CreationDate":"2020-04-28T10:38:00.000","Title":"Using numpy.ndarray.ndim(arr) directly get the number of dimensions","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"File \"\/Users\/zineb\/.local\/lib\/python2.7\/site-packages\/nltk\/probability.py\", line 333\nprint(\"%*s\" % (width, samples[i]), end=\" \")\n ^\nSyntaxError: invalid syntax","AnswerCount":1,"Available Count":1,"Score":0.537049567,"is_accepted":false,"ViewCount":4152,"Q_Id":61483027,"Users Score":3,"Answer":"You shouldn't be developing using python 2.7 anymore, 3.xx has been out for a long time and 2.x was EOL'd recently. Mac OS X has python3 installed as \/usr\/bin\/python3.\nTo fix this error, you'll need to add from future import print_function at the top of \/Users\/zineb\/.local\/lib\/python2.7\/site-packages\/nltk\/probability.py.","Q_Score":5,"Tags":"python,jupyter-notebook","A_Id":61483116,"CreationDate":"2020-04-28T14:45:00.000","Title":"when running import nltk, Syntax Error is displayed","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I was going through some solutions for an online code for sorting a series . In this case, why is pd.Series called twice ? what is the point when it seems to create the same series?\nimport pandas as pd\ns = pd.Series(['100', '200', 'python', '300.12', '400'])\nprint(\"Original Data Series:\")\nnew_s = pd.Series(s).sort_values()\nprint(new_s)\nalso, why does pd.apply(pd.Series) create a Dataframe? Thank you!!","AnswerCount":4,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":78,"Q_Id":61494223,"Users Score":0,"Answer":"I think you could simply write it this way:\ns = pd.Series(['100', '200', 'python', '300.12', '400'])\nnew_s = s.sort_values()\nprint(new_s)","Q_Score":0,"Tags":"python,pandas,dataframe","A_Id":61494279,"CreationDate":"2020-04-29T04:26:00.000","Title":"Why is pd.Series called twice?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using tensorflow to train a RNN with more than 200k of data , the training process takes up to 2 hours for every epoch. I save the model for every epoch with custom callback and this function:\nmodel.save_weights()\ncan I stop the training and resume it later from last epoch like this? Does it make a diffrence in the result?\nmodel.load_wieghts(last_epoch_dir)\nmodel.fit()","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":61,"Q_Id":61500035,"Users Score":2,"Answer":"Yes, you can retrain from the last epoch but the problem is that you might loose your optimiser state but it\u2019s no problem because optimiser will go back to its original state or even better within a few epochs.","Q_Score":0,"Tags":"python,tensorflow,keras,neural-network,recurrent-neural-network","A_Id":61500188,"CreationDate":"2020-04-29T10:49:00.000","Title":"Tensorflow train on a saved model","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm implementing a pytorch neural network (regression) and want to identify the best network topology, optimizer etc.. I use cross validation, because I have x databases of measurements and I want to evaluate whether I can train a neural network with a subset of the x databases and apply the neural network to the unseen databases. Therefore, I also introduce a test database, which I doesn't use in the phase of the hyperparameter identification.\nI am confused on how to treat the number of epochs in cross validation, e.g. I have a number of epochs = 100. There are two options:\n\nThe number of epochs is a hyperparameter to tune. In each epoch, the mean error across all cross validation iterations is determined. After models are trained with all network topologies, optimizers etc. the model with the smallest mean error is determined and has parameters like: -network topology: 1\n-optimizer: SGD\n-number of epochs: 54\nTo calculate the performance on the test set, a model is trained with exactly these parameters (number of epochs = 54) on the training and the validation data. Then it is applied and evaluated on the test set.\nThe number of epochs is NOT a hyperparameter to tune. Models are trained with all the network topologies, optimizers etc. For each model, the number of epochs, where the error is the smallest, is used. The models are compared and the best model can be determined with parameters like:\n-network topology: 1 \n-optimizer: SGD\nTo calculate the performance on the test data, a \u201csimple\u201d training and validation split is used (e.g. 80-20). The model is trained with the above parameters and 100 epochs on the training and validation data. Finally, a model with a number of epochs yielding the smallest validation error, is evaluated on the test data.\n\nWhich option is the correct or the better one?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":523,"Q_Id":61504356,"Users Score":0,"Answer":"The number of epochs is better not to be fine-tuned.\nOption 2 is a better option.\nActually, if the # of epochs is fixed, you need not to have validation set. Validation set gives you the optimal epoch of the saved model.","Q_Score":1,"Tags":"python,neural-network,pytorch,cross-validation","A_Id":64492698,"CreationDate":"2020-04-29T14:33:00.000","Title":"Cross-validation of neural network: How to treat the number of epochs?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a time-series data frame with 27 different variables. In reality, they are all different instruments recording the same measurand every 5 minutes.\nI want to know if there is a way of determining which (say top 5 most similar) of the variables are numerically most similar.\nIf I was to calculate this, I would calculate the average difference between the recorded values for every possible instrument pair for every 5 minutes and then find the 5 instrument pairs with the smallest average difference. Doing this manually would take a long time, as I would need to calculate approximately 27*27=729 pairs and then find the pairs with the smallest average difference.\nIs there a better\/simpler way of doing this?\nI have looked into correlation, but this will not yield the result I want - this will show how correlated the variables are, not which ones are most similar numerically.\nHopefully, this makes sense.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":21,"Q_Id":61504969,"Users Score":0,"Answer":"Since it is a measurement problem, maybe what you want to look at is how similarly the instruments mismeasure the ground truth or actual phenomenon. That is, look at the correlation of the measurement error (defined as the measurement minus the ground truth) between pairs of instruments. \nIf you create a matrix X which has 1 column for each instrument and 1 row for each set of measurement errors at a given time, then the correlation is just transpose(X) times X. If you don't have ground truth, maybe the mean of the measurements is a workable substitute. If you aren't measuring the instruments all at the same time, calculating the correlation between errors will be more involved.\nSince this is mostly a discussion question, it's really more suitable for stats.stackexchange.com. Good luck and have fun, it's an interesting problem.","Q_Score":1,"Tags":"python,statistics,time-series","A_Id":61505972,"CreationDate":"2020-04-29T15:01:00.000","Title":"Is there a way to determine the most similar variables from a number of different time-series?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to return the index of my DataFrame as a string. I am using this commandp_h = peak_hour_df.index.astype(str).str.zfill(4) It is not working, I am getting this result: Index(['1645'], dtype='object', name I need it to return the string '1645' How do I accomplish this?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":161,"Q_Id":61508867,"Users Score":2,"Answer":"In short:\ndo p_h = list(peak_hour_df.index.astype(str).str.zfill(4)). This will return a list and then you can index it.\nIn more detail:\nWhen you do peak_hour_df.index.astype(str), as you see, the dtype is already an object (string), so that job is done. Note this is the type of the contents; not of the object itself. Also I am removing .str.zfill(4) as this is additional and does not change the nature of the problem or the retuning type.\nThen the type of the whole objet you are returning is pandas.core.indexes.base.Index. You can check this like so: type(peak_hour_df.index.astype(str)). If you want to return a single value from it in type str (e.g. the first value), then you can either index the pandas object directly like so:\npeak_hour_df.index.astype(str)[0]\nor (as I show above) you can covert to list and then index that list (for some reason, most people find it more intuitive):\n\npeak_hour_df.index.astype(str).to_list()[0]\nlist(peak_hour_df.index.astype(str))[0]","Q_Score":2,"Tags":"python-3.x,pandas,dataframe","A_Id":61509026,"CreationDate":"2020-04-29T18:17:00.000","Title":"Returning a Pandas DataFrame Index as a String","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a group of excel files in a directory. I put the list of file names in a list and iterate over them to concatenate certain columns into a single file. Periodically, one of the files does not have the proper sheet name, and the my notebook throws an error. \nI get it that I could first open the file another way and then query the file to see if it contains the sheet_name. I just want to be Pythonic: I am asking if file lacks sheet_name='Unbilled' go to next file. \n...\nfor file in files_to_process:\n df = pd.read_excel(file, usecols=colNames, sheet_name='Unbilled', index=0, header=4)\n...\nI am doing this in a Jupyter notebook, just FYI","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":58,"Q_Id":61511574,"Users Score":0,"Answer":"As I thought about my question while working on my question in stackoverflow and reading not on point questions, an answer came to me. This works and seems Pythonic to me:\n...\nfor file in files_to_process:\n try:\n df = pd.read_excel(file, usecols=colNames, sheet_name='Unbilled', index=0, header=4)\n except:\n print('The following file lacks sheet_name=Unbilled: ', file)\n pass\n...","Q_Score":0,"Tags":"python,excel,pandas,iterator,try-catch","A_Id":61511575,"CreationDate":"2020-04-29T20:59:00.000","Title":"iterating through list of excel files; how to skip opening file if excel file lacks sheet_name criteria","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm analysing a big graph - 30M nodes and 350M+ edges - using the python interface of igraph. I can load the edges without any issue but executing a function like transitivity_local_undirected to compute the clustering coefficient of each node returns the error \"Transitivity works on simple graphs only, Invalid value\".\nI can't find anything online - any help would be much appreciated, thanks!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":247,"Q_Id":61525978,"Users Score":0,"Answer":"A simple graph is a graph with no loops or multiple edges -- it sounds like the computer thinks your graph is non-simple for some reason.\nAre you sure your nodes have no loops or multiple edges between them?","Q_Score":0,"Tags":"python,igraph","A_Id":61526091,"CreationDate":"2020-04-30T14:38:00.000","Title":"\"Transitivity works on simple graphs only\" InternalError in igraph","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Does anyone have or know of any tutorials \/ courses that teach q learning without the use of open ai gym.\nI'm trying to make a convolutional q learning model and I have no problem doing this with pytorch and open ai gym, easy! but when I try and apply it all to an environment that isn't in open ai gym its a whole different story, trying to apply this to other games that aren't Atari so I don't have access to the env.reset and all those other nice options, it becomes a whole new ball game. If someone knows of a place to learn this or who is willing to teach me \/ help me with it I am more than willing to pay for any help as well.\nThanks.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":1305,"Q_Id":61526437,"Users Score":0,"Answer":"You can take a code of an environnement such as a game and then you implement your algorithms. \nBut think to be explicit in your code for the rewards and the actions. Return a reward for each action. \nIf you want to start RL without Gym. Try to do a simple game and implement NEAT algorithm. And then try to implement Q-learning and modify your code to add a reward for each action.","Q_Score":2,"Tags":"python,reinforcement-learning,q-learning","A_Id":62005390,"CreationDate":"2020-04-30T14:58:00.000","Title":"Deep Q Learning **WITHOUT** OpenAI Gym","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Say I have N numpy arrays, each of size (x, y, z), where y and z are the same for all but x differs for each. How would I combine these to a numpy array of size (w, y, z) where w is the sum of all x.\nOr, for a numerical example: I have a list of 3 numpy array with sizes (14, 32, 32), (7, 32, 32), (50, 32, 32). How do I turn these into a (71, 32, 32) sized numpy array efficiently?","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":94,"Q_Id":61534749,"Users Score":3,"Answer":"You can just concatenate them along the first axis. If your 3 numpy arrays are named x1, x2, and x3, your new array would be defined as x_combined = np.concatenate((x1,x2,x3),axis=0)","Q_Score":1,"Tags":"python,numpy,numpy-ndarray","A_Id":61534786,"CreationDate":"2020-04-30T23:54:00.000","Title":"List of numpy arrays to one numpy array","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm new to Python, so my question may be very basic, sorry\/\/ \nI'm struggling to create one dummy variable on two columns in Python. I have a column(died) which is a dummy on its own with 1 corresponding to a death, 0 - no death. The second column is 'Age' that tells the age of death in months. What i need is to create a dummy for children who died before 5 years ('died'==1 & 'Age' < 60) and a dummy for children who died before 1 year ('died' == 1 & Age' < 12). I usually work in Stata in which this is very easy, but in Python I am struggling. I've been trying to use get_dummies function from pandas:\n dummy= pd.get_dummies(df['died']) & (df.aad < 60.).astype('int') \nbut it returns an error that it can't perform add, my guess is that it can't add indicator variable'died' with a continuous variable 'aad'. Is there a straightforward (beginner friendly) way to combine information from two columns to generate a new dummy variable? Thanks a lot!","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":144,"Q_Id":61550532,"Users Score":1,"Answer":"import numpy as np\ndf['dummy'] = np.where((df['died']==1) & (df['aad']<60), 1, 0)","Q_Score":0,"Tags":"python,pandas,dummy-variable","A_Id":61551121,"CreationDate":"2020-05-01T20:44:00.000","Title":"Dummy variable from two columns in Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"can someone give me a hint on how I can load a model, trained and exported in python with keras, with the C++ API of tensorflow 2.0?\nI can't find information about that, only with tensorflow version < 2.\nKind regards","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":4107,"Q_Id":61552420,"Users Score":0,"Answer":"You have to check the inputs and output names. Use tensorboard option for show the model structure. It is in Graph tab. Or some net viewer like Netron, etc.","Q_Score":7,"Tags":"python,c++,keras,load,tensorflow2.0","A_Id":69650057,"CreationDate":"2020-05-01T23:31:00.000","Title":"TensorFlow 2.0 C++ - Load pre-trained model","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a text and want to find e.g.\n\nAll Animals\nAll Superlatives\n\nIs there a \"simple\" way to do this?\nIm completely new to NLP.\nIm not even sure if this is a NLP Problem in the first place.\nOr does this just sound simple and is actually very complex?\nIf you have a tip for adding\/removing tags on this question all feedback is welcome.","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":177,"Q_Id":61553401,"Users Score":2,"Answer":"You don't need anything sophisticated to do this. It can be achieved with simple string matching, with a few caveats:\n\nAnimals - simply create a list of animals you want to recognise. You can probably find lists of animals on the web, Wikipedia, or similar. The complication is that you might need to trim a plural marker (horse\/horses \u2014 I'm assuming English here). You could simply look up each word in the list, and if it's not in there and ends in -s, look again with the final s trimmed off. Irregular plurals exist (ox\/oxen), but there are very few of those.\nSuperlatives - again you can create a list. Superlative forms usually end in -est, so just get an English word list, throw away everything that doesn't end in -est, and then go through the remaining words removing false positives like nest etc. There will also be some irregular ones. How do you want to treat combined ones, such as most beautiful? In that case you might check for most followed by an adjective.\n\nFor superlatives there would be a second, more complicated, option, and that is using a part-of-speech tagger. Tag your text, and then get all words that have been tagged as superlative adjective. In most English tagsets that will be JJS. But taggers are not necessarily better than a word-list in terms of accuracy, so it depends on how much effort you want to spend on it.\nYou gave those as examples. For many other categories of words there are similar ways of just extracting them fairly easily, without needing complicated machine learning systems. But don't forget that creating lists might be a low-tech solution that might be quickest and most easy, with the best accuracy.","Q_Score":1,"Tags":"python,nlp,nltk,spacy","A_Id":61558948,"CreationDate":"2020-05-02T01:38:00.000","Title":"Finding words with specific criteria in a text in python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to implement a function interpolate(x, y, X_new) that computes the linear interpolation of the unknown function f at a new point x_new. The sample is given in the form of two sequences x and y. Both sequences have the same length, and their elements are numbers. The x sequence contains the points where the function has been sampled, and the y sequence contains the function value at the corresponding point. (without using import statement).","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":388,"Q_Id":61554543,"Users Score":0,"Answer":"As I understand your question, you want to write some function y = interpolate(x_values, y_values, x), which will give you the y value at some x? The basic idea then follows these steps:\n\nFind the indices of the values in x_values which define an interval containing x. For instance, for x=3 with your example lists, the containing interval would be [x1,x2]=[2.5,3.4], and the indices would be i1=1, i2=2 \nCalculate the slope on this interval by (y_values[i2]-y_values[i1])\/(x_values[i2]-x_values[i1]) (ie dy\/dx).\nThe value at x is now the value at x1 plus the slope multiplied by the distance from x1.\n\nYou will additionally need to decide what happens if x is outside the interval of x_values, either it's an error, or you could interpolate \"backwards\", assuming the slope is the same as the first\/last interval.\nDid this help, or did you need more specific advice?","Q_Score":1,"Tags":"python","A_Id":61554695,"CreationDate":"2020-05-02T04:38:00.000","Title":"How to implement linear interpolation in python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have created model dogs and cats classifier using CNN using tensorflow.Its accuracy is around 90% and validation accuracy is 80%.But when I input my own downloaded images of cats and dogs it gives wrong results.I make sure that the input images are of the same size as that when used in training.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":27,"Q_Id":61560918,"Users Score":0,"Answer":"I had same problems when I started some tutorial. Please check that you have the same color channels (like RGB). In my case the training and validation set had other color channels than the images I downloaded.","Q_Score":0,"Tags":"python,tensorflow,deep-learning,classification,conv-neural-network","A_Id":61563183,"CreationDate":"2020-05-02T14:25:00.000","Title":"Created model in CNN doesnt give the expected result","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"say you have a dataset of relatively similar images and for each image, the first half of the image is the input and the second half would be the output of the model. In other word you want to teach the model the first half of a single image, and have it generate the second half. which framework would best suit this issue?","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":63,"Q_Id":61561316,"Users Score":2,"Answer":"You can read about Generative Adversarial Networks (GANs). Then use either PyTorch \n or Tensorflow on Python, though PyTorch is pretty famous for GANs.","Q_Score":0,"Tags":"python,tensorflow,deep-learning","A_Id":61561395,"CreationDate":"2020-05-02T14:51:00.000","Title":"which deep learning framework to use for generating predictive images","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Is there a way to see the vectors I got per paragraphs and not per each word in the vocabulary with doc2vec. By using model.wv.vectors I get all the vectors per words. Now, I would need this in order to apply a clusterization algorithm on the embedded paragraphs which I can hopefully obtain. I am not sure though if this approach is good. This is how the paragraphs look:\n[TaggedDocument(words=['this', 'is', 'the', 'effect', 'of', 'those', 'states', 'that', 'went', 'into', 'lockdown', 'much', 'later', 'they', 'are', 'just', 'starting', 'to', 'see', 'the', 'large', 'increase', 'now', 'they', 'have', 'to', 'ride', 'it', 'out', 'and', 'hope', 'for', 'the', 'best'], tags=[0])\nTaggedDocument(words=['so', 'see', 'the', 'headline', 'is', 'died', 'not', 'revised', 'predictions', 'show', 'more', 'hopeful', 'situation', 'or', 'new', 'york', 'reaching', 'apex', 'long', 'before', 'experts', 'predicted', 'or', 'any', 'such', 'thing', 'got', 'to', 'keep', 'the', 'panic', 'train', 'rolling', 'see'], tags=[1])]","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":19,"Q_Id":61565514,"Users Score":0,"Answer":"model.docvecs.vectors will contain all the trained-up document vectors.","Q_Score":0,"Tags":"python,doc2vec","A_Id":61565956,"CreationDate":"2020-05-02T20:00:00.000","Title":"Is there a way in which I can get the equivalent list of vectors per paragraph in doc2vec?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm currently using elastic beanstalk and apscheduler to run Pandas reports everyday automatically on it. The data set is getting larger and i've already increased the memory size 3x. \nElastic Beanstalk is running Dash - dashboard application and runs the automated Pandas reports once every night. \nI've tried setting up AWS Lambda to run Pandas reports on there but I couldn't figure out how to use it. \nI'm looking for the most cost-effective way to run my reports without having to increase memory usage on Beanstalk. When I run it locally it takes 1gb but running it on beanstalk, it's using more than 16gb. \nCurious if someone else has a better option or process how they automatically run their Pandas reports.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":43,"Q_Id":61566053,"Users Score":0,"Answer":"Create an .exe using Pyinstaller\nSchedule .exe on Task Scheduler on computer\nCheaper than scaling AWS Beanstalk resources which use more resources calculating pandas than your computer locally at least for my case.","Q_Score":0,"Tags":"python,pandas,amazon-web-services,amazon-elastic-beanstalk","A_Id":63367773,"CreationDate":"2020-05-02T20:44:00.000","Title":"What options are there to setup automatic reporting processes for Pandas on AWS?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":1,"Web Development":1},{"Question":"i have a question just for a general case. So i am working with the poker-hand-dataset, which has 10 possible outputs from 0-9, each number gives a poker-hand, for example royal flush.\nSo i read in the internet, that it is necessary to use OHE in a multiclass problem because if not there would be like a artificial order, for example if you work with cities. But in my case with the poker hands there is a order from one pair over flush and straight to royal flush, right?\nEven though my nn performs better with OHE, but it works also (but bad) without.\nSo why does it work better with the OHE? I did a Dense Network with 2 hidden layer.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":45,"Q_Id":61572297,"Users Score":1,"Answer":"Short answer - depending on the use of the feature in the classification and according to the implementation of the classifier you use, you decide if to use OHE or not. If the feature is a category, such that the rank has no meaning (for example, the suit of the card 1=clubs, 2=hearts...) then you should use OHE (for frameworks that require categorical distinction), because ranking it has no meaning. If the feature has a ranking meaning, with regards to the classification, then keep it as-is (for example, the probability of getting a certain winnig hand).\nAs you did not specify to what task you are using the NN nor the loss function and a lot of other things - I can only assume that when you say \"...my nn performs better with OHE\" you want to classify a combination to a class of poker hands and in this scenario the data just presents for the learner the classes to distinguish between them (as a category not as a rank). You can add a feature of the probability and\/or strength of the hand etc. which will be a ranking feature - as for the resulted classifier, that's a whole other topic if adding it will improve or not (meaning the number of features to classification performance).\nHope I understood you correctly.\nNote - this is a big question and there is a lot of hand waving, but this is the scope.","Q_Score":0,"Tags":"python,neural-network,one-hot-encoding","A_Id":61572776,"CreationDate":"2020-05-03T09:32:00.000","Title":"Why performs the NN better with OneHotEncoding?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Suppose I run the GC-test:\ngrangercausalitytests(np.vstack((df['target'], df['feature'])).T, maxlag=5)\nI can pick the lag of the \"feature\" variable, which most likely Granger-causes the \"target\" variable. \n\nBut what number of lags does the \"target\" variable have in this model? \nFurther, how do I estimate this ADL model (some autoregressive lags + some lags of the independent variable)? I've seen somewhere, that ADL should be substituted with OLS\/FGLS in Python, since there is no package for ADL. Yet I do not understand how to do that","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":54,"Q_Id":61573582,"Users Score":0,"Answer":"I found out that the model, corresponding to each particular number\nof lags in the GC-test has already been fit and is contained in the\ntest return. The output looks messy, but it's there. \nUnfortunately,\nthere seems to be no capacity to estimate ADL models in Python yet\n:(","Q_Score":0,"Tags":"python,statistics,statsmodels","A_Id":61598835,"CreationDate":"2020-05-03T11:20:00.000","Title":"How to estimate the optimal model, following from the granger causality test?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Problem statement\nI doing 3D reconstruction using Logitech webcam with fixed lens before. Every time I change distance between scene and camera I need to manually adjust lens focus by hand. (Open the cover and turn lens knob) which very inconvenience. So I decide to by new webcam with auto focus feature (Logitech C922) and gonna use it in project. than I notice then when focus change, The image change a bit not only blur and sharpness and also scaling.\n I've read the article about camera calibration, it said I must fixed focus length when calibrating and and use same focus length while running application. which means I need to re-calibrate every time I use camera in new environment (distance changed cause focus length to change).\nThe question\n\nThe focus length only move the lens form image sensor, is it possible to find relation of camera focus value to camera matrix (intrinsic and extrinsic) and how?\nHow to use camera in vary distant without re-calibration?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":417,"Q_Id":61575873,"Users Score":1,"Answer":"With a cheap webcam? No.\nGet yourself a better lens with longer depth-of-field and\/or an iris that can be closed\n\nEdited\nBy \"cheap webcam\" above I mean any autofocus camera\/lens combination without (a) highly repeatable focusing geartrain and (b) programmatic access to the lens focus control setting. Point (a) is - of course - required for any form of calibration. Point (b) allows one to build a table of calibration parameters keyed on the focus setting. I have seen this done in some applications where dynamical focusing was an unavoidable requirement, but the necessary gear tends to be very expensive and fragile.","Q_Score":0,"Tags":"python,opencv,autofocus","A_Id":61583268,"CreationDate":"2020-05-03T14:12:00.000","Title":"How to use auto focus along side with 3d reconstruction using python opencv","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"When trying to import tensorflow I keep on getting this error. I have tried reinstalling tensorflow but I still revive this problem on this statement:\nimport tensorflow as tf\nDoes anyone have advice? Tensorflow worked on my system before I originally reinstalled it but now I have no luck. Thanks.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":459,"Q_Id":61581658,"Users Score":0,"Answer":"I ended up deleting my python and re downloading it","Q_Score":0,"Tags":"python,tensorflow","A_Id":63651632,"CreationDate":"2020-05-03T21:09:00.000","Title":"module 'tensorflow.python.keras.utils.generic_utils' has no attribute 'populate_dict_with_module_objects'","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working on measuring the projected area of a cube facing the sun for my spacecraft coursework. The cube is of 1x1x1 dimensions, and constantly rotates due to its orbit. Using a program called \"STK\", data for the angle shift according to a reference was obtained. So now I have the shift of orientation of the cube every 30 minutes but now I need to calculate how much of the projected area will be exposed to the sun (I can assume the Sunlight is coming from a single direction).\nI need to be able to translate the coordinate shift in orientation of the cube to how much of a projected area will be facing the sun at each interval of time. Let me give you an example:\nAt the initial time, the cube is facing you (you are the sun...because you are my sunshine ;) ) and no shift has occurred, hence the projected area will be 1 m^2.\nAfter 30 mins, there has been a shift only on the x axis of 45 degrees. Now the projected area is 1.4142 m^2 (since cos 45 * 1 = 0.7071 and now you have 2 faces facing you).\nAfter 60 mins, only a shift in the y axis occurs (45 degrees). Now you have 3 partial faces of the cube facing you and possess a projected area of 1.707 m^2.\nThis isn't to hard to do with little shifts, but I need to do this for multiple (more than a 100 shifts). I am thinking of writing a python program that rotates a 3D object and measures the projected area at each interval. Any recommendations on libraries that allow 3D body definition and rotation? libraries that can measure areas of projected surfaces?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":389,"Q_Id":61583787,"Users Score":1,"Answer":"Establish a unit vector perpendicular to each face of the cube. Depending on the output of your rotation program, you may be using angular rotations from the base axes or you can take vector cross product of 2 edges of face (be careful w\/ right hand rule to ensure result faces outward)\ntake the dot product of each of the resultant 6 vectors individually with a vector \"pointing to the sun\"\ndrop any negative results (facing away from sun)\nsum the remainder\n\nUnit vectors will suffice because the surface area of each face is 1 sq unit.","Q_Score":0,"Tags":"python,image-processing,vector","A_Id":61584119,"CreationDate":"2020-05-04T01:21:00.000","Title":"Projected Area calculation of a cube","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I\u00b4m new to Python and I\u00b4m having a problem. I have 2 lists containing the names of the columns of a dataset: one has all the columns names (columnas = total.columns.values.tolist()); and the other one has a subset of them ( in the form of \"c = [a,b,c,d,c,e,...]\".\nI would like to know how could I check if each element in \"c\" is contained in the longer list \"columnas\". The result i have been trying to get is as it follows ( this is just an example):\na: True \nb: True\nc: False\n...\nLooking forward to your answers, Santiago","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":45,"Q_Id":61593044,"Users Score":1,"Answer":"a=[ ]\nfor i in c:\n if i in columns:\n a.append(true)\n else:\n a.append(false)\na=[ ]\nfor i in c:\n if i in columns:\n a.append(true)\n else:\n a.append(false)","Q_Score":1,"Tags":"python,string,list,contains,exists","A_Id":61593126,"CreationDate":"2020-05-04T13:11:00.000","Title":"How do i check if the elements in a list are contained in other list?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to identify the fittings of the transmission line first, and then the micro parts such as bolt and pin. I may have to train a model using tensorflow and will apply in UAV inspection. Any suggestions?(existed or related algorithm\/paper\/idea) Thanks!!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":18,"Q_Id":61593698,"Users Score":0,"Answer":"You can you instance segmentation. Annotate at pixel level the bolts and pins, you can then train Mask RCNN. Hope it helps?","Q_Score":0,"Tags":"python,tensorflow,deep-learning,computer-vision,object-detection","A_Id":61599248,"CreationDate":"2020-05-04T13:43:00.000","Title":"How to recognize a larger object and then some tiny ones in it in a picture?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm working on a biomedical image segmentation task. The data I got from the hospital has been split into training set, validation set, test set. But I'm confused about the splitting. \nThe data consists of images from different patients, each patient has 2 ~ 3 2D slices taken from the 3D image. For one patient, his or her 2 ~ 3 slices are adjacent or close to each other, which means that these slices have only very small differences that are barely visible to the naked eye. These 2~3 slices are split into training set, test set and validation set. So the proportion of training set, test set and validation set is close to 1:1:1. \nHowever, the splitting of medical image datasets I found is mostly based on patients. Three sets are slices of different patients, instead of distributing the slices of the same patient into three sets like the hospital's way. I'll give an example.\nExample\nLet i_j be the j-th slice of the i-th patient, and i_j & i_j+1 are adjacent slices. All slice numbers are as follows:\n\n1_1 1_2 1_3 \/ 2_1 2_2 2_3 \/ 3_1 3_2 3_3 \/ 4_1 4_2 \/ 5_1 5_2\n\nA possible splitting in the hospital's way:\n\nTrain: 1_1 2_1 3_1 4_1 5_1 Val: 1_2 2_2 3_2 4_2 Test: 1_3 2_3 3_3 5_2\n\nA possible splitting in my way:\n\nTrain: 1_1 1_2 1_3 2_1 2_2 2_3 4_1 4_2 Val: 3_1 3_2 3_3 Test: 5_1 5_2\n\nI think in the first way, the training set, validation set and test set are actually too similar. This will make the accuracy rate of the validation set and training set higher, but the generalization ability of the model will be worse. So which splitting method is correct? Or both are OK?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":459,"Q_Id":61596143,"Users Score":1,"Answer":"Your way is definitely the right way to go. The hospital's method will lead to massive overfitting for exactly the reasons you specified.","Q_Score":1,"Tags":"python,dataset,semantic-segmentation","A_Id":67388911,"CreationDate":"2020-05-04T15:44:00.000","Title":"Dataset spliting in semantic segmentation","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am quite confused by Tensorflow's reduce axis function. For example, reduce_max(). Suppose I have a four dimension variable a with a shape of a = [x, y, z, w] where x, y, z, and w are the length that dimension. I have a command like b = tf.reduce_max(a, axis=(1, 3)), in this case, what will be the shape of b? b = [x, z] or b=[y, w]? Basically, I am just wondering which axis is the reduce_max() operating on. If the axis is defined from 0, then b = [x, z]. Otherwise, b = [y, w].","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":275,"Q_Id":61599630,"Users Score":1,"Answer":"So you have a tensor a, with shape [x, y, z, w]. When using a function which expects the axis parameter, the axis numbering for a will be [0, 1, 2, 3]. Reducing axes 1 and 3 results in those axes \"disappearing\" (because you are reducing those axes), so the output will consist of original axes [0, 2] which means the resulting shape is [x, z].","Q_Score":0,"Tags":"python,numpy,tensorflow","A_Id":61599838,"CreationDate":"2020-05-04T18:59:00.000","Title":"tensorflow axis definition starts from 0 or 1?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am having an issue with SciPy not importing properly in my DM script. The script will get stuck on the \"import scipy\" line. I installed scipy using miniconda, have tried reinstalling with no success. \nThank you","AnswerCount":3,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":84,"Q_Id":61602031,"Users Score":0,"Answer":"DM uses C:\\ProgramData\\Miniconda3\\envs\\GMS_VENV_PYTHON for Phyton environment, so you should install scipy there, I don't know how select that location to install, so I\n\ninstall Miniconda3 in a folder \"user\\Miniconda3\"\nRun AnacondaPromt(miniconda3) and install scipy by run \"conda install scipy\"\ncopy content of \"user\\Miniconda3\" folder to \"C:\\ProgramData\\Miniconda3\\envs\\GMS_VENV_PYTHON\"","Q_Score":0,"Tags":"python,scipy,dm-script","A_Id":64543507,"CreationDate":"2020-05-04T21:34:00.000","Title":"SciPy will not import while trying to run DM script","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am having an issue with SciPy not importing properly in my DM script. The script will get stuck on the \"import scipy\" line. I installed scipy using miniconda, have tried reinstalling with no success. \nThank you","AnswerCount":3,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":84,"Q_Id":61602031,"Users Score":0,"Answer":"(Windows) I have found that on my system using pip as recommended (via pip install x) does not work for any package, however using conda as not recommended (via conda install) in the command prompt allowed me to install scipy for GMS.\nAlso make sure you start the command prompt in administrator mode.","Q_Score":0,"Tags":"python,scipy,dm-script","A_Id":62766482,"CreationDate":"2020-05-04T21:34:00.000","Title":"SciPy will not import while trying to run DM script","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm using OneHotEncoding to generate dummies for a classification problem. When used on the training data, I get ~300 dummy columns, which is fine. However, when I input new data (which is fewer rows), the OneHotEncoding only generates ~250 dummies, which isn't surprising considering the smaller dataset, but then I can't use the new data with the model because the features don't align.\nIs there a way to retain the OneHotEncoding schema to use on new incoming data?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":23,"Q_Id":61604255,"Users Score":1,"Answer":"I think you are using fit_transform on both training and test dataset, which is not the right approach because the encoding schema has to be consistent on both the dataset for the model to understand the information from the features. \nThe correct way is do \n\nfit_transform on training data\ntransform on test data\n\nBy doing this way, you will get consistent number of columns.","Q_Score":0,"Tags":"python,scikit-learn,one-hot-encoding","A_Id":61613724,"CreationDate":"2020-05-05T01:23:00.000","Title":"How to retain Scikit-learn OneHotEncoding from model generation to use on new data?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"My primary issue is to somehow localize the range of k-values to perform the elbow-analysis on. At present, I can only think of a range between 2 to min(num_rows, num_columns). Is there any other optimal method that might be more suitable, especially if you have a dataset that has an extremely large number of rows and columns?\nP.S., also, is there some way to automate it so that we do not have to look at the elbow-plot? At present, I'm using the KneeLocator function of the Kneed library but I wanted to consider more options. \nThank you.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":24,"Q_Id":61604365,"Users Score":1,"Answer":"As you might know, there is not always an \"elbow\". Even if there is one, that does not necessarily represent the best number of clusters.\nThe KneeLocator function of Kneed is probably your best bet, because it finds the K with maximum curvature.","Q_Score":0,"Tags":"python,cluster-analysis,k-means","A_Id":61604427,"CreationDate":"2020-05-05T01:39:00.000","Title":"Is there any study on what the optimal range will be k-values in the elbow method?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to create a vector with the size 10^15 with numpy and fill it with random numbers, but I get the following error:\nMaximum allowed dimension exceeded.\nCan it help if i use MPI? \nThank you","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":65,"Q_Id":61611256,"Users Score":0,"Answer":"The Message Passing Interface (MPI) is mainly used to do parallel computations across multiple machines (nodes). Large arrays can be split into smaller arrays and stored on different machines. However, while it's of course possible to distribute the data to different nodes, you should carefully think about the necessity of doing this for your particular task. Additionally, if you are able to split your array, you could also do this on one machine. If performance is not an issue, avoid parallel computing.","Q_Score":0,"Tags":"python,arrays,numpy","A_Id":61611674,"CreationDate":"2020-05-05T10:44:00.000","Title":"Create big Vector with numpy","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a dataframe that with an index of magic card names. The columns are the same index, resulting in a 1081 x 1081 dataframe of each card in my collection paired with each other card in my collection.\nI have code that identifies combos of cards that go well together. For example \"Whenever you draw a card\" pairs well with \"Draw a card\" cards. I find the junction of those two cards and increase its value by 1. \nNow, I need to find the maximum value for 36 cards.\nBut, how?\nRandomly selecting cards is useless, there are 1.717391336 E+74 potential combinations. I've tried pulling out the lowest values and that reduces the set of potential combinations, but even at 100 cards you're talking about 1.977204582 E+27 potentials. \nThis has to have been solved by someone smarter than me - can ya'll point me in the right direction?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":52,"Q_Id":61614686,"Users Score":1,"Answer":"As you pointed out already, the combinatorics are not on your side here. There are 1081 choose 36 possible sets (binomial coefficient), so it is out of question to check all of them.\nI am not aware of any practicable solution to find the optimal set for the general problem, that is without knowing the 1081x1081 matrix.\nFor an approximate solution for the general problem, you might want to try a greedy approach, while keeping a history of n sets after each step, with e.g. n = 1000.\nSo you would start with going through all sets with 2 cards, which is 1081 * 1080 \/ 2 combinations, look up the value in the matrix for each and pick the n max ones.\nIn the second step, for each of the n kept sets, go through all possible combinations with a third card (and check for duplicate sets), i.e. checking n * 1079 sets, and keep the n max ones.\nIn the third step, check n * 1078 sets with a fourth card, and so on, and so forth.\nOf course, this won't give you the optimal solution for the general case, but maybe it's good enough for your given situation. You can also take a look at the history, to get a feeling for how often it happens that the best set from step x is caught up by another set in a step y > x. Depending on your matrix, it might not happen that often or even never.","Q_Score":0,"Tags":"python,pandas,math,matrix","A_Id":61746981,"CreationDate":"2020-05-05T13:45:00.000","Title":"Matrix Math - Maximizing","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a few files. The big one is ~87 million rows. I have others that are ~500K rows. Part of what I am doing is joining them, and when I try to do it with Pandas, I get memory issues. So I have been using Dask. It is super fast to do all the joins\/applies, but then it takes 5 hours to write out to a csv, even if I know the resulting dataframe is only 26 rows. \nI've read that some joins\/applies are not the best for Dask, but does that mean it is slower using Dask? Because mine have been very quick. It takes seconds to do all of my computations\/manipulations on the millions of rows. But it takes forever to write out. Any ideas how to speed this up\/why this is happening?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":362,"Q_Id":61615480,"Users Score":0,"Answer":"You can use Dask Parallel Processing or try writing into Parquet file instead of CSV as Parquet operation is very fast with Dask","Q_Score":0,"Tags":"python,pandas,csv,dask","A_Id":61615572,"CreationDate":"2020-05-05T14:28:00.000","Title":"Pandas\/Dask - Very long time to write to file","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a pandas dataframe and I want to select the maximum and minimum values across certain columns to use those values to plot a graph. \nExample: \nA | B | C\n1 | 2 | 3\n5 | 6 | 4\n9 | -2 | -1\nI want to take the columns A B C and find the maximum value out of the 3 columns and use that as my maximum point (which would be 9 in column A). Then I would like to take the smallest value out of the 3 columns and use that as my minimum point(in this case it would be -2 in column B).","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":394,"Q_Id":61621077,"Users Score":0,"Answer":"Maybe you could try this for the maximum value. df.loc[df['A'].idxmax()]","Q_Score":0,"Tags":"python,python-3.x,pandas,dataframe","A_Id":61621174,"CreationDate":"2020-05-05T19:08:00.000","Title":"How to pick the maximum and minimum value across a number of columns in pandas dataframe?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a problem that i can't install tensorflow 2.1.0 version using pip\nevery time i try , i have this message:\nERROR: Could not find a version that satisfies the requirement tensorflow (from versions: none)\nERROR: No matching distribution found for tensorflow \nmy machine specs: windows 10 , 64 bit , python 3.7 pip 20.1","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":1084,"Q_Id":61623355,"Users Score":0,"Answer":"I got the problem resolved by upgrading the pip.\npip3 install --upgrade pip","Q_Score":0,"Tags":"python,tensorflow2.0","A_Id":65691855,"CreationDate":"2020-05-05T21:25:00.000","Title":"I can't install tensorflow 2.1.0 version","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a problem that i can't install tensorflow 2.1.0 version using pip\nevery time i try , i have this message:\nERROR: Could not find a version that satisfies the requirement tensorflow (from versions: none)\nERROR: No matching distribution found for tensorflow \nmy machine specs: windows 10 , 64 bit , python 3.7 pip 20.1","AnswerCount":2,"Available Count":2,"Score":0.0996679946,"is_accepted":false,"ViewCount":1084,"Q_Id":61623355,"Users Score":1,"Answer":"Yep this is an issue with that version of python, try using python 3.6, it solved the issue for me","Q_Score":0,"Tags":"python,tensorflow2.0","A_Id":61623460,"CreationDate":"2020-05-05T21:25:00.000","Title":"I can't install tensorflow 2.1.0 version","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working on project which deals with calculation of halsted matrix and mccabe cyclomatic complexity for the codes in various languages. I found this library multimeric but its documentation is not intuitive. Please explain to me how to use this library for finding code metrics.\nif you know any other library which does this work then please suggest.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":204,"Q_Id":61627907,"Users Score":1,"Answer":"install multimetric follow the instruction from PyPI. go to the code(example.py) location. e.g. cd \/user\/Desktop\/code\nThen type these in terminal:\nmultimetric example.py\nthen you can see the result.","Q_Score":0,"Tags":"python,code-metrics","A_Id":64200291,"CreationDate":"2020-05-06T05:20:00.000","Title":"How to use multimetric python library for calculating code parameters?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to program a python OpenCV app for my own use because I can't go to gyms for some time. I would like to do the following:\n\nCapture frames from a video flow using OpenCV [ done ]\nHave OpenCV track a yellow soccer and return the coordinate of this soccer in the frame [done]\nCome up with an algorithm to detect when a soccer juggling failed, for example the soccer went out of frame and so on [ done ]\n\nNow my question is: let's say I want to save the \"10 seconds right before this event\" of video into a mp4 file. How should I do it? Is there any good template that I can follow?\nThanks!","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":307,"Q_Id":61628371,"Users Score":2,"Answer":"You may create a memory buffer worth of 10sec of video (~about 300 frames for most web-cameras), then save frames to that buffer, removing the old ones while adding the new ones.\nOnce your ball is out of the frame -- open a video file, and save your frames from the buffer.","Q_Score":0,"Tags":"python,opencv","A_Id":61629736,"CreationDate":"2020-05-06T05:57:00.000","Title":"how to let OpenCV save the last few seconds of analyzed video","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to add a new column named CleanedText in a csv file in jupyter. The variable name for the file is e_data_raw.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":14,"Q_Id":61628781,"Users Score":0,"Answer":"The code will be : \ne_data_raw.append(['CleanedText'])","Q_Score":0,"Tags":"python,csv,jupyter-notebook","A_Id":61628879,"CreationDate":"2020-05-06T06:30:00.000","Title":"Add a new column named CleanedText to a csv file in jupyter","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I try to switch from pytorch to tensorflow and since the model now seems to be a fixed thing in tensorflow, i stumble upon a problem when working with Convolutional Neural Networks.\nI have a very simple model, just one Conv1D layer and a kernel with size 2.\nI want to train it on a small Configuration, say 16 input size and then export the training results on a 32 input size.\nHow can i access the 3 parameters in this network? (2 kernel, 1 bias) I want to do so to apply them for the higher size case. I struggle because i need to pre-define a input size of the model, this was not the case with pytorch.\nThanks for answering, I've only found outdated answers to this question","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":58,"Q_Id":61638155,"Users Score":2,"Answer":"model.layers[0].get_weights() yields the weights of the first layer, assuming model is a tf.keras.Model object.","Q_Score":0,"Tags":"python,tensorflow,neural-network,conv-neural-network","A_Id":61638348,"CreationDate":"2020-05-06T14:45:00.000","Title":"Access Convolutional Neural Network Parameters","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to separate a white animation from a black background. The results were poor (black pixelation around edges of animation) when using: mask_color(clip, color=[0,0,0]). I know the function's optional parameters thr=SomeNumber and s=SomeNumber will fix this but I'm unsure what they mean and how they can be chosen in the interests of good quality results and quick rendering times.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":126,"Q_Id":61646853,"Users Score":1,"Answer":"hi thanks for posting the question. First let's quickly go through the meaning of these parameters;\n\nthr: threshold. Only well beyond this threshold is the masking effective, ie transparent\ns: stiffness. How strong the effect will be.\n\nSo as you can imagine, the values that you would feed into these arguments are highly dependent with your inputs and your desired outputs. So maybe you can let the s be its default, and slowly increase thr from 0 to 100 in a linear manner and inspect its output every steps of 10. then choose the best one. then if this is not satisfactory per your requirement, then you can try fine-tuning the stiffness if this would help you get the output that you need.","Q_Score":0,"Tags":"python,mask,moviepy,video-editing","A_Id":61696834,"CreationDate":"2020-05-06T22:55:00.000","Title":"How can the \"thr\" and \"s\" parameters in MoviePy's mask_color function be optimized for maximum quality and minimum rendering time?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a torch tensor of size torch.Size([1, 128, 56, 128])\n1 is channel, 128 is the width, and height. 56 are the stacks of images.\nHow can I resize it to torch.Size([1, 56, 128, 128]) ?","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":4683,"Q_Id":61667967,"Users Score":3,"Answer":"You could simply use permute or transpose.","Q_Score":3,"Tags":"python,pytorch,permutation","A_Id":61674341,"CreationDate":"2020-05-07T21:22:00.000","Title":"How can I swap axis in a torch tensor?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a DataFrame with shape 330000, 70, when I try to save it as csv a got the following error:\nUnicodeEncodeError: 'charmap' codec can't encode character '\\uff91' in position 110: character maps to \nIs there any way to locate the character at position 110 in the DataFrame?\nThanks in advance.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":30,"Q_Id":61674479,"Users Score":0,"Answer":"If you google what \\uff91 is, you may be able to filter on it, or replace it with something else\nAnother option - export it to excel and locate it that way. \nNot elegant but it will probably get you the answer","Q_Score":1,"Tags":"python,pandas","A_Id":61674697,"CreationDate":"2020-05-08T07:48:00.000","Title":"DataFrame.to_csv Error, is there any way to locate the character causing error in the DataFrame?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a dataset that keeps a record of customer's activities on a website in a sequence. I have to predict whether the customer makes a purchase or not given his sequence of interactions with the site with LSTM network. However, I also have to incorporate some static info(like whether he is a prior client or not, his nationality,his gender etc.) about customer in the same LSTM network. How should I incorporate these static info. in my model?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":40,"Q_Id":61687646,"Users Score":0,"Answer":"You can add those data as feature to each activity. If you consider data as a table, basically you add more columns (features) to it. For this, you should consider also using one hot encoding as well.","Q_Score":0,"Tags":"python,tensorflow,keras,deep-learning,lstm","A_Id":61689055,"CreationDate":"2020-05-08T20:33:00.000","Title":"How to incorporate static information(time independent) to sequential(time dependent) data","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"'''model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, verbose=2)'''\nin the above line of code model is a sequential keras model having layers and is compiled.\nwhat is the use of the parameter validaiton_data. the model is going to train on X_train and y_train data. so based on y_train the parameters would be adjusted and back propagation is done.\nwhat is the use of validation_data and why is a different data in this case testing data provided.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":607,"Q_Id":61688767,"Users Score":1,"Answer":"During training, (x_train, y_train) data is used to adjust trainable parameters of the model. However, we don't know whether model is overfit or under fit, whether model is going to do well when new data is provided. So, that is the reason why we have validation data (x_test, y_test) to test the accuracy of model on any unseen data.\nDepending on training and validation accuracy, we can decide.\n- Whether the model is overfit\/underfit,\n- whether to collect more data,\n- do we need to implement regularization technique,\n- do we need to use data augmentation techniques,.\n- whether we need to do tune hyper parameters etc.","Q_Score":0,"Tags":"python,tensorflow,keras,deep-learning,neural-network","A_Id":61689769,"CreationDate":"2020-05-08T21:58:00.000","Title":"how does validation_split work in training a neural network model?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have to compare data from different csv files on Python that consist of 84 columns and about 40.000 ~ 50.000 rows. This is a process that I need to do several times for several files. Which library should I use to have good performance? Should I use the regular csv library from python or would it be better to use something like Pandas?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":31,"Q_Id":61689527,"Users Score":0,"Answer":"Working with csvs usually will import the data in table formats. Typically R is a great language to manipulate columns and data in table (data frames) format, but when doing this in python, pandas is the go to library.","Q_Score":0,"Tags":"python-3.x,csv","A_Id":61689562,"CreationDate":"2020-05-08T23:04:00.000","Title":"Handling csv files on Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a training set containing 272 images.\n\nbatch size = 8, steps per epoch = 1 > train the model for just 8 images and jumps to next epoch?\nbatch size = 8, steps per epoch = 34 (no shuffle) > train the model for all 272 images and jumps to the next epoch?\nAt the end of each steps per epoch does it update the weights of the model?\nIf so, by increasing the number of steps per epoch does it gives a better result?\nIs there a convention in selecting batch size & steps per epoch?","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":654,"Q_Id":61693941,"Users Score":1,"Answer":"If I provide the definition using the 272 images as the training dataset and 8 as batch size,\n\nbatch size - the number of images that will be feed together to the neural network.\nepoch - an iteration over all the dataset images\nsteps - usually the batch size and number of epochs determine the steps. By default, here, steps = 272\/8 = 34 per epoch. In total, if you want 10 epochs, you get 10 x 34 = 340 steps. \n\nNow, if your dataset is very large, or if there are many possible ways to augment your images, which can again lead to a dataset of infinite or dynamic length, so how do you set the epoch in this case? You simply use steps per epoch to set a boundary. You pick an arbitrary value like say 100 and you assume your total dataset length to be 800. Now, it is another thing on how you do the augmentation. Normally, you can rotate, crop, or scale by random values each time.\nAnyway, coming to the answers to your questions -\n\nYes\nYes\nYes if you are using Mini-batch gradient descent\nWell, yes unless it overfits or your data is very small or ... there are a lot of other things to consider.\nI am not aware of any. But for a ballpark figure, you can check on the training mechanism of high accuracy open source trained models in your domain.\n\n(Note: I am not actively working in this field any more. So some things may have changed or I may be mistaken.)","Q_Score":0,"Tags":"python,tensorflow,machine-learning,keras,deep-learning","A_Id":61694526,"CreationDate":"2020-05-09T08:36:00.000","Title":"Can someone explain the relationship between batch size and steps per epoch?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using Redis with Python to store my per second ticker data (price and volume of an instrument). I am performing r.hget(instrument,key) and facing the following issue.\nMy key (string) looks like 01\/01\/2020-09:32:01 and goes on incrementing per second till the user specified interval. \nFor example 01\/01\/2020-09:32:01\n01\/01\/2020-09:32:02 01\/01\/2020-09:32:03 ....\nMy r.hget(instrument,key) result looks likeb'672.2,432'(price and volume separated by a comma).\nThe issue am facing is that a user can specify a long time interval, like 2 years, that is, he\/she wants the data from 01\/01\/2020 to 31\/12\/2020 (d\/m\/y format).So to perform the get operation I have to first generate timestamps for that period and then perform the get operation to form a panda dataframe. The generation of this datastamp to use as key for get operation is slowing down my process terribly (but it also ensures that the data is in strict ordering. For example 01\/01\/2020-09:32:01 will definitely be before 01\/01\/2020-09:32:02). Is there another way to achieve the same?\nIf I simply do r.hgetall(...) I wont be able to satisfy the time interval condition of user.","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":447,"Q_Id":61703506,"Users Score":0,"Answer":"So to perform the get operation I have to first generate timestamps for that period and then perform the get operation...\nNo. This is the problem.\nMake a function that calculates the timestamps and yield a smaller set of values, for a smaller time span (one week or one month).\nSo the new workflow will be in batches, see this loop:\n\ngenerate a small set of timestamps\nfetch items from redis\n\nPros:\n\nminimize the memory usage\neasy to change your current code to this new algo.\n\nI don't know about redis specific functions, so other specific solutions can be better. My idea is a general approach, I used it with success for other problems.","Q_Score":0,"Tags":"python,pandas,redis","A_Id":61705153,"CreationDate":"2020-05-09T20:45:00.000","Title":"Extract data faster from Redis and store in Panda Dataframe by avoiding key generation","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a 4D data np.array consisting of 150 images 50X70 decomposed to 3 channels.\nThe shape of the data is (150, 50, 70, 3). \nI need the average of those 150 images by channel, with the shape (50, 70, 3) \n(where R channel of average would be the average of 150 R channels, etc.)\nI've tried:\naverage = data.mean(axis=0)\naverageimage = Image.fromarray(average, 'RGB')\naverageimage.show()\nbut even tho it gives correct shape, the image looks like random color noise. \nEDIT: I've tried \ndef average_image(a_lot_of_images):\n avg = np.zeros((a_lot_of_images.shape[1], a_lot_of_images.shape[2], a_lot_of_images.shape[3]))\n for i in range(a_lot_of_images.shape[0]):\n avg[:,:,0] += a_lot_of_images[i,:,:,0]\n avg[:,:,1] += a_lot_of_images[i,:,:,1]\n avg[:,:,2] += a_lot_of_images[i,:,:,2]\n for i in [0,1,2]:\n avg[:,:,i] = avg[:,:,i]\/a_lot_of_images.shape[0]\n return avg\nand the output still looks like color noise.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":109,"Q_Id":61705427,"Users Score":0,"Answer":"def average_image(a_lot_of_images):\n avg = np.zeros((a_lot_of_images.shape[1], a_lot_of_images.shape[2], a_lot_of_images.shape[3]), dtype=float)\n for i in range(a_lot_of_images.shape[0]):\n avg[:, :, 0] += a_lot_of_images[i, :, :, 0]\n avg[:, :, 1] += a_lot_of_images[i, :, :, 1]\n avg[:, :, 2] += a_lot_of_images[i, :, :, 2]\n for i in [0,1,2]:\n avg[:, :, i] = avg[:, :, i]\/a_lot_of_images.shape[0]\n avg = np.array(np.round(avg), dtype=np.uint8)\n return avg\nworks! Is there a way to do this in a more elegant way?","Q_Score":0,"Tags":"python-imaging-library,rgb,mean,numpy-ndarray,tensor","A_Id":61706774,"CreationDate":"2020-05-10T00:00:00.000","Title":"Mean RGB image out of 4D np.array","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I read that it is possible to convert a TensorFlow Model (.pb) file to CoreML (.mlmodel) to run it on iOS platforms. But I have some .mlmodel files that I want to run on tensorflow. So I want to know if there is any way I could convert them to .pb files or any other way I could use them in Tensorflow.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":1543,"Q_Id":61712399,"Users Score":1,"Answer":"The good news: Yes, you can do this.\nThe bad news: You'll have to do it by hand. There are no tools for doing this automatically.\nThe easiest solution is to define the model in TensorFlow, then copy the weights from the Core ML model into the TF model.","Q_Score":2,"Tags":"python,tensorflow,coreml","A_Id":61717136,"CreationDate":"2020-05-10T12:58:00.000","Title":"How to convert a CoreML Model to a TensorFlow Model?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a sequence of (x, y) points approximating a road segment, and I would like to identify and split them into groups of two types: \n\nStraight line segments\nNon-straight line segments. At the moment I am not concerned about the parametrization of these. They may be constant curvature arcs, changing curvature clothoids... anything (but simplicity is preferred)\n\nAny hints about how to solve this problem in Python? I can find some academic publications about it, by searching for terms like \"curve decomposition into lines and arcs\" or similar, but they do not provide any example code, and implementing the entire method from scratch is not feasible for me. Any help is appreciated!\nThanks!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":879,"Q_Id":61717945,"Users Score":0,"Answer":"Use triplets P1,P2,P3 or P3,P4,P5 or P100,P101,P102 etc.\nWith three points you can find the circumference going through them. If its radious is too big (say 100 km) it's probably a straight, although it may be also the beginning of a clothoid (R is infinite where a clothoid joins a straight).\nSo you must test also the fourth point, telling if it belongs to that cicumference or it's in the clothoid. The parameter A of this clothoid knowing 4 points can be calculated by consecutive iterarions.\nIf you are given with an axis that is not the road axis, but a parallel to it, then remember that the curve parallel to a clothoid is not another clothoid.\nOnce you have all segments type-defined, you need a fine adjust so all segments are tangent at their end-points. This job can be done by working with triplets of segments, divide the tangent-error value rotating the middle segment or some other method you can think of.","Q_Score":0,"Tags":"python,geometry,line,curve,decomposition","A_Id":61719626,"CreationDate":"2020-05-10T19:55:00.000","Title":"How to split arbitrary curve into line and arc segments in Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm in this problem for hours, because I can't find a method that can remove the edges from a adjacency map graph in O(1) time.\nIf anyone has any idea, it would be very helpful.","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":556,"Q_Id":61718579,"Users Score":1,"Answer":"You should have HashMap (or dict in python) with Keys some kind of Node-index and Values to be for example HashSet (or set in python) of Node-indexes, edges from given Key node reach to.\nFor example {1: {2, 3}, 2: {1, 3}, 3: {1}} means, you have 3 nodes: 1, 2, 3 and eges are: [1, 2], [1, 3], [2, 1], [2, 3], [3, 1] - assuming it's directed graph. If you want to remove edge let's say 2, 3, obtain key (starting node of the edge) from your hashmap in O(1) time:\nsomething like graph.get(2) which will return you your value - hashSet of Nodes edges lead to, in this case {1, 3}. From this set, you can remove 3 (end node) again in O(1) time.\nRepeat this process for all edges you may have.","Q_Score":0,"Tags":"python,algorithm,data-structures,graph","A_Id":61718889,"CreationDate":"2020-05-10T20:52:00.000","Title":"Adjacency Map - How to remove a edge from a Graph","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to build a model that's able to classify the author of a book (just fiction books for the moment) by looking at its text. At first, I just worked with authors that had at least 30 books. In my dataset, that was ~2000 books written by ~30 authors in total, and that went pretty great, so I decided to raise the stakes. By lowering the threshold to 10 books, the database grew to ~400 authors and ~9000 books.\nThe way I classified the books is as follows: I removed punctuation, newlines, extra spaces, and stopwords from every text, then I extracted the features with sklearn CountVectorizer and TfidfVectorizer. With this approach, the F1 score was 0.95 for the 2000 books db and 0.62 for the 9000 books db. In both cases I used the SGD model from scikit learn.\nThe training with the larger dataset was much slower, so I decided to get 5000 random words from each book and use only those. This decreased the training time from 20 minutes to only 2 minutes, and enabled me to try something different. There wasn't a big difference in the various metrics, so I decided to try and remove the tfidf features. Using only CountVectorizer I got a 0.87 F1 score.\nI'm not sure why this is happening, my expectation was that the tfidf would make things easier and therefore better my score. In theory, tfidf should help with the sparsity of the matrix. Do you have any clue on why removing it improved the score instead?\nAre there other strategies, maybe better suited to work with long texts? Should I consider trimming the dataset in a certain way?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":44,"Q_Id":61718786,"Users Score":0,"Answer":"There might be 2 problems here:\n\nYou have not tuned the parameters for TFIDF and hence it is giving low scores. Try to do a grid search and parameters such as min_df, max_df, max_features etc. This might increase the scores. CountVectorizer might be preforming good because the classifier might be associating some unique words with a certain author. \nThe data imbalance problem. You can try to use SMOTE on the TFIDF features, or if you are using Logistic Regression you can set class_weights='balanced' and that might also increase scores.","Q_Score":0,"Tags":"python,machine-learning,scikit-learn,nlp","A_Id":61718856,"CreationDate":"2020-05-10T21:10:00.000","Title":"Literary author classification from book content","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am enquiring about assistance regarding regression testing. I have a continuous time series that fluctuates between positive and negative integers. I also have events occurring throughout this time series at seemingly random time points. Essentially, when an event occurs I grab the respective integer. I then want to test whether this integer influences the event at all. As in, are there more positive\/negative integers. \nI originally thought logistic regression with the positive\/negative number but that would require at least two distinct groups. Whereas, I only have info on events that have occurred. I can't really include that amount of events that don't occur as it's somewhat continuous and random. The amount of times an event doesn't occur is impossible to measure. \nSo my distinct group is all true in a sense as I don't have any results from something that didn't occur. What I am trying to classify is: \nWhen an outcome occurs, does the positive or negative integer influence this outcome.","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":183,"Q_Id":61721366,"Users Score":0,"Answer":"Although, the question is quite difficult to understand after first paragraph. Let me help from what I could understand from this question.\nAssuming you want to understand if there is relationship between the events happening and the integers in the data.\n1st approach: Plot the data on a 2d scale and check visually if there is a relationship between data.\n2nd approach: make the data from the events continuous and remove the events from other data and using rolling window smooth out the data and then compare both trends.\nAbove given approach only works well if I am understanding your problem correctly. \nThere is also one more thing known as Survivorship bias. You might be missing data, please also check that part also.","Q_Score":1,"Tags":"python,pandas,regression","A_Id":61868967,"CreationDate":"2020-05-11T02:28:00.000","Title":"Statistical test for time series where outcome occurs - python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"InvalidArchiveError('Error with archive C:\\Users\\Sahaja Reddy\\Anaconda3\\pkgs\\openssl-1.1.1g-he774522_0.conda. You probably need to delete and re-download or re-create this file. Message from libarchive was:\\n\\nCould not unlink (errno=22, retcode=-25, archive_p=1873471744752)')","AnswerCount":5,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":23794,"Q_Id":61726576,"Users Score":5,"Answer":"InvalidArchiveError when trying to install with conda can happen if you don't have enough free space on the hard disk. Make sure you have enough free space.","Q_Score":16,"Tags":"python,anaconda,spacy","A_Id":63716148,"CreationDate":"2020-05-11T09:38:00.000","Title":"I am getting an InvalidArchiveError in anaconda prompt when I am trying to install spacy. How to solve it?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"Suppose one classroom contains 40 students.\nThen I trained model for all images of 40 students and then try to detect all 40 students in one picture.\nBut not getting good accuracy.\nWhy this is happing? Is any other measure criteria other than just measuring the accuracy of the model?","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":56,"Q_Id":61726951,"Users Score":0,"Answer":"A little improvement can be achieved through data augmentation. For every image (in your case, every student), you could say that an object rotated by 10 percent, is still the same object for the observer. The same goes for mirroring the image. By adding a couple of new data points this way, you would probably get better results.","Q_Score":0,"Tags":"python,tensorflow,image-processing,keras,deep-learning","A_Id":61728954,"CreationDate":"2020-05-11T09:57:00.000","Title":"How to Train model in which number of classes is equal to number of instances in particular image used for prediction","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"So I have a seasonal time-series with 2 variable \"Time\" and \"Sensor mesure\" and I want to predict the date when that measure would reach a certain value . Can anyone suggest models\/Algos that can help (I'm a beginner)\nPS : Using python","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":44,"Q_Id":61727130,"Users Score":0,"Answer":"For time series data, you can use LSTM or GRU neural networks. They would be the easiest to solve your problem.","Q_Score":0,"Tags":"python,time-series,forecasting,sensor-fusion","A_Id":61727264,"CreationDate":"2020-05-11T10:06:00.000","Title":"Time series : Predicting when a variable will reach a certain value (seasonal sensor data) python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Not really a coding related question.\nI am trying to install tensorflow on Intel Xeon(R) CPU E5620 which has Ubuntu 19.10. I can't install it with pip( could someone please explain why). It does gets installed using pip but it just says,\nillegal instruction (core dumped)\nI have tried building it from the source, but that was a pretty painful process, takes way too much time. \nMy question is, is their any easier way to install tensorflow on my PC?","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":1396,"Q_Id":61745843,"Users Score":1,"Answer":"Try using conda environment. I have no problem installing and using tensorflow on my machine. I am using tensorflow 1.15 btw and as far as I recall I installed it using pip install tensorflow-gpu==1.15\nCpu model: Intel(R) Xeon(R) CPU E5-2620 v4 @ 2.10GHz\nOS: Ubuntu 18.04\nconda environment python version: 3.5.6","Q_Score":0,"Tags":"python,tensorflow","A_Id":61748069,"CreationDate":"2020-05-12T07:13:00.000","Title":"How to install Tensorflow on Intel Xeon Processor based PC?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have 2 data sets of images, one is perfect square, so resizing to 224x224 for CNN will not result in any distortion, the other dataset is not square so resizing to 224x224 will result in image distortion.\nI will split the sets to train and validation, is this a good way to train the model? will there be any bias in the model?\nI am afraid the model will identify distortion rather than the real differences between the 2 sets..","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":62,"Q_Id":61746181,"Users Score":0,"Answer":"In case you want to preserve your data, you can crop it randomly and use it to transform to square. That way your model will look on the cropped part of the image. Doing so can increase your data but this is one good data if you save the transformed image. However using random crop function from from the dataloader will stream line the process. Cropping is a good augmentation technique for preprocessing the data.","Q_Score":0,"Tags":"python,machine-learning,deep-learning,neural-network,conv-neural-network","A_Id":61746227,"CreationDate":"2020-05-12T07:35:00.000","Title":"convolution neural network image size distortion","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm experiencing an issue while using VS Code to debug Python files. It seems that since last updating VS Code matplotlib figures have stopped being displayed after calls of plt.show(). There are no errors reported, and the script continues to execute as though the call had been successful, so I'm not sure what the cause is.\nInitially I thought it was perhaps something to do with the backend, so I tried running in various Python environments with different matplotlib.plot backends and Python versions but no success.\nMy only though is that it's possible VS Code settings are overriding the backend or environment somehow and might be causing this behaviour?","AnswerCount":4,"Available Count":2,"Score":-0.049958375,"is_accepted":false,"ViewCount":7888,"Q_Id":61757455,"Users Score":-1,"Answer":"set\n\"terminal.integrated.inheritEnv\": true,\nin your user settings\n#and# then don't forget to put\nplt.show()\nat the end of your python file. Without plt.show() your images will not be dispayed.","Q_Score":8,"Tags":"python,matplotlib,visual-studio-code,vscode-settings","A_Id":68928356,"CreationDate":"2020-05-12T16:55:00.000","Title":"matplotlib figure won't show when Python is run from VS Code integrated terminal","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm experiencing an issue while using VS Code to debug Python files. It seems that since last updating VS Code matplotlib figures have stopped being displayed after calls of plt.show(). There are no errors reported, and the script continues to execute as though the call had been successful, so I'm not sure what the cause is.\nInitially I thought it was perhaps something to do with the backend, so I tried running in various Python environments with different matplotlib.plot backends and Python versions but no success.\nMy only though is that it's possible VS Code settings are overriding the backend or environment somehow and might be causing this behaviour?","AnswerCount":4,"Available Count":2,"Score":-0.049958375,"is_accepted":false,"ViewCount":7888,"Q_Id":61757455,"Users Score":-1,"Answer":"while accessing the file from terminal in VSCode, Save the plot, then it will be visible\nplt.savefig('file_name.png')","Q_Score":8,"Tags":"python,matplotlib,visual-studio-code,vscode-settings","A_Id":66433583,"CreationDate":"2020-05-12T16:55:00.000","Title":"matplotlib figure won't show when Python is run from VS Code integrated terminal","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I optimized my code to process images with pillow. It uses all the sources to get as fast as possible. Just the GPU would make it faster. I don't find any solution beside CUDA and that wont't work on Catalina. Is there any way to use my GPU(NVIDIA GeForce GT 750M 2 GB\nIntel Iris Pro 1536 MB) to make the process more efficient?\nThanks for your help!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":705,"Q_Id":61761582,"Users Score":0,"Answer":"Actually there is no way to use pillow to do that! If you need a better speed, you can use ImageMagick (Wand as python wrapper) or GraphicsMagick (pgmagick as Python wrapper). If you need to use GPU, ImageMagick gives some option to use it if possible (I am not sure about GM) but it is not neither as efficient nor complete as you use CUDA or OpenCL. I recommend you to use Vulkan if you need better result and cross platform (Nvidia and AMD, MacOS, Linux Windows...).","Q_Score":1,"Tags":"python,macos,gpu,python-imaging-library,macos-catalina","A_Id":61761902,"CreationDate":"2020-05-12T20:45:00.000","Title":"Use GPU for PIL in python on mac (macOS Catalina)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to classify a list of documents. I'm using CountVectorizer and TfidfVectorizer to vectorize the documents before the classification. The results are good but I think that they could be better if we will consider not only the existence of specific words in the document but also the order of these words. I know that it is possible to consider also pairs and triples of words but I'm looking for something more inclusive.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":41,"Q_Id":61767647,"Users Score":0,"Answer":"Believe it or not, but bag of words approaches work quite well on a wide range of text datasets. You've already thought of bi-grams or tri-grams. Let's say you had 10-grams. You have information about the order of your words, but it turns out there are rarely more than one instance of each 10-gram, so there would be few examples for your classification model to learn from. You could try some other custom feature engineering based on the text, but it would be a good amount of work that rarely help much. There are other successful approaches in Natural Language Processing, especially in the last few years, but they usually focus on more than word ordering.","Q_Score":0,"Tags":"python,machine-learning,scikit-learn","A_Id":61783485,"CreationDate":"2020-05-13T06:17:00.000","Title":"classification of documents considering the order of words","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to import \nimport tensorflow.python.keras.applications.MobileNetV2\nbut it gives the bellow error:\nModuleNotFoundError: No module named 'tensorflow.python.keras.applications.MobileNetV2'\nmy tensorflow version is 1.8.0\nand keras version is 2.2.0","AnswerCount":3,"Available Count":1,"Score":-0.0665680765,"is_accepted":false,"ViewCount":6144,"Q_Id":61768883,"Users Score":-1,"Answer":"Try using the following:\nfrom tensorflow.keras.applications.mobilenet_v2 import preprocess_input","Q_Score":0,"Tags":"python,tensorflow,keras","A_Id":69853083,"CreationDate":"2020-05-13T07:37:00.000","Title":"ModuleNotFoundError: No module named 'tensorflow.python.keras.applications.MobileNetV2'","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using DAHUA Thermal Camera\nCamera can provide two streams (Color_Stream + Thermal_Stream).\nI am getting the color stream from my thermal camera in python through the given URL with cv2.VideoCapture() function (keeping channel=1 in the URL)\n\nrtsp:\/\/admin:admin@10.7.6.67:554\/cam\/realmonitor?channel=1&subtype=0\n\nand thermal stream with the given URL (keeping channel=2 in the URL)\n\nrtsp:\/\/admin:admin@10.7.6.67:554\/cam\/realmonitor?channel=2&subtype=0\n\nIs there a way that I can get both of the streams together? (by calling only one function)","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":318,"Q_Id":61775836,"Users Score":0,"Answer":"I have not tried this with an IP camera. But perhaps what you can try is using 2 threads to open the 2 streams. Then you may be able to fetch both streams. If that does not work, you can try switching between streams alternately, if it helps","Q_Score":0,"Tags":"python,opencv,video-capture,ip-camera,opencv-python","A_Id":66982485,"CreationDate":"2020-05-13T13:24:00.000","Title":"Is there a way to get the both main stream and sub stream together in opencv python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've recently started exploring for myself features columns by TensorFlow. \nIf I understood documentation right, feature columns are just a 'frame' for further transformations just before fitting data to the model. So, if I want to use it, I define some feature columns, create DenseFeatures layer from them, and when I fit data into a model, all features go through that DenseFeatures layer, transforms and then fits into first Dense layer of my NN.\nMy question is that is it possible at all somehow check correlations of transformed features to my target variable? \nFor example, I have a categorical feature, which corresponds to a day of a week (Mon\/Tue...\/Sun) (say, I change it to 1\/2..7). Correlation of it to my target feature will not be the same as correlation of categorical feature column (f.e. indicator), as a model don't understand that 7 is the maximum of the possible sequence, but in case of categories, it will be a one-hot encoded feature with precise borders.\nLet me know if all is clear.\nWill be grateful for the help!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":181,"Q_Id":61776353,"Users Score":0,"Answer":"Tensorflow does not provide the feature_importance feature with the way Sklearn provides for XGBoost.\nHowever, you could do this to test the importance or correlation of your feature with the target feature in TensorFlow as follows.\n1) Shuffle the values of the particular feature whose correlation with the target feature you want to test. As in, if your feature is say fea1,the value at df['fea1'][0] becomes the value df['fea1'][4], the value at df['fea1'][2] becomes the value df['fea1'][3] and so on.\n2) Now fit the model to your modified training data and check the accuracy with validation data.\n3) Now if your accuracy goes down drastically, it means your feature had a high correlation with the target feature, else if the accuracy didn't vary much, it means the feature isn't of great importance (high error = high importance).\nYou can do the same with other features you introduced to your training data.\nThis could take some time and effort.","Q_Score":0,"Tags":"python,tensorflow,deep-learning,tensorflow2.0","A_Id":61776929,"CreationDate":"2020-05-13T13:46:00.000","Title":"Correlations of feature columns in TensorFlow","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I was able to train a model with the python TensorFlow API following some tutorials. \nI also managed to freeze the model from the latest checkpoints.\nHowever, I wanted to have the best instead of the latest model, so I checked to get the best models written to the disc. At last, I found it in a \"saved model\" format and now I want to convert it to a frozen model. I think this should be something straight forward. \nIt might be a stupid question but I already spent some hours looking for a simple way.\nYour help would be much appreciated!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":48,"Q_Id":61776651,"Users Score":0,"Answer":"When you save a model, it is done i.e. it is frozen. Its weight won't change. Usually, during testing, you will instantiate your model and then load the saved i.e. frozen model and run predictions on it.\nIf you don't want the network to learn after you load your frozen model weights, then, go to model.layers and set the trainable false for every layer.\nmodel.load_weights(checkpoint_path) is used for loading weights.","Q_Score":0,"Tags":"python,tensorflow","A_Id":61778281,"CreationDate":"2020-05-13T13:59:00.000","Title":"Freezing a saved tensorflow model","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have 2 dataframes in Spark 2.4, they are close to the same size. Each has about 40 million records. One is generated simply by loading the dataframe from S3, the other loads a bunch of dataframes and uses sparkSQL to generate a big dataframe. Then I join these 2 dataframes together multiple times into multiple dataframes and try to write them as CSV to S3... However I am seeing my write times upwards of 30 minutes, I am not sure if it is re-evaluating the dataframe or if perhaps I need more CPUs for this task. Nonetheless, I was hoping someone may have some advice on how to optimize these write times.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":1337,"Q_Id":61780798,"Users Score":0,"Answer":"So when a dataframe is created from other dataframes it seems an execution plan is what is first created. Then when executing a write operation that plan gets evaluated. \nThe best way to take care of this particular situation is to take advantage of the spark lazy-loading caching (I have not seen an eager-loading solution for spark but if that exists it could be even better). \nBy doing:\ndataframe1.cache()\nAnd\ndataframe2.cache()\nwhen you join these 2 dataframes the first time both dataframes are evaluated and loaded into cache. Then when joining and writing again the 2 dataframe execution plans are already evaluated and the join and write becomes much faster.\nThis means the first write still takes over 30 minutes but the other 2 writes are much quicker.\nAdditionally, you can increase performance with additional CPUs and proper paritioning and coalesce of the dataframes. That could help with the evaluation of the first join and write operation.\nHope this helps.","Q_Score":0,"Tags":"python,scala,apache-spark","A_Id":61780799,"CreationDate":"2020-05-13T17:15:00.000","Title":"How to speed up large data frame joins in Spark","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Using Nifi, I want to:\n\nrun a Python script that exports a pandas dataframe\nsend it e.g. through ExecuteStreamCommand to a variety of plug-and-play Python scripts that both input and output pandas dataframes, not knowing they are running via Nifi and which I cannot modify to use STDIN\/STDOUT instead of pandas.\npass the output dataframe on for further processing.\n\nIs this possible? If so, how?\nPut another way:\n\nFirst Script: flowfile -> pandas\nMany Scripts: do stuff with pandas\nLast Script: pandas -> flowfile","AnswerCount":1,"Available Count":1,"Score":1.0,"is_accepted":false,"ViewCount":823,"Q_Id":61785013,"Users Score":6,"Answer":"NiFi's ExecuteScript supports Jython, which does not allow Python native libraries (pandas is a native library), so you cannot perform this action directly in NiFi. I'd recommend you write an encompassing Python shell script which performs the following actions and invoke it from NiFi using the ExecuteStreamCommand processor:\nPython wrapper script:\n\nAccept input from STDIN (this will be the flowfile content)\n\n\nYou can also put flowfile attributes on the command line as arguments using the \"Command Arguments\" property of the ESC processor\n\nConvert the STDIN input to a pandas dataframe\nPass the dataframe between the arbitrary Python scripts which will have no knowledge of NiFi\nOutput the final dataframe as STDOUT\n\nThis will allow the incoming flowfile content to be sent to this wrapper script, all the internal modifications made using the included scripts, and then the output to be translated from STDOUT back to flowfile content.","Q_Score":2,"Tags":"python,pandas,dataframe,apache-nifi","A_Id":61786176,"CreationDate":"2020-05-13T21:16:00.000","Title":"How can I pass a pandas dataframe in Nifi from processor to processor?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am implementing a MultiLayer Perceptron , I am extracting the features of images using SIFT algorithm of image processing and I pass those features to the neural network , the features of images that I am considering are descriptors ,every image has different length of descriptors , some image has 200 descriptors and some image has 240 descriptors , means it's varying . But neural networks accepts fixed size of input data .\nHow can I pass this type of input to it if it accept varied input then how ?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":111,"Q_Id":61790496,"Users Score":0,"Answer":"I think you could try to pad your data to a fixed size(like the maximum length of your descriptors) vector with all 0 or mean value of this vector.","Q_Score":0,"Tags":"python,machine-learning,image-processing,deep-learning,computer-vision","A_Id":61790560,"CreationDate":"2020-05-14T06:11:00.000","Title":"Do neural networks accepts other than fixed size of input data?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"how adjacency list and adjacency matrix are able to logically present a non-linear data structure, even though they are themselves linear. Someone Pls explain","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":199,"Q_Id":61798347,"Users Score":0,"Answer":"Stacks, queues, lists, vectors\/arrays: they all store data linearly in the sense that items are stored one after the other. There is the notion of \"item A comes before item B\", and \"item C comes after item B\". One before, one after. They only differ in how items can be accessed (FIFO, LIFO, by rank, by position).\nTrees (a type of graph) store data hierarchically. There's not really a before\/after relation. Instead, items are stored based on a parent\/child relationship. Then, we can say \"the parent of item A is B\", and \"the children of item A are B, C, D, and E\".\nGraphs store any type of relation between elements. An item can be related to any other item, as expressed by an edge. We can say \"item A is related to B, C, D, E\" and \"item B is related to A and F\". It is in this sense that they are nonlinear. An adjacency list and adjacency matrix accomplish this by, effectively, maintaining a (linear) list of these relationships.","Q_Score":1,"Tags":"python,algorithm,data-structures","A_Id":61798980,"CreationDate":"2020-05-14T13:17:00.000","Title":"adjacency list and adjacency matrix are able to logically present a non-linear data structure","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"Basically my questions is how list and matrix can be used to represent the graph, as list and matrix is linear data structure and graph is a non-linear data structure","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":47,"Q_Id":61801650,"Users Score":0,"Answer":"So in matrix representation, we only change the value of a particular cell when the vertex represented by column and row number are connected. And list is simply the list for all the neighbors of a particular vertex. In matrix, we store zeroes for pair of vertices not connected and is extra space.","Q_Score":0,"Tags":"python,algorithm,data-structures,graph","A_Id":61801948,"CreationDate":"2020-05-14T15:46:00.000","Title":"How a linear datastructure can be used to implement a non linear datastructure","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Traceback (most recent call last):\n File \"C:\\Users\\George Adamopoulos\\Anaconda3\\envs\\Computer Vision Code\\lib\\site-packages\\tensorflow\\python\\pywrap_tensorflow.py\", line 58, in \n from tensorflow.python.pywrap_tensorflow_internal import *\n File \"C:\\Users\\George Adamopoulos\\Anaconda3\\envs\\Computer Vision Code\\lib\\site-packages\\tensorflow\\python\\pywrap_tensorflow_internal.py\", line 28, in \n _pywrap_tensorflow_internal = swig_import_helper()\n File \"C:\\Users\\George Adamopoulos\\Anaconda3\\envs\\Computer Vision Code\\lib\\site-packages\\tensorflow\\python\\pywrap_tensorflow_internal.py\", line 24, in swig_import_helper\n _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)\n File \"C:\\Users\\George Adamopoulos\\Anaconda3\\envs\\Computer Vision Code\\lib\\imp.py\", line 242, in load_module\n return load_dynamic(name, filename, file)\n File \"C:\\Users\\George Adamopoulos\\Anaconda3\\envs\\Computer Vision Code\\lib\\imp.py\", line 342, in load_dynamic\n return _load(spec)\nImportError: DLL load failed: The specified module could not be found.\nDuring handling of the above exception, another exception occurred:\nTraceback (most recent call last):\n File \"C:\/Users\/George Adamopoulos\/Desktop\/All My Files\/Fear Neural Net Project\/Computer Vision Code\/ML Zero to Hero\/Part_2.py\", line 1, in \n import tensorflow as tf\n File \"C:\\Users\\George Adamopoulos\\Anaconda3\\envs\\Computer Vision Code\\lib\\site-packages\\tensorflow__init__.py\", line 41, in \n from tensorflow.python.tools import module_util as _module_util\n File \"C:\\Users\\George Adamopoulos\\Anaconda3\\envs\\Computer Vision Code\\lib\\site-packages\\tensorflow\\python__init__.py\", line 50, in \n from tensorflow.python import pywrap_tensorflow\n File \"C:\\Users\\George Adamopoulos\\Anaconda3\\envs\\Computer Vision Code\\lib\\site-packages\\tensorflow\\python\\pywrap_tensorflow.py\", line 69, in \n raise ImportError(msg)\nImportError: Traceback (most recent call last):\n File \"C:\\Users\\George Adamopoulos\\Anaconda3\\envs\\Computer Vision Code\\lib\\site-packages\\tensorflow\\python\\pywrap_tensorflow.py\", line 58, in \n from tensorflow.python.pywrap_tensorflow_internal import *\n File \"C:\\Users\\George Adamopoulos\\Anaconda3\\envs\\Computer Vision Code\\lib\\site-packages\\tensorflow\\python\\pywrap_tensorflow_internal.py\", line 28, in \n _pywrap_tensorflow_internal = swig_import_helper()\n File \"C:\\Users\\George Adamopoulos\\Anaconda3\\envs\\Computer Vision Code\\lib\\site-packages\\tensorflow\\python\\pywrap_tensorflow_internal.py\", line 24, in swig_import_helper\n _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)\n File \"C:\\Users\\George Adamopoulos\\Anaconda3\\envs\\Computer Vision Code\\lib\\imp.py\", line 242, in load_module\n return load_dynamic(name, filename, file)\n File \"C:\\Users\\George Adamopoulos\\Anaconda3\\envs\\Computer Vision Code\\lib\\imp.py\", line 342, in load_dynamic\n return _load(spec)\nImportError: DLL load failed: The specified module could not be found.\nFailed to load the native TensorFlow runtime.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":87,"Q_Id":61804098,"Users Score":0,"Answer":"Delete it from the console and reinstall it and try adding it again.","Q_Score":0,"Tags":"python,tensorflow","A_Id":68278106,"CreationDate":"2020-05-14T17:53:00.000","Title":"Unable to import tensorflow into PyCharm","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"As someone who just got into data science (no prior coding history) I am new to using terminals, Python, and coding in general. While I do have some basic Python knowledge now, and I want to work on my first machine learning project, I am looking to use some packages that are not standard to python or jupyter lab, namely: TensorFlow.\nAfter much struggle I was able to download TensorFlow in my terminal (i'm on Mac). Yet when I try to import to module I come to the following problem:\nwhen I create a new file in jupyterlab (accessed via Anaconda) I have the option to create a python file using python 3 or python 3.7.2. When using python 3, I have access to packages to sklearn, SciPy, yet no TensorFlow. Then when I create a 3.7.2. file I can import the TensorFlow package, yet I cannot import the sklearn and SciPy packages anymore.... \nDid someone experience similar problems? Are there ways to solve this?\nP.s. Using the 'pip install ...' command in terminal only sees to work rarely. Or I must be something wrong.\nThanks in advance,\nJohn","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":212,"Q_Id":61825562,"Users Score":0,"Answer":"I know what you are going through as even I went through a similar problem when I started. It seems that there are two different environments. One with Python3 and one with Python 3.7.2. The problem is arising because the modules are installed in different environments. Your TensorFlow module in Python 3.7.2 environment and sklearn modules in another environment. \nIt will better if you install all your modules in the base environment for ease in use.\nI hope this helps.","Q_Score":0,"Tags":"python,pip,jupyter-notebook,python-import,jupyter-lab","A_Id":61825684,"CreationDate":"2020-05-15T17:59:00.000","Title":"Python packages not working in either python 3 or python 3.7.2. files","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a XGBRegressor model and now I'm curious if there is a way to generate the final prediction equation in Python.\nP.S: I do not have mathematical background so if my question is considered basic, please understand.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":98,"Q_Id":61831268,"Users Score":0,"Answer":"Depending on the problem, the final 'equation' could be arbitrarily complex.\nA good place to start is to inspect one or some of the decision trees:\nfrom xgboost import plot_tree\nWhich takes your trained model and the tree index as arguments.","Q_Score":0,"Tags":"python,math,data-science,xgboost","A_Id":61831414,"CreationDate":"2020-05-16T02:51:00.000","Title":"Python XGBoost Generate Prediction Mathematical Equation","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"From excel file i want to read each row and use it independently to process\nhere how the data looks like in excel file\n12 32 45 67 89 54 23 56 78 98\n34 76 34 89 34 3\n76 34 54 12 43 78 56\n76 56 45 23 43 45 67 76 67 8\n87 9 9 0 89 90 6 89\n23 90 90 32 23 34 56 9 56 87\n23 56 34 3 5 8 7 6 98\n32 23 34 6 65 78 67 87 89 87\n12 23 34 32 43 67 45\n343 76 56 7 8 9 4\nbut when i read it through pandas then the remaining columns are filled with NaN.\nthe data after reading from pandas looks like\n\n0 12 32 45 67 89 54 23.0 56.0 78.0 98.0\n1 34 76 34 89 34 3 NaN NaN NaN NaN\n2 76 34 54 12 43 78 56.0 NaN NaN NaN\n3 76 56 45 23 43 45 67.0 76.0 67.0 8.0\n4 87 9 9 0 89 90 6.0 89.0 NaN NaN\n5 23 90 90 32 23 34 56.0 9.0 56.0 87.0\n6 23 56 34 3 5 8 7.0 6.0 98.0 NaN\n7 32 23 34 6 65 78 67.0 87.0 89.0 87.0\n8 12 23 34 32 43 67 45.0 NaN NaN NaN\n9 343 76 56 7 8 9 4.0 5.0 8.0 68.0\n\nHere it can be seen the remaining columns of each row is filled with NaN which i don't want.\nNor i wanted to replace it with some other value or drop the whole rows contains NaN .\nHow can i read columns of each row till the first occurence of NaN. ? \n\nFor eg.The second row in pandas is 34 76 34 89 34 3 NaN NaN NaN NaN\nso my desired output will be that it reads only 34 76 34 89 34 3\n\nMy preference is pandas but if not possible then is their any other way of doing it like with some other libraries\nAny resource or reference will be helpful?\nThanks","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":120,"Q_Id":61839733,"Users Score":0,"Answer":"While calling the pd.read_excel function, try setting keep_default_na = False. This will avoid default NaN values while reading.","Q_Score":0,"Tags":"python,python-3.x,pandas,dataframe,data-science","A_Id":61839989,"CreationDate":"2020-05-16T16:06:00.000","Title":"How can i read each row till the first occurence of NaN.?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've come across many such situations where I have used in built functions or modules where the syntax is sometimes \"X.func_name\" and other times (X.func_name()\".\nFor example : \nIn Pandas \"df.columns\" gives names of all columns and throws and throws error if written by mistake as \"df.columns()\" #TypeError: 'Index' object is not callable.\nAlso in Pandas, \"count()\", \"min()\" etc are written as df.count() | df.min()\nI hope I have explained my question properly.\nI believe it has something to do with the OOP concept of Class and it's member functions but I'd like a more in-dept understanding.","AnswerCount":2,"Available Count":2,"Score":0.0996679946,"is_accepted":false,"ViewCount":244,"Q_Id":61840466,"Users Score":1,"Answer":"The functions with parens are functions (actually class methods), which can take parameters and so on. Without parentheses, these are class variables.","Q_Score":0,"Tags":"python,pandas,oop","A_Id":61840582,"CreationDate":"2020-05-16T16:59:00.000","Title":"Difference between X.func and X.func( )","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've come across many such situations where I have used in built functions or modules where the syntax is sometimes \"X.func_name\" and other times (X.func_name()\".\nFor example : \nIn Pandas \"df.columns\" gives names of all columns and throws and throws error if written by mistake as \"df.columns()\" #TypeError: 'Index' object is not callable.\nAlso in Pandas, \"count()\", \"min()\" etc are written as df.count() | df.min()\nI hope I have explained my question properly.\nI believe it has something to do with the OOP concept of Class and it's member functions but I'd like a more in-dept understanding.","AnswerCount":2,"Available Count":2,"Score":1.2,"is_accepted":true,"ViewCount":244,"Q_Id":61840466,"Users Score":2,"Answer":"The syntax to access an attribute foo of an object or module is always .foo.\nAn attribute may or may not be callable. An int is not callable (it's just a number), but a function is callable. To call a function foo, you use parentheses, possibly with parameters inside, e.g. foo() or foo(\"bar\"). Attempting to call something that is not callable will give you a TypeError.\nSo what syntax you use depends on whether the attribute is itself the value you want (e.g. an int or a str, or if it's a function that will return that value). In your example, columns is itself an int, whereas count is a function that you need to call in order to get an int.\nNote that it's possible in Python to wrap any value in a function, or to turn a function into a property (i.e. make an attribute that automatically calls a function to produce its value), but in general the convention is that if something requires some kind of dynamic computation it will be a function, and values that are predetermined will not require a function invocation to retrieve.","Q_Score":0,"Tags":"python,pandas,oop","A_Id":61840680,"CreationDate":"2020-05-16T16:59:00.000","Title":"Difference between X.func and X.func( )","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"Error\ntensorflow.python.framework.errors_impl.UnknownError: Failed to get convolution algorithm. This is probably because cuDNN failed to initialize, so try looking to see if a warning log message was printed above.\n [[node conv2d_1\/Conv2D (defined at C:\\Users\\Rajshree\\Anaconda3\\lib\\site-packages\\tensorflow_core\\python\\framework\\ops.py:1751) ]] [Op:__inference_keras_scratch_graph_808]\nI'm running 2 programs . Both are using this and performing similar task of recognizing human expression. The difference only lies in the model of CNN they are using. One is working perfectly fine so what could be the possible problem with the other.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":667,"Q_Id":61842692,"Users Score":0,"Answer":"This could be due to a multitude of things. Are you running the two programs at the same time? Are you running this on a GPU? If so, it could be that one is already using the GPU, and the other finds that the GPU is already in use so it throws an error.","Q_Score":0,"Tags":"python,tensorflow,conv-neural-network","A_Id":61846743,"CreationDate":"2020-05-16T19:47:00.000","Title":"Failed to get convolution algorithm.This is probably because cuDNN failed to initialize.[{node conv2d_1\/Conv2D}]","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a dataset in which each datapoint consists of 5 videos in two dimensions, as a numpy array with shape (48,128,42,5). (height, width, frames, video index). The multiple videos basically serve as \"slices\" to get some information about depth, although imperfect.\nI want to create a CNN using Keras\/Tensorflow for regression, but Keras only has built-in Convolutional layers for up to 3 dimensions. Is there a good way to perform convolution and max-pooling on 4 dimensional data? Or will I need to create my own layer using Tensorflow?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":135,"Q_Id":61843677,"Users Score":0,"Answer":"TL;DR - You still only need Conv3D\nDon't let the vector shape confuse you, the number of dimensions of the convolution layer refers to the dimensions on which the filter slides, not the input shape. \nFor example, if you'd want to process audio, you would still use Conv1D as you only slide the filter over time (1-D), even though the audio signal might have 2 channels and therefore shape e.g. (1,44100,2) (1 file, 44100 samples per second - assuming 1s audio lenght, 2 channels - left and right). \nSimilarly, for a 28x28 RBG image (1,28,28,3) you would still use Conv2D, as the filter slides vertically and horizontally across the image. \nFinally, for your video example, you need your convolutional filter to slide through the image (2D) PLUS the different frames. Therefore, you end up using Conv3D","Q_Score":1,"Tags":"python,tensorflow,keras","A_Id":61843999,"CreationDate":"2020-05-16T21:16:00.000","Title":"Using Keras for a CNN to perform regression on a set of videos","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I trained a time series model with LSTM (Shape is N, 20, 1).\nSuppose N is the last data.\nUsing model.predict gives the N + 1 th predicted value.\nHow do I predict data values after N + 2, N + 3, N + 4 .... etc.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":128,"Q_Id":61845462,"Users Score":0,"Answer":"In a time series model like LSTM, predicting a new datapoint depends on the previous datapoints. To predict n + 1, you use [N-19...N]. Now to predict n + 2, you need [N-18...N+1]. Repeat this process if you want to predict farther and farther in the future.\nOf course, the farther ahead you go, the less accurate your predictions will be. RNNs are good at predicting the next timestep, but not so good at predicting things far in the future. That's why if you look at books or sentences generated by neural nets, they don't make much sense.\nOnce you have the real value for n + 1, the n + 2 prediction will be more accurate than if you had to use your predicted value.","Q_Score":1,"Tags":"python,tensorflow,lstm,recurrent-neural-network","A_Id":61846716,"CreationDate":"2020-05-17T00:31:00.000","Title":"How can I predict the following values after RNN model training?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I plotted an image in jupyter notebook, and instead of 'loss' I typed 'accuracy' in the image title and saved it in 'svg' format, and notebook is saved in github repo. \nI want to know is there any way to edit it the image, without running the whole script again?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":16,"Q_Id":61852226,"Users Score":0,"Answer":"I think you can re-run the part of code for printing\/saving that image only in the new cell in the same jupyter file if you haven't closed that file yet","Q_Score":0,"Tags":"python,matplotlib,jupyter-notebook","A_Id":61852376,"CreationDate":"2020-05-17T13:02:00.000","Title":"Can i edit image created in jupyter notebook without re running","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm making an RNN language model with Keras and in order to train the model (supervised learning) I have to create a numpy array y (with the labels of each observation for each sequence) of shape (num_of_training_sequences, size_of_vocabulary) containing one-hot vectors.\nWhen I have too many training sequences, this array is too big to fit in memory. However, it doesn't have to be! Since the number of possible one-hot vectors is only size_of_vocabulary, then y could just be a num_of_training_sequences sized array that contains references (aka pointers) to pre-allocated one-hot vectors. This way, if two sequences end in the same word and should have the same one-hot vector, then they would just reference the same address in memory of that one-hot vector. \nAnd everyone should be happy, except from numpy arrays. Because when I cast this magesticly efficient data structure to numpy array, it tries to allocate the whole array into memory, along with duplicate and reduntant one-hot vectors. \nIs there anything I can do to overcome this? Keras's code and documentation says fit() only accepts numpy arrays and tensors.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":43,"Q_Id":61853084,"Users Score":0,"Answer":"The way I overcame my memory issue is by using fit_generator() instead of fit(). The generator function can take my more efficient list of lists structure and generate the (now much smaller) numpy array just-in-time for each batch, reducing the memory needed overall.\nAnother topic I ran into is sparse arrays. Because one-hot vector arrays contain a lot of zeros, they are sparse and it is much more efficient to store them as such e.g. with scipy's sparse matrix implementations. The generator function will again need to convert them to dense numpy arrays for fit_generator().\nThere is also a sparse tensor implemented in tf that should not require a generator to convert it to a dense array but I wasn't able to make it work.","Q_Score":0,"Tags":"python,arrays,numpy,keras","A_Id":61855086,"CreationDate":"2020-05-17T14:05:00.000","Title":"How do I use the same memory address for redundant rows of numpy array?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"When I try to install scikit-learn using PyCharm by going into the settings->Project Settings->Project Interpreter-> '+' button and serching for and installing scikit-learn, it gives me this error:\nCould not install packages due to an EnvironmentError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '\"C:'\nI installed numpy without any problems before this.\nIs there anything I am missing or another way I can try to install scikit-learn?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":358,"Q_Id":61859877,"Users Score":0,"Answer":"Update: I found the answer.\nFor anyone out there with the same problem as me, you should go to settings->Project Settings->Project Interpreter in Pycharm. There you will find pip, which for me was out dated. If this is the case, then click on pip and then the upgrade button that looks like an up arrow. After it finishes installing the latest version of pip, retry installing scikit-learn or any other package that would not previously install and gave the error \"Could not install packages due to an EnvironmentError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '\"C:'\"","Q_Score":0,"Tags":"python,python-3.x,scikit-learn,pip","A_Id":61881125,"CreationDate":"2020-05-17T22:57:00.000","Title":"Why is scikit-learn not installing on python 3.8 using pycharm on windows 10?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I updated from ubuntu 12.04 to ubuntu 12.10 and the python module I have written suddenly no longer works with the error message that the module scipy does not have the attribute 'misc'. This worked previously. I am still using python 2.7 after the update. Here is where the code crashes","AnswerCount":1,"Available Count":1,"Score":-0.1973753202,"is_accepted":false,"ViewCount":289,"Q_Id":61860317,"Users Score":-1,"Answer":"it's very easy\nu have to do this step\n1-pip install imageio\n2-import imageio\n3-replace scipy.misc.imsave(image_name,data)\nwith this code\nimageio.imwrite(image_name, data)\nenjoy............","Q_Score":1,"Tags":"python,scipy","A_Id":61860318,"CreationDate":"2020-05-17T23:51:00.000","Title":"how u can fix this problem AttributeError: 'scipy' object (scipy) has no attribute 'misc'?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"This is my understanding of convolutional neural networks and my best practices. Please advise if my though-process is accurate.\n1) If input set has small details, have a smaller filter size.\n2) Qty is dependent on how many small details.\n3) Always have a maxpool layer for showing the output layers the most important parts of the image.\n4) if accuracy between the last few epochs is very small, and training time is long, consider increasing learning rate and\/or decreasing epochs\n5) if dropout is to be used, use it between two dense layers, preferably right before the output layer\nThanks for your expertise in advance.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":62,"Q_Id":61861533,"Users Score":1,"Answer":"Let's evaluate point by point.\n1) If input set has small details, have a smaller filter size. -> Yes, you can use the most 3x3 common filter or if need be then 2x2. But, still you will have to go through a lot of prototyping. An added fact to this, the number of filters is directly proportional to the position of layers. So, in first layer, have 16, then next layers 32 and so on.\n2) Qty is dependent on how many small details. -> You don't know the number of small details. Neural networks are effectively a black-box, there is no rigorous mathematical way to define neural networks till now.\n3) Always have a maxpool layer for showing the output layers the most important parts of the image. -> By that logic, you would just put MaxPool at the end of the network. Usually, have a MaxPool, after 2-3 Conv layers. The point of MaxPool is to highlight the important features but also at the same time to reduce parameter space. Using it sparingly defeats it purpose.\n4) If accuracy between the last few epochs is very small, and training time is long, consider increasing learning rate and\/or decreasing epochs. -> Accuracy usually slows increases towards the end of training. Even in learning rate schedules, you decrease the learning rate w.r.t to increasing epochs. Don't expect big jumps in accuracy towards the end of training. Try to find a good learning rate and train till satisfaction w.r.t validation set.\n5) If dropout is to be used, use it between two dense layers, preferably right before the output layer. -> The point of dropout is to give a regularization effect. You can use dropout in Conv layers also. Use dropout to reduce overfitting, the place doesn't matter. The effectiveness of using dropout in Dense layers should be more as they are towards the end of network holding the weights that result into your prediction but dropout should be used throughout the network if possible. Or you can use regularizer on layer weights.","Q_Score":0,"Tags":"python,tensorflow,deep-learning,neural-network,conv-neural-network","A_Id":61863256,"CreationDate":"2020-05-18T02:32:00.000","Title":"Are these advisable best practices for convolutional neural networks?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm working on a project that requires training a PyTorch framework NN on a very large dataset of images. Some of these images are completely irrelevant to the problem, and but these irrelevant images are not labelled as such. However, there are some metrics I can use to calculate if they are irrelevant (e.g. summing all the pixel values would give me a good sense of which are the relevant images and which are not). What I would ideally like to do is have a Dataloader that can take in a Dataset class, and create batches only with the relevant images. The Dataset class would just know the list of images and their labels, and the Dataloader would interpret whether or not the image it is making a batch with is relevant or not, and would then only make batches with relevant images.\nTo apply this to an example, lets say I have a dataset of black and white images. The white images are irrelevant, but they are not labelled as such. I want to be able to load batches from a file location, and have these batches only contain the black images. I could filter at some point by summing all the pixels and finding it equals to 0. \nWhat I am wondering is if a custom Dataset, Dataloader, or Sampler would be able to solve this task for me? I already have written a custom Dataset that stores the directory of all the saved images, and a list of all the images in that directory, and can return an image with its label in the getitem function. Is there something more I should add there to filter out certain images? Or should that filter be applied in a custom Dataloader, or Sampler?\nThank you!","AnswerCount":2,"Available Count":2,"Score":1.2,"is_accepted":true,"ViewCount":178,"Q_Id":61863541,"Users Score":0,"Answer":"I'm assuming that your image dataset belongs to two classes (0 or 1) but it's unlabeled. As @PranayModukuru mentioned that you can determine the similarity by using some measure (e.g aggregating all the pixels intensity values of a image, as you mentioned) in the getitem function in tour custom Dataset class.\nHowever, determining the similarity in getitem function while training your model will make the training process very slow. So, i would recommend you to approximate the similarity before start training (not in the getitem function). Moreover if your image dataset is comprised of complex images (not black and white images) it's better to use a pretrained deep learning model (e.g. resnet or autoencoder) for dimentionality reduction followed by applying clustering approach (e.g. agglomerative clustering) to label your image.\nIn the second approach you only need to label your images for exactly one time and if you apply augmentation on images while training you don't need to re-determine the similarity (label) in the getitem funcion. On the other hand, in the first approach you need to determine the similarity (label) every time (after applying transformation on images) in the getitem function which is redundant, unnecessary and time consuming.\nHope this will help.","Q_Score":0,"Tags":"python,pytorch,dataloader","A_Id":61879851,"CreationDate":"2020-05-18T06:23:00.000","Title":"Custom Dataset, Dataloader, Sampler, or something else?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm working on a project that requires training a PyTorch framework NN on a very large dataset of images. Some of these images are completely irrelevant to the problem, and but these irrelevant images are not labelled as such. However, there are some metrics I can use to calculate if they are irrelevant (e.g. summing all the pixel values would give me a good sense of which are the relevant images and which are not). What I would ideally like to do is have a Dataloader that can take in a Dataset class, and create batches only with the relevant images. The Dataset class would just know the list of images and their labels, and the Dataloader would interpret whether or not the image it is making a batch with is relevant or not, and would then only make batches with relevant images.\nTo apply this to an example, lets say I have a dataset of black and white images. The white images are irrelevant, but they are not labelled as such. I want to be able to load batches from a file location, and have these batches only contain the black images. I could filter at some point by summing all the pixels and finding it equals to 0. \nWhat I am wondering is if a custom Dataset, Dataloader, or Sampler would be able to solve this task for me? I already have written a custom Dataset that stores the directory of all the saved images, and a list of all the images in that directory, and can return an image with its label in the getitem function. Is there something more I should add there to filter out certain images? Or should that filter be applied in a custom Dataloader, or Sampler?\nThank you!","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":178,"Q_Id":61863541,"Users Score":0,"Answer":"It sounds like your goal is to totally remove the irrelevant images from training.\nThe best way to deal with this would be to figure out the filenames of all the relevant images up front and save their filenames to a csv or something. Then pass only the good filenames to your dataset.\nThe reason is you will run through your dataset multiple times during training. This means you will be loading, analyzing and discarding irrelevant images over and over again, which is a waste of compute.\nIt's better to do this sort of preprocessing\/filtering once upfront.","Q_Score":0,"Tags":"python,pytorch,dataloader","A_Id":61880237,"CreationDate":"2020-05-18T06:23:00.000","Title":"Custom Dataset, Dataloader, Sampler, or something else?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am able to do that same thing with DataTable where clicking on a given row triggers callback using source.selected.on_change() however this doesnt seem to work for DataCube","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":99,"Q_Id":61863824,"Users Score":0,"Answer":"As of Bokeh 2.0.2, this functionality is not implemented at all. Please feel free to create a feature request on Bokeh's GitHub page.","Q_Score":0,"Tags":"python-3.x,bokeh","A_Id":61864082,"CreationDate":"2020-05-18T06:44:00.000","Title":"Python- Bokeh - DataCube - Not able to select any row and extract information through callback","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"How to generate random 20 digit UID(Unique Id) in python. I want to generate UID for each row in my data frame. It should be exactly 20 digits and should be unique.\nI am using uuid4() but it generates 32 digits UID, would it be okay to slice it [:21]? I don't want the id to repeat in the future.\nAny suggestions would be appreciated!","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":750,"Q_Id":61866295,"Users Score":0,"Answer":"I think uuid4() in python works, just slice it accordingly","Q_Score":2,"Tags":"python,pandas,numpy,uuid,uid","A_Id":61898840,"CreationDate":"2020-05-18T09:17:00.000","Title":"How to generate random 20 digit uid(Unique Id) in python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working on a Supervised ML classification use case and I have 5 features and a target variable. Suppose the 5 feature are A, B, C, D, E, F and the target variable being G. The E feature isn't a raw feature meaning it is predicted from some other features. I tried using that feature for model building and the classification metrics were pretty good. But now my boss said that the we cannot use Feature E as it isn't directly available, we need to predict that first and then use it for predicting target G.\nBelow are some of the things I tried:\n\nI tried building a model by removing feature E from my feature list, the metrics dropped meaning that the feature E is important.\nBoss says that the feature E is derived or dependent on feature A, B, C, D and F so we can use that to predict feature E and then use features A, B, C, D, E, F to predict G.\n\nHere are my concerns:\n\nIf feature E is dependent on features A, B, C, D and F then not using feature E while building model should not affect my metrics much.\nIf I use features A, B, C, D and F to predict feature E and indeed use features A, B, C, D, E, F to predict G won't I be using correlated feature for model building because E is predicted using A, B, C, D and F. Using F won't add any extra information to my feature set.\n\nMy understanding is that if building model by removing feature E from my feature list dropped my metrics then it means that feature E comes from somewhere else i.e. other than features A, B, C, D, F.\nI am not an experienced person in ML and these are my thoughts are about the problem.\nPlease let me know whether my thought process is right?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":854,"Q_Id":61869533,"Users Score":1,"Answer":"If feature E is dependent on features A, B, C, D and F then not using feature E while building model should not affect my metrics\n much.\n\n\nIt really depends on the model you're using, but a simple example, let's imagine you are using a linear regression model, and the value you're trying to predict is y=x\u00b2\nYou can't find a fitting model with a simple linear regressor (A*x+B). However, you can create a new feature x' = x\u00b2, and now you can fit y A*x'+b . So a feature dependant on a combination of the other features can help your model sometimes.\n\n\nIf I use features A, B, C, D and F to predict feature E and indeed use features A, B, C, D, E, F to predict G won't I be using correlated\n feature for model building because E is predicted using A, B, C, D and\n F. Using F won't add any extra information to my feature set.\n\n\nThis question is more tricky, because it all really depends on the model you use to predict E, and the model you use to predict y.\nIf you use a simple linear regressor for both, then yes, E will be a linear combination of the other variables and won't help predicting y. \nBut you could imagine predicting E using a non-linear model, like RandomForest, and that could help your final model.\nBottom line is : it doesn't cost much to try, just be careful using the same train\/test for both models to avoid any leakage.","Q_Score":0,"Tags":"python,machine-learning,supervised-learning","A_Id":61890247,"CreationDate":"2020-05-18T12:24:00.000","Title":"Predicting a feature and using the predicted feature to predict the target","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a network in TensorFlow which uses tf.nn.embedding_lookup because of that the input placeholder is self.input_x = tf.placeholder(tf.int32, [None, sequence_length], name=\"input_x\"), I want to add an MLP network to this current network such that input of the MLP network is the input of the current network. For the MLP network, I need a float input type, but the type of current input placeholder is tf.int32. so when I run the code it shows the error. How can I solve this?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":58,"Q_Id":61876856,"Users Score":0,"Answer":"Using with tf.variable_scope and with tf.name_scope for both networks solved the problem.","Q_Score":1,"Tags":"python,tensorflow","A_Id":62022858,"CreationDate":"2020-05-18T18:50:00.000","Title":"How to have two networks together in TensorFlow?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a UNet Segmentation network implemented in Keras that simply maps all pixels in an RGB image to 4 categories which is trained on a heat map mask (Low, Low-Med, High-Med, High). Using CCE or categorical Dice loss I am able to get decent results.\nHowever, The mask in it's original form is a heat map image with 255 bits of resolution. It seems like a totally arbitrary introduction of error to shoehorn it into the Unet by reducing the 255 bits of resolution into 4 categories.\nI would like the network to output an image with each pixel having a value between (0,1), and train the network with masks that are produced by multiplying the heat map image by 1.\/255.\nWhere, in this case, the loss function would incorporate the mathematical difference between the mask and the prediction from the network. Can anyone point me in the direction of someone who has done something similar? I think I am just awful at describing what I'm looking for with relevant terminology because it seems like this would be a fairly common goal in computer vision..?","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":2534,"Q_Id":61878950,"Users Score":2,"Answer":"If I understand your question correctly - the \"ground truth\" mask is just a gray-scale image with values in range [0,255], meaning , there is a strong relation between it's values (for example - 25 is closer to 26 then to 70. this is not the case with regular segmentation, where you assign a different class to each pixel and the classes values may represent arbitrary objects such as \"bicycle\" or \"person\"). In other words, this is a regression problem, and to be more specific an image-to-image regression. You are trying to reconstruct a gray-scale image which should be identical to the ground truth mask, pixel-wise. \nIf I understood you correctly - you should look for regression losses. Common examples that can be used are Mean Squared Error (aka MSE, L2 norm) or Mean Absolute Error (aka MAE, L1 norm). Those are the \"usual suspects\" and I suggest you start with them, although many other losses exists.","Q_Score":1,"Tags":"python,keras,deep-learning,computer-vision,semantic-segmentation","A_Id":61988296,"CreationDate":"2020-05-18T21:02:00.000","Title":"UNet Loss function for non-categorical Mask?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I would like to convert the following time format to a valid date time format for my graphs. \n2020-05-06T08:49:23.004+10:00\nSo far I've been removing the +10:00 in order to make it work.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":42,"Q_Id":61880376,"Users Score":1,"Answer":"Have you tried pandas.to_datetime(time), where time = 2020-05-06T08:49:23.004+10:00?","Q_Score":0,"Tags":"python,pandas","A_Id":61880571,"CreationDate":"2020-05-18T22:55:00.000","Title":"Pandas convert time format","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have directory with small parquet files(600), I wanted to do ETL on those parquet and merge those parquet to 128mb each file. what is the optimal way to process the data. \nshould I read each file in the parquet directory and concat as a single data frame and do groupBY ? or provide parquet directory name to dd.read_parquet and process it? \nI feel like, when I read the file by file, it creates a very large dask graph that cannot be fit as an image. \nI guess it will work with those many numbers of threads as well? which leads to a memory error.\nwhich way is best to read the parquet file to process as dask dataframe ? file by file or provide entire directory ??","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":144,"Q_Id":61884851,"Users Score":0,"Answer":"Unfortunately there is no single best eway to read a Parquet file for all situations. In order to properly answer the question you will need to know more about your situation.","Q_Score":0,"Tags":"python,dask,parquet,pyarrow,dask-dataframe","A_Id":61976131,"CreationDate":"2020-05-19T06:49:00.000","Title":"which way is best to read the parquet file to process as dask dataframe","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am looking for an Opencv method or a way to calculate a per-block motion vectors for two consecutive images.","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":760,"Q_Id":61891430,"Users Score":2,"Answer":"Your comment on another answer\n\nThis contains a dense (per-pixel) motion estimation, and a per feature estimation. Nothing for a per-block estimation\n\nmakes me (perhaps mistakenly) think that you're looking for a function whose existence wouldn't really make sense: assuming you pre-define your blocks with some desired granularity, how are you going to compute the flow for each of the blocks? There are two possibilities:\n\nCompute sparse (cv.calcOpticalFlowPyrLK()) or dense (cv.calcOpticalFlowFarneback()) flow over the entire image, and average\/downsample the result over each block (with some smoothing afterwards).\n\nCompute some sort of \"block flow\" (which seems to be what you had in mind), where you define higher level blocks or super-pixels that you express using some statistics (or features) and compute the flow over them. In that case you'll probably violate the brightness constancy assumptions that most flow methods rely on, and even if you don't, this will very probably be similar to computing dense flow on a very low-resolution image, which in this case, again, could be achieved with cv.calcOpticalFlowFarneback().\nUsing higher-level blocks would make sense if you were learning them in a flow estimation pipline, though, but that is not the case here as they're predefined.\n\n\nThe second solution doesn't make much sense here, and the first solution is just a simple post-processing that depends on the user's needs.","Q_Score":1,"Tags":"python,opencv,computer-vision","A_Id":61893875,"CreationDate":"2020-05-19T12:49:00.000","Title":"Is there any function in OpenCV to calculate per block motion vectors for two images?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to use spacy's pretrained BERT model for text classification but I'm a little confused about cased\/uncased models. I read somewhere that cased models should only be used when there is a chance that letter casing will be helpful for the task. In my specific case: I am working with German texts. And in German all nouns start with the capital letter. So, I think, (correct me if I'm wrong) that this is the exact situation where cased model must be used. (There is also no uncased model available for German in spacy). \nBut what must be done with data in this situation?\nShould I (while preprocessing train data) leave it as it is (by that I mean not using the .lower() function) or it doesn't make any difference?","AnswerCount":3,"Available Count":3,"Score":0.0,"is_accepted":false,"ViewCount":11834,"Q_Id":61902426,"Users Score":0,"Answer":"The difference between \"BERT cased\" and \"BERT uncased\" can to finded in different contexts. For example, in the dialogs system, the users rarely put the text in their correct form, so, is ordinary to find the words in lower case. Maybe, in this case, the BERT in uncased have an advantage.","Q_Score":10,"Tags":"python,spacy,bert-language-model","A_Id":66482983,"CreationDate":"2020-05-19T23:20:00.000","Title":"Cased VS uncased BERT models in spacy and train data","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to use spacy's pretrained BERT model for text classification but I'm a little confused about cased\/uncased models. I read somewhere that cased models should only be used when there is a chance that letter casing will be helpful for the task. In my specific case: I am working with German texts. And in German all nouns start with the capital letter. So, I think, (correct me if I'm wrong) that this is the exact situation where cased model must be used. (There is also no uncased model available for German in spacy). \nBut what must be done with data in this situation?\nShould I (while preprocessing train data) leave it as it is (by that I mean not using the .lower() function) or it doesn't make any difference?","AnswerCount":3,"Available Count":3,"Score":0.2605204458,"is_accepted":false,"ViewCount":11834,"Q_Id":61902426,"Users Score":4,"Answer":"In simple terms, BERT cased doesn't lowercase the word starting with a capital letter for example in the case of Nouns in the German language.\nBERT cased is helpful where the accent plays an important role.\nFor example sch\u00f6n in German\nIf we convert sch\u00f6n to schon using BERT uncased, it will have a different meaning.\nsch\u00f6n means beautiful whereas schon means already","Q_Score":10,"Tags":"python,spacy,bert-language-model","A_Id":68660367,"CreationDate":"2020-05-19T23:20:00.000","Title":"Cased VS uncased BERT models in spacy and train data","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to use spacy's pretrained BERT model for text classification but I'm a little confused about cased\/uncased models. I read somewhere that cased models should only be used when there is a chance that letter casing will be helpful for the task. In my specific case: I am working with German texts. And in German all nouns start with the capital letter. So, I think, (correct me if I'm wrong) that this is the exact situation where cased model must be used. (There is also no uncased model available for German in spacy). \nBut what must be done with data in this situation?\nShould I (while preprocessing train data) leave it as it is (by that I mean not using the .lower() function) or it doesn't make any difference?","AnswerCount":3,"Available Count":3,"Score":1.2,"is_accepted":true,"ViewCount":11834,"Q_Id":61902426,"Users Score":12,"Answer":"As a non-German-speaker, your comment about nouns being uppercase does make it seem like case is more relevant for German than it might be for English, but that doesn't obviously mean that a cased model will give better performance on all tasks.\nFor something like part-of-speech detection, case would probably be enormously helpful for the reason you describe, but for something like sentiment analysis, it's less clear whether the added complexity of having a much larger vocabulary is worth the benefits. (As a human, you could probably imagine doing sentiment analysis with all lowercase text just as easily.)\nGiven that the only model available is the cased version, I would just go with that - I'm sure it will still be one of the best pretrained German models you can get your hands on. Cased models have separate vocab entries for differently-cased words (e.g. in english the and The will be different tokens). So yes, during preprocessing you wouldn't want to remove that information by calling .lower(), just leave the casing as-is.","Q_Score":10,"Tags":"python,spacy,bert-language-model","A_Id":61906361,"CreationDate":"2020-05-19T23:20:00.000","Title":"Cased VS uncased BERT models in spacy and train data","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a triangular sparse matrix of dimension n where the only coefficients that appear are c_1, c_2,...c_n. There are at most n repetitions of a single coefficient in the matrix. Is there any way to use the fact that there are many elements of the matrix that are the same and use much less memory instead of assigning the same value to many different (row, column) and not exploiting the fact that many are the same. At the end of the day I want to apply the inverse of the said matrix to an arbitrary vector.\nThank you!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":67,"Q_Id":61903281,"Users Score":0,"Answer":"Definitely, you can use the sparse matrix data structures from 'scipy.sparse'. If you know the values tend to group in certain patterns you can use specific sparse matrix structures optimized for that pattern. If the values group along diagonals use 'dia_matrix', columns use 'csc_matrix', rows use 'csr_matrix', and blocks use 'bsr_matrix'.","Q_Score":0,"Tags":"python,scipy,sparse-matrix","A_Id":61903483,"CreationDate":"2020-05-20T00:53:00.000","Title":"Sparse matrices with lots of repeated elements in Scipy","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"As the title suggests, I want to generate a random N x d matrix (N - number of examples, d - number of features) where each column is linearly independent of the other columns. How can I implement the same using numpy and python?","AnswerCount":3,"Available Count":1,"Score":0.0665680765,"is_accepted":false,"ViewCount":801,"Q_Id":61905733,"Users Score":1,"Answer":"If you just generate the vectors at random, the chance that the column vectors will not be linearly independent is very very small (Assuming N >= d).\nLet A = [B | x] where A is a N x d matrix, B is an N x (d-1) matrix with independent column vectors, and x is a column vector with N elements. The set of all x with no constraints is a subspace with dimension N, while the set of all x such that x is NOT linearly independent with all column vectors in B would be a subspace with dimension d-1 (since every column vector in B serves as a basis vector for this set).\nSince you are dealing with bounded, discrete numbers (likely doubles, floats, or integers), the probability of the matrix not being linearly independent will not be exactly zero. The more possible values each element can take, in general, the more likely the matrix is to have independent column vectors.\nTherefore, I recommend you chose elements at random. You can always verify after the fact that the matrix has linearly independent column vectors by calculating it's column-echelon form. You could do this with np.random.rand(N,d).","Q_Score":4,"Tags":"python,numpy,scipy","A_Id":61906800,"CreationDate":"2020-05-20T05:28:00.000","Title":"Generating linearly independent columns for a matrix","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am looking into the ways for comparing records from same table but on different databases. I just need to compare and find the missing records.\nI tried out a few methods.\nloading the records into a pandas data frame, I used read_sql. But it is taking more time and memory to complete the load and if the records are large, I am getting a memory error.\nTried setting up a standalone cluster of spark and run the comparison, it is also throwing java heap space error. tuning the conf is not working as well.\nPlease let me know if there are other ways to handle this huge record comparison.\n--update\nDo we have a tool readily available for cross data source comparison","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":28,"Q_Id":61906560,"Users Score":0,"Answer":"If your data size is huge you can use cloud services to run your spark job and get the results. Here you can use aws glue which is serverless and is charged as you go.\nOr if your data is not considerably large and is something one time job then you can use google colab which is free and run your comparision over it .","Q_Score":0,"Tags":"python-3.x,database,pyspark,apache-spark-sql","A_Id":61906771,"CreationDate":"2020-05-20T06:33:00.000","Title":"Possible ways of comparing large records from one table on a database and another table on another database","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"i am trying implement from scipy.spatial import distance as dist library however it gives me File \"\/home\/afeyzadogan\/anaconda3\/envs\/untitled\/lib\/python3.7\/inspect.py\", line 56, in \n for k, v in dis.COMPILER_FLAG_NAMES.items():\nAttributeError: module 'dis' has no attribute 'COMPILER_FLAG_NAMES'\nerror how can i solve it?\n'''\nfor k, v in dis.COMPILER_FLAG_NAMES.items():\n mod_dict[\"CO_\" + v] = k\n'''","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":641,"Q_Id":61910425,"Users Score":1,"Answer":"We ran across this issue in our code with the same exact AttributeError.\nTurns out it was a totally unrelated file in the current directory called dis.py.","Q_Score":0,"Tags":"python,inspect","A_Id":67427679,"CreationDate":"2020-05-20T10:08:00.000","Title":"How can i solve AttributeError: module 'dis' has no attribute 'COMPILER_FLAG_NAMES' in anaconda3\/envs\/untitled\/lib\/python3.7\/inspect.py","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I wonder if there is a way to evaluate batches of individuals when running deap ? The classic implementations evaluate individuals one by one but my evaluation function requires me to evaluate the inidviduals with a surrogate model that is only accessible online and connecting to the server where this model is kept is time-consuming so I would prefer directly sending the whole population to the server for evaluation instead of having to connect for each individual.\n(It takes approx. 40 seconds to get my results whatever the number of evaluation I am asking and there is no way for me to change this as it is due to the software I am connecting to that can't be changed)\nEvaluation function is called with : fitnesses = toolbox.map(toolbox.evaluate, invalid_ind) and I have previously defined toolbox.register(\"evaluate\", evaluation_fct)","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":79,"Q_Id":61910667,"Users Score":1,"Answer":"By calling fitnesses = evaluation_fct(invalid_ind) I managed what I wanted to do (invalid_ind being a list of the individuals to evaluate) and therefore it becomes unnecesaary to call the toolbox.register(\"evaluate\", evaluation_fct)","Q_Score":1,"Tags":"python,python-3.x,deap","A_Id":61934052,"CreationDate":"2020-05-20T10:21:00.000","Title":"Evaluate batch of individuals in Deap instead of one-by-one evaluation","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to use lasso regression in sklearn to run on my data.\nall my attributes in my dataframe is numeric type(by numeric, I mean they are all integer). \nbut some of them clearly should be categorical(for example, 'race' attribute in my dataframe is an attribute have three value 1,2,3 where each value represent one race).\nWhat I did is first set those columns as string type by using astype('str') then use code astype('categorical') to transform those column's data type to categorical.\nFinally, I used sklearn.linear_model.Lasso on those transformed features.\nMy question is can sklearn.linear_model.Lasso recognize those variables are categorical? Or the only way to deal with those type of categorical data is one hot encoding?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":380,"Q_Id":61914504,"Users Score":0,"Answer":"I would use OneHotEncoding to separate the categorical variables into different columns. However, make sure that you avoid the \"dummy variable trap\" by getting rid of the first column of your new dummy variables. \nYou want to use OneHotEncoding so that your program is able to recognize that no category of your categorical variables is numerically greater than the others. For example, let's say you have a column wherein 0 = Spain, 1 = Germany, and 2 = France. In this case, your program would assume that the column for geography is a continuous variable, wherein 2(France) is greater than 1(Germany). Thus, you must use OneHotEncoding to create three separate columns of 0's and 1's. \nI hope that answers your question.","Q_Score":1,"Tags":"python,pandas,scikit-learn","A_Id":61920131,"CreationDate":"2020-05-20T13:36:00.000","Title":"Can sklearn.linear_model.Lasso recognize the categorical data type in pandas dataframe?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"How can I save a plot in a 750x750 px using savefig?\nThe only useful parameter is DPI, but I don't understand how can I use it for setting a precise size","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":262,"Q_Id":61914547,"Users Score":0,"Answer":"I added plt.tight_layout() before savefig(), and it solved the trimming issue I had. Maybe it will help yours as well.\nI also set the figure size at the begining rcParams['figure.figsize'] = 40, 12(you can set your own width and height)","Q_Score":0,"Tags":"python,matplotlib","A_Id":61914735,"CreationDate":"2020-05-20T13:37:00.000","Title":"save a figure with a precise pixels size with savefig","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Given a matrix representing a video, where the rows represent video frames and the columns represent frame features, are there any techniques I can use to create a single feature vector from this without losing the spatio-temporal information from the matrix? i.e. 40 frame vectors with 36 features each converted to 1 vector with 36 features representing the entire 40 frames.\nI've already tried taking the mean for each feature but I'm wondering about other techniques.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":73,"Q_Id":61919224,"Users Score":0,"Answer":"I have no experience on video data. But I had a sense that your problem is the same\/or very similar to text summarization problem. \nIn principle, what you want is to \"summarize\" all your different time frames into just only one frame. It is very much like you have many sentences in one article but you just want to have one sentence which can summarize all the sentences in one article. \nIn general there are two methods:\n1. Extract methods: :Evaluate the importance of each frame and put weights on different frames. Then simply use linear combination to have a summarize vector. In extreme case, you can just use the dominant frame as a representative frame if its weight is much bigger than the others. This method is very similar to TextRank or TextTeasing algorithm in NLP. \n2. Abstract methods: : In case of NLP, you need some knowledge of linguist and sentence semantic structures in order to develop this approach. In your case, I believe you need to do the same thing for your video data.","Q_Score":0,"Tags":"python,machine-learning","A_Id":61929407,"CreationDate":"2020-05-20T17:27:00.000","Title":"Converting matrix to spatio-temporal feature vector","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've been studying python for data science for about 5 months now. But I get really stucked when it comes to matplotlib. There's always so many options to do anything, and I can't see a well defined path to do anything. Does anyone have this problem too and knows how to deal with it?","AnswerCount":3,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":45,"Q_Id":61921792,"Users Score":0,"Answer":"I think your question is stating that you are bored and do not have any projects to make. If that is correct, there are many datasets available on sites like Kaggle that have open-source datasets for practice programmers.","Q_Score":0,"Tags":"python,matplotlib,data-science","A_Id":61922150,"CreationDate":"2020-05-20T19:55:00.000","Title":"Tips to practice matplotlib","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've been studying python for data science for about 5 months now. But I get really stucked when it comes to matplotlib. There's always so many options to do anything, and I can't see a well defined path to do anything. Does anyone have this problem too and knows how to deal with it?","AnswerCount":3,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":45,"Q_Id":61921792,"Users Score":0,"Answer":"in programming in general \" There's always so many options to do anything\".\ni recommend to you that read library and understand their functions and classes in a glance, then go and solve some problems from websites or give a real project if you can. if your code works do not worry and go ahead. \nafter these try and error you have a lot of real idea about various problems and you recognize difference between these options and pros and cons of them. like me three years ago.","Q_Score":0,"Tags":"python,matplotlib,data-science","A_Id":61922191,"CreationDate":"2020-05-20T19:55:00.000","Title":"Tips to practice matplotlib","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"My target is continuous value like house price. I am training a regression tree on it. I use Gradientboostregressor in scklearn, Python. \nMy target value(house price) has a L shape distribution: house price on high end is like 10 times higher than price on low end. My regression tree model under-predict high values, and over-predict low values. \nAnything I can do to improve model prediction? I tried to model log(price), then exp(prediction),but not work well. \nThank you very much.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":155,"Q_Id":61922639,"Users Score":0,"Answer":"A single decision tree often does not work very well. Of course you could try to optimize the tree. But I think it is better to change to random forest or gradient boosting if you want to work with trees.","Q_Score":1,"Tags":"python,regression,decision-tree","A_Id":61922711,"CreationDate":"2020-05-20T20:49:00.000","Title":"Regression tree does not perform well","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a trained model that determines if an image contains either cat or dog. I'm using SVM to classify. I want a new model that determines if an image is a mouse or not. It's different from the first model that classifies into 2 classes. This new model will return TRUE or FALSE only.\nI don't think I can use a classifier model since I have only 1 class; the mouse. I don't intend to use the first model or anything related to it in the 2nd model.\nWhat is the best way to approach this?","AnswerCount":5,"Available Count":3,"Score":0.0,"is_accepted":false,"ViewCount":891,"Q_Id":61930631,"Users Score":0,"Answer":"If you already have a mouse class, you can use supervised learning. \nwhen you train your model, let the model learn what is a mouse by defining him that this is a specific object is mouse and define him what is not a mouse...\nWith this approach you just need a class of mouse to define your model and \"teach\" him what is a mouse, after this, your model will classify \"mouse\" and \"not mouse\"","Q_Score":0,"Tags":"python-3.x,machine-learning,computer-vision","A_Id":61930765,"CreationDate":"2020-05-21T08:46:00.000","Title":"How to determine if image is something or not?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a trained model that determines if an image contains either cat or dog. I'm using SVM to classify. I want a new model that determines if an image is a mouse or not. It's different from the first model that classifies into 2 classes. This new model will return TRUE or FALSE only.\nI don't think I can use a classifier model since I have only 1 class; the mouse. I don't intend to use the first model or anything related to it in the 2nd model.\nWhat is the best way to approach this?","AnswerCount":5,"Available Count":3,"Score":0.0399786803,"is_accepted":false,"ViewCount":891,"Q_Id":61930631,"Users Score":1,"Answer":"If you'd like to be able to predict if an image has a mouse, this is still a classification problem where you're classifying images into two classes - Mouse and Not a Mouse. \nAny classifier you intend to use might need to learn a boundary to separate the mouse images from non mouse images in the n-dimensional input space. \nIn case you employ a neural network, you could make do with just one output neuron that will ideally give high probability when the image is a mouse and low when there isn't a mouse in the image.","Q_Score":0,"Tags":"python-3.x,machine-learning,computer-vision","A_Id":61930853,"CreationDate":"2020-05-21T08:46:00.000","Title":"How to determine if image is something or not?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a trained model that determines if an image contains either cat or dog. I'm using SVM to classify. I want a new model that determines if an image is a mouse or not. It's different from the first model that classifies into 2 classes. This new model will return TRUE or FALSE only.\nI don't think I can use a classifier model since I have only 1 class; the mouse. I don't intend to use the first model or anything related to it in the 2nd model.\nWhat is the best way to approach this?","AnswerCount":5,"Available Count":3,"Score":0.0399786803,"is_accepted":false,"ViewCount":891,"Q_Id":61930631,"Users Score":1,"Answer":"The best approach, the one that seems to have better results in research and industry is to use a Neural Network, a CNN (convolutional network to be more precise, although a linear forward layer would also work). \nNothing has changed from cats vs dogs to mouse vs not mouse. Still a classification problem.Since you are using an SVM I assume you don't have a lot of data, maybe try using transfer learning with resnet models ? It might yield good results. \nIf it's still not enough, you can still use SVM for classification 1-mouse 0- not a mouse.!\nHope it helped !\nBest!","Q_Score":0,"Tags":"python-3.x,machine-learning,computer-vision","A_Id":61932247,"CreationDate":"2020-05-21T08:46:00.000","Title":"How to determine if image is something or not?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to implement a stacked ensemble model for multiclass prediction. \nEach training example is a vector with 14 features.\nThere are a total of 12 possible classes.\nThe three base models (described below) each ingest a 14-dimensional feature vector training example and output a 12-dimensional vector of probabilities (1 probability \/ class).\nThe three base classification models were built from scratch (i.e. not built using sklearn so I can't simply use the sklearn ensemble methods) and are as follows:\n\nBayes Net: outputs a 12-dimensional vector of probabilities (1 probability \/ class) for each 14-dimensional training example\nOther graphical model: outputs a 12-dimensional vector of probabilities (1 probability \/ class) for each 14-dimensional training example\nMetric learning model: outputs a 12-dimensional vector of probabilities (1 probability \/ class) for each 14-dimensional training example\n\nI would like to stack the outputs from the base models for each training example (i.e. stack 3 x 12-d probability vectors) for each training example and feed this 3x12 array as an input to the multinomial logistic regression ensemble model to output a 12-dimensional vector of probabilities for the final multi-class predictions for each training example.\nI'm not sure, however, if this is possible using the sklearn multinomial regression model. From my understanding, the sklearn model can only ingest a 1-d array of features rather than a 2-d array of features.\nAny advice would be welcome. Thank you.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":180,"Q_Id":61947232,"Users Score":0,"Answer":"So the ultimate workaround ended up being very simple: flattening the 3x12 vector outputs for each base model into a 1x36 feature vector that was then fed into the ensemble model. \nThe other option was to build a tensor out of the base model predictions and then use a different type of ensemble classifier i.e. a CNN, but that approach was rejected.","Q_Score":0,"Tags":"python,scikit-learn,logistic-regression,ensemble-learning","A_Id":62142782,"CreationDate":"2020-05-22T03:11:00.000","Title":"Multinomial logistic regression for stacked ensemble learning with 2d input into regression","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have upgraded my spyder to 4.0.1 , but now i get this error with matplotlib. The error:\nAttributeError: module 'sip' has no attribute 'setapi'\ncomplete error:\nNOTE: The following error appeared when setting your Matplotlib backend!!\nTraceback (most recent call last):\n File \"C:\\Users\\premp\\anaconda3\\envs\\tfcuda\\lib\\site-packages\\spyder_kernels\\console\\kernel.py\", line 568, in _set_mpl_backend\n get_ipython().run_line_magic(magic, backend)\n File \"C:\\Users\\premp\\anaconda3\\envs\\tfcuda\\lib\\site-packages\\IPython\\core\\interactiveshell.py\", line 2317, in run_line_magic\n result = fn(*args, **kwargs)\n File \"\", line 2, in matplotlib\n File \"C:\\Users\\premp\\anaconda3\\envs\\tfcuda\\lib\\site-packages\\IPython\\core\\magic.py\", line 187, in \n call = lambda f, *a, **k: f(*a, **k)\n File \"C:\\Users\\premp\\anaconda3\\envs\\tfcuda\\lib\\site-packages\\IPython\\core\\magics\\pylab.py\", line 99, in matplotlib\n gui, backend = self.shell.enable_matplotlib(args.gui.lower() if isinstance(args.gui, str) else args.gui)\n File \"C:\\Users\\premp\\anaconda3\\envs\\tfcuda\\lib\\site-packages\\IPython\\core\\interactiveshell.py\", line 3419, in enable_matplotlib\n pt.activate_matplotlib(backend)\n File \"C:\\Users\\premp\\anaconda3\\envs\\tfcuda\\lib\\site-packages\\IPython\\core\\pylabtools.py\", line 320, in activate_matplotlib\n from matplotlib import pyplot as plt\n File \"C:\\Users\\premp\\anaconda3\\envs\\tfcuda\\lib\\site-packages\\matplotlib\\pyplot.py\", line 2282, in \n switch_backend(rcParams[\"backend\"])\n File \"C:\\Users\\premp\\anaconda3\\envs\\tfcuda\\lib\\site-packages\\matplotlib\\pyplot.py\", line 221, in switch_backend\n backend_mod = importlib.import_module(backend_name)\n File \"C:\\Users\\premp\\anaconda3\\envs\\tfcuda\\lib\\importlib__init__.py\", line 127, in import_module\n return _bootstrap._gcd_import(name[level:], package, level)\n File \"C:\\Users\\premp\\anaconda3\\envs\\tfcuda\\lib\\site-packages\\matplotlib\\backends\\backend_qt5agg.py\", line 11, in \n from .backend_qt5 import (\n File \"C:\\Users\\premp\\anaconda3\\envs\\tfcuda\\lib\\site-packages\\matplotlib\\backends\\backend_qt5.py\", line 15, in \n import matplotlib.backends.qt_editor.figureoptions as figureoptions\n File \"C:\\Users\\premp\\anaconda3\\envs\\tfcuda\\lib\\site-packages\\matplotlib\\backends\\qt_editor\\figureoptions.py\", line 12, in \n from matplotlib.backends.qt_compat import QtGui\n File \"C:\\Users\\premp\\anaconda3\\envs\\tfcuda\\lib\\site-packages\\matplotlib\\backends\\qt_compat.py\", line 163, in \n _setup()\n File \"C:\\Users\\premp\\anaconda3\\envs\\tfcuda\\lib\\site-packages\\matplotlib\\backends\\qt_compat.py\", line 124, in _setup_pyqt4\n _setup_pyqt4_internal(api=2)\n File \"C:\\Users\\premp\\anaconda3\\envs\\tfcuda\\lib\\site-packages\\matplotlib\\backends\\qt_compat.py\", line 107, in _setup_pyqt4_internal\n sip.setapi(_sip_api, api)\nAttributeError: module 'sip' has no attribute 'setapi'\nCurrently i have matplotlib 3.2.1 , i have tried downgrading and also tried changing the setting from automatic to inline. But not able to figure out the issue. Is this a bug?","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":681,"Q_Id":61948243,"Users Score":1,"Answer":"I had a similar problem and fixed it by adding the sip module to my anaconda environment.","Q_Score":0,"Tags":"python-3.x,anaconda,spyder","A_Id":63556541,"CreationDate":"2020-05-22T05:09:00.000","Title":"Mtaplotlib issue with spyder 4.0.1","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"TypeError: can\u2019t convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.\nlearned_pred = euclidean_distances(answer.cpu().data.numpy(), predicates_emb).argmin(axis=1)\nThe type error is raised in the above line of code I used .cpu() so I cannot understand why..\nHow can I solve this problem?","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":891,"Q_Id":61960705,"Users Score":0,"Answer":"The conversion from variable answer is true. Therefore, I think the problem may stay in the variable predicates_emb.\nCan you check if var predicates_emb is tensor or not. If it is, you should convert it to numpy array.","Q_Score":0,"Tags":"python","A_Id":63796282,"CreationDate":"2020-05-22T17:33:00.000","Title":"TypeError: can\u2019t convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"TypeError: can\u2019t convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.\nlearned_pred = euclidean_distances(answer.cpu().data.numpy(), predicates_emb).argmin(axis=1)\nThe type error is raised in the above line of code I used .cpu() so I cannot understand why..\nHow can I solve this problem?","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":891,"Q_Id":61960705,"Users Score":0,"Answer":"I had the same issue, a answer.cpu() did not work for me but answer.to('cpu')... did work for me.","Q_Score":0,"Tags":"python","A_Id":67373990,"CreationDate":"2020-05-22T17:33:00.000","Title":"TypeError: can\u2019t convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"MemoryError: Unable to allocate 1.68 TiB for an array with shape (120000, 20, 95932) and data type float64\nand this is the line that is causing the problem : \nouts = np.zeros((context_1.shape[0], maxLen, vocab_size))\nis there a workaround for this error?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":258,"Q_Id":61962199,"Users Score":1,"Answer":"You are trying to create very large array. That's way too much data to store in memory. You should redesign your algorithm, may be use generators to reduce memory requirements.","Q_Score":0,"Tags":"python,tensorflow,keras","A_Id":61963391,"CreationDate":"2020-05-22T19:07:00.000","Title":"Memory Error while trying to calculate np.zeros","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I was looking through the architecture of EfficientnetB0 and noticed DepthwiseConv2D operation. Did some digging and found that there's also a SeparableConv2D. What exactly are these operations?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":1644,"Q_Id":61967172,"Users Score":0,"Answer":"DepthwiseConv2d performs the first step in a depthwise spatial convolution, apply convolution operation on each input channel separately.","Q_Score":3,"Tags":"python,tensorflow,keras,conv-neural-network","A_Id":66944281,"CreationDate":"2020-05-23T03:46:00.000","Title":"What is DepthwiseConv2D and SeparableConv2D? How is it different from normal Conv2D layer in keras?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I work in Python. I have a problem with the categorical variable - \"city\". \nI'm building a predictive model on a large dataset-over 1 million rows. \nI have over 100 features. One of them is \"city\", consisting of 33 000 different cities.\nI use e.g. XGBoost where I need to convert categorical variables into numeric. Dummifying causes the number of features to increase strongly. XGBoost (and my 20 gb RAM) can't handle this.\nIs there any other way to deal with this variable than e.g. One Hot Encoding, dummies etc.?\n(When using One Hot Encoding e.g., I have performance problems, there are too many features in my model and I'm running out of memory.)\nIs there any way to deal with this?","AnswerCount":3,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":1451,"Q_Id":61975690,"Users Score":0,"Answer":"You could use some kind of embeddings that reflect better those cities (and compress the number of total features by direct OHE), maybe using some features to describe the continet where each city belongs, then some other features to describe the country\/region, etc.\nNote that since you didn't provide any specific detail about this task, I've used only geographical data on my example, but you could use some other variables related to each city, like the mean temprature, the population, the area, etc, depending on the task you are trying to address here.\nAnother approach could be replacing the city name with its coordinates (latitude and longitude). Again, this may be helpful depending on the task for your model.\nHope this helps","Q_Score":1,"Tags":"python,xgboost,forecasting","A_Id":61978233,"CreationDate":"2020-05-23T17:06:00.000","Title":"How to deal with the categorical variable of more than 33 000 cities?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I work in Python. I have a problem with the categorical variable - \"city\". \nI'm building a predictive model on a large dataset-over 1 million rows. \nI have over 100 features. One of them is \"city\", consisting of 33 000 different cities.\nI use e.g. XGBoost where I need to convert categorical variables into numeric. Dummifying causes the number of features to increase strongly. XGBoost (and my 20 gb RAM) can't handle this.\nIs there any other way to deal with this variable than e.g. One Hot Encoding, dummies etc.?\n(When using One Hot Encoding e.g., I have performance problems, there are too many features in my model and I'm running out of memory.)\nIs there any way to deal with this?","AnswerCount":3,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":1451,"Q_Id":61975690,"Users Score":0,"Answer":"Beside the models, you could also decrease the number of the features (cities) by grouping them in geographical regions. Another option is grouping them by population size.\nAnother option is grouping them by their frequency by using quantile bins. Target encoding might be another option for you.\nFeature engineering in many cases involves a lot of manual work, unfortunately you cannot always have everything sorted out automatically.","Q_Score":1,"Tags":"python,xgboost,forecasting","A_Id":69550804,"CreationDate":"2020-05-23T17:06:00.000","Title":"How to deal with the categorical variable of more than 33 000 cities?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"So, I'm building a model and trying to use | for a new column and I'm confused as to what I'm doing wrong. It's supposed to make a new column and type 1 when the value is true.\n\nFor example, this worked : \nfeature_matrix[\"After 2016\"] = (feature_matrix.index.year > 2016).astype(int)\nHowever this does nothing :\nfeature_matrix[\"Summer\"] = (feature_matrix.index.month == 6|7|8|9).astype(int)\nSame thing goes for this when I try to do the weekend using the same method.\n\nI tried solving it using : \nfeature_matrix[\"Summer\"] = (feature_matrix.index.month == 6| feature_matrix.index.month == 7).astype(int)\nBut that gives me : unsupported operand type(s) for |: 'int' and 'Int64Index'","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":42,"Q_Id":61980838,"Users Score":0,"Answer":"Yoben's answer is correct and complete, but a note: 6|7|8\\9 is always true, and unless you have True in your column, this will do nothing.","Q_Score":0,"Tags":"python,pandas,dataframe,datetime","A_Id":61980866,"CreationDate":"2020-05-24T02:15:00.000","Title":"How to use or in pandas and datetime","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"Hey I am training a CNN model , and was wondering what will happen if I use the same data for validation and test?\nDoes the model train on validation data as well? (Does my model see the validation data?) Or just the error and accuracy are calculatd and taken into account for training?","AnswerCount":3,"Available Count":2,"Score":1.2,"is_accepted":true,"ViewCount":772,"Q_Id":61985581,"Users Score":1,"Answer":"You use your validation_set to tune your model. It means that you don`t train on this data but the model takes it into account. For example, you use it to tune the model's hyperparameters. \nIn order to have a good evaluation - as test set you should use a data which is totally unknown to this model.","Q_Score":0,"Tags":"python,tensorflow,deep-learning,conv-neural-network","A_Id":61985649,"CreationDate":"2020-05-24T11:55:00.000","Title":"Use same data for test and validation","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Hey I am training a CNN model , and was wondering what will happen if I use the same data for validation and test?\nDoes the model train on validation data as well? (Does my model see the validation data?) Or just the error and accuracy are calculatd and taken into account for training?","AnswerCount":3,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":772,"Q_Id":61985581,"Users Score":0,"Answer":"If you use the same set for validation and test, your model may overfit (since it has seen the test data before the final test stage).","Q_Score":0,"Tags":"python,tensorflow,deep-learning,conv-neural-network","A_Id":61985665,"CreationDate":"2020-05-24T11:55:00.000","Title":"Use same data for test and validation","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm pretty new to pandas and got an assignment asking me to compare & match two columns of 2 different .csv files. \ndtypes are strings\n1st df\nName | Subjects \nStudent1 | Biology, Math, German\nStudent2 | Sport, Biology, English\nStudent3 | Chemistry, Math, Biology\n2nd df\nName | Subjects\nTeacher1 | Biology, Sport, English\nTeacher2 | Chemistry, Math, Physics\nTeacher3 | Biology, Physics, Chemistry, English\n...\nNow, I should compare and find the best match between a Student & Teacher. \nMeaning, they should match at least 1 subject, but for a \"perfect match\" all of them.\nI tried different things already - pd.merge, iterrows, isin, etc. - but can't find a great performant solution.\nI'm not asking for a solution for my assignment, but for a small push in the right direction.\nThank you!","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":203,"Q_Id":61988485,"Users Score":0,"Answer":"You can first pivot on subject column using pd.pivot_table and then do a ofpd.merge on subject columns of student and teacher tables to relate teachers and students based on subjects.","Q_Score":1,"Tags":"python,pandas,dataframe","A_Id":61988603,"CreationDate":"2020-05-24T15:53:00.000","Title":"pandas - comparing two columns of different dataframes with multiple strings","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I extracted some data from investing but columns values are all dtype = object, so i cant work with them...\nhow should i convert object to float?\n(2558 6.678,08 2557 6.897,23 2556 7.095,95 2555 7.151,21 2554 7.093,34 ... 4 4.050,38 3 4.042,63 2 4.181,13 1 4.219,56 0 4.223,33 Name: Alta, Length: 2559, dtype: object)\nWhat i want is :\n2558 6678.08 2557 6897.23 2556 7095.95 2555 7151.21 2554 7093.34 ... 4 4050.38 3 4042.63 2 4181.13 1 4219.56 0 4223.33 Name: Alta, Length: 2559, dtype: float\nTried to use the a function which would replace , for .\ndef clean(x): x = x.replace(\".\", \"\").replace(\",\",\".\")\nbut it doesnt work cause dtype is object\nThanks!","AnswerCount":4,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":2019,"Q_Id":61991204,"Users Score":0,"Answer":"That is because there is a comma between the value\nBecause a float cannot have a comma, you need to first replace the comma and then convert it into float\nresult[col] = result[col].str.replace(\",\",\"\").astype(float)","Q_Score":0,"Tags":"python,pandas,dataframe","A_Id":71562110,"CreationDate":"2020-05-24T19:16:00.000","Title":"How can i change dtype from object to float64 in a column, using python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Recently I have started to model pandemics as a part of personal project work. I am trying to do this in Python\nOne of the requirements that I have come across is how to perform curve fitting in Python. I have come across some articles which explain how to perform curve fitting for exponential or linear functions using scipy library. But in pandemic the growth curve could be either exponential, or linear\nHow do I perform a curve fit for any random data in Python without knowing if it will be linear or exponential ?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":216,"Q_Id":61992008,"Users Score":0,"Answer":"Basically any model used for prediction\/extrapolate needs certain assumption(s).\nFor real world data as pandemic curve, I suggest you resort to more sophisticated methods such as LSTM, 1-D CNN, or Gaussian process with different combinations of kernels.","Q_Score":0,"Tags":"python,scipy","A_Id":61992498,"CreationDate":"2020-05-24T20:23:00.000","Title":"Fitting a random curve in Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I had old version catboost 0.23 or probably 0.22 don't remember , but sure one of these was on my machine. Somehow catboost new version 0.23.1 has been released and get installed in my machine. I noticed my model which was trained on old version had good performance , same old model with same old features\/data and data processing, everything same is giving a little bit off performance on catboost 0.23.1. Previously recall was 0.77 now it has been 0.74 , data is also same ,preprocessing is also same.\nI doubt there is some issue with new version want to double check ,for that what i want to uninstall catboost which i did but getting nowhere old version of catboost 0.22 , any body has any clue please?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":465,"Q_Id":61996230,"Users Score":1,"Answer":"You can explicitly specify package version using pip like this:\npip install catboost==0.23","Q_Score":0,"Tags":"python,catboost","A_Id":61996409,"CreationDate":"2020-05-25T05:17:00.000","Title":"Re installing Catboost 0.22 or 0.23","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I need to find argmax index in pd.DataFrame. I want exacly the same result, as pandas.DataFrame.idxmax does, but this function returns index of first occurrence of maximum over requested axis. I want find index of last occurrence of maximum. Thank you in advance.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":887,"Q_Id":62001463,"Users Score":1,"Answer":"Run df[::-1].idxmax()\nThe trick is to process rows in reversed order.","Q_Score":0,"Tags":"python,pandas,pandas-groupby","A_Id":62001586,"CreationDate":"2020-05-25T11:26:00.000","Title":"Find index of the last occurence for maximal value in pd.DataFrame","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a dataset which includes socioeconomic indicators for students nationwide as well as their grades. More specifically, this dataset has 36 variables with about 30 million students as predictors and then the students grades as the responses.\nMy goal is to be able to predict whether a student will fail out (ie. be in the bottom 2%ile of the nation in terms of grades). I understand that classification with an imbalanced dataset (98% : 2%) will introduce a bias. Based on some research I planned to account for this by increasing the cost of an incorrect classification in the minority class.\nCan someone please confirm that this is the correct approach (and that there isn't a better one, I'm assuming there is)? And also, given the nature of this dataset, could someone please help me choose a machine learning algorithm to accomplish this? \nI am working with TensorFlow 2.0 in a Google Colab. I've compiled all the data together into a .feather file using pandas.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":126,"Q_Id":62007061,"Users Score":1,"Answer":"In case of having imbalanced dataset, using weighted class is the most common approach to do so, but having such large dataset (30M training example) for binary classification problem representing 2% for the first class and 98% for the second one, I can say it's too hard to prevent model to be unbiased against first class using weighted class as it's not too much differ from reducing the training set size to be balanced.\nHere some steps for the model accuracy evaluation.\n\n\nsplit your dataset set to train, evalution and test sets.\nFor evaluation metric I suggest these alternatives.\na. Make sure to have at least +20%, representing the first class for both \n evaluation and test sets.\nb. Set evalution metric to be precision and recall for your model accuracy \n (rather than using f1 score).\nc. Set evalution metric to be Cohen's kapp score (coefficient).\nFrom my own perspective, I prefer using b.\n\n\nSince you are using tensorflow, I assume that you are familiar with deep learning. so use deep learning instead of machine learning, that's gives you the ability to have many additional alternatives, anyway, here some steps for both machine learning and deep learning approach.\nFor Machine Leaning Algorithms\n\n\nDecision Trees Algorithms (especially Random Forest).\nIf my features has no correlation, correlation approach to zero (i.e. 0.01),\nI am going to try Complement Naive Bayes classifiers for multinomial features \nor Gaussian Naive Bayes using weighted class for continuous features. \nTry some nonparametric learning algorithms. You may not able to fit this \ntraining set using Support Vector Machines (SVM) easily because of you \nhave somehow large data set but you could try.\nTry unsupervised learning algorithms \n(this sometimes gives you more generic model)\n\n\nFor Deep Leaning Algorithms\n\n\nEncoder and decoder architectures or simply generative adversarial \nnetworks (GANs).\nSiamese network.\nTrain model using 1D convolution Layers.\nUse weighted class.\nBalanced batches of the training set, randomly chosen.\n\nYou have many other alternatives, From my own perspective, I may try hard to get it with 1, 3 or 5.\nFor Deep learning 5th approach sometimes works very well and I recommend to try it with 1, 3.","Q_Score":2,"Tags":"python,tensorflow,machine-learning,classification,large-data","A_Id":62008911,"CreationDate":"2020-05-25T16:52:00.000","Title":"Advice for my plan - large dataset of students and grades, looking to classify bottom 2%","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am doing image classification based on a CNN in tensorflow and Keras. I am classifying images of faces, into which emotion is being expressed (happy, sad, etc). This actually works pretty well, but there is something I don't really understand. \nFor each image, I also have the age of the person that is on the image. I want to add this information (age) to the CNN. So right now the CNN only uses the pixels of the image, but i want to make the CNN to take the age into account. Is this possible \/ what is the method for this? \nMy first thought was to add an extra dimension to the image, with the age, but then I'm kind of stuck... Because age is just 1 number, and of course each layer in the image is width x height. Can I just ad a layer that consists of a whole matrix with just the age as value of each pixel? \nAnyone who knows how such a thing usually is done...?\nThanks in advance","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":55,"Q_Id":62019558,"Users Score":0,"Answer":"I would add it to the CNN output, i.e. the last tensor before the dense layer.\nIn classification, a CNN is used as a feature extractor. The goal is, given an image, to find the best feature vector that should be passed to the dense layer. So each element represents something for your neural network, a feature.\nIf you have any other feature you want to add, put it there and let the dense layers do the work.","Q_Score":0,"Tags":"python,image,tensorflow,classification,conv-neural-network","A_Id":62022506,"CreationDate":"2020-05-26T10:03:00.000","Title":"Image classification with extra 'dimension'","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've set up a neural network regression model using Keras with one target. This works fine,\nnow I'd like to include multiple targets. The dataset includes a total of 30 targets, and I'd rather train one neural network instead of 30 different ones.\nMy problem is that in the preprocessing of the data I have to remove some target values, for a given example, as they represent unphysical values that are not to be predicted.\nThis creates the issues that I have a varying number of targets\/output.\nFor example:\nTargets =\n\nNone, 0.007798, 0.012522\n0.261140, 2110.000000, 2440.000000\n0.048799, None, None\n\nHow would I go about creating a keras.Sequential model(or functional) with a varying number of outputs for a given input?\nedit: Could I perhaps first train a classification model that predicts the number of outputs given some test inputs, and then vary the number of outputs in the output layer according to this prediction? I guess I would have to use the functional API for something like that.\n\nThe \"classification\" edit here is unnecessary, i.e. ignore it. The number of outputs of the test targets is a known quantity.","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":165,"Q_Id":62019570,"Users Score":1,"Answer":"(Sorry, I don't have enough reputation to comment)\nFirst, do you know up front whether some of the output values will be invalid or is part of the problem predicting which outputs will actually be valid?\nIf you don't know up front which outputs to disregard, you could go with something like the 2-step approach you described in your comment. \nIf it is deterministic (and you know how so) which outputs will be valid for any given input and your problem is just how to set up a proper model, here's how I would do that in keras:\n\nUse the functional API\nCreate 30 named output layers (e.g. out_0, out_1, ... out_29)\n\n\nWhen creating the model, just use the outputs argument to list all 30 outputs\n\nWhen compiling the model, specify a loss for each separate output, you can do this by passing a dictionary to the loss argument where the keys are the names of your output layers and the values are the respective losses\n\n\nAssuming you'll use mean-squared error for all outputs, the dictionary will look something like {'out_0': 'mse', 'out_1': 'mse', ..., 'out_29': 'mse'}\n\nWhen passing inputs to the models, pass three things per input: x, y, loss-weights\n\n\ny has to be a dictionary where the key is the output layer name and the value is the target output value\nThe loss-weights are also a dictionary in the same format as y. The weights in your case can just be binary, 1 for each output that corresponds to a real value, 0 for each output that corresponds to unphysical values (so they are disregarded during training) for any given sample\nDon't pass None's for the unphysical value targets, use some kind of numeric filler, otherwise you'll get issues. It is completely irrelevant what you use for your filler as it will not affect gradients during training\n\n\nThis will give you a trainable model. BUT once you move on from training and try to predict on new data, YOU will have to decide which outputs to disregard for each sample, the network will likely still give you \"valid\"-looking outputs for those inputs.","Q_Score":1,"Tags":"python,tensorflow,keras,neural-network","A_Id":62020648,"CreationDate":"2020-05-26T10:03:00.000","Title":"How would I go about creating a keras model with a varying number of targets\/outputs?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Residual networks are always built with convolutional layers. I have never seen residual networks with only fully connected layers. Does it work to build a residual network with only fully connected layers?","AnswerCount":3,"Available Count":1,"Score":0.0665680765,"is_accepted":false,"ViewCount":1607,"Q_Id":62023882,"Users Score":1,"Answer":"As Tapio, I also disagree with Giuseppe's conclusion. Residual layers are said to help improving performance in multiple ways: They let the gradient flow better, they might help in localization etc. My guess is that some of these advantages like gradient flow, hold also for networks consisting of fully connected layers.\nOther ideas like saying we learn residuals F(X)-X, where F is a residual block are more questionable due to absence of spatial correlation. That is, for CNNs, where residual connections are mostly used, we have some form of locality, that is if you have the feature map X of some layer (you can also think of X as the input) and the output of a residual block F(X) then both X and F(X) correlate. That is, oftentimes the map at location X[i,j] is similar to that of F(X)[i,j]. This does not hold for fully connected networks, since neurons do not contain spatial information. However, to what extent this matters is probably an open problem :-) .","Q_Score":6,"Tags":"python,machine-learning,neural-network,conv-neural-network,deep-residual-networks","A_Id":66249604,"CreationDate":"2020-05-26T14:00:00.000","Title":"Does it make sense to build a residual network with only fully connected layers (instedad of convolutional layers)?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Why does this\n'''tensor_ques[1:3,1]=0'''\nwork \nand this\n'''tensor_ques[1:3,1] =[0,0]'''\ndoes not work\ntensor_ques is a torch.tensor()\nI know [0,0] is not a tensor then why does =0 work fine","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":60,"Q_Id":62029416,"Users Score":0,"Answer":"It doesn't work because [0,0] is a list, and torch does not allow you to assign a list to a tensor. It'll only work if the item being assigned is also a tensor, i.e. tensor_ques[1:3,1] = torch.tensor([0,0]).","Q_Score":0,"Tags":"python,tensorflow,deep-learning,pytorch,tensor","A_Id":62030908,"CreationDate":"2020-05-26T18:59:00.000","Title":"Tensor slicing conditions for assignement","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to train a model for autonomous driving that converts input from the front camera, to a bird's eye view image.\nThe input and output, both are segmentation masks with shape (96, 144) where each pixel has a range from 0 to 12 (each number represents a different class).\nNow my question is how should i preprocess my data and which loss function should i use for the model (I am trying to use a Fully convolutional Network).\nI tried to convert input and outputs to shape (96, 144, 13) using keras' to_categorical utility so each channel has 0s and 1s of representing a specific mask of a category. I used binary_crossentropy ad sigmoid activation for last layer with this and the model seemed to learn and loss started reducing. \nBut i am still unsure if this is the correct way or if there are any better ways.\nwhat should be the:\n\ninput and ouptput data format\nactivation of last layer\nloss function","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":35,"Q_Id":62038389,"Users Score":1,"Answer":"I found the solution, use categorical crossentropy with softmax activation at last layer. Use the same data format as specified in the question.","Q_Score":0,"Tags":"python,tensorflow,machine-learning,keras,loss-function","A_Id":62104557,"CreationDate":"2020-05-27T08:12:00.000","Title":"Loss function and data format for training a ''categorical input' to 'categorical output' model?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"i was trying to use average ensembling on a group of models i trained earlier (i'm creating a new model in the ensemble for each pre-trained model i'm using and then loading the trained weights onto it, it's inefficient this way i know but i'm just learning about it so it doesn't really matter). and I mistakenly changed some of the network's parameters when loading the models in the ensemble code like using Relu instead of leakyRelu which i used in training the models and a different value for an l2 regularizer in the dense layer in one of the models. this however gave me a better testing accuracy for the ensemble. can you please explain to me if\/how this is incorrect, and if it's normal can i use this method to further enhance the accuracy of the ensemble.","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":252,"Q_Id":62039819,"Users Score":0,"Answer":"Though you changed the network's parameters when loading the models. It is not incorrect to alter the hyper-parameters of your ensemble's underlying models. In some cases, the models that are used in an ensemble method require unique tunings which can, as you mentioned, give \"you a better testing accuracy for the ensemble model.\"\nTo answer your second question, you can use this method to further enhance the accuracy of the ensemble, you can also use Bayesian optimization, GridSearch, and RandomSearch if you prefer more automated means of tuning your hyperparameters.","Q_Score":0,"Tags":"python,tensorflow,keras,deep-learning,ensemble-learning","A_Id":62052799,"CreationDate":"2020-05-27T09:29:00.000","Title":"is it incorrect to change a model's parameters after training it?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"i was trying to use average ensembling on a group of models i trained earlier (i'm creating a new model in the ensemble for each pre-trained model i'm using and then loading the trained weights onto it, it's inefficient this way i know but i'm just learning about it so it doesn't really matter). and I mistakenly changed some of the network's parameters when loading the models in the ensemble code like using Relu instead of leakyRelu which i used in training the models and a different value for an l2 regularizer in the dense layer in one of the models. this however gave me a better testing accuracy for the ensemble. can you please explain to me if\/how this is incorrect, and if it's normal can i use this method to further enhance the accuracy of the ensemble.","AnswerCount":2,"Available Count":2,"Score":1.2,"is_accepted":true,"ViewCount":252,"Q_Id":62039819,"Users Score":0,"Answer":"I believe it is NOT correct to chnage model's parameters after training it. parameters here I mean the trainable-parameters like the weights in Dense node but not hyper-parameters like learning rate.\nWhat is training?\nTraining essentially is a loop that keeps changing, or update, the parameters. It updates the parameter in such a way that it believes it can reduce the loss. It is also like moving your point in a hyper-spaces that the loss function gives a small loss on that point. \nSmaller loss means higher accruacy in general.\nChanging Weights\nSo now, changing your parameters values, by mistake or by purpose, is like moving that point to somewhere BUT you have no logical reason behind that such move will give you a smaller loss. You are just randomly wandering around that hyper-space and in your case you are just lucky that you land to some point that so happened give you a smaller loss or a better testing accuracy. It is just purely luck.\nChanging activation function\nAlso, altering the activation function from leakyRelu to relu is similar you randomly alter the shape of your hype-space. Even though you are at the some point the landscape changes, you are still have no logical reason to believe by such change of landscape you can have a smaller loss staying at the same point\nWhen you change the model manually, you need to retrain.","Q_Score":0,"Tags":"python,tensorflow,keras,deep-learning,ensemble-learning","A_Id":62058898,"CreationDate":"2020-05-27T09:29:00.000","Title":"is it incorrect to change a model's parameters after training it?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"It says: Stable-Baselines supports Tensorflow versions from 1.8.0 to 1.15.0, and does not work on Tensorflow versions 2.0.0 and above.\nSo I tried to install \"sudo pip3 install tensorflow==1.15.0\"\nBut I get the message:\nERROR: Could not find a version that satisfies the requirement tensorflow==1.15.0 (from versions: 2.2.0rc1, 2.2.0rc2, 2.2.0rc3, 2.2.0rc4, 2.2.0)\nERROR: No matching distribution found for tensorflow==1.15.0\nI'm using:\nUbuntu 20.04 LTS\nPython 3.8.2\npip 20.1.1 from ...\/python3.8\/site-packages\/pip (python 3.8)\nHow can I install a tensorflow version that works with stable-baselines?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":868,"Q_Id":62042491,"Users Score":0,"Answer":"I solved the problem by using anaconda instead.\nThanks for the help!","Q_Score":2,"Tags":"python-3.x,tensorflow,ubuntu,pip,stable-baselines","A_Id":62470111,"CreationDate":"2020-05-27T11:53:00.000","Title":"stable-baseline with tensorflow issue","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am currently learning nltk in Python where I am writing a program for sentiment analysis. While working on it, I found out that \"not, nor, never\" are considered stopping words. So my question is why that is because these kinds of words can change the entire meaning of sentences and could lead to failure in sentiment analysis.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":278,"Q_Id":62051187,"Users Score":0,"Answer":"Stop words are usually created based on analysis of the most common words in the language (that is the main reason \"not\" is in there). The idea behind them is to allow analysis (normally a bag of words approach) to focus on the more interesting words of the document.\nThey are used for multiple purposes: they were not designed specifically for sentiment analysis. That is another reason \"not\" is in there.\nA bag-of-words approach to sentiment analysis is always going to end up a bit crude, with or without stop words. E.g. It is not hard to create realistic-sounding positive movie reviews using negative words:\n\"This movie was not at all what I expected: I usually hate Tom Cruise but he made this movie work.\"\n\"I never watch chick-flicks, but as they say, never say never.\"\nAnyway try customizing your stopword list, removing \"not\" and \"never\" to see if it improves results. Then try again using no stopwords at all.","Q_Score":1,"Tags":"python,nltk,sentiment-analysis,stop-words","A_Id":62081378,"CreationDate":"2020-05-27T19:19:00.000","Title":"Why in NLTK \"not\" is considered as stopping word in English?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to apply spelling correction to some tweets. \nI have tried the following code: \ntrain.text.apply(lambda x: \" \".join([TextBlob(i).correct() for i in x.split()]))\nHowever, I get an error. Could you please advise? Thanks in advance!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":445,"Q_Id":62051560,"Users Score":0,"Answer":"Could you try to update this code with \ntrain.apply(lambda x: \" \".join([TextBlob(i).correct() for i in x['text'].split()]))\nHope this helps!!","Q_Score":0,"Tags":"python,nlp,textblob,spelling","A_Id":62070191,"CreationDate":"2020-05-27T19:42:00.000","Title":"How to use TextBlob.correct() for a column in a dataframe","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a dataframe with 3,000,000 IDs. Each ID has the month range from 2015-01-01 \nt0 2018-12-01. Each ID has column \"A\" and \"B\" with numeric values. I need to create a new column \"C:. \nFor each ID, when Date == '2015-01-01' which is the first month for that ID, column C value equal to exp(column_A value).\n For the next month (Date == '2015-02-01'), column C value equal to exp(log(column_C_value in previous month) + column_B_value at this month), so here is exp(log(column C @ 2015-01-01) + column_B @ 2015-02-01). Each of the following months has the same pattern until it reaches 2018-12-01.\nIn Python, I can setup the loop for each ID and for each row\/month, such as:\nfor ID in range(xxx):\n for month in range(xxxx):\nHowever, such calculation takes long time. Can anyone tell me a faster way to do this calculation? Very appreciated for your help!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":38,"Q_Id":62052129,"Users Score":0,"Answer":"Consider that\n(1) exp(x+y) == exp(x)*exp(y).\nAnd\n(2) exp(log(x)) == x.\nSo exp(log(c1) + b2) == c1 * exp(b2).\nThe next value simplifies to c1 * exp(b2) * exp(b3), and so on.\nThat means, you have to multiply all exp(b) values, which can be turned\ninto adding all(b)-s and then applying exp() to the result.\nAnd don't forget to multiply it with a1, the initial value.\na1 * exp(b2 * b3 * ...)","Q_Score":0,"Tags":"python-2.7,dataframe","A_Id":62088543,"CreationDate":"2020-05-27T20:16:00.000","Title":"How to forecast the column value based on its previous value in Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"In python when using plotly and sklearn I installed both packages and checked that their locations were added to my system environment variables but I still get the error \"No module named 'plotly'\" and same for sklearn and I don't know what else to do. I would really appreciate any help.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":173,"Q_Id":62052780,"Users Score":0,"Answer":"Are you sure you are operating within the virtual environment?\nTry pip list to show what is installed in this environment. If plotly and sklearn are not listed, you are either not operating within the virtual environment when executing the script or you haven't installed the modules within the virtualenv","Q_Score":0,"Tags":"python,scikit-learn,plotly","A_Id":62052876,"CreationDate":"2020-05-27T21:00:00.000","Title":"How do I fix Module not found error in Python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to calculate the ridge regression B coefficients through this formula in Python:\n(X^T * X + \u03bb*I)^(\u22121) + X^T * y\nwhere:\nX^T = X transposed\nX^(-1) = inverse matrix of X\nQuestion: What shape should the identity matrix (I) take? X.shape or y.shape?\nThank you for your help!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":37,"Q_Id":62053996,"Users Score":0,"Answer":"I should be the shape of X'X, only then will matrix addition be permitted. X is generally of shape [n,m], where n is the number of instances (rows) and m is the number of features (columns). Therefore, X'X is of shape [m,m], which should be the shape of I. \nAlso note that often when we formulate X, we have a column for the bias terms. Meaning, you might have m features, but X will have m+1 columns, including the bias. \nHope this helps.","Q_Score":0,"Tags":"python,statistics,regression","A_Id":62054145,"CreationDate":"2020-05-27T22:36:00.000","Title":"Ridge Regression B Coefficients Calculation","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm new to Python and I want to create an array which has 0.00 has first element, and then adds 0.01 for its next elements until the last one is less than or equal to a given number (in my case 0.55).\nIn Matlab the code for it would be (0: 0.01: 0.55)\nAnd the result would be: [0.00, 0.01, 0.02, ... , 0.55]\nNow of course I think it can be done really easily in Python with a loop, but I'm wondering if there is a direct way to achieve this with a NumPy function\nI tried arange but failed, maybe it's not the right one.\nThanks","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":73,"Q_Id":62063085,"Users Score":1,"Answer":"Like Milan mentioned, my first thought was to use np.arange(0, 0.55, 0.01) but I just ran it, and it only goes from 0 to 0.54, which made me think it was treating the ending point as exclusive. To that end, i bumped it up to np.arange(0, 0.56, 0.01), but then that returned everything up to 0.56. \nFrankly, i'm not sure why that's happening (maybe a bug?), so here's an alternative that achieves the same result using np.linspace()\nnp.linspace(0, 0.55, 56)","Q_Score":2,"Tags":"python,numpy","A_Id":62063720,"CreationDate":"2020-05-28T11:00:00.000","Title":"How to build this simple vector in NumPy","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've just built a function that is working fine on my laptop (Mac, but I'm working on a Windows virtual machine of the office laptop), but when I pass it to a colleague o'mine, it raises a ValueError:\n\"You are trying to merge on object and int64 columns. If you wish to proceed you should use pd.concat\"\nThe line of the code that raises the error is a simple merge that on my laptop works perfectly:\ndf = pd.merge(df1, df2, on = \"x\", how = \"outer)\nThe input files are exactly the same (taken directly from the same remote folder).\nI totally don't know how to fix the problem, and I don't understand why on my laptop it works (even if I open a new script or I restart the kernel, so no stored variables around) and in the one of my colleague it doesn't.\nThanks for your help!","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":78,"Q_Id":62063460,"Users Score":0,"Answer":"my guess (a wild guess) is that the data from the 2 tab-separated CSV files (i.e., TSV files) is somehow converted using different locales on your computer and your colleague's computer.\nCheck if you have locale-dependent operations that could cause a number with the \"wrong\" decimal separator not to be recognized as a number.\nThis should not happen in pd.read_csv() because the decimal parameter has a well-defined default value of \".\".\nBut from an experience I had with timestamps in another context, one timestamp with a \"bad\" format can cause the whole column to be of the wrong type. So if just one number of just one of the two files, in the column you are merging on, has a decimal separator, and this decimal separator is only recognized as such on your machine, only on your machine the join will succeed (I'm supposing that pandas can join numeric columns even if they are of different type).","Q_Score":1,"Tags":"python,pandas,merge,valueerror","A_Id":62064583,"CreationDate":"2020-05-28T11:22:00.000","Title":"Python ValueError if running on different laptop","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have large CSV files that represent weather data for the US at hourly resolution for a 5-km grid. The data was saved for each day, so I concatenated them together for a yearly file. The ultimate goal is to compute daily, weekly and monthly averages of the variables (wind speed, temperature, precipitation, pressure, etc) by latitude and longitude. There are no column headers so I add column names to the file when I read it in. \nWhen I tried reading in with Pandas in Python, it failed because it did not fit into memory. I can read in with Dask, but then I can't find a way to add the dimensions to the Dask dataframe or convert to xarray and do the same. Is there a way to read in these too-large for memory files, add the lat, lon, datetime dimensions, compute daily, weekly and monthly averages for each lat\/lon and output the file? Or, do I need to convert the csv to netCDF or similar before reading in?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":81,"Q_Id":62063819,"Users Score":0,"Answer":"As far as I know, you cannot load a CSV into xarray without going through pandas. So, yes, you will need to change the file format in order to use xarray. You might also consider breaking your data up into smaller files.","Q_Score":0,"Tags":"python,csv,multidimensional-array,dask,dask-dataframe","A_Id":62132433,"CreationDate":"2020-05-28T11:42:00.000","Title":"How to read in large CSV files, add multidimensions, and convert hourly to daily?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I know this question was already asked, but this is special:\nI am using Windows and I am trying to allocate a 250000*200 Array (via numpy.random.normal) out of float64 variables. Those add up to 50000000 float64 variables, which (when they each take 4 Byte) need 200.000.000 Bytes, which are approx. 190 MB. \nI have 8GB RAM and always AT LEAST 2 GB RAM free and I still get the same error. AND I actually allocated 10GB RAM from my SSD, that means that I should have at least 12GB RAM free.\nUsing Windows 10 64bit","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":1332,"Q_Id":62066438,"Users Score":0,"Answer":"I got it working! I had the 32 Bit Version of Python (I should be ashamed of me :D) and now I installed the 64 bit version and it works fine.\nTHANKS for everyone who had liked to help me though!","Q_Score":1,"Tags":"python,numpy,ram","A_Id":62066916,"CreationDate":"2020-05-28T13:53:00.000","Title":"Python\/Windows doesn't let numpy allocate RAM \"numpy.core._exceptions.MemoryError\"","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"How is this range function working here? It is generating an answer but I can't understand it it has created the resulted ndarray. \nnp.array([range(i, i + 3) for i in [2, 4, 6]])","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":29,"Q_Id":62066606,"Users Score":1,"Answer":"A range is a sequence of numbers. The function range normally accepts 1-3 params range(start, stop[, step]). In your case the step is ommited, thus the default 1 is applied. So it is creating ranges from a given number i to that number +3 \u2192 range(i, i + 3)\nThe list comprehension, makes that the given number i will iterate over the list [2,4,6], so you will create a list with 3 sublists: [range(2,2+3), range(4,4+3), range(6,6+3)] wich equals to [[2,3,4], [4,5,6], [6,7,8]].\nFinally, all is wrapped as a numpy array and the output is \u2192 array([[2, 3, 4],[4, 5, 6],[6, 7, 8]])","Q_Score":1,"Tags":"python,numpy","A_Id":62066833,"CreationDate":"2020-05-28T14:01:00.000","Title":"how range functions works in creating ndarray?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to use additional data to 'update' an already trained Light Gradient Boosting Model (LGBM). Is there a way to do that?\nI am looking for an approach that uses the Skealrn API and thus can be used in a pipeline.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":747,"Q_Id":62069508,"Users Score":2,"Answer":"An LGBM model in python can be fitted both with the original model API and with the Sklearn API.\nI couldn't find any examples of using the Sklearn API for continuous learning.\nRegardless of that, you can fit a model either way and it is compatible with the .train() function from the original API.\nIt can be saved with save_model() or with joblib.dump().\nThis does not affect its compatibility with Python Pileline() - it is perfectly compatible.","Q_Score":0,"Tags":"python,machine-learning,scikit-learn,lightgbm","A_Id":62082407,"CreationDate":"2020-05-28T16:16:00.000","Title":"Updating an LGBM model with new data","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am training a CNN model that has to classify 4 objects. 3 mugs (white, black, blue) and 1 glass. When I train my model for only 10 epochs, I get a validation accuracy of 25%, where everything is being labeled as the white mug. However when I would train the same model for longer, it eventually diverts from this 25% accuracy and climbs up to 80%, the only problem it has, is classifying the white mug.\nIn other words, if I am able to find why my classifier classifies the white mug wrongly, then I could potentially reach validation_accuracy of 90%. My question thus is, what are some things I could try to find out why it mispredicts, or things to improve. I have already used LIME to check why my model classifies something, but I could not get any wiser from it.\nSome specs of the model:\n\nNo data augmentation\n5 convolutional layers (32, 64, 128, 256, 512) -> into GlobalMaxPooling, Flatten, and 2 dense layers (128, 4)\nActivation layers (relu)\n2000 training images, 1000 validation images (classes are balanced)\n\nExtra: The model gets 100% accuracy on the training data after 2 epochs, and slowly climbs up to 80% on the validation data (after about 40-50 epochs).\nExtra 2: Sometimes the model gets 80%, sometimes only 74%","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":43,"Q_Id":62073259,"Users Score":0,"Answer":"There could be multiple issues here. It looks like your network is overfitting, so first off you may want to add regularization or dropout to your training process. Secondly, you'll also want to make sure your images come from the same source, i.e. if your training\/test examples all come from Google images or have vastly different qualities, angles, colors, etc, this might harm the network's ability to classify the mug correctly.\nFinally, you might want to add a softmax layer at the end of your network since you're doing a multiclass classification. By doing this, you'll be able to see what the probability is for the white mug compared to the other objects, which can help you with debugging.","Q_Score":1,"Tags":"python,tensorflow,machine-learning,keras","A_Id":62074878,"CreationDate":"2020-05-28T19:44:00.000","Title":"How should I interpret or intuitively explain the following results for my CNN model?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am training a CNN model that has to classify 4 objects. 3 mugs (white, black, blue) and 1 glass. When I train my model for only 10 epochs, I get a validation accuracy of 25%, where everything is being labeled as the white mug. However when I would train the same model for longer, it eventually diverts from this 25% accuracy and climbs up to 80%, the only problem it has, is classifying the white mug.\nIn other words, if I am able to find why my classifier classifies the white mug wrongly, then I could potentially reach validation_accuracy of 90%. My question thus is, what are some things I could try to find out why it mispredicts, or things to improve. I have already used LIME to check why my model classifies something, but I could not get any wiser from it.\nSome specs of the model:\n\nNo data augmentation\n5 convolutional layers (32, 64, 128, 256, 512) -> into GlobalMaxPooling, Flatten, and 2 dense layers (128, 4)\nActivation layers (relu)\n2000 training images, 1000 validation images (classes are balanced)\n\nExtra: The model gets 100% accuracy on the training data after 2 epochs, and slowly climbs up to 80% on the validation data (after about 40-50 epochs).\nExtra 2: Sometimes the model gets 80%, sometimes only 74%","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":43,"Q_Id":62073259,"Users Score":0,"Answer":"The model is reaching 100% training accuracy when validation accuracy is still only 25%. A 75% gap between training and validation accuracy is enormous and indicates the model is overfitting to the training data, likely due to the small size of the training data set (2000). Data augmentation would likely significantly reduce overfitting and improve validation accuracy - I would start with random cropping, brightness, and saturation. Collecting more training data with varied backgrounds, orientations, and lighting conditions would also help.","Q_Score":1,"Tags":"python,tensorflow,machine-learning,keras","A_Id":62074782,"CreationDate":"2020-05-28T19:44:00.000","Title":"How should I interpret or intuitively explain the following results for my CNN model?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"The default start of the weekday is Monday (0) in Pandas. Am trying to make this as Sunday instead on datetimeindex for getting weekly counts ending on Saturday to forecast a timeseries model.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":276,"Q_Id":62081229,"Users Score":0,"Answer":"I got a breakthrough, yes.\nFrom my previous code, I redefined W-SAT instead of the default W.\nPrevious code:\nweekreq = daysreq.resample('W').apply({'Numbers':'sum'})\nto \nNew code: \nweekreq = daysreq.resample('W-SAT').apply({'Numbers':'sum'})","Q_Score":0,"Tags":"python-3.x,pandas,time-series,weekday","A_Id":62098954,"CreationDate":"2020-05-29T07:56:00.000","Title":"Change start of weekday from monday to sunday in datetimeindex in python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"My goal is to evaluate model performance on test dataset for object detection task. Model was trained on dataset with 6 classes with Tensorflow Object Detection API. For some class there are 20 samples of objects and for some it can be only one sample. So data is imbalanced for both train and test sets. \nCan I use mean average precision (mAP) as metrics for evaluation?\nIt seems to me that it is not correct to use it for imbalanced data. Therefore I don't know which other metrics to use. So what kind of metrics is suitable for this case?\nI would appreciate any help on this.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":408,"Q_Id":62081792,"Users Score":0,"Answer":"Mean average precision will still work. As you can see, it is mean average precision, so, since precision will be averaged over all classes their number won't matter.","Q_Score":0,"Tags":"python,tensorflow,object-detection,object-detection-api","A_Id":62081931,"CreationDate":"2020-05-29T08:30:00.000","Title":"Mean average precision metrics for evaluation multilabel object detection model","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"For the normal BatchNorm, the least batch size per GPU is 2.\nI wonder if I use the SyncBatchNorm, can I use batch_size=1 for every GPU with more than a single GPU?\nI.e, the total_batch_size is more than 1 but batch_size_per_gpu is 1.\nI would appreciate answers for any deep learning framework, pytorch, tensorflow, mxnet, etc","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":109,"Q_Id":62110937,"Users Score":1,"Answer":"For PyTorch, using batch_size_per_gpu=1 and more than one GPU is fine.","Q_Score":1,"Tags":"python,tensorflow,pytorch,mxnet,batch-normalization","A_Id":62153083,"CreationDate":"2020-05-31T02:43:00.000","Title":"What is the least total batch size for SyncBatchNorm","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I got a question about splitting the data into a training and test set in Time Series tasks.\nI know that the data can't be shuffled because it's important to keep the time nature of the data, so we do not create scenarios where we are able to look into the future.\nHowever, when I shuffle the data (for experimenting), I get a ridiculously high R-Squared score.\nAnd yes, the R-squared is evaluated with the test set.\n\nCan someone maybe simply explain why this is the case?\nWhy does shuffling train and test data in time series produce a high R-Squared score? My guess is that it has something to the with the trend of the time series, but I am not sure. I am just asking out of curiosity, thanks!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":144,"Q_Id":62117759,"Users Score":0,"Answer":"It really depends upon your problem. If:\n\nif your model has no memory, and merely a mapping tasks then attached timestamp does not have any significance it is better in fact recommended to shuffle the data for better distribution. If this is the case and you are getting a higher R-squaed value you shoud definitely go for it. (I assume this is the case since R-squared is usually used for these types of tasks)\nIf your task is pattrn dependent and each prediction is affecting next in the sequence. This is where order matters. In this case you should never shuffle the data. Any metric which suggest that is lying. The best you can do is split train and test set based on a timestamp prior to which you have your train set and afterwards test set. Then divide train and test sets into fixed time windows. You can shuffle those windows now only if the window span is large enough for your case.\n\nHope this helps!","Q_Score":1,"Tags":"python,time-series","A_Id":62119424,"CreationDate":"2020-05-31T14:34:00.000","Title":"Why does shuffling train and test data in time series produce a high R-Squared score?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I an a novice in Machine Learning and while going through the course I came across the \"Scoring Parameter\". I understood for Regression model evaluation, we consider the negatives of Mean Squared error, mean absolute error etc.\nWhen I wanted to know the reason, I went through SKLearn documentation which says \"All scorer objects follow the convention that higher return values are better than lower return values. Thus metrics which measure the distance between the model and the data, like metrics.mean_squared_error, are available as neg_mean_squared_error which return the negated value of the metric.\"\nThis explanation does not answer my why's completely and I am confused. So, why is the negatives taken more because logically if the difference in prediction is higher whether -ve or +ve, it makes our models equally bad. Then why is it that scoring parameter is focused on negative differences?","AnswerCount":2,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":4661,"Q_Id":62125674,"Users Score":2,"Answer":"It's simple: minimizing MSE is equivalent to maximizing negative-MSE.\nAn objective function that the scorer can maximize is just by \"convention\" as the Sklearn documentation suggests.","Q_Score":2,"Tags":"python,machine-learning,scikit-learn,regression,scoring","A_Id":62125933,"CreationDate":"2020-06-01T04:23:00.000","Title":"Why is negative (MSE or MAS) Scoring parameter like- neg_mean_absolute_error in SKLEARN is considered for regression model evaluation","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using pyomo for optimization modeling, including multiple continuous and discrete variables, but I am not clear how to define a discrete variable.The value of discrete variable is either 0 or 100.\nmy question is : how to define a discrete variable which value is either 0 or 100\nthans all!","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":358,"Q_Id":62126655,"Users Score":1,"Answer":"You would have to declare a binary variable, e.g. y, in addition to your discrete variable, e.g. myvar.\nThen, you need a constraint that says: myvar = 100 * y\nIf y=0, then myvar will necessarily be 0 too. If y=1, then myvar will be equal to 100.\nI assume you would be able to express these in Pyomo syntax.","Q_Score":0,"Tags":"python,pyomo","A_Id":62130354,"CreationDate":"2020-06-01T06:14:00.000","Title":"python pyomo: declaration of discrete variable","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"Getting below error while running this code in Python, If anyone could advise me on this that would be appreciated. Thanks\ndataframe = pandas.read_sql(sql,cnxn)\nDatabaseError: Execution failed on sql 'SELECT * FROM train_data': ('HY000', \"[HY000] [Dremio][Connector] (1040) Dremio failed to execute the query: SELECT * FROM train_data\\n[30038]Query execution error. Details:[ \\nVALIDATION ERROR: Table 'train_data' not found\\n\\nSQL Query SELECT * FROM train_data\\nstartLine 1\\nstartColumn 15\\nendLine 1\\nendColumn 24\\n\\n[Error Id: 24c7de0e-6e23-44c6-8cb6-b0a110bbd2fd on user:31010]\\n\\n (org.apache.calcite.runtime.CalciteContextException) From line 1, column 15 to line 1, column 24: ...[see log] (1040) (SQLExecDirectW)\")","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":644,"Q_Id":62131393,"Users Score":0,"Answer":"this is being solved, it says that table does not exist, should give a valid table, in dremio it can be inside a specific space","Q_Score":0,"Tags":"python,sql,pyodbc,dremio","A_Id":62146385,"CreationDate":"2020-06-01T11:43:00.000","Title":"Dremio ODBC with Python","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using pandas to read CSV file data, but the CSV module is also there to manage the CSV file.\nso my questions are :-\nwhat is the difference between these both?\nwhat are the cons of using pandas over the CSV module?","AnswerCount":3,"Available Count":2,"Score":0.1973753202,"is_accepted":false,"ViewCount":10152,"Q_Id":62139040,"Users Score":3,"Answer":"csv is a built-in module but pandas not. if you want only reading csv file you should not install pandas because you must install it and increasing in dependencies of project is not a best practice.\nif you want to analyze data of csv file with pandas, pandas changes csv file to dataframe needed for manipulating data with pandas and you should not use csv module for these cases.\nif you have a big data or data with large volume you should consider libraries like numpy and pandas.","Q_Score":10,"Tags":"python,pandas,csv","A_Id":62139217,"CreationDate":"2020-06-01T18:55:00.000","Title":"python CSV module vs Pandas","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using pandas to read CSV file data, but the CSV module is also there to manage the CSV file.\nso my questions are :-\nwhat is the difference between these both?\nwhat are the cons of using pandas over the CSV module?","AnswerCount":3,"Available Count":2,"Score":0.0665680765,"is_accepted":false,"ViewCount":10152,"Q_Id":62139040,"Users Score":1,"Answer":"Pandas is better then csv for managing data and doing operations on the data. CSV doesn't provide you with the scientific data manipulation tools that Pandas does.\nIf you are talking only about the part of reading the file it depends. You may simply google both modules online but generally I find it more comfortable to work with Pandas. it provides easier readability as well since printing there is better too.","Q_Score":10,"Tags":"python,pandas,csv","A_Id":62139102,"CreationDate":"2020-06-01T18:55:00.000","Title":"python CSV module vs Pandas","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've to build an ML model to classify sentences into different categories. I have a dataset with 2 columns (sentence and label) and 350 rows i.e. with shape (350, 2). To convert the sentences into numeric representation I've used TfIdf vectorization, and so the transformed dataset now has 452 columns (451 columns were obtained using TfIdf, and 1 is the label) i.e. with shape (350, 452). More generally speaking, I have a dataset with a lot more features than training samples. In such a scenario what's the best classification algorithm to use? Logistic Regression, SVM (again what kernel?), neural networks (again which architecture?), naive Bayes or is there any other algorithm?\nHow about if I get more training samples in the future (but the number of columns doesn't increase much), say with a shape (10000, 750)?\nEdit: The sentences are actually narrations from bank statements. I have around 10 to 15 labels, all of which I have labelled manually. Eg. Tax, Bank Charges, Loan etc. In future I do plan to get more statements and I will be labelling them as well. I believe I may end up having around 20 labels at most.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":50,"Q_Id":62145159,"Users Score":0,"Answer":"With such a small training set, I think you would only get any reasonable results by getting some pre-trained language model such as GPT-2 and fine tune to your problem. That probably is still true even for a larger dataset, a neural net would probably still do best even if you train your own from scratch. Btw, how many labels do you have? What kind of labels are those?","Q_Score":0,"Tags":"python,machine-learning,classification","A_Id":62145580,"CreationDate":"2020-06-02T05:00:00.000","Title":"Given the dataset, how to select the learning algorithm?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I know that similar precision questions have been asked here however I am reading a code of a project that is doing an exact equality comparison among floats and is puzzling me. \nAssume that x1 and x2 are of type numpy.ndarray and of dtype np.float32. These two variables have been computed by the same code executed on the same data but x1 has been computed by one machine and x2 by another (this is done on an AWS cluster which communicates with MPI).\nThen the values are compared as follows\nnumpy.array_equal(x1, x2)\nHence, exact equality (no tolerance) is crucial for this program to work and it seems to work fine. This is confusing me. How can one compare two np.float32 computed on different machines and face no precision issues? When can these two (or more) floats can be equal?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":155,"Q_Id":62146800,"Users Score":1,"Answer":"The arithmetic specified by IEEE-754 is deterministic given certain constraints discussed in its clause 11 (2008 version), including suitable rules for expression evaluation (such as unambiguous translation from expressions in a programming language to IEEE-754 operations, such as a+b+c must give (a+b)+c, not a+(b+c)).\nIf parallelism is not used or is constructed suitably, such as always partitioning a job into the same pieces and combining their results in the same way regardless of order of completion of computations, then obtaining identical results is not surprising.\nSome factors that prevent reproducibility include varying parallelism, using different math libraries (with different implementations of functions such as pow), and using languages that are not strict about floating-point evaluation (such as permitting, but not requiring, extra precision).","Q_Score":2,"Tags":"python,numpy,floating-point,precision,equality","A_Id":62150052,"CreationDate":"2020-06-02T07:19:00.000","Title":"Numpy array_equal and float exact equality check","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"My R squared score for Linear regression is -1.56 but my R squared score for Random Forest regressor is around 0.48. Is it okay to get scores like this?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":192,"Q_Id":62147114,"Users Score":0,"Answer":"Is it okay to get scores like this?\n\nYes.\nExplanation - Linear Regression and Random Forest are two very different models. It is highly possible that the data on which you are trying to fit the model is so complicated that linear regression does not fit it well. \nRegarding the negative R squared score - It simply means that the linear regression model fits worse than a horizontal line.","Q_Score":0,"Tags":"python,machine-learning,regression,linear-regression,random-forest","A_Id":62147427,"CreationDate":"2020-06-02T07:41:00.000","Title":"Negative r squared for linear regression but positive r squared with Random forest regressor","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"i want to import PCA from sklearn.decomposition, but following error occurs: \n\"ModuleNotFoundError: No module named 'sklearn.decomposition'\". (just import sklearn works)\nDoes someone know how i can solve this problem?\nI have installed the packages in Anaconda (conda version : 4.8.3)","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":3773,"Q_Id":62149948,"Users Score":1,"Answer":"If the module installed, uninstall and install Sklearn again.\npython -m pip install -U sklearn.","Q_Score":1,"Tags":"python,tensorflow,anaconda","A_Id":62150166,"CreationDate":"2020-06-02T10:29:00.000","Title":"ModuleNotFoundError: No module named 'sklearn.decomposition'","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm working with a company on a project to develop ML models for predictive maintenance. The data we have is a collection of log files. In each log file we have time series from sensors (Temperature, Pressure, MototSpeed,...) and a variable in which we record the faults occurred. The aim here is to build a model that will use the log files as its input (the time series) and to predict whether there will be a failure or not. For this I have some questions:\n1) What is the best model capable of doing this?\n2) What is the solution to deal with imbalanced data? In fact, for some kind of failures we don't have enough data. \nI tried to construct an RNN classifier using LSTM after transforming the time series to sub time series of a fixed length. The targets were 1 if there was a fault and 0 if not. The number of ones compared to the number of zeros is negligible. As a result, the model always predicted 0. What is the solution?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":353,"Q_Id":62152465,"Users Score":0,"Answer":"Mohamed, for this problem you could actually start with traditional ML models (random forest, lightGBM, or anything of this nature). I recommend you focus on your features. For example you mentioned Pressure, MototSpeed. Look at some window of time going back. Calculate moving averages, min\/max values in that same window, st.dev. To tackle this problem you will need to have a set of healthy features. Take a look at featuretools package. You can either use it or get some ideas what features can be created using time series data. Back to your questions.\n1) What is the best model capable of doing this? Traditional ML methods as mentioned above. You could also use deep learning models, but I would first start with easy models. Also if you do not have a lot of data I probably would not touch RNN models.\n2) What is the solution to deal with imbalanced data? You may want to oversample or undersample your data. For oversampling look at the SMOTE package.\nGood luck","Q_Score":0,"Tags":"python,classification,lstm,recurrent-neural-network,prediction","A_Id":62153294,"CreationDate":"2020-06-02T12:52:00.000","Title":"Best model to predict failure using time series from sensors","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I would like to customize axis titles in a Seaborn pairplot, e.g., I would like to use the formatted versions (r'$I_{bs}$') and (r'$k_{HL}$') instead of \"Ibs\" and \"kHL\" which are the column titles in the dataframe I use to generate the plot. How can I achieve this?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":47,"Q_Id":62154130,"Users Score":0,"Answer":"Problem solved. I named columns using formatted strings in defining the dataframe I used to create the pairplot:\ndf_red=pd.DataFrame(DataMatrix_red,columns=['shape',r'$d_n$',r'$\\nu_s$',r'$D_s$[%]',r'$I_{{bs}}$',r'$k_{{VssL}}$',r'$k_{{HL}}$'])","Q_Score":0,"Tags":"python,matplotlib,seaborn","A_Id":62332247,"CreationDate":"2020-06-02T14:18:00.000","Title":"Customizing axis titles in Seaborn pairplots","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a large CSV file with about 10000 rows of text information and each row of my dataset consists of a number of lines. However I just want to read say first 20 lines of each of the rows of my CSV file. \nI came across n_rows parameter in pandas read_csv method which helps us in limiting the number of rows of the dataset that we would like to load. Is there also a way where we could only read first 20 lines of data from each of the rows in pandas?","AnswerCount":3,"Available Count":2,"Score":0.0665680765,"is_accepted":false,"ViewCount":632,"Q_Id":62168254,"Users Score":1,"Answer":"You can read in the csv with df = pd.read_csv('path\\file.csv') and than just select the first 20 rows by df_new = df.head(20). Is that what you where thinking of?","Q_Score":0,"Tags":"python,pandas,csv,dataframe","A_Id":62168448,"CreationDate":"2020-06-03T08:22:00.000","Title":"Pandas - Read only first few lines of each rows","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a large CSV file with about 10000 rows of text information and each row of my dataset consists of a number of lines. However I just want to read say first 20 lines of each of the rows of my CSV file. \nI came across n_rows parameter in pandas read_csv method which helps us in limiting the number of rows of the dataset that we would like to load. Is there also a way where we could only read first 20 lines of data from each of the rows in pandas?","AnswerCount":3,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":632,"Q_Id":62168254,"Users Score":0,"Answer":"If TiTo's answer is not what you are looking for, maybe the iloc method is. You can store the first 20 rows by doing firstRows = df.iloc[:20].\nHowever, if you only ever need the first 20 rows, you shouldn't load the whole file into memory. As you mentioned, this can be achieved with the nrows parameter.","Q_Score":0,"Tags":"python,pandas,csv,dataframe","A_Id":62168592,"CreationDate":"2020-06-03T08:22:00.000","Title":"Pandas - Read only first few lines of each rows","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Should the inference model in a chatbot model with keras lstm, have the same amount of layers as the main model or it doesnt matter?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":67,"Q_Id":62169402,"Users Score":1,"Answer":"I don't know what you exactly mean by inference model. \nThe number of layers of a model is an hyperparameter that you tune during training. Let's say that you train an LSTM model with 3 layers, then the model used for inference must have the same number of layers and use the weights resulting from the training.\nOtherwise, if you add non trained layer when inference, the results won't make any sense.\nHope this helps","Q_Score":1,"Tags":"python,keras,lstm","A_Id":62171243,"CreationDate":"2020-06-03T09:26:00.000","Title":"LSTM, Keras : How many layers should the inference model have?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"How can I identify a vector in Python?\nLike does it have a single dimension or is it n-dimensions, I got really confused when trying to understand this in NumPy.\nAlso, what's the difference between static memory allocation and a dynamic one in vectors?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":177,"Q_Id":62174437,"Users Score":0,"Answer":"A vector has a single dimension and is create with method such as numpy.array and numpylinspace. A n-dimension array would be a matrix created with methods such as zeros or numpy.random.uniform(...). You dont have to use numpy to use vectors in python. You can simply use the basic array type.\nIn python you usually dont have to worry about memory allocation. A dynamic memory allocation means that elements can added or removed to the vector whereas in a static memory allocation, there would be a fixed number of elements in the vector.","Q_Score":0,"Tags":"python,numpy,memory,vector,dimension","A_Id":62174665,"CreationDate":"2020-06-03T13:46:00.000","Title":"Structure of a vector in python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I get the below error while trying to fetch rows from Excel using as a data frame. Some of the columns have very big values like 1405668170987000000, while others are time stamp columns having values like 11:46:00.180630.\nI did convert the format of the above columns to text. However, I'm still getting the below error for a simple select statement (select * from df limit 5):\n\nOverflow Error: Python int too large to convert to SQLite INTEGER","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":125,"Q_Id":62176746,"Users Score":0,"Answer":"SQLite INTEGERS are 64-bit, meaning the maximum value is 9,223,372,036,854,775,807.\nIt looks like some of your values are larger than that so they will not fit into the SQLite INTEGER type. You could try converting them to text in order to extract them.","Q_Score":0,"Tags":"python,python-3.x","A_Id":62176901,"CreationDate":"2020-06-03T15:32:00.000","Title":"overflow error in Python using dataframes","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I get the below error while trying to fetch rows from Excel using as a data frame. Some of the columns have very big values like 1405668170987000000, while others are time stamp columns having values like 11:46:00.180630.\nI did convert the format of the above columns to text. However, I'm still getting the below error for a simple select statement (select * from df limit 5):\n\nOverflow Error: Python int too large to convert to SQLite INTEGER","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":125,"Q_Id":62176746,"Users Score":0,"Answer":"SQL integer values have a upper bound of 2**63 - 1. And the value provided in your case 1405668170987000000 is simply too large for SQL.\n\nTry converting them into string and then perform the required operation","Q_Score":0,"Tags":"python,python-3.x","A_Id":62176934,"CreationDate":"2020-06-03T15:32:00.000","Title":"overflow error in Python using dataframes","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am facing a problem of improving the training speed \/ efficiency of a Tensorflow implementation of point cloud object detection algorithm.\nThe input data is a [8000, 100, 9] float32 tensor, with a size roughly 27MB per sample. On a batch size of 5, data loading becomes a bottleneck in training as most of the time GPU utlization rate is 0% until data arrives.\nI have tried the following methods to increase data loading speed.\n\nUse num_parallel_calls in tf.Dataset .map API, and use multiple threads for reading this big tensor. The problem is .map wraps a py_fun which is subject to Global Interpreter Lock and thus multi-threading does not improve I\/O efficiency.\nUse tf.Dataset .interleave API. Since it's also multi-threading based, it has the same problem as 2.\nUse TFRecord format. This is even slower than method 1 and 2. Possibility is TFRecord will convert tensor to numpy, then serialize numpy to bytes, then wrap this bytes to tensorflow structure and write to disk. Numpy to Tensor takes a long time for my data as measured by tf.convert_to_tensor().\n\nAny suggestions how to move forward would be helpful. Thanks!\nFollow up on comments\n\nAm I using slow disks? Data is stored on a mounted disk. Could be a reason. \nCan the data be fit into GPU memory? Unfortunately no. There are ~70,000 samples. I tried cache a small dataset into RAM and GPU utlization rate is 30%~40%, which is probably the highest expectation for this particular network.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":710,"Q_Id":62178275,"Users Score":3,"Answer":"Some ideas: \n\nYou should use a combination of 1,2 and 3. If you save your files as TFRecords, you can read them in parallel, that's what they are designed for. Then, you will be able to use num_parallel_calls and interleave, because that way you don't have to wrap a py_func. \n.map doesn't have to wrap a .py_func, you could for example use tf.keras.utils.get_file. That way you also avoid using py_func and use num_parallel_calls efficiently. I still recommend using TFRecords, they are designed for this use case. \nAnother option is to use an SSD to store your data instead of a Hard Disk. \nYou can also look into the .cache function of the tf.Dataset API. Maybe you can try loading a random subset of the data, training multiple eopchs on that, and then in the mean time fetch another subset of the data (using tf.prefetch), and then train multiple epochs on that, and so on. This idea is more of a long shot as it might affect performance, but it just might work in your case.","Q_Score":2,"Tags":"python,tensorflow","A_Id":62179455,"CreationDate":"2020-06-03T16:50:00.000","Title":"Increase I\/O bound tensorflow training speed","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I would like to search for multiple words using the Twint Python Library. However, I can only find guidance on searching for one word within tweets. So, for example, \"twint -s \"pregnant\" --since \"2020-03-01 13:13:59\" -o \"sample.csv\" --csv\" gathers tweets that contain the word pregnant. When I add ...-s \"pregnant -s \"COVID,\" the code runs, but gathers tweets containing the word pregnant or COVID. How do I search for multiple words? Even better would be the ability to search multiple words using and\/or.","AnswerCount":2,"Available Count":1,"Score":-0.0996679946,"is_accepted":false,"ViewCount":2644,"Q_Id":62198077,"Users Score":-1,"Answer":"There are probably more elegant ways of doing this, but grep actually works.","Q_Score":0,"Tags":"python,web-scraping,twitter,twint","A_Id":63363015,"CreationDate":"2020-06-04T15:12:00.000","Title":"Search multiple words in Twint Python Library","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"Maps give O(1) look-up. Can't we go through the array once and build a map corresponding to its index (the opposite of array) and when we want to search something we can call map[VALUE] and it will return the index.\nIt might not work for large values in array but assuming a[i]<10^5, can't we do this instead of binary search? Then, each query will be O(1). \nP.S: i did mean unordered map..","AnswerCount":3,"Available Count":2,"Score":0.0665680765,"is_accepted":false,"ViewCount":342,"Q_Id":62201467,"Users Score":1,"Answer":"Here are the problems you might want to consider - \n\nYou can't store multiple elements of the same value in map\nThe lookup time is O(log(n)) and not O(1)\nIt's not magic that happens in map which allows us to access it in lesser time. There's an hashing process going on in the background in unordered_map which gives O(1)and that takes time as well. So, the big O hides a big constant time factor. Standard map gives you a O(logn) lookup, same time complexity as binary search in an array.\n\n\nThe average time complexity of searching you get is about the same. The main problem you will have using standard maps in C++ is that it won't be able to hold multiple elements that have same values. One advantage that you might get using map is the deletion and insertion time will be O(logn).\nSo, if you know that the dataset you will be working on doesn't have duplicate elements and\/or there will be frequent addition\/deletion of elements, then you can surely consider map as the better alternative in this case","Q_Score":2,"Tags":"python,c++,algorithm,data-structures","A_Id":62201590,"CreationDate":"2020-06-04T18:13:00.000","Title":"Can we use maps for searching instead of binary search?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"Maps give O(1) look-up. Can't we go through the array once and build a map corresponding to its index (the opposite of array) and when we want to search something we can call map[VALUE] and it will return the index.\nIt might not work for large values in array but assuming a[i]<10^5, can't we do this instead of binary search? Then, each query will be O(1). \nP.S: i did mean unordered map..","AnswerCount":3,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":342,"Q_Id":62201467,"Users Score":0,"Answer":"As the exact running time will depend on the length and type of the keys, their distribution, their number, it is advisable to benchmark for your particular application.","Q_Score":2,"Tags":"python,c++,algorithm,data-structures","A_Id":62202384,"CreationDate":"2020-06-04T18:13:00.000","Title":"Can we use maps for searching instead of binary search?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"On the official Tensorflow Lite website they show the support for GPU acceleration for Android and iOS but they don't say anything about support for Raspberry Pi.","AnswerCount":2,"Available Count":1,"Score":-0.0996679946,"is_accepted":false,"ViewCount":3569,"Q_Id":62202550,"Users Score":-1,"Answer":"You cant use the raspberry Pi GPU for machine learning. First, it doesnt meet the hardware requirements for most DL models and second you probably need a Nvidia GPU. What you are looking for is a Jetson Nano from nvidia, which is like a RPi but has a GPU that supports cuda. These are made to deploy machine learning models, check it out!","Q_Score":5,"Tags":"python,deep-learning,gpu,tensorflow-lite,raspberry-pi4","A_Id":62202935,"CreationDate":"2020-06-04T19:20:00.000","Title":"Is there a way to get GPU acceleration on Raspberry Pi 4 for Deep Learning?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"On the web, the only solution I find to plot the values of a two-dimensional function is to have a file with the matrix A(nxm) of the function's values and use matplotlib imshow. This will produce a map, whose extent (dimension along axes) has to be known and explicitly indicated.\nNow, my concern arises from the fact that I need to plot two maps on the same axis, but one is slanted with respect to the other. So to say, I have a large main rectangular map and a smaller one that is oblique and superimposed.\nIn the end, the question is: is it possible to plot 2d maps starting from a file that is written as x, y, f(x,y) rather than just using f(x,y) so the plotting tool knows exactly where to draw?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":306,"Q_Id":62204411,"Users Score":0,"Answer":"I luckily found what I was looking for in pcolormesh that can draw a map given the coordinates of each point and its \"colour\"-value.","Q_Score":0,"Tags":"python,2d,colormap,color-mapping","A_Id":62349214,"CreationDate":"2020-06-04T21:27:00.000","Title":"In python, is it possible to plot colour map by giving coordinates and function value?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a dataset containing 1.3 Million records categorized into 109 classes. Obviously there is class imbalance with highest class being 18% in the data and lowest class being less than 1%\nNow, my task is to devise a general forumula\/technique\/code for sampling from these reords such that: What is the minimum number of records we need to select such that it contains records from K classes (where K can vary from 1 to 109) and is representetive of the original data for these classes. Obviuosly tehre cant be an exact solution so we can deal with 'high confidence' solution","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":33,"Q_Id":62212049,"Users Score":0,"Answer":"It seems that you have a simple combinatorics problem.\nAssume you have M red marbles and N green marbles in a box. You pull out K marbles randomly. What is the expected values of a ratio of red to green in your sample? Furthermore, what is the variance? Lets define \"representative\" as extreme values in 95% confidence interval of the ratio (expected-2*std, expected+2*std) been no more than 10% wide relative to the expected value of the ratio. It as straightforward to express it as a function of K (in fact you can do it with pencil and paper for 2 classes). For three classes you can say that the highest variance of the ratio between any two classes should be no more than 10%.","Q_Score":0,"Tags":"python,scikit-learn,data-science,sampling","A_Id":62213036,"CreationDate":"2020-06-05T09:21:00.000","Title":"SubSampling data such that at least K classes are selected from a huge dataset containing N classes","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have x and y coordinates in a df from LoL matches and i want to create a contour plot or heat map to show where the player normally moves in a match.\nDoes any one know how can I do it?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":1958,"Q_Id":62215345,"Users Score":0,"Answer":"A contour plot or heat map needs 3 values. You have to provide x, y and z values in order to plot a contour since x and y give the position and z gives the value of the variable you want to show the contour of as a variable of x and y.\nIf you want to show the movement of the players as a function of time you should look at matplotlib's animations. Or if you want to show the \"players density field\" you have to calculate it.","Q_Score":1,"Tags":"python,heatmap,contourf","A_Id":62215414,"CreationDate":"2020-06-05T12:25:00.000","Title":"Python Contour Plot\/HeatMap","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"If I have x.shape = (n,) and y.shape = (n,), then x @ y returns their dot product, rather than their outer product. I was wondering if there was some underlying reason for this, or if its just for convenience.\nThanks.","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":188,"Q_Id":62219910,"Users Score":1,"Answer":"Function np.matmul was added when @ operator was introduced to Python.\nThe new function was designed to behave as similar to np.dot as reasonable.\nSo why np.dot(vector, vector) performs inner product?\nBefore @, the function np.dot was used to perform matrix algebra in numpy.\nActually, vectors in linear algebra are not 1D arrays but rather matrices with one of dimensions set to 1. In order to multiply 1D array by matrix, the former has to be somehow promoted to either row or column vector.\nWe have 3 cases here:\n\nvector by matrix, 1D array is promoted to row vector (1xN) to make operation valid\nmatrix by vector, 1D array is promoted to column vector (Nx1)\nvector by vector, left operand is promoted to row vector, right to column vector, as in previous both cases\n\nAs result in the last case we have a normal inner product between two vectors.\nThis policy is both logical and practical because inner products are used more often.","Q_Score":2,"Tags":"python,numpy","A_Id":62222800,"CreationDate":"2020-06-05T16:21:00.000","Title":"Why is the matrix @ product of two numpy (n,) vectors the dot product, rather than the outer product?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"So I wrote a function that fills any null values in 2 dataframe columns baded on a condition being met. I've written unit tests, they all work.\nWhen running it on actual data, it sometimes leads to a ValueError: cannot set using a list-like indexer with a different length than the value\nI'm confused because my unit tests pass. The code is essentially this:\ndf.loc[df['column'].isin(column_values_to_update), ['col2', 'col3']] = df[['col2', 'col3']].fillna(0)\nIt works when column_values_to_update is empty, it works when its full...yet when running on certain datasets, I get the ValueError and I'm not sure why....I've reset the index before getting to this point and no luck.\nAnyone have any idea why sometimes this error can arise, and sometimes it doesn't? Let me know if you need more info...","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":51,"Q_Id":62224335,"Users Score":0,"Answer":"in the end I solved the issue by adding an if clause where I use .loc only if column_values_to_update (which is a Set) is not empty.\nI'm still baffled because my unit tests where column_values_to_update was empty still passed.....\noh well","Q_Score":0,"Tags":"python-3.x,pandas","A_Id":62227676,"CreationDate":"2020-06-05T21:26:00.000","Title":"Filling null values in multiple dataframe columns based on condition","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using California housing data, which has latitude and longitude. Is it good practice to remove them (latitude & longitude)before I continue to train my model?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":281,"Q_Id":62227841,"Users Score":0,"Answer":"If you are just using raw lat\/long information, then yes, you should remove them. That's because the values of lat\/long are not meaningful in and of themselves, conditional on your model not having any \"understanding\" of what a change in lat\/long means. For instance, what would a change in 1 degree in latitude mean in terms of a change in your target variable? If there is nothing related that way, then you introduce either noise or potentially spurious relationships. \nLat\/long are more often useful as a way to calculate a feature that does have a meaningful impact on your response variable: distance between points, area withing boundries, or anything where you can say \"the change in this feature that I calculate from spatial information correlates with a change in the response\". \nIn short: either take it out, or use it to calculate a feature you do want to include.","Q_Score":0,"Tags":"python,database,pandas,data-science,feature-engineering","A_Id":62267845,"CreationDate":"2020-06-06T05:40:00.000","Title":"Latitude and Longitude data in dataset while training the model","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to combine two feature extraction methods and classify in python.I am using sklearn.But the accuracy is not improved.What is wrong?How to combine two numpy arrays of feature extraction methods to improve accuracy?Please answer the way to combine in order to improve accuracy.Thanks in advance!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":51,"Q_Id":62228734,"Users Score":0,"Answer":"It's not necessary that every time you add a new feature, the accuracy of your model increases. So, it is necessary that you set up local cross-validation. Data science is all about experimenting. The more you experiment, the better results you might get.","Q_Score":1,"Tags":"python,scikit-learn","A_Id":62228885,"CreationDate":"2020-06-06T07:36:00.000","Title":"How to combine two or three feature extraction methods?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Anyone know how you get a dataframe from Quantopian to excel - I try - results.to_excel\nresults are the name of my dataframe","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":30,"Q_Id":62246095,"Users Score":0,"Answer":"Try this :\nName of your DataFrame: Result.to_csv(\"result.csv\")\nhere Result is your DataFrame Name , while to_csv() is a function","Q_Score":0,"Tags":"python,quantopian","A_Id":65324001,"CreationDate":"2020-06-07T13:31:00.000","Title":"How to transfer data from Quantopian to Excel","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have objective function for Revenue which is in the form of e^(beta1*log(P1) + beta2*log(P2) +....beta250*log(P250)) where P1,P2... P250 are price of certain items and beta1,beta2,... beta250.are elasticity coefficients from model. I would like to maximize Revenue and currently using SLSQP provided constraints on prices, units and guest count. The problem I am facing is optimizer is getting stuck at local minima (It return same o\/p when I relax bounds on price by 5% or 10% or even more). I tried using manually written gradient and using approx_fprime. In both the cases it is getting stuck at local. I could not go with global optimizers as they take lot of time and we are planning to deploy optimizer in real time so that store managers can use it. Can you suggest some algorithm which do not have local minima problem and should converge in less than 30 to 45 secs. \nThanks","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":527,"Q_Id":62246325,"Users Score":1,"Answer":"We don't have the whole model, so bring limited to work with partial information, here are some remarks:\n\nThe max Exp(sum()) objective can be replaced by max sum() (as exp() is monotonic). \nFor global optimization problems, I often use solvers like Baron, Couenne, and Antigone. The problem may be small enough to prove global optimality.\nYou can also try a multi-start approach: use multiple different starting points. This will at least prevent some really bad solutions. Some solvers have this built-in (e.g. Knitro) but it is not very difficult to implement this with a simple loop.\nSLSQP is a local solver. In theory, you could use basinhopping + SLSQP but I am not sure this works correctly with constraints.","Q_Score":0,"Tags":"python,optimization,scipy-optimize","A_Id":62252763,"CreationDate":"2020-06-07T13:49:00.000","Title":"Facing Local Minima Problem using SLSQP Optimizer","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to identify how many rows and columns are in a pandas Dataframe called df, I tried using the functions:\nlen(df) => I get only the number of rows\nlen(df.columns) => I get only the number of columns \nIs there a single command\/function that will reveal the rows and columns?\nThanks!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":600,"Q_Id":62250242,"Users Score":0,"Answer":"After quick research I found I can use: \ndf.shape\nAnswer comes back as (# of rows, # of columns) \nFor example if df has 421 rows and 33 columns then:\ndf.shape will respond\n(421,33)","Q_Score":0,"Tags":"python,pandas","A_Id":62250243,"CreationDate":"2020-06-07T19:00:00.000","Title":"How to determine how many rows and columns are in a pandas dataframe in Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Currently, I am working on a map visualization project using Bokeh.\nBecause the legend of the map is too many, the legend crowded the map.\nIs there any way to make the legend into something like a dropdown menu in Bokeh?\nThank you","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":53,"Q_Id":62254273,"Users Score":1,"Answer":"In Bokeh, the widget is called Select. There's no function like legend_to_select if that's what you want. But you can just avoid creating the legend at all and create the select widget manually. You will have to manually hook it up to the glyphs via a CustomJS callback and it won't support displaying glyphs since it supports only text. If you require displaying glyphs as well, you will have to create a custom Bokeh model that extends Select and overrides the item rendering mechanism.","Q_Score":0,"Tags":"python,bokeh","A_Id":62256596,"CreationDate":"2020-06-08T02:52:00.000","Title":"How to make legend into dropdown?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am having trouble when migrating to Python from R. When I worked with data frame in R, using the dollar sign will let know all the name of the column and easily choose the one that i need from a suggestion list even though I don't remember exactly the column's name. Is there any way I can do that in Python?\nUpdate:\nThank you all for the quick respondes. I have looked around and figured out that using df. to bring up the auto complete box works only in the console, not in the editor. However, I have no idea whether it is a bug, or JetBrains just hasn't implemented the feature from R yet.","AnswerCount":2,"Available Count":1,"Score":0.2913126125,"is_accepted":false,"ViewCount":395,"Q_Id":62254876,"Users Score":3,"Answer":"There are two parts to your question: there is a language part about what the equivalent syntax\/usage is and a platform part about how things are exposed to the user.\nThe language part is that indexing using df[\"colname\"] in on a Pandas Dataframe is the equivalent of df$colname in R. Depending on your column name, you might also be able to use df.colname although I discourage this usage.\nIf you would like to have completion of this, Jupyter Lab supports tab completion on dataframes, where you would type df[\" and see a list of possible column completions.","Q_Score":0,"Tags":"python,r,pandas,dataframe","A_Id":62255058,"CreationDate":"2020-06-08T04:10:00.000","Title":"Does Python have any equivalent to R's $ sign?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"When I run Keras Tuner search, the code runs for some epochs and then says:\n'INFO:tensorflow:Oracle triggered exit'.\nWhat does this mean? I am still able to extract best hyperparameters. Is it due to early stopping? I have tried both randomsearch and hyperband.","AnswerCount":9,"Available Count":7,"Score":0.0,"is_accepted":false,"ViewCount":7326,"Q_Id":62258704,"Users Score":0,"Answer":"I had the same question and didn't find what I was looking for.\nIf the tuner have finished at trial, that is lower then your max_trial parameter, the most probable reason is that the tuner have already tried all the combinations possible for the field of hyperparameters that you set before.\nExample: I have 2 parameters for tuner to try, fist can optain 8 values, second 18. If you multiply these two it gives you 144 combinations and that is exactly the number of trials that the tuner stopped at.","Q_Score":7,"Tags":"python,tensorflow,keras,neural-network,keras-tuner","A_Id":71874696,"CreationDate":"2020-06-08T09:13:00.000","Title":"What does 'INFO:tensorflow:Oracle triggered exit' mean with keras tuner?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"When I run Keras Tuner search, the code runs for some epochs and then says:\n'INFO:tensorflow:Oracle triggered exit'.\nWhat does this mean? I am still able to extract best hyperparameters. Is it due to early stopping? I have tried both randomsearch and hyperband.","AnswerCount":9,"Available Count":7,"Score":0.022218565,"is_accepted":false,"ViewCount":7326,"Q_Id":62258704,"Users Score":1,"Answer":"I found the same issue and I found a very easy solution. It can be very easy if you just remove two files from the directory generated by the keras tunner. oracle.json and other .json files and Run it again it will work.","Q_Score":7,"Tags":"python,tensorflow,keras,neural-network,keras-tuner","A_Id":70181061,"CreationDate":"2020-06-08T09:13:00.000","Title":"What does 'INFO:tensorflow:Oracle triggered exit' mean with keras tuner?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"When I run Keras Tuner search, the code runs for some epochs and then says:\n'INFO:tensorflow:Oracle triggered exit'.\nWhat does this mean? I am still able to extract best hyperparameters. Is it due to early stopping? I have tried both randomsearch and hyperband.","AnswerCount":9,"Available Count":7,"Score":0.0665680765,"is_accepted":false,"ViewCount":7326,"Q_Id":62258704,"Users Score":3,"Answer":"Probably the reason is, directory is already created.\nTry following steps:\n\nChange the directory name.\nRestart the kernel.\nre-run all the codes.","Q_Score":7,"Tags":"python,tensorflow,keras,neural-network,keras-tuner","A_Id":67093410,"CreationDate":"2020-06-08T09:13:00.000","Title":"What does 'INFO:tensorflow:Oracle triggered exit' mean with keras tuner?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"When I run Keras Tuner search, the code runs for some epochs and then says:\n'INFO:tensorflow:Oracle triggered exit'.\nWhat does this mean? I am still able to extract best hyperparameters. Is it due to early stopping? I have tried both randomsearch and hyperband.","AnswerCount":9,"Available Count":7,"Score":0.0,"is_accepted":false,"ViewCount":7326,"Q_Id":62258704,"Users Score":0,"Answer":"For me i resolved this issue by removing the hp = HyperParameters() out of the build_model function. I mean, initialize the hp variable outside of the build model function.","Q_Score":7,"Tags":"python,tensorflow,keras,neural-network,keras-tuner","A_Id":67942570,"CreationDate":"2020-06-08T09:13:00.000","Title":"What does 'INFO:tensorflow:Oracle triggered exit' mean with keras tuner?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"When I run Keras Tuner search, the code runs for some epochs and then says:\n'INFO:tensorflow:Oracle triggered exit'.\nWhat does this mean? I am still able to extract best hyperparameters. Is it due to early stopping? I have tried both randomsearch and hyperband.","AnswerCount":9,"Available Count":7,"Score":0.022218565,"is_accepted":false,"ViewCount":7326,"Q_Id":62258704,"Users Score":1,"Answer":"I solved this issue by setting these two conditions in my Tuner:\n\noverwrite = False\na value for max_trials in the Oracle greater than the one I used until the error \"Oracle triggered exit\" occurred (I'm using kerastuner.oracles.BayesianOptimization Oracle)","Q_Score":7,"Tags":"python,tensorflow,keras,neural-network,keras-tuner","A_Id":67971100,"CreationDate":"2020-06-08T09:13:00.000","Title":"What does 'INFO:tensorflow:Oracle triggered exit' mean with keras tuner?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"When I run Keras Tuner search, the code runs for some epochs and then says:\n'INFO:tensorflow:Oracle triggered exit'.\nWhat does this mean? I am still able to extract best hyperparameters. Is it due to early stopping? I have tried both randomsearch and hyperband.","AnswerCount":9,"Available Count":7,"Score":0.0,"is_accepted":false,"ViewCount":7326,"Q_Id":62258704,"Users Score":0,"Answer":"I had the same issue with the Hyperband search.\nFor me the issue was solved by removing the \"Early Stopping\" callback from the tuner search.","Q_Score":7,"Tags":"python,tensorflow,keras,neural-network,keras-tuner","A_Id":63204590,"CreationDate":"2020-06-08T09:13:00.000","Title":"What does 'INFO:tensorflow:Oracle triggered exit' mean with keras tuner?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"When I run Keras Tuner search, the code runs for some epochs and then says:\n'INFO:tensorflow:Oracle triggered exit'.\nWhat does this mean? I am still able to extract best hyperparameters. Is it due to early stopping? I have tried both randomsearch and hyperband.","AnswerCount":9,"Available Count":7,"Score":0.0,"is_accepted":false,"ViewCount":7326,"Q_Id":62258704,"Users Score":0,"Answer":"I believe this is occuring because you are working on a small dataset which is resulting in a large number of collisions while performing random search.\nPlease try reducing the number of 'max-trials' in your random-search, that may fix the issue.","Q_Score":7,"Tags":"python,tensorflow,keras,neural-network,keras-tuner","A_Id":62258845,"CreationDate":"2020-06-08T09:13:00.000","Title":"What does 'INFO:tensorflow:Oracle triggered exit' mean with keras tuner?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm using confluent-Kafka with python.\nI want to connect Kafka to Hdfs and store some particular data direct in Hdfs.\nI found the confluent HDFS connector, but I didn't get how to connect it with my python script.\nany idea ? or any alternative methods to store messages directly from Kafka to Hdfs?","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":389,"Q_Id":62260047,"Users Score":1,"Answer":"I didn't get how to connect it with my python script\n\nKafka Connect is written in Java, so you cannot integrate with Python. If the documentation could be more clear on this, you should let somebody know. \nThat being said, it does have a REST API. You would use requests or urllib.request to interact with it from Python, just as any other HTTP service\n\nYou could also use PySpark \/ Flink \/ Beam to transfer data from Kafka to HDFS in Python","Q_Score":0,"Tags":"python,apache-kafka,hdfs,apache-kafka-connect,confluent-platform","A_Id":62274586,"CreationDate":"2020-06-08T10:31:00.000","Title":"store message from kafka to hdfs","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":1,"Web Development":0},{"Question":"I am working with properties dataset and I am trying to deal with missing values in Land Square Feet Column. There are almost 160000 records in the dataset. Out of which 70000 records have missing LandSquareFeet. I also have a feature which tells about the type of building. When the building types are CONDO\/Walkup I have many missing values in LandSquareFeet. There are 47k records of condo type which has 44k records with missing values in LandsquareFeet. Similarly for most of the properties of Elevator\/Walkup apartments. Other categories of buildings have a very small amount of records missing with LandSquareFeet. I am confused about how to deal with missing Landsquarefeet feature. If I remove the records with missing LandSquareFeet, I will lose almost half of my dataset. I don't know if it is wise to remove the feature for all the records. I did a Little's MCAR test to find if it is MCAR but I got a p-value of 0.000 so it is not MCAR. Is it MAR? Any leads on how to deal with this will be helpful.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":148,"Q_Id":62261268,"Users Score":0,"Answer":"First of all, it might be a good idea if you study the missingness in your data, as tools and methods of missingness resolving often are categorized with respect to these characteristics\n\nMissingness Pattern: if you only have 1 column with missingness, then your missingness pattern is nonresponse. it could have been otherwise monotone multivariate, general form, case matching etc... the pattern describes the distribution of missingness occurrence\nMissingness Mechanism: as you have already mentioned, we might have MCAR, MNAR, and MAR missingness. I don't know what you actually mean by MCAR test, basically, MNAR missingness happens if the missingness occurrence is correlated with other features, and MAR is when the missingness occurrence is correlated with the masked value of the feature itself. According to your description, your case is clearly a MNAR (predicted by type of the house). but it could also be MAR, suppose that small values are often unobserved or unrecorded for an arbitrary reason.\n\nMCAR missingness can be resolved by imputation techniques easily, you can search for MICE algorithm, or MissForest, as a special case of MICE.\nMNAR and MAR missingness mechanisms are called non-ignorable mechanism. there are techniques such as IP-weighting to deal with this types. Recently papers also have been published where they deal with missingness as a causal inference problem.\nBad News is in some special cases, MAR missingness is theoretically impossible to curate. Good news is that there are several really really complex cases studied and investigated, and hopefully your case is not more complex than those, thus you could apply the existing methods.\nI tried not to solve your problem, but to give you essential keywords, by which you might be able to find your material. If you are willing to spend a good deal of time on that, you can read a great book on the subject:\n\nR. J. Little and D. B. Rubin, Statistical analysis with missing data, vol. 793. John Wiley & Sons, 2019.\n\nMy final thought: I have a gut feeling that you can be able to solve your problem by IP-Weighting of all possible methods and approaches. look it up.","Q_Score":0,"Tags":"python,data-mining,data-analysis,missing-data,data-handling","A_Id":62261530,"CreationDate":"2020-06-08T11:41:00.000","Title":"How to deal with missing values in Real-Estate data?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to convert the pretrained ResNet50 model to be used on GPU using the Pytorch function resnet50.to().\nThe problem is that I am using an Intel Iris Plus Graphics 655 1536 MB GPU on Mac, and I don't know what argument to pass to the function as I only found the one for NVIDIA GPUs (resnet50.to('cuda:0')).","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":186,"Q_Id":62262241,"Users Score":1,"Answer":"PyTorch uses Nvidia's CUDA API for all GPU interactions. Other GPUs that don't utilise the CUDA API (such as AMD or Intel GPUs) are therefore not supported.\nIf you don't have an Nvidia GPU, you cannot run PyTorch on the GPU.","Q_Score":0,"Tags":"python,deep-learning,pytorch,gpu,resnet","A_Id":62262509,"CreationDate":"2020-06-08T12:37:00.000","Title":"resnet50.to() function on a non-NVIDIA GPU","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am new to the Analytics field and I have few doubts.\nI hope I can get my answers here.\nI am in the middle of implementing Logistic regression using python.\nIf we need to apply the logistic on the categorical variables, I have implemented get_dummies for that. Suppose the column name is house type (Beach, Mountain and Plain).\nWhat we do here is create three dummy variables in this case and drop one of them, as we can infer the Plain using the other 2 dummy variables. \nBut when I implement RFE on the data. Do I need to include all the 3 variables?\n(I saw this in some blog where dummy was not dropped and got confused)\nAlso, I need to add an intercept column also, as I was using statsmodel (which does not add intercept on it's own). So, in that case if there are multiple categorical variables (and we have dropped a dummy for each) there won't be any issue right ?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":692,"Q_Id":62267152,"Users Score":2,"Answer":"You should end up seeing multicolinearity as the third dummy column is always the opposite of the sum of the first two (1 if they sum to 0, and 0 if they sum to 1). \nThis should be removed prior to feature selection, such as RFE.\nIf you don't, statsmodel is going to throw an warning in the summary and if you check the VIF of the features post fitting, you'll see unacceptable scores that are suggesting colinear features.\nIn any case once this is done, it is feasible that one of your dummy columns could actually be a constant, such as if you had no beach houses in your data set. The default behavior of statsmodel ignore the add_constant statement when a constant exists. To get around this you may consider the has_constant parameter, passing 'add' to indicate you'd like to get an intercept even if there is already a constant column.\nX = sm.add_constant(X, has_constant='add')","Q_Score":1,"Tags":"python,logistic-regression,data-analysis,statsmodels,dummy-variable","A_Id":62267460,"CreationDate":"2020-06-08T16:47:00.000","Title":"Logistic Regression using Python statsmodel","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"i had installed python 3.6.5 and pycharm community version 2020.1.2 on windows 8.1 pro..it works completely fine on numpy but when i imported pandas,it shows error....please help me to get out of this problem.....\nit just show this...\nC:\\Users\\india\\Desktop\\final\\venv\\Scripts\\python.exe C:\/Users\/india\/Desktop\/final\/test.py\nTraceback (most recent call last):\n File \"C:\/Users\/india\/Desktop\/final\/test.py\", line 1, in \n import pandas\n File \"C:\\Users\\india\\Desktop\\final\\venv\\lib\\site-packages\\pandas__init__.py\", line 55, in \n from pandas.core.api import (\n File \"C:\\Users\\india\\Desktop\\final\\venv\\lib\\site-packages\\pandas\\core\\api.py\", line 29, in \n from pandas.core.groupby import Grouper, NamedAgg\n File \"C:\\Users\\india\\Desktop\\final\\venv\\lib\\site-packages\\pandas\\core\\groupby__init__.py\", line 1, in \n from pandas.core.groupby.generic import DataFrameGroupBy, NamedAgg, SeriesGroupBy\n File \"C:\\Users\\india\\Desktop\\final\\venv\\lib\\site-packages\\pandas\\core\\groupby\\generic.py\", line 60, in \n from pandas.core.frame import DataFrame\n File \"C:\\Users\\india\\Desktop\\final\\venv\\lib\\site-packages\\pandas\\core\\frame.py\", line 124, in \n from pandas.core.series import Series\n File \"C:\\Users\\india\\Desktop\\final\\venv\\lib\\site-packages\\pandas\\core\\series.py\", line 4572, in \n Series._add_series_or_dataframe_operations()\n File \"C:\\Users\\india\\Desktop\\final\\venv\\lib\\site-packages\\pandas\\core\\generic.py\", line 10349, in _add_series_or_dataframe_operations\n from pandas.core.window import EWM, Expanding, Rolling, Window\n File \"C:\\Users\\india\\Desktop\\final\\venv\\lib\\site-packages\\pandas\\core\\window__init__.py\", line 1, in \n from pandas.core.window.ewm import EWM # noqa:F401\n File \"C:\\Users\\india\\Desktop\\final\\venv\\lib\\site-packages\\pandas\\core\\window\\ewm.py\", line 5, in \n import pandas._libs.window.aggregations as window_aggregations\nImportError: DLL load failed: The specified module could not be found.\nProcess finished with exit code 1","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":4077,"Q_Id":62277970,"Users Score":0,"Answer":"Kindly Install all pending updates and retry.\nI experienced same error before where I couldn't import seaborn and train_test_split module from sklearn.model.\nI tried many fixes I found online but didn't work,\nI discovered that I have many pending windows updates so I downloaded and installed all pending updates and everything was fine.","Q_Score":1,"Tags":"python,python-3.x,pandas","A_Id":64295894,"CreationDate":"2020-06-09T08:13:00.000","Title":"how to fix ImportError: DLL load failed: The specified module could not be found","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"Adding UUID as an id column to the DataFrame and push to BigQuery using to_gbq maintains the uniqueness?","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":240,"Q_Id":62298118,"Users Score":1,"Answer":"it is the same - UUID in Python generate such unique Id like UUID in BQ","Q_Score":0,"Tags":"python,google-bigquery","A_Id":62299551,"CreationDate":"2020-06-10T07:34:00.000","Title":"How safe to use Python UUID instead of BigQuery GENERATE_UUID() when inserting data?","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I recently installed Pop!_OS on my laptop for development purposes, but i found out the version of python installed is 3.8.2, which unfortunately doesnt support versions of tensorflow below 2.0. I need to use tensorflow 1.14 for my work and this is not possible with python 3.8.\nIm willing to use python 3.6 in a virtual environment or have it alongside 3.8 in my laptop. Im rather new to linux so please excuse any mistakes. Thanks in advance!","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":3751,"Q_Id":62300705,"Users Score":0,"Answer":"easiest way is to create a virtual env with a specific python version\nvirtualenv envname --python=python3.6","Q_Score":2,"Tags":"python,debian-based","A_Id":64048270,"CreationDate":"2020-06-10T09:53:00.000","Title":"How to install python 3.6.10 alongside presinstalled 3.8.2","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":1,"Web Development":0},{"Question":"TL;DR\nWhat's the fasted way to get near-zero loading time for a pandas dataset I have in memory, using ray?\nBackground\nI'm making an application which uses semi-large datasets (pandas dataframes between 100MB to 700MB) and are trying to reduce each query time. For a lot of my queries the data loading is the majority of the response times. The datasets are optimized parquet files (categories instead of strings, etc) which only reads the columns it needs. \nCurrently I use a naive approach that per-requests loads the require dataset (reading the 10-20 columns out of 1000 I need from the dataset) and then filter out the rows I need. \nA typical request:\n\nRead and parse the contract (~50-100ms) \nLoad the dataset (10-20 columns) (400-1200ms) \nExecute pandas operations (~50-100ms)\nSerialise the results (50-100ms)\n\nI'm now trying to speed this up (reduce or remove the load dataset step). \nThings I have tried:\n\nUse Arrow's new row-level filtering on the dataset to only read the rows I need as well. This is probably a good way in the future, but for now the new Arrow Dataset API which is relies on is significantly slower than reading the full file using the legacy loader. \nOptimize the hell out of the datasets. This works well to a point, where things are in categories, the data types is optimized. \nStore the dataframe in Ray. Using ray.put and ray.get. However this doesn't actually improve the situation since the time consuming part is deserialization of the dataframe. \nPut the dataset in ramfs. This doesn't actually improve the situation since the time consuming part is deserialization of the dataframe.\nStore the object in another Plasma store (outside of ray.put) but obviously the speed is the same (even though I might get some other benefits)\n\nThe datasets are parquet files, which is already pretty fast for serialization\/deserialization. I typically select about 10-20 columns (out of 1000) and about 30-60% of the rows. \nAny good ideas on how to speed up the loading? I haven't been able to find any near zero-copy operations for pandas dataframes (i.e without the serialization penalty). \nThings that I am thinking about:\n\nPlacing the dataset in an actor, and use one actor per thread. That would probably give the actor direct access to the dataframe without any serialization, but would require me to do a lot of handling of:\n\nMaking sure I have an actor per thread\nDistribute requests per threads\n\"Recycle\" the actors when the dataset gets updated\n\n\nRegards,\nNiklas","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":290,"Q_Id":62306438,"Users Score":1,"Answer":"After talking to Simon on Slack we found the culprit:\n\nsimon-mo: aha yes objects\/strings are not zero copy. categorical or fixed length string works. for fixed length you can try convert them to np.array first\n\nExperimenting with this (categorical values, fixed length strings etc) allows me not quite get zero-copy but at least fairly low latency (~300ms or less) when using Ray Objects or Plasma store.","Q_Score":0,"Tags":"python,pandas,parquet,pyarrow,ray","A_Id":62429365,"CreationDate":"2020-06-10T14:46:00.000","Title":"Low-latecy response with Ray on large(isch) dataset","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have an old Macbook Pro 3,1 running ubuntu 20.04 and python 3.8. The mac CPU doesn't have support for avx (Advanced Vector Extensions) which is needed for tensorflow 2.2 so whilst tensorflow installs, it fails to run with the error:\n\nillegal instruction (core dumped)\n\nI've surfed around and it seems that I need to use tensorflow 1.5 however there is no wheel for this for my configuration and I have the impression that I need to build one for myself.\nSo here's my question... how do I even start to do that? Does anyone have a URL to Building-Stuff-For-Dummies or something similar please? (Any other suggestions also welcome)\nThanks in advance for your help","AnswerCount":3,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":299,"Q_Id":62308415,"Users Score":0,"Answer":"Update: I installed python 3.6 alongside the default 3.8 and then installed tensorflow 1.5 and it looks like it works now (albeit with a few 'future warnings'.)","Q_Score":0,"Tags":"python,tensorflow,ubuntu","A_Id":62385426,"CreationDate":"2020-06-10T16:24:00.000","Title":"Building Tensorflow 1.5","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have an old Macbook Pro 3,1 running ubuntu 20.04 and python 3.8. The mac CPU doesn't have support for avx (Advanced Vector Extensions) which is needed for tensorflow 2.2 so whilst tensorflow installs, it fails to run with the error:\n\nillegal instruction (core dumped)\n\nI've surfed around and it seems that I need to use tensorflow 1.5 however there is no wheel for this for my configuration and I have the impression that I need to build one for myself.\nSo here's my question... how do I even start to do that? Does anyone have a URL to Building-Stuff-For-Dummies or something similar please? (Any other suggestions also welcome)\nThanks in advance for your help","AnswerCount":3,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":299,"Q_Id":62308415,"Users Score":0,"Answer":"Usually there are instructions for building in the repository's README.md. Isn't there such for TensorFlow? It would be odd.","Q_Score":0,"Tags":"python,tensorflow,ubuntu","A_Id":62308529,"CreationDate":"2020-06-10T16:24:00.000","Title":"Building Tensorflow 1.5","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Training on tensorflow 1.15, python3.7.\nI am currently training stylegan2 on a custom dataset consisting of 30000 images, each 256 by 256. Since style gan creates different tf record files, each storing dataset with size 2^x. the 8th tf record (storign 256x256 images) is 5Gb just for context, the rest are super small (all less than a gb). \nMy current setup is a P100, 16 gigs VRam, 32 gb ram and abundance of storage . I also 2vCpus (training on gcp). \nI am running into this error as mentioned above. Initially my memory was 13 gigs, after seeing the exact error multiple times, i iteratively upped my memory to an eventual 32 gb. \nAny and all \"pointers\" would be helpful (Notice the pun on pointers haha)","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":584,"Q_Id":62317096,"Users Score":0,"Answer":"OKAY I SOLVED IT. there was an issue with the .pkl file that I was using for transfer learning. use a pickle file that contains a model whos discriminator starts with input layer of your image shape (eg 256x256).","Q_Score":0,"Tags":"python,tensorflow","A_Id":62318366,"CreationDate":"2020-06-11T04:30:00.000","Title":"MemoryError: Unable to allocate 5.62 GiB for an array with shape (16384, 30720, 3) and data type float32 When training StyleGan2","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to use conda to set up one of my projects. I installed openCV by conda install -c conda-forge opencv. When I run conda list, I can see openCV in the list. Running python -i and then import cv2 works, but when I open up Jupyter Notebook and navigate to that folder (I have to do it this way because running jupyter notebook in the directory also pulls up an error), and open up a notebook which imports cv2, I get an error. Why is this happening, and how would I solve it? Any kind of help will be greatly appreciated.","AnswerCount":4,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":977,"Q_Id":62329185,"Users Score":0,"Answer":"Usually that indicates that the notebook is running with a different Python or in a different environment from Python in the command prompt. Check sys.executable to see which Python it's running in, and sys.path to see where it's looking for imports","Q_Score":1,"Tags":"python,jupyter-notebook,anaconda,conda","A_Id":62329248,"CreationDate":"2020-06-11T16:37:00.000","Title":"ModuleNotFoundError in jupyter notebook when importing a module after conda install","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to use conda to set up one of my projects. I installed openCV by conda install -c conda-forge opencv. When I run conda list, I can see openCV in the list. Running python -i and then import cv2 works, but when I open up Jupyter Notebook and navigate to that folder (I have to do it this way because running jupyter notebook in the directory also pulls up an error), and open up a notebook which imports cv2, I get an error. Why is this happening, and how would I solve it? Any kind of help will be greatly appreciated.","AnswerCount":4,"Available Count":2,"Score":1.2,"is_accepted":true,"ViewCount":977,"Q_Id":62329185,"Users Score":1,"Answer":"So as I said before, I wasn't able to start Jupyter Notebook from the command line, I had to start it from the start menu and navigate to my folder. Because of that, my notebook wasn't working in the conda environment that I created. I fixed that by running python -m ipykernal install --user --name --display-name \"\". I had to conda install ipykernel. It works now. Thanks for the other answers.","Q_Score":1,"Tags":"python,jupyter-notebook,anaconda,conda","A_Id":62345858,"CreationDate":"2020-06-11T16:37:00.000","Title":"ModuleNotFoundError in jupyter notebook when importing a module after conda install","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have two-time series datasets i.e. errors received and bookings received on a daily basis for three years (a few million rows). I wish to find if there is any relationship between them.As of now, I think that cross-correlation between these two series might help. I order to so, should I perform any transformations like stationarity, detrending, deseasonality, etc. If this is correct, I'm thinking of using \"scipy.signal.correlate\u00b6\" but really want to know how to interpret the result?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":704,"Q_Id":62335396,"Users Score":2,"Answer":"scipy.signal.correlate is for the correlation of time series. For series y1 and y2, correlate(y1, y2) returns a vector that represents the time-dependent correlation: the k-th value represents the correlation with a time lag of \"k - N + 1\", so that the N+1 th element is the similarity of the time series without time lag: close to one if y1 and y2 have similar trends (for normalized data), close to zero if the series are independent.\nnumpy.corrcoef takes two arrays and aggregates the correlation in a single value (the \"time 0\" of the other routine), the Pearson correlation, and does so for N rows, returning a NxN array of correlations. corrcoef normalizes the data (divides the results by their rms value), so that he diagonal is supposed to be 1 (average self correlation).\nThe questions about stationarity, detrending, and deseasonality depend on your specific problem. The routines above consider \"plain\" data without consideration for their signification.","Q_Score":3,"Tags":"python,scipy,time-series,cross-correlation","A_Id":62385883,"CreationDate":"2020-06-11T23:53:00.000","Title":"How do I perform crosscorelation between two time series and what transformations should I perform in python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have gotten decent results using the default regression objective function with XGBoost and a random forest with early stopping. \nMy goal is to be able to predict the bottom decile of my data well, and I am wondering if there is an objective function that will allow me to do this? I am less concerned about the other deciles, so long as I can predict the bottom well.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":47,"Q_Id":62335589,"Users Score":1,"Answer":"Well, you could define a categorical variable, equal to 0 in the bottom decile and 1 otherwise, and then use XGBClassifier. This has the potential of working better (I have had some success with classifiers in regression problems).","Q_Score":1,"Tags":"python,regression,xgboost","A_Id":62335720,"CreationDate":"2020-06-12T00:20:00.000","Title":"XGBoost objective function for regression where I am most concerned about predicting bottom decile","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Here is the thing.\nI build a trained network and save .meta and .data in ckpt. The optimizer is MomentumOptimizer:\ntf.train.MomentumOptimizer(learning_rate=lr, momentum=0.9, name='Momentum'), \nwhich is also saved in .meta.\nBut I forget to save paramters to do with Momentum, So when I load graph form .meta, there will be Error:\n\nAttempting to use uninitialized value fc.bias\/Momentum\n\nI know that I can use initializer() , but in this way how to set\nmomentum=0.9 ? would this initializer() just give a random values to momentum?\nI have trained the model for a long time, there is not way for me to train it from scratch again to save xx\/Momentum. So what can I do to fix it? That is, how can I set momentum=0.9 in MomentumOptimizer when loading .meta ?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":30,"Q_Id":62345912,"Users Score":0,"Answer":"momentum=0.9is saved when saving the model, so don't worry about it.\n Or you can make momentum a placeholder so you can load whatever you want when resotring models.","Q_Score":0,"Tags":"python,tensorflow,optimization,deep-learning,momentum","A_Id":62368990,"CreationDate":"2020-06-12T14:04:00.000","Title":"tensorflow Optimizer: Attempting to use uninitialized value fc.bias\/Momentum","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to change what happens in train_step when using a custom optimizer but I get this error message when trying to compile the model: \n\nraise ValueError('Could not interpret optimizer identifier:', identifier) ValueError: ('Could not interpret optimizer identifier:', )\n\nThe problem I'm having is that I want to selectively be able to feed the same data during training depending on what happens in the optimizer. My optimizer has a variable which basically say \"I want the same data again\" and I want to modify the fit function so that when the optimizer needs it I can feed it the same data instead of going to the next batch.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":46,"Q_Id":62346973,"Users Score":0,"Answer":"Ops, I was using different API's for my optimizer and my model, one was using keras, the other was using tensorflow.keras. If anyone runs into similar issues this might be the problem.","Q_Score":0,"Tags":"python,tensorflow,keras","A_Id":62390245,"CreationDate":"2020-06-12T15:02:00.000","Title":"Keras customizing train_step when using a custom optimizer","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am faced with a problem regarding a categorical variable. In my case, my variable may have varying number of levels. For example, suppose, my categorical variable represents type_of_cars. Initially, it had only three types (for argument's sake):gas,\ndiesel and hybrid. I have used an encoding to represent them. Now a new type of cars come to the market which is eV (for electric vehicle). I want to know if there is a way to accommodate EVs without retraining a model. \nIn my case, the categorical variable has roughly 50 different levels and new levels may be added as time goes on or old ones may be deleted. How do I go about modeling the data without retraining the entire model each time it happens, if it is at all possible?\nYour suggestions will be greatly appreciated.\nThank you.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":71,"Q_Id":62350752,"Users Score":1,"Answer":"The best way is to just retrain your model. \nThinking about how a categorical variable affects your model might be helpful. Categorical variables are generally treated a binary variables where each category is its own column, the row in that column is a 1 if that category is present and a 0 otherwise. Now imagine adding an additional column to your data for which your model has not been trained, as would be the case with a new category... this will result in sub-optimal performance. Most likely, this new column will have no affect on the model prediction. \nThere are examples of what you are suggesting, but they require a secondary model be fed into a primary model. We see this often in Natural Language Processing, where there is a model for how texts are similar (a word vector) and this model is then fed into another model that predicts things like text category and sentiment. \nSo basically, if you can model the similarities of your categorical variables (this is your secondary model), and feed that model into primary model, then you would only need update your secondary model when you get new data. But this approach has its issues...","Q_Score":2,"Tags":"python,data-science,statsmodels","A_Id":62351156,"CreationDate":"2020-06-12T18:57:00.000","Title":"How to handle modeling categorical variables where categories may change over time?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Say for example the values for a certain column is a dictionary which can be of different lengths. How do I subset the dataframe rows such that the length of the dictionary is more than 1? \nI tried,\nmore_than_1 = data[len(data[\"column_name\"]) > 1] \nBut it doesn't work?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":88,"Q_Id":62359848,"Users Score":0,"Answer":"You can apply len to the column containing the dict, and boolean index on that.\ndf[df[\"column_name\"].apply(len)>1]","Q_Score":0,"Tags":"python-3.x,pandas,numpy","A_Id":62360707,"CreationDate":"2020-06-13T12:36:00.000","Title":"How do I subset a dataframe based on the length of the dictionary?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a large dataset spanning many years and I want to subset this data frame by selecting data based on a specific day of the month using python.\nThis is simple enough and I have achieved with the following line of code:\ndf[df.index.day == 12]\nThis selects data from the 12th of each month for all years in the data set. Great.\nThe problem I have however is the original data set is based on working day data. Therefore the 12th might actually be a weekend or national holiday and thus doesnt appear in the data set. Nothing is returned for that month as such. \nWhat I would like to happen is to select the 12th where available, else select the next working day in the data set.\nAll help appreciated!","AnswerCount":3,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":61,"Q_Id":62376907,"Users Score":0,"Answer":"You can backfill the dataframe first to fill the missing values then select the date you want\ndf = df.asfreq('d', method='bfill')\nThen you can do df[df.index.day == 12]","Q_Score":0,"Tags":"python,pandas,date,datetime","A_Id":62376993,"CreationDate":"2020-06-14T18:53:00.000","Title":"select a specifc day from a data set, else the next working day if not available","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I use custom dateset while using code of stylegan. \nwhen it building tensorflow graph the following error will come:\nValueError: Op type not registered 'MaxBytesInUse' in binary running on DESKTOP. Make sure the Op and Kernel are registered in the binary running in this process. Note that if you are loading a saved graph which used ops from tf.contrib, accessing (e.g.) tf.contrib.resampler should be done before importing the graph, as contrib ops are lazily registered when the module is first accessed. while building NodeDef 'MaxBytesInUse'\nI am new to deep learning \nyour help will be great favour for me.\nThanks in advance","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":210,"Q_Id":62379805,"Users Score":0,"Answer":"in stylgan repo, itst recommended to use TensorFlow 1.10.0 which led to the \"MaxByteinUse\" error,\nchanging to'tensorflow-gpu==1.11.0' worked for me","Q_Score":0,"Tags":"python,tensorflow","A_Id":67822262,"CreationDate":"2020-06-15T00:47:00.000","Title":"Op type not registered 'MaxBytesInUse' in binary running on DESKTOP","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have an Excel sheet where one column has XMLs (each row is a different xml). I am trying to use Pyspark and spark-xml to parse these, by doing df = spark.read.format('xml').options(rowTag = 'book').load(___). \nThe load works fine when you specify an xml file, but is it possible to read in the Excel sheet and loop in those xmls to be parsed without having to convert each one to its own xml file?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":128,"Q_Id":62388441,"Users Score":1,"Answer":"You need to first read the Excel file as a Spark DataFrame. Then you can further parse a String column containing XML with the from_xml function. That gives a new column with the parsed data from the XML column.","Q_Score":2,"Tags":"python,excel,xml,pyspark","A_Id":63676518,"CreationDate":"2020-06-15T12:41:00.000","Title":"Spark XML - Use XMLs from Excel","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":1,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"what image classification to use for training? \nwe want to train a model with our own pictures for a school project. Can I use resnet50 or any other trainable model? I couldn't find Resnet50 trainable model and I found only pre-trained resnet50 model. We are using Tensorflow 2.\nThanks","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":54,"Q_Id":62393326,"Users Score":1,"Answer":"You don't have to use the pre-trained Resnet. Load the keras version of resnet with weights=None and train the model yourself.","Q_Score":0,"Tags":"python,tensorflow,tensorflow2.0,training-data,resnet","A_Id":63254361,"CreationDate":"2020-06-15T17:06:00.000","Title":"Train an image classification model using Tesnsorflow","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Is it possible to write a custom loss function in keras that says \"for all data from dataset A: calculate loss like this... And for all data from dataset B: calculate loss like this instead\"\nMy current implementation has 2 separate models with their own loss functions and then the 2 data feeds are given in separate train_on_batch calls.\nFor context, my system is a GAN that is tasked with creating a domain indistinguishable representation between two datasets, while also performing classification. However with my current method it feels as though the \"domain indistinguishability\" task is taking priority and my classification accuracy is not rising above random. (whereas if I turn off the domain task, the classification accuracy rises to approximately 80%). And one issue I'd like to rule out is multiple calls of train_on_batch with non-shuffled data per training loop.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":61,"Q_Id":62395291,"Users Score":0,"Answer":"For anyone that might stumble upon this question later, I realise now that I worded the question poorly with respect to what the actual answer is. The question is actually answered by \"how to calculate gradients and apply them as separate operations in keras\"\nMy solution is to overwrite the Model class, create a new train_on_batch method that accepts more than one dataset.\nThen apply however many calculations and loss functions you want inside a gradientTape. Then finally use optimizer.apply_gradient() to actually apply the gradients to the model","Q_Score":0,"Tags":"python,tensorflow,keras,generative-adversarial-network","A_Id":62882571,"CreationDate":"2020-06-15T19:12:00.000","Title":"Splitting up types of data in a keras loss function (equivalent to if statements in loss functions?)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"import tensorflow \nIt shows \n2020-06-16 07:15:04.362632: W tensorflow\/stream_executor\/platform\/default\/dso_loader.cc:55] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found\n2020-06-16 07:15:04.394714: I tensorflow\/stream_executor\/cuda\/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":113,"Q_Id":62399711,"Users Score":0,"Answer":"install everything what tensorflow needs \nand download everything still won't get the program","Q_Score":0,"Tags":"python,tensorflow,gpu","A_Id":62399712,"CreationDate":"2020-06-16T01:47:00.000","Title":"How to install tensorflow in windows 10 operating system after installed everything still got an error","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have some questions about how to deal with 0 value in 2d array.\nI am planning to work on regression 1d CNN, but most of the data is made of 0.\nI would like to replace this 0 to other small values such as 0.000001 simply because, if I put 0, regression process would not take into account the dataset values and find what is optimized model for my data set.\nI have some instinct but, I need to prove it by referencing.\nWould you be kind enough as to recommend me some references or any idea of this?\nThank you for reading.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":42,"Q_Id":62400584,"Users Score":1,"Answer":"The easiest thing to do is to jitter your data by adding 0.0001 * numpy.raodom.randn(*your array shape*) to your data. Whether it will help you in your specific problem, no one can tell, of course.","Q_Score":1,"Tags":"python,deep-learning,regression,artificial-intelligence,image-preprocessing","A_Id":62401006,"CreationDate":"2020-06-16T03:43:00.000","Title":"Many values in the dataset","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am training a Support Vector Machine using sklearn. In the beginning, I did not encode the class labels in any form and left them as Strings (e.g. [\"A\", \"B\", \"C\"]). The resulting accuracy was comparable to when I used a LabelEncoder [0, 1, 2]. So is sklearn automatically converting the Strings into integers\/one-hot-representations in the background? Or am I missing something here?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":526,"Q_Id":62405788,"Users Score":3,"Answer":"The labels have to be encoded only if the labels are part of the independent variables. So, if you have a list of labels that are used by the SVM to determine the dependent variable, you would have to encode them either using labelencoder or onehotencoder or however fits your dataset best. Scikit-learn encodes strings automatically, so you don't have to encode them manually by writing the code. This means that for text targets, Scikit-learn encodes them without you having to make the encoding. Hope this helped!","Q_Score":1,"Tags":"python,encoding,scikit-learn,svm","A_Id":62406309,"CreationDate":"2020-06-16T09:56:00.000","Title":"Is label encoding automatically done by sklearn SVC?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I need to install older versions of tensorflow to get the deepface library to work properly, however whenever I run pip install tensorflow==1.9.0, I get: ERROR: Could not find a version that satisfies the requirement tensorflow==1.9.0 (from versions: 2.2.0rc1, 2.2.0rc2, 2.2.0rc3, 2.2.0rc4, 2.2.0)\nAnyone else run into this issue\/know how to fix it? Thanks!","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":407,"Q_Id":62415403,"Users Score":2,"Answer":"You can install TensorFlow 1.9.0 with the following Python versions: 2.7 and 3.4 to 3.6.","Q_Score":2,"Tags":"python,tensorflow,pip","A_Id":62415559,"CreationDate":"2020-06-16T18:37:00.000","Title":"Cannot install older versions of tensorflow: No matching distribution found for tensorflow==1.9.0","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have two tables with same columns, and I concatenated them vertically. I want to remove duplicates based on col1 but keep records that have latest time_stamp","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":17,"Q_Id":62436315,"Users Score":1,"Answer":"sort the dataframe on the value of time stamp descending and the default behaviour of the pandas drop_duplicates method will keep the latest","Q_Score":0,"Tags":"python-3.x,pandas,dataframe,join,duplicates","A_Id":62436554,"CreationDate":"2020-06-17T18:52:00.000","Title":"drop dupliactes but keep records based on a condtion","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to remove the non-ASCII Character '\\xa0' while reading my CSV file using read_csv into a dataframe with python. Can someone tell me how to achieve this?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":562,"Q_Id":62437622,"Users Score":0,"Answer":"You can use x = txt.replace(u'\\xa0', u'') for text you're reading.","Q_Score":0,"Tags":"python,csv,replace,encoding,character","A_Id":62437674,"CreationDate":"2020-06-17T20:14:00.000","Title":"Remove character '\\xa0' while reading CSV file in python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"If you are looking for a simple script to do vector calculations in python, you can use this one. Enjoy ;) I didn't find some other easy to use scripts, so created my own. You can do these basic calculations with the vector class\n\nsum \nnorm\nscalar product\ncross product\netc","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":395,"Q_Id":62438309,"Users Score":1,"Answer":"I think your scalar product calculation is wrong\u2026scalar product should yield a real number, not a vector. Other calculations use this, so those are also broken.","Q_Score":0,"Tags":"python,vector","A_Id":71610959,"CreationDate":"2020-06-17T21:01:00.000","Title":"Vector Calculations in Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"My question is very specific. Given a k dimensional Gaussian distribution with mean and standard deviation, say I wish to sample 10 points from this distribution. But the 10 samples should be very different from each other. For example, I do not wish to sample 5 of those very close to the mean (By very close, we may assume for this example within 1 sigma) which may happen if I do random sampling. Let us also add an additional constraint that all the drawn samples should be at least 1 sigma away from each other. Is there a known way to sample in this fashion methodically? Is there any such module in PyTorch which can do so? \nSorry if this thought is ill posed but I am trying to understand if such a thing is possible.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":384,"Q_Id":62439852,"Users Score":0,"Answer":"To my knowledge there is no such library. The problem you are trying to solve is straightforward. Just check if the random number you get is 'far enough' from the mean. The complexity of that check is constant. The probability of a point not to be between one sigma from the mean is ~32%. It is not that unlikely.","Q_Score":0,"Tags":"python,pytorch,sampling,normal-distribution","A_Id":62440013,"CreationDate":"2020-06-17T23:15:00.000","Title":"Sampling from gaussian distribution","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Background: I have a huge DataFrame with 40 million rows. I have to run some functions on some columns. The loops were taking too long, so I decided to go with Multiprocessing. \nCPU: 8 cores 16 threads\nRAM: 128 GB\nQuestion: How many chunks should I break the data into? And how many workers are properly for this dataset? \np.s. I found out that when I set the max_workers = 15, all threads are running 100%. But if I change the max_workers to 40, they dropped to 40%. \nThank you!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":177,"Q_Id":62441519,"Users Score":0,"Answer":"There are three types of parallel computing. Those are io-intensive, cpu-intensive and io-cpu intensive computing.\nIf your thread is runing on cpu-intensive task, then You can increase your worker numbers as you want to get better performance.\nBut If it is runing on io-intensive, it willl no effect to increase them.\nYou seems to be working on io-cpu intensive task.\nSo If you increase worker numbers, you can get good result until there is no competition for using io resource(hard disk)\nso In local machine . it is not a good choice to increase worker numbers.\nYou can use Hadoop on GPS or AWS for this work.","Q_Score":0,"Tags":"python,multiprocessing,large-data","A_Id":62441716,"CreationDate":"2020-06-18T02:46:00.000","Title":"Python Multiprocessing: How to set up the number of max_workers properly?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to create a UDF in PySpark. The function takes in an input string which is an xml. It then uses lxml to parse it and returns a list of dictionaries with the attributes. I created the function parse_xml, but when I try the line spark.udf.register(\"parse_xml\", parse_xml) but this gives the error: PicklingError: Could not serialize object: TypeError: can't pickle lxml.etree.XMLParser objects. \nIt seems as if lxml objects are not serializable, but the input is a string and the output is a list\/dictionary -- is there any way to create a UDF like this?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":382,"Q_Id":62449753,"Users Score":0,"Answer":"The library used by pyspark is cpickle which stands for cloud pickle and serializing libraries written in C is not supported by it yet.\nIf you want to parse xml use databricks XML parser instead and it'll be fast as well.","Q_Score":1,"Tags":"python,apache-spark,pyspark,lxml,user-defined-functions","A_Id":62455447,"CreationDate":"2020-06-18T12:15:00.000","Title":"Unable to serialize PySpark UDF","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":1,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I just started learning ML and wondered why one would do .fit() and .transform() separately, when .fit_transform() exists. Also, I am generally confused on what exactly fitting\/.fit() does.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":27,"Q_Id":62450620,"Users Score":1,"Answer":"I assume you are talking about sklearn's scalers or sklearn's feature transformation algorithms in general.\nLet's say your dataset is splitted in 5 sub-sets and you want to scale each of them between -1 and 1:\n\nYou fit your scaler on each sub-set using fit, this basically searches for the maximum and minimum over all of your sets\nThen, you can scale your sub-sets using transform\n\nIf you had used fit_transform, on the first sub-set, then used it on the second one, it would have been scaled differently, and you don't want that.\nMoreover, instead of sub-sets, you can think of fitting once on your training set and keeping the transformation in memory to scale future samples you want to pass to your model.","Q_Score":0,"Tags":"python,python-3.x,scikit-learn","A_Id":62450696,"CreationDate":"2020-06-18T13:02:00.000","Title":"Is there any reason to do .fit() and .transform() instead of just .fit_transform()?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am in trouble to understand Word2Vec. I need to do a help desk text classification, based on what users complain in the help desk system. Each sentence has its own class.\nI've seen some pre-trained word2vec files in the internet, but I don't know if is the best way to work since my problem is very specific. And my dataset is in Portuguese.\nI'm considering that I will have to create my own model and I am in doubt on how to do that. Do I have to do it with the same words as the dataset I have with my sentences and classes?\nIn the frst line, the column titles. Below the first line, I have the sentence and the class. Could anyone help me? I saw Gensin to create vector models, and sounds me good. But I am completely lost. \n\n: chamado,classe 'Prezados n\u00e3o estou conseguindo gerar uma nota fiscal\n do m\u00f3dulo de estoque e custos.','ERP GEST\u00c3O', 'N\u00e3o consigo acessar o\n ERP com meu usu\u00e1rio e senha.','ERP GEST\u00c3O', 'M\u00e9dico n\u00e3o consegue gerar\n receitu\u00e1rio no m\u00f3dulo de Medicina e seguran\u00e7a do trabalho.','ERP\n GEST\u00c3O', 'O produto 4589658 tinta hologr\u00e1fica n\u00e3o est\u00e1 dispon\u00edvel no\n EIC e n\u00e3o consigo gerar a PO.','ERP GEST\u00c3O',","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":118,"Q_Id":62457316,"Users Score":0,"Answer":"Your inquiry is very general, and normally StackOverflow will be more able to help when you've tried specific things, and hit specific problems - so that you can provide exact code, errors, or shortfalls to ask about. \nBut in general:\n\nYou might not need word2vec at all: there are many text-classification approaches that, with sufficient training data, may assign your texts to helpful classes without using word-vectors. You will likely want to try those first, then consider word-vectors as a later improvement.\nFor word-vectors to be helpful, they need to be based on your actual language, and also ideally your particular domain-of-concern. Generic word-vectors from news articles or even Wikipedia may not include the important lingo, and word-senses for your problem. But it's not too hard to train your own word-vectors \u2013 you just need a lot of varied, relevant texts that use the words in realistic, relevant contexts. So yes, you'd ideally train your word-vectors on the same texts you eventually want to classify. \n\nBut mostly, if you're \"totally lost\", start with more simple text-classification examples. As you're using Python, examples based on scikit-learn may be most relevant. Adapt those to your data & goals, to familiarize yourself with all the steps & the ways of evaluating whether your changes are improving your end results or not. Then investigate techniques like word-vectors.","Q_Score":0,"Tags":"python,word2vec","A_Id":62458138,"CreationDate":"2020-06-18T18:48:00.000","Title":"Text classification using Word2Vec","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Is known that the convolution has the associative property: (A*B)*C=A*(B*C), where (*) denotes the convolutional operator. In keras, perform a 2D Convolution + 2D Average Pooling (with strides=(2,2)) is less expensive that perform only one convolution with strides=(1,1). I think that this is possible applying the associative property and doing first the convolution of kernel B and C, but I'm trying achieve the same result that keras via A*(B*C) instead of (A*B)*C, where A is the image input and B and C are the kernels, but the result differs from keras. \nIt's really possible convolve first the kernel, K=B*C and finally convolve the input with K: A*K?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":78,"Q_Id":62460763,"Users Score":0,"Answer":"(A * B) * C is not equal A * (B * C)\n(A * B) is matrix multiply but (B * C) isn't, you can't just reverse the process","Q_Score":0,"Tags":"python,tensorflow,keras,conv-neural-network,convolution","A_Id":62462118,"CreationDate":"2020-06-18T23:05:00.000","Title":"Perform convolution 2D + Average pooling in Tensorflow\/Keras","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to plot a grid of 13 graphs. But due to the nature of the code, I have to say:\nfig, axes = plt.subplots(nrows=3, ncols=5, figsize=(16,10))\nThis creates a grid of 15 plots. While the last two remain unused. \nIs there a way to plot only 13 plots?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":18,"Q_Id":62466702,"Users Score":0,"Answer":"Unfortunately 13 is a prime number, this means that you cannot find a grid shape that will fit all plots without any white space. The only way you can use is to plot a single row of 13 plots, otherwise you have to find a compromise like 4x4, 5x3 or 3x5","Q_Score":0,"Tags":"python,matplotlib,data-visualization,seaborn","A_Id":62467231,"CreationDate":"2020-06-19T08:54:00.000","Title":"Is there a way to get a specific number of plots in seaborn?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am a novice in using tensorflow and I built a CNN which is trained and tested both with 80-85% accuracy. I tried to save my trained model using model.save('example.h5'), and download the file using files.download('example.h5')\nAfterwards I tried to load it to my flask back-end using model = tf.keras.models.load_model('example.h5').\nWhen I tried using it with random images, it's like the model has never been trained before. Any solutions? thank you","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":43,"Q_Id":62473334,"Users Score":0,"Answer":"A common reason to this might be that you are normalizing your data on training but not before predicting. Make sure you normalize the input data before you run predictions, if you have trained on normalized data.","Q_Score":0,"Tags":"python,tensorflow,flask,keras,backend","A_Id":62483847,"CreationDate":"2020-06-19T15:16:00.000","Title":"CNN trained model not saved properly","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Does it make sense to use numpy's memmap across multiple cores (MPI)?\nI have a file on disk.\nCan I create a separate memmap object on each core, and use it to read different slices from the file?\nWhat about writing to it?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":297,"Q_Id":62480538,"Users Score":3,"Answer":"Q : \"Does it make sense to use numpy's memmap across multiple cores (MPI)?\"\n\nYes ( ... even without MPI, using just Python native { thread- | process-}-based forms of concurrent-processing )\n\nQ : \"Can I create a separate memmap-object on each core, and use it to read different slices from the file?\"\n\nYes.\n\nQ : \"What about writing to it?\"\n\nThe same ( sure, if having been opened in write-able mode ... )","Q_Score":2,"Tags":"python,numpy,parallel-processing,mpi,memmap","A_Id":62483960,"CreationDate":"2020-06-20T01:13:00.000","Title":"Python: numpy memmap in parallel","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am interested in using the tensor cores from NVIDIA RTX GPUs in python to benefit from its speed up in some scientific computations. Numba is a great library that allows programming kernels for cuda, but I have not found how to use the tensor cores. Can it be done with Numba? If not, what should I use?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":838,"Q_Id":62486362,"Users Score":2,"Answer":".... I have not found how to use the tensor cores. Can it be done with Numba?\n\nNo. Numba presently doesn't have half precision support or tensor core intrinsic functions available in device code.\n\nIf not, what should I use?\n\nI think you are going to be stuck with writing kernel code in the native C++ dialect and then using something like PyCUDA to run device code compiled from that C++ dialect.","Q_Score":0,"Tags":"python,cuda,gpu,nvidia,numba","A_Id":62487175,"CreationDate":"2020-06-20T13:21:00.000","Title":"How to program NVIDIA's tensor cores in RTX GPU with python and numba?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am a starter in the field of ML and wants to understand \"Multi Dimensional Array\". My current understanding is as follows. Please help me where i am wrong.\nSuppose I have data of customers, we can refer customers as items.\nNow suppose each item i.e. each individual has a Customer identification no (CIN) - we can call this as a one dimensional matrix.\nextending the same example,\nnow each item has list of attributes e.g. CIN, Gender, Height, weight, Eye colour. If i want to arrange them it will be a 2 dimensional matrix. Row representing students, columns representing their physical attributes \"Roll No, Gender, Height, weight, Eye colour\".\nNow suppose i add another list of different attributes - Past purchase history i.e. Last purchase date and invoice no.\nCan we call a matrix which has both phyical attributes \"Roll No, Gender, Height, weight, Eye colour\" and \"Last purchase date and invoice no.\" is this a 3 dimensional matrix ?\nIs it the grouping into physical and purchase history which will make it a 3 d matrix.\nI can still store it as a 2 d matrix (like a spread sheet) with physical and purchase history as columns or like 2 sheets with common link as CIN.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":34,"Q_Id":62486844,"Users Score":1,"Answer":"I think you are getting confused between dimensions of an array and dimensions for a ML model also called features or independent variables.\nWhen you train a model each piece of information that you pass to the model is a feature or a dimension. So for example Roll No, Gender, Height are all features. If you add Last purchase date and invoice those are also features. If you add all of them in a dataframe, each row of the dataframe can be thought of as an 1-D array.\nThe grouping of physical attributes and purchase history which will not make it a 3-D matrix.\n3-D arrays or n-D arrays are called tensors. They are something completely different.","Q_Score":1,"Tags":"python,arrays,multidimensional-array","A_Id":62486969,"CreationDate":"2020-06-20T14:04:00.000","Title":"What are dimensions in multi dimensional array in practical sense","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am new to deep learning and am currently researching a certain topic. I am looking for machine learning detection of anomalies in time series pattern and their implementation in python.\nFor example, I have a recording of the different CPU frequencies of my computer during a certain time interval. I would like to implement a supervised learning algorithm that takes a time series of CPU frequency as an input and decides, whether anything \"unusual\" happened during that time (unusual CPU usage etc).\nEDIT:\nMy data sets look the following way, every 10 seconds the current CPU frequency is measured. I have not specified an exact number of datapoints per set, the following is just for illustration. But I am expecting around 2500 datapoints per set:\nDataset_1: {1.2, 1.2, 1.6, 1.3, 1.5, 1.7, 1.6, 1.4, 1.5} -> Label: \"good\"\nDataset_2: {1.3, 1.2, 1.4, 1.3, 1.4, 1.5, 1.9, 2.1, 2.0} -> Label: \"good\"\nDataset_n: {1.3, 1.2, 3.6, 3.5, 1.4, 1.5, 3.3, 3.2,\n1.2} -> Label: \"bad\"\nMy understanding of a supervised ML algorithm is that i have training datasets. However, every tutorial that i have found so far always labels each value in a data set. In my case that would not be possible, as I could only tell my ML algorithm:\na) this time series data set is normal\n\nb) in this data set something is not normal\n\n\nbut i wouldn't be able to label each individual value, meaning i cannot say:\n1.2 -> good\n1.3 -> bad\n1.4 -> good\nAs there are many different ML algorithm, it is hard for a beginner to determine which is a good one to use. So my question is:\nWhich (python implemented) algorithm could i use as a start, that accepts labels for entire datasets and does not expect each value to be labeled.\nI hope this question makes sense, edits are highly welcome as much as your time! thanks!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":71,"Q_Id":62491406,"Users Score":0,"Answer":"For this application I would go with KNN(K - nearest neighbors). Tech with Tim has a great tutorial on KNN, explains it well and shows the implementation.\nHope this helps","Q_Score":0,"Tags":"python,deep-learning,pattern-matching","A_Id":62491620,"CreationDate":"2020-06-20T20:39:00.000","Title":"python supervised learning with data set classification","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"During the execution of my job I want to build a pandas DataFrame with its internal state at each step of execution. I want to do that because I want to be able to use the DataFrame later to do some analysis. So, that's the context: I start with an empty DataFrame and, after the job has finishing producing all its data, the final DataFrame size is 7GB (at most).\nThese are the approaches I've tried this far:\n\nI can maintain a list of lists, my job keeps appending new rows to that list. At the end I run something like: df = pd.DataFrame(rows, columns=list(\"abc\")). This is the fastest method, but it's very wasteful in terms of memory usage.\nI don't use the lists of lists anymore, but, instead I keep calling df = df.append([{\"a\": 1.0, \"b\": 1.0, \"c\": \"hello\"}]). This starts off ok, but as the DataFrame grows a lot of memory copying starts happening and it becomes really slow.\n\nSo, neither of them are ideal. I can estimate the final size of the DataFrame before my job runs (I think I can usually match the size precisely, to be honest), so I would like to tell pandas to allocate the entire memory ahead (or at least a large enough chunk to last for a while) and then, I'd like a method similar to df.append that will just add the new row at the end of the preallocated memory. Ideally, it would be smart enough to resize memory, if needed.\nI may be grossly missing something, but I sincerly couldn't find a way to do that anywhere I looked.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":276,"Q_Id":62492801,"Users Score":1,"Answer":"Use approach 1, but every time you get to (say) 10000 rows, convert the list of lists to a DataFrame, append the dataframe to a list of dataframes, and clear your list of lists (by setting it to []). At the end, take your list of df chunks and pd.concat them together.","Q_Score":1,"Tags":"python,pandas,dataframe","A_Id":62493142,"CreationDate":"2020-06-20T23:21:00.000","Title":"How to preallocate memory when creating pandas DataFrames","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working on multi-label image classification where some labels have very few images. How to handle these cases?","AnswerCount":3,"Available Count":1,"Score":0.0665680765,"is_accepted":false,"ViewCount":148,"Q_Id":62497352,"Users Score":1,"Answer":"Data augmentation, which means making 'clones' (reverse image\/ set different angle\/ etc.)","Q_Score":0,"Tags":"python,deep-learning,multilabel-classification","A_Id":62497465,"CreationDate":"2020-06-21T10:35:00.000","Title":"Class Imbalance for image classification","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to do a 1\/3rd octave band analysis of a noise signal. I have got a time signal representing sound pressure(Pa). I have arrays of the central frequencies and of the lower and upper cutoffs.The final aim is to get a bar chart representing sound level versus the 1\/3rd octave bands.\nFrom a theory that I followed suggested to first do FFT of the signal. Then reconstruct the signal in the 1\/3rd octave bands. In each of the construction, compute the RMS values of the pressure. That's it. Convert these RMS values into sound level(dB) and plot against the central frequencies.\nThe issue I am facing is how to reconstruct the signal using IFFT function given that the new signal has less number of amplitude points. So, the reconstruction is essentially not possible because of dimension inconsistency between time and amplitude. I am stuck at this point.\nI have a very little experience in DSP. So, any help even if the approach is different from what I tried explaining above will be much appreciated. Thanks in advance.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":417,"Q_Id":62498174,"Users Score":0,"Answer":"To reconstruct the time-domain signal for a particular 1\/3 octave band, you set the amplitude to zero for all the frequencies outside of your band before you do the IFFT. The IFFTs for each of those bands will be the same size as our original FFT, so you will end up with the same time resolution on output from each band.\nDoing a full-size IFFT for each band is obviously pretty expensive. There are ways to optimize this, but really there is probably no reason for you to be reconstructing the time-domain signal in the first place.\nThe IFFT operation1 will not change the RMS value of signal, so just calculate this using the frequency-domain components and forget about the IFFT altogether. Because of the way the RMS computation works, you don't even need to remember that the frequency-domain amplitudes are complex numbers -- you get a proportional answer if you treat the real and imaginary components the same way. Just don't forget to include all the extra zeros in the RMS divisor, since there are a different number of them for each band.\n1 - This is true for a mathematically standard IFFT. Some implementations will divide the outputs by the signal length. This will be the same for all bands, so it won't affect their relative values and it's easy to correct for.","Q_Score":1,"Tags":"python,signal-processing,fft,noise,time-frequency","A_Id":62500207,"CreationDate":"2020-06-21T11:56:00.000","Title":"1\/3rd Octave Band analysis of a noise signal","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Is there any quicker way to physically transpose a large 2D numpy matrix than array.transpose.copy()? And are there any routines for doing it with efficient memory use?","AnswerCount":3,"Available Count":1,"Score":0.0665680765,"is_accepted":false,"ViewCount":312,"Q_Id":62505938,"Users Score":1,"Answer":"Whatever you do will require O(n^2) time and memory. I would assume that .transpose and .copy (written in C) will be the most efficient choice for your application.\nEdit: this assumes you actually need to copy the matrix","Q_Score":1,"Tags":"python,numpy,matrix,linear-algebra,transpose","A_Id":62505960,"CreationDate":"2020-06-22T00:41:00.000","Title":"Physically transposing a large non-square numpy matrix","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to resolve a Linear Regression problem using TensorFlow & I came across this RuntimeError\n\"loss passed to Optimizer.compute_gradients should be a function when eager execution is enabled.\"\nafter execution of 'train = optimizer.minimize(loss)' in the below code :\na = tf.Variable(20.0)\nb = tf.Variable(30.2)\ny = a * train_x + b\nloss = tf.reduce_mean(tf.square(y - train_y))\noptimizer = tf.compat.v1.train.GradientDescentOptimizer(0.05)\ntrain = optimizer.minimize(loss)\nwhere train_x, train_y --> a set of array values from a column of data frame","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":500,"Q_Id":62510960,"Users Score":0,"Answer":"When eager execution is enabled, loss should be a Python function that takes no arguments and computes the value to be minimized.","Q_Score":0,"Tags":"python,tensorflow,linear-regression","A_Id":62510998,"CreationDate":"2020-06-22T09:09:00.000","Title":"`loss` passed to Optimizer.compute_gradients should be a function when eager execution is enabled. --> optimizer.minimize()","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have two sequences (x_t, y_t) in time and would like to perform a perform rolling linear regression. The problem in my mind is that:\n\nGiven a window size w, compute y the time t based on the linear combination of x within time window (t-w,...,t,...t+w). That is, y_t = sum_{i=t-w}^{t+w} b_i x_{i} + b_0,\n\nSo I would like to fit the constants b_i using my data.\n\nIs statsmodels.regression.rolling.RollingOLS the correct package to do that?\nThe problem is that it only gives me the predict values and parameters along the same time axis, i.e., y_hat_i and b_i for each t. Instead, I would like to have a small set of b that I can use it for x data at other time t.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":553,"Q_Id":62520659,"Users Score":0,"Answer":"Yes, it is the right package. However, the regression coefficients will vary a lot, however you can smooth them by taking moving averages (of the coefficients), and then sampling from the moving averages.","Q_Score":1,"Tags":"python,time-series,regression,statsmodels,rolling-computation","A_Id":62521177,"CreationDate":"2020-06-22T17:59:00.000","Title":"How to make predictions from the rolling regression module in statsmodel?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"In order to use the gensim.similarities.docsim.Similarity class to compute similarities between words, one need to provide the corpus and the size of the dictionary.\nIn my case, the corpus are the word vectors computed using a word2vec model.\nI wonder why gensim needs the size of the dictionary? And also, if it needs here the size of the dictionary used to create the word2vec model, or the size of the dictionary of the corpus, for which I want to compute the similarities.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":41,"Q_Id":62529967,"Users Score":1,"Answer":"Note that you don't need to use gensim.similarities.docsim.Similarity to calculate word-to-word similarities.\nThere are individual methods on the word-vector supporting objects for doing things like calculating similarity between 2 words (model.similarity(wordA, wordB)) or getting the list of most-similar 'neighbor' words (model.most_similar(target_word)).","Q_Score":0,"Tags":"python,nlp,gensim","A_Id":62540245,"CreationDate":"2020-06-23T07:55:00.000","Title":"Why computing similarity with gensim needs the size of the dictionary?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Is there any way to set the 'min_frequency' in tf.keras.preprocessing.text.tokenizer, just like the 'min_frequency' in tf.contrib.learn.preprocessing.VocabularyProcessor?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":132,"Q_Id":62530401,"Users Score":0,"Answer":"The num_words actually helps in doing the same thing, here num_words will take the top num_words words with the highest frequency.\nSo, the functionality you got from min_frequency in tf.contrib.learn.preprocessing.VocabularyProcessor you can get the same but not in the same way though.","Q_Score":0,"Tags":"python-2.7,tensorflow","A_Id":62532368,"CreationDate":"2020-06-23T08:20:00.000","Title":"How to set the min_frequency while using tf.keras.preprocessing.text.tokenizer and ignore the words which are less then min_frequency?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a dataframe with one of the column as timedelta64 dtype. The values appear to be fine in IDE but when I export the dataframe to excel using ExcelWriter and to_excel(), the values in the Excel are all 0. (It's actually not 0 but a very small floating points.)","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":29,"Q_Id":62530983,"Users Score":0,"Answer":"If you export the values to an .xls file do you get the same issue? XLS is a binary file format, not a collection of XML files. This should allow you to check whether this is a file format issue or not.","Q_Score":0,"Tags":"python,pandas","A_Id":62531156,"CreationDate":"2020-06-23T08:57:00.000","Title":"Python - Why does timedelta64 values appear as 0 in excel","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"im totally lost right now.\nI have a binomical function of a stock option. I have to plot the\nfunction for a given amount of times. I tried to plot it wi\nbh the help of a loop, but without success.\nAnyone got an idea how to solve this?","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":109,"Q_Id":62543722,"Users Score":0,"Answer":"I'm assuming you put the plt.show() inside the loop. This won't work, as it will only plot the plots of the first iteration.\nTry putting the plt.show() in the very bottom of your code.","Q_Score":1,"Tags":"python,loops,plot,options,stock","A_Id":62543788,"CreationDate":"2020-06-23T21:04:00.000","Title":"Plotting a graph of a function for n amount of times","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am learning how to use Alpha_Vantage api and came across this line of code. I do not understand what is the purpose of [0].\nSATS = ts.get_daily('S58.SI', outputsize = \"full\")[0]","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":107,"Q_Id":62546248,"Users Score":0,"Answer":"ts.get_daily() appears to return an array.\nSATS is getting the 0 index of the array (first item in the array)","Q_Score":0,"Tags":"python,alpha-vantage","A_Id":63682164,"CreationDate":"2020-06-24T01:35:00.000","Title":"Alpha_Vantage ts.get_daily ending with [0]","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have three classification models as follows where the labels of my data is 1 or 0.\n\nlstm model with some timeseries data that has one node as the output (i.e. model.add(Dense(1, activation='sigmoid'))) so my output is similar to [0.1, 0.1, 0.6, 0.9, ...]\ntraditional random forest with features set 1 - I am using sklearn's predict_proba: so my output is similar to [[0.9, 0.1], [0.8, 0.2], ...]\ntraditional random forest with features set 2 - I am using sklearn's predict_proba: so my output is similar to [[0.8, 0.2], [0.9, 0.1], ...]\n\nI want to combine the predictions of my three models to get one probability list that reflects my classification. I searched this in SO, however the suggestions like bagging and stacking is not possible for me as I am also using a lstm model in to consideration.\nI am wondering if there is any other way that I can use to combine these prediction probabilities in python.\nI am happy to provide more details if needed.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":451,"Q_Id":62547103,"Users Score":3,"Answer":"You can do one of two solutions, but first you need to make the representation of the output the same for the three models so for the second and third models\npred_2 = [y[0] for y in pred_2] to look like the first model. (y[0] or y[1] depending on the meaning of the probabilities in your first model).\nThe first solution is to make a majority voting by computing the average of the three lists\nmajority_voting = [v\/3.0 for v in[sum(x) for x in zip(pred_1, pred_2, pred_3)]]\nThe second solution is a little bit harder as you can use another deep learning model to make it choose the best result between the three models. You need to prepare the data_x as list that has three columns a column for each model output and data_y the same labels for your original data, by doing so you are letting the model to learn how to use the three models to predict the output instead of just majority voting.","Q_Score":0,"Tags":"python,machine-learning,scikit-learn,deep-learning,classification","A_Id":62547698,"CreationDate":"2020-06-24T03:24:00.000","Title":"How to combine the classification results of deep learning models and traditional machine learning models in python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I would like to use tensorflow with ROS and ROS 1 does only support python 2.7 at the moment.\nIs there a way to install tensorflow 1 or 2 for python 2.7?\nThanks","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":984,"Q_Id":62547864,"Users Score":0,"Answer":"The easiest way of using tensorflow is to download anaconda and then download the packages of anaconda!","Q_Score":0,"Tags":"python-2.7,tensorflow","A_Id":62547884,"CreationDate":"2020-06-24T04:49:00.000","Title":"How to install tensorflow for python 2?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I trained a deep learning-based detection network to detect and locate some objects. I also trained a deep learning-based classification network to classify the color of the detected objects. Now I want to combine these two networks to detect the object and also classify color. I have some problems with combining these two networks and running them together. How do I call classification while running detection?\nThey are in two different frameworks: the classifier is based on the Keras and TensorFlow backend, the detection is based on opencv DNN module.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":43,"Q_Id":62549254,"Users Score":0,"Answer":"I have read your question and from that, I can infer that your classification network takes the input from the output of your first network(object locator). i.e the located object from your first network is passed to the second network which in turn classifies them into different colors. The entire Pipeline you are using seems to be a sequential one. Your best bet is to first supply input to the first network, get its output, apply some trigger to activate the second network, feed the output of the first net into the second net, and lastly get the output of the second net. You can run both of these networks in separate GPUs.\nThe Trigger that calls the second function can be something as simple as cropping the located object in local storage and have a function running that checks for any changes in the file structure(adding a new file). If this function returns true you can grab that cropped object and run the network with this image as input.","Q_Score":0,"Tags":"python,classification,detection,yolo","A_Id":62549592,"CreationDate":"2020-06-24T06:47:00.000","Title":"how do I run two separate deep learning based model together?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a query with respect to using external libraries like delta-core over AWS EMR notebooks. Currently there isn\u2019t any mechanism of installing the delta-core libraries through pypi packages. The available options include.\n\nLaunching out pyspark kernel with --packages option\nThe other option is to change the packages option in the python script through os configuration, but I don\u2019t see that it is able to download the packages and I still get import error on import delta.tables library.\nThird option is to download the JARs manually but it appears that there isn\u2019t any option on EMR notebooks.\n\nHas anyone tried this out before?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":516,"Q_Id":62574687,"Users Score":0,"Answer":"You can download the jars while creating EMR using bootstrap scripts.\nYou can place the jars in s3 and pass it to pyspark with --jars option","Q_Score":0,"Tags":"python,amazon-web-services,amazon-emr","A_Id":62586305,"CreationDate":"2020-06-25T11:52:00.000","Title":"Accessing delta lake through Pyspark on EMR notebooks","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":1,"Web Development":0},{"Question":"I have a dataset, on which i am working on Data Cleaning part, where one of the attribute or feature is having the values with various units. for example some of the values are as follow.\n1 kg; 6 LB; 900 gms; 32 oz; etc.\nIf i use the standard scaler then it will not be fair as the values and their units are different, so cannot treat them as is.\nPlease do suggest how to handle such data.","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":52,"Q_Id":62585046,"Users Score":1,"Answer":"I will recommend to change the different value to same unit first of all. For example, you can make all the value to kg or whatever suits best for you, and then perform the standard scale.","Q_Score":0,"Tags":"python-3.x,pandas,data-manipulation","A_Id":62586121,"CreationDate":"2020-06-25T22:05:00.000","Title":"How to handle various units in a single attribute \/ feature using Pandas?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"We are ingesting data in Janusgraph on Kubernetes(GCP) using python. We are doing multithreading, node chaining, indexing but still we are able to ingest only 100k (Nodes) records in 60 minutes from bigquery.\nKubernetes spec - 1 Pod with 25 vCPUs and 150 GiB RAM\nids.block-size = 10 million\nthread pool - 16\nnode pool - 16\nheap size - 4 gb\nQuestions:\n\nAny more approach we can take to increase the ingestion performance, reducing the overall time.\n\nHow many multiple connections at a time we can create with Janusgraph via Python Driver. Currently we are able to create 30 threads(connections) but when we increase the number of threads the connection either stuck or performance goes down.\n\n\nAny details\/help will be highly appreciated\nGremlin Query: g.V().hasLabel(\"http:\/\/purl.uniprot.org\/core\/Helix_Annotation\").has(\"id\", \"http:\/\/purl.uniprot.org\/uniprot\/P06931#SIPC5C5063B7561AB45\").has(\"node_id\", \"http:\/\/purl.uniprot.org\/uniprot\/P06931#SIPC5C5063B7561AB45\").has(\"rdf_type\", \"http:\/\/purl.uniprot.org\/uniprot\/\").has(\"http:\/\/purl.uniprot.org\/core\/range\", \"http:\/\/purl.uniprot.org\/range\/22571007582875950tt125tt127\").fold().coalesce(unfold(), addV(\"http:\/\/purl.uniprot.org\/core\/Helix_Annotation\").property(\"id\", \"http:\/\/purl.uniprot.org\/uniprot\/P06931#SIPC5C5063B7561AB45\").property(\"node_id\", \"http:\/\/purl.uniprot.org\/uniprot\/P06931#SIPC5C5063B7561AB45\").property(\"rdf_type\", \"http:\/\/purl.uniprot.org\/uniprot\/\").property(\"http:\/\/purl.uniprot.org\/core\/range\", \"http:\/\/purl.uniprot.org\/range\/22571007582875950tt125tt127\")).V().hasLabel(\"http:\/\/www.w3.org\/1999\/02\/22-rdf-syntax-ns#Statement\").has(\"id\", \"http:\/\/purl.uniprot.org\/uniprot\/#_kb.P06931_up.annotation_FA85AD309172A9A7\").has(\"node_id\", \"http:\/\/purl.uniprot.org\/uniprot\/#_kb.P06931_up.annotation_FA85AD309172A9A7\").has(\"rdf_type\", \"http:\/\/purl.uniprot.org\/uniprot\/\").has(\"http:\/\/purl.uniprot.org\/core\/attribution\", \"http:\/\/purl.uniprot.org\/uniprot\/P06931#attribution-AE0E09C5B47CC2714C9061D3806995B4\").fold().coalesce(unfold(), addV(\"http:\/\/www.w3.org\/1999\/02\/22-rdf-syntax-ns#Statement\").property(\"id\", \"http:\/\/purl.uniprot.org\/uniprot\/#_kb.P06931_up.annotation_FA85AD309172A9A7\").property(\"node_id\", \"http:\/\/purl.uniprot.org\/uniprot\/#_kb.P06931_up.annotation_FA85AD309172A9A7\").property(\"rdf_type\", \"http:\/\/purl.uniprot.org\/uniprot\/\").property(\"http:\/\/purl.uniprot.org\/core\/attribution\", \"http:\/\/purl.uniprot.org\/uniprot\/P06931#attribution-AE0E09C5B47CC2714C9061D3806995B4\"))","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":80,"Q_Id":62587526,"Users Score":0,"Answer":"Have you tried using groovy scripts? I was able to insert ~5K nodes in ~10 sec single threaded into a janusgraph that has much lesser RAM and CPU.","Q_Score":4,"Tags":"google-cloud-platform,gremlin,janusgraph,gremlinpython,knowledge-graph","A_Id":62702269,"CreationDate":"2020-06-26T03:21:00.000","Title":"JanusGraph Data Ingestion atscale","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":1,"Web Development":0},{"Question":"before i have never working with synthetic dataset, but in my project I do not have enough dataset, that is why I want use hull synthetic dataset to my network. It is posible?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":23,"Q_Id":62587882,"Users Score":0,"Answer":"Yes sure, it is possible and widely used in machine learning when there is lack of dataset.","Q_Score":0,"Tags":"python,generative-adversarial-network","A_Id":62588212,"CreationDate":"2020-06-26T04:09:00.000","Title":"Training network with synthetic dataset","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to calculate the inverse of a 2d array in python that holds fractions and cannot convert it to float because I need to maintain the ratio correctly between numerator and denominator.\nA = np.array([[Fraction(1), Fraction(-0.5)],\n[Fraction(-4\/9), Fraction(1)]])\nWhen I try np.linalg.inv(A) I get the following error:\n'TypeError: No loop matching the specified signature and casting was found for ufunc inv'","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":204,"Q_Id":62595267,"Users Score":1,"Answer":"Fraction is a Python type but not a native numpy dtype. Said differently, for a numpy point of view, Fractions are (opaque) objects. If you manage to do operations over them with numpy methods, chances are that they will be automatically converted to floating point types (which are native in numpy).\nLong story short, no numpy vectorized method will be able to process Fraction objects, so you should not use np.array to store them but stick to a plain old list, or to lists of lists if you want to process 2D arrays.","Q_Score":0,"Tags":"python,numpy,fractions","A_Id":62595697,"CreationDate":"2020-06-26T12:59:00.000","Title":"How to calculate the inverse of ndarray holding variables of type Fraction in python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to fit quantile regression with statsmodels. The same code that works in my laptop fails in the cloud and says it does not have fit method. But in the documentation, I see it has fit method. What is causing it? I am using it inside zeppelin notebook.\n from statsmodels.regression.quantile_regression import QuantReg\nfrom statsmodels.tools.tools import add_constant\nX = temp[['X']]\ny = temp['y']\nX = add_constant(X)\nmod = QuantReg(y, X)\nres = mod.fit(q = 0.5)\n \nThis is the error message I am getting:\n\nAttributeError: 'Interactive' object has no attribute 'fit'","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":216,"Q_Id":62596493,"Users Score":1,"Answer":"It seems that the variable (mod) might have a namespace conflict internally within the statsmodel. Using a different name for mod variable to mod1 etc might help here.","Q_Score":0,"Tags":"python-3.x,statsmodels,quantile-regression","A_Id":62745865,"CreationDate":"2020-06-26T14:04:00.000","Title":"QuantReg:'Interactive' object has no attribute 'fit'","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to get the sum of the digits of an integer, and found the solutions below:\n\nsum(map(int,list(str(123))))\n\nsum(int(digit) for digit in str(123))\n\n\nHowever, when I run this, I get the below error:\n\nTypeError: 'int' object is not callable","AnswerCount":4,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":87,"Q_Id":62597880,"Users Score":2,"Answer":"Contrary to other answers, both your code works fine.\nI think you are shadowing something on your code. Perhaps you used int as a variable?","Q_Score":0,"Tags":"python,python-3.x,sum,int,typeerror","A_Id":62598281,"CreationDate":"2020-06-26T15:21:00.000","Title":"Sum of the digits","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm getting these weird errors in Google Colab when using TensorFlow, like:\n\nAttributeError: module 'tensorflow' has no attribute\n'reset_default_graph'\n\nor\n\nmodule 'tensorflow' has no attribute 'placeholder'\n\nHelp would appreciated.","AnswerCount":3,"Available Count":1,"Score":0.0665680765,"is_accepted":false,"ViewCount":2666,"Q_Id":62598537,"Users Score":1,"Answer":"Try using tf.compat.v1.placeholder and tf.compat.v1.reset_default_graph. If you have any more attribute errors, you can look at the tensorflow documentation.","Q_Score":0,"Tags":"python,tensorflow,google-colaboratory","A_Id":62598671,"CreationDate":"2020-06-26T16:00:00.000","Title":"module 'Tensorflow' has no atributte","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Ive got two separate models, one for mask recognition and another for face recognition. The problem now is that how do I combine these both models so that it performs in unison as a single model which is able to :-\n\nRecognize whether or not a person is wearing mask\nSimultaneously recognize who that person is if he isn't wearing mask apart from warning about no mask.\n\nWhat are the possibilities I have to solve this problem!!","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":42,"Q_Id":62600397,"Users Score":1,"Answer":"You don't have to combine the both models and train them you have to train them seprately. And after training the model first you have to check with the mask detection model what's the probability\/confidence score that there's a mask detected and if the probability is low say like 40%-45% then you have to use the other model that recognises the person.","Q_Score":0,"Tags":"python,machine-learning,deep-learning,computer-vision,face-recognition","A_Id":62601074,"CreationDate":"2020-06-26T17:58:00.000","Title":"How to train a model for recognizing two objects?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have been attempting to create a model that given an image, can read the text from it. I am attempting to do this by implementing a cnn, rnn, and ctc. I am doing this with TensorFlow and Keras. There are a couple of things I am confused about. For reading single digits, I understand that your last layer in the model should have 9 nodes, since those are the options. However, for reading words, aren't there infinitely many options, so how many nodes should I have in my last layer. Also, I am confused as to how I should add my ctc to my Keras model. Is it as a loss function?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":57,"Q_Id":62602511,"Users Score":0,"Answer":"I see two options here:\n\nYou can construct your model to recognize separate letters of those words, then there are as many nodes in the last layer as there are letters and symbols in the alphabet that your model will read.\nYou can make output of your model as a vector and then \"decode\" this vector using some other tool that can encode\/decode words as vectors. One such tool I can think of is word2vec. Or there's an option to download some database of possible words and create such a tool yourself.\nDescription of your model is very vague. If you want to get more specific help, then you should provide more info, e.g. some model architecture.","Q_Score":1,"Tags":"python,tensorflow,machine-learning,keras","A_Id":62602819,"CreationDate":"2020-06-26T20:38:00.000","Title":"model for hand written text recognition","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am learning about the Gradient Descent Algorithm and I implemented one such**(in python)** over the Boston Housing data set(in sklearn). I have implemented a cost function as well which takes in all the coefficients, the intercept and the training data and returns the cost for those coefficients and intercept. I ran the algorithm over the Boston data set for 1500 iterations and learning_rate = 0.000003202, and It converged successfully, giving the least cost as 61.840725406571245, but when I trained the sklearn's LinearRegression() algorithm over the same training data, and found the cost using .coef_ and .intercept_. It gave the least cost as 19.958219814238042. So My question is How can one say the a certain number of iterations, will give me the least\/optimal cost? Like say I run the algorithm for n times, and obtain a particular cost, then How will I know that this cost is good enough or do I need to reduce it further?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":1157,"Q_Id":62608927,"Users Score":0,"Answer":"You can use validation sets in training. They will be a better indicator for the testing phase of your model performance than only the training error. Also, your learning_rate is quite small, which can cause the model to converge in large number of iterations. You can play with those parameters to see how it effects your training.","Q_Score":0,"Tags":"python,machine-learning,regression,gradient-descent","A_Id":62609207,"CreationDate":"2020-06-27T10:44:00.000","Title":"Number of Iterations (Gradient Descent)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm still new to AWS ecosystem and doing a POC on certain components of aws. I have to match CSVs data with Redshift table data - col to col match. Can anybody direct me to point where I can get an idea how to execute above. Thanks in advance.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":251,"Q_Id":62618797,"Users Score":0,"Answer":"One way to do this can be like\n\nCreate a glue catalog (No cost)\nCreate external table using redshift query editor (Still no cost and no need to run crawler as well)\nNow you have the data as a table.\nCompare both the table one in your redshift cluster and another one is extenal table.\n\nThe only cost that will be incurred is of scanning the data while running query which is equal to 5$ per TB.","Q_Score":1,"Tags":"python,python-3.x,amazon-s3,amazon-redshift","A_Id":62636653,"CreationDate":"2020-06-28T05:57:00.000","Title":"Match CSV columns data sitting at S3 with Redshift table column data","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a program running on Google Colab in which I need to monitor GPU usage while it is running. I am aware that usually you would use nvidia-smi in a command line to display GPU usage, but since Colab only allows one cell to run at once at any one time, this isn't an option. Currently, I am using GPUtil and monitoring GPU and VRAM usage with GPUtil.getGPUs()[0].load and GPUtil.getGPUs()[0].memoryUsed but I can't find a way for those pieces of code to execute at the same time as the rest of my code, thus the usage numbers are much lower than they actually should be. Is there any way to print the GPU usage while other code is running?","AnswerCount":6,"Available Count":2,"Score":1.0,"is_accepted":false,"ViewCount":17260,"Q_Id":62620268,"Users Score":17,"Answer":"If you have Colab Pro, can open Terminal, located on the left side, indicated as '>_' with a black background.\nYou can run commands from there even when some cell is running\nWrite command to see GPU usage in real-time:\nwatch nvidia-smi","Q_Score":15,"Tags":"python,gpu,google-colaboratory","A_Id":65461405,"CreationDate":"2020-06-28T08:49:00.000","Title":"Display GPU Usage While Code is Running in Colab","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a program running on Google Colab in which I need to monitor GPU usage while it is running. I am aware that usually you would use nvidia-smi in a command line to display GPU usage, but since Colab only allows one cell to run at once at any one time, this isn't an option. Currently, I am using GPUtil and monitoring GPU and VRAM usage with GPUtil.getGPUs()[0].load and GPUtil.getGPUs()[0].memoryUsed but I can't find a way for those pieces of code to execute at the same time as the rest of my code, thus the usage numbers are much lower than they actually should be. Is there any way to print the GPU usage while other code is running?","AnswerCount":6,"Available Count":2,"Score":0.1325487884,"is_accepted":false,"ViewCount":17260,"Q_Id":62620268,"Users Score":4,"Answer":"There is another way to see gpu usage but this method only works for seeing the memory usage. Go to click runtime -> manage sessions. This allows you to see how much memory it takes so that you can increase your batch size.","Q_Score":15,"Tags":"python,gpu,google-colaboratory","A_Id":68175628,"CreationDate":"2020-06-28T08:49:00.000","Title":"Display GPU Usage While Code is Running in Colab","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Can anyone please explain the difference between generalized linear model and logistic regression model table with statsmodels. Why do I get different results with both the models while performing logistic regression??","AnswerCount":2,"Available Count":2,"Score":0.0996679946,"is_accepted":false,"ViewCount":859,"Q_Id":62622779,"Users Score":1,"Answer":"GLM is a generalized linear model and Logit Model is specific to models with binary classification. While using GLM model you have to mention the parameter family which can be binomial (logit model), Poisson etc. This parameter is not required in Logit model as its only for binary output. The difference in the output can be because of regularization parameters.","Q_Score":3,"Tags":"python-3.x,machine-learning,logistic-regression,statsmodels,glm","A_Id":65565144,"CreationDate":"2020-06-28T12:50:00.000","Title":"What is the difference between GLM and Logit model with statsmodels?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Can anyone please explain the difference between generalized linear model and logistic regression model table with statsmodels. Why do I get different results with both the models while performing logistic regression??","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":859,"Q_Id":62622779,"Users Score":0,"Answer":"GLM with Binomial family and Logit link and the discrete Logit model represent the same underlying model and both fit by maximum likelihood estimation\nImplementation, default optimization method, options for extensions and the availability of some results statistics differs between GLM and their discrete counterparts.\nFor regular, well defined cases and well behaved data, both model produce the same results, up to convergence tolerance in the optimization and numerical noise.\nHowever, the behavior of the estimation methods can differ in corner cases and for singular or near-singular data.\nRelated aside:\nFor models with non-canonical links using GLM there can be differences in the definitions used across optimization methods, e.g. whether standard errors are based on expected or observed information matrix. With canonical links like logit those two are the same.","Q_Score":3,"Tags":"python-3.x,machine-learning,logistic-regression,statsmodels,glm","A_Id":65572173,"CreationDate":"2020-06-28T12:50:00.000","Title":"What is the difference between GLM and Logit model with statsmodels?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've a dataset with 48 obs (monthly) and python have been able to fit the SARIMAX ((4, 1, 3), (3, 0, 5)) model... which to me seems quite odd. How does it calculates the B^(12*5) term and the subsequent ones since I have just 48 data points?\nI've also tried with ((0, 1, 4), (5, 0, 1)) and it works... Also, I've computed the MAPE agaist the next 12 periods and it's quite good (3% and 6%).\nThoughts?\nThank you","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":59,"Q_Id":62623481,"Users Score":1,"Answer":"Basically, estimation is done using the assumption that pre-sample observations are drawn from the unconditional distribution of the implied SARIMA process.\nSARIMAX models are estimated using a state space approach, and if you are a frequentist the this process is referred to as the \"initialization\" of the first state vector, while if you are a Bayesian then you would think of this as putting a particular prior on the first state vector (the state vector contains all the required lags of the process, so the \"initialization\", or prior, describes enough pre-sample observations to allow the model to be fit).\nWhile this is a perfectly reasonable approach to setting up the model so that it can be estimated, it doesn't necessarily mean that it is a good idea to specify a model with so many parameters and so few observations. Your estimates will begin to depend more on the prior rather than on the data.","Q_Score":1,"Tags":"python,statsmodels","A_Id":62650104,"CreationDate":"2020-06-28T13:53:00.000","Title":"Strange SARMAX fit with python statsmodels","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"What the difference between att_mask and key_padding_mask in MultiHeadAttnetion of pytorch:\n\nkey_padding_mask \u2013 if provided, specified padding elements in the key will be ignored by the attention. When given a binary mask and a value is True, the corresponding value on the attention layer will be ignored. When given a byte mask and a value is non-zero, the corresponding value on the attention layer will be ignored\n\n\nattn_mask \u2013 2D or 3D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all the batches while a 3D mask allows to specify a different mask for the entries of each batch.\n\nThanks in advance.","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":3279,"Q_Id":62629644,"Users Score":16,"Answer":"The key_padding_mask is used to mask out positions that are padding, i.e., after the end of the input sequence. This is always specific to the input batch and depends on how long are the sequence in the batch compared to the longest one. It is a 2D tensor of shape batch size \u00d7 input length.\nOn the other hand, attn_mask says what key-value pairs are valid. In a Transformer decoder, a triangle mask is used to simulate the inference time and prevent the attending to the \"future\" positions. This is what att_mask is usually used for. If it is a 2D tensor, the shape is input length \u00d7 input length. You can also have a mask that is specific to every item in a batch. In that case, you can use a 3D tensor of shape (batch size \u00d7 num heads) \u00d7 input length \u00d7 input length. (So, in theory, you can simulate key_padding_mask with a 3D att_mask.)","Q_Score":12,"Tags":"python,deep-learning,pytorch,transformer,attention-model","A_Id":62633542,"CreationDate":"2020-06-29T00:31:00.000","Title":"what the difference between att_mask and key_padding_mask in MultiHeadAttnetion","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working on Audio Classification and using Spectrograms and MFCC plots im order to train CNN image classifier. Currently, I have two separate ConvNets trained on these features giving average ( 55-60% accuracy ). I have two separate weight files for each model.\nNow I want to combine the two models i.e. I want to extract Spectrograms and MFCC from each audio file and test on my already built models and get higher accuracy. How can I do that?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":146,"Q_Id":62631685,"Users Score":1,"Answer":"One way to combine already trained models would be to use a common fully-connected layer and train the network.\nYou can place this fully-connected layer at the end of both the convolutional models.\nSo, input will go into ConVModel-1 and ConvModel-2. You will get 2 output vectors. Combine these 2 output vectors (concatenate, average, etc.). Now pass this newly formed vector to the fully connected layer.\nYou can now train this network in 2 ways -\n\nUpdate weights for only the FC layer.\nUpdate weights for FC layer + both the ConvModels.","Q_Score":1,"Tags":"python,image,tensorflow,conv-neural-network,audio-processing","A_Id":62631893,"CreationDate":"2020-06-29T05:20:00.000","Title":"Combining Convolution Neural Network","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"2 questions :\n\nWhen we delete\/drop a dataframe and use gc.collect(), Does the python empty the ram occupied?\n\nif we do df.to_csv(filename), will that df be referring to the file after that or the data still being referred from in-memory(RAM)?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":37,"Q_Id":62632339,"Users Score":0,"Answer":"When we delete\/drop a dataframe and use gc.collect(), Does the python empty the ram occupied?\n\n\nYes, it will be empty space in the RAM.\n\n\nIf we do df.to_csv(filename), will that df be referring to the file after that or the data still being referred from in-memory(RAM)?\nNo, it will be not refer from the file it will still refer to the df variable.","Q_Score":0,"Tags":"python,pandas,memory,ram","A_Id":62632853,"CreationDate":"2020-06-29T06:22:00.000","Title":"Python Pandas memory management","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Are there any rules when it comes to determining the Order and the Seasonal Order in a SARIMA?\nI have noticed that when I use StatsModels in Python I can't choose a seasonal lag that is below or equal to the number of AR lags.\nExample:\nI am running a SARIMA with order (3,1,3) and seasonal order (3,1,3,3).\nThis generates an error: ValueError: Invalid model: autoregressive lag(s) {3} are in both the seasonal and non-seasonal autoregressive components.","AnswerCount":1,"Available Count":1,"Score":0.6640367703,"is_accepted":false,"ViewCount":973,"Q_Id":62634182,"Users Score":4,"Answer":"Specifying an order of (3, *, *) includes lags 1, 2, and 3\nSpecifying a seasonal order of (3,,,3) includes lags 3, 6, 9, and 12.\n\nBy specifying this model, you would be including the third lag twice, which can cause numerical problems when estimating the parameters.\nInstead, you should specify: order=(2, 1, 3) and seasonal_order=(3, 1, 3, 3). Then you will include the third lag as you want, but you won't have a duplicate.","Q_Score":2,"Tags":"python,time-series,arima","A_Id":62650035,"CreationDate":"2020-06-29T08:34:00.000","Title":"Are there any rules when it comes to determining the Order and the Seasonal Order in a SARIMA?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a dataframe which has 10 000 rows.\nI need to extract the rows into a new dataframe according to a condition (where name is in name_list)\nWhat is the easiest way to do this","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":32,"Q_Id":62640558,"Users Score":1,"Answer":"Let's say this is your dataframe structure and name:\ndataframe = pd.DataFrame(record, columns = ['Name', 'Age', 'Stream', 'Percentage']\nAccordingly, the new dataframe can be created as :\nrslt_df = dataframe[dataframe['Name'].isin(name_list)]\nalternatively, you can use :\nrslt_df = dataframe.loc[dataframe['Name'].isin(name_list)]","Q_Score":0,"Tags":"python,dataframe","A_Id":62640912,"CreationDate":"2020-06-29T14:40:00.000","Title":"Python: Append from one dataframe to a new dataframe","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"How do I install a specific version of tensorflow on windows ?(I'm using pip 20.1.1 and python 3.8)\nI've tried the command\npip install tensorflow==1.14.0 \nI get the following error\n\nERROR: Could not find a version that satisfies the requirement\ntensorflow==1.14.0 (from versions: none) ERROR: No matching\ndistribution found for tensorflow==1.14.0\n\nI've also tried using to install it by downloading the .whl file by running the command\npip install C:\\Users\\Admin\\Downloads\\tensorflow-1.14.0-cp37-cp37m-win_amd64.whl\nHere I get this error\n\nERROR: tensorflow-1.14.0-cp37-cp37m-win_amd64.whl is not a supported\nwheel on this platform.","AnswerCount":2,"Available Count":1,"Score":-0.0996679946,"is_accepted":false,"ViewCount":401,"Q_Id":62641686,"Users Score":-1,"Answer":"So far, Tensorflow isn't supported for Python v3.8\nTo make use of tensorflow, you need to download previous versions of python.\nAbout the wheel file you downloaded a file for v3.7 and trying to install with v3.8 which is why you get is not a supported wheel on this platform.\nEDIT:\nPython 3.8 supports Tensorflow v2 but not v1.","Q_Score":0,"Tags":"python,tensorflow,pip","A_Id":62641979,"CreationDate":"2020-06-29T15:38:00.000","Title":"Installing previous version of tensorlfow on windows using pip","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to split my dataset to training and validation sets I don't know whether I should split the dataset before applying pca dimensionality reduction or after pca to avoid leakage of data.\nAny help would be appreciated.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":82,"Q_Id":62643565,"Users Score":1,"Answer":"The dataset should split before applying PCA to avoid leakage of data","Q_Score":2,"Tags":"python,validation,deep-learning,conv-neural-network,training-data","A_Id":62701465,"CreationDate":"2020-06-29T17:27:00.000","Title":"When I can split my dataset into training and validation set before PCA or after PCA?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"My question is: imagine you have a list of length 484 and each element of the list is also a list of length of 484. Basically these lists in the list are going to be the rows in my matrix. I was wandering how can I plot this matrix and the color it based on the values of the matrix.\nThank you in advance.","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":72,"Q_Id":62647761,"Users Score":1,"Answer":"You can use:\nplt.matshow(my_list)\nThis would work for your nested list but in general you can convert your nested list into a matrix by calling:\nmy_array = np.asarray(my_list)","Q_Score":0,"Tags":"python,matplotlib,matrix","A_Id":62648465,"CreationDate":"2020-06-29T22:47:00.000","Title":"How to create a matrix colored plot from a list of lists (Python)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a question. Suppose I run a python script on the server where my data are stored. What is the faster way to have a spark dataframe of my data between :\n\nMake a complex query with lot of conditions but it return me the exact dataframe I need or\nMake a simple query and make the dataframe I need with .filter \/ .select\n\nYou can also suppose that the dataframe I need is small enough to fit on my RAM.\nThanks","AnswerCount":3,"Available Count":3,"Score":0.0,"is_accepted":false,"ViewCount":239,"Q_Id":62652101,"Users Score":0,"Answer":"First of all I think we should be careful when dealing with small data in our Spark programs. It was designed to give you parallel processing for big data.\nSecond, we have something like Catalyst query optimizer and lazy evaluation, which is a good tool for Spark to optimize everything what was put either in SQL query or API call transformations.","Q_Score":4,"Tags":"python,sql,apache-spark,pyspark","A_Id":62652604,"CreationDate":"2020-06-30T07:13:00.000","Title":"Do we must make a complex query in PySpark or a simple, and use .filter \/ .select?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a question. Suppose I run a python script on the server where my data are stored. What is the faster way to have a spark dataframe of my data between :\n\nMake a complex query with lot of conditions but it return me the exact dataframe I need or\nMake a simple query and make the dataframe I need with .filter \/ .select\n\nYou can also suppose that the dataframe I need is small enough to fit on my RAM.\nThanks","AnswerCount":3,"Available Count":3,"Score":0.1325487884,"is_accepted":false,"ViewCount":239,"Q_Id":62652101,"Users Score":2,"Answer":"IIUC, everything depends on from where you are reading the data, So here are some scenarios\nDataSource: RDBMS(oracle, postgres, mysql....)\nIf you want to read data from RDBMS system then you have to establish a JDBC connection to the database then fetch the results.\nNow remember spark is slow when fetching data from relational databases over JDBC and it is recommended you filter most of your records on database side itself as it will allow the minimum data to be transferred over the network\nYou can control the read speed using some tuning parameters but it is still slow.\nDataSource: Redshift, Snowflake\nIn this scenario if your cluster is large and relatively free then pushdown the query to the cluster itself or if you want to read data using JDBC then it is also fast as BTS it unloads the data to a temp location and then spark reads it as file source.\nDataSource: Files\nAlways try to pushdown the filter as they are there for a reason, so that your cluster needs to do the minimum work as you are reading only the required data.\nBottom line is that you should always try to pushdown the filters on the source to make your spark jobs faster.","Q_Score":4,"Tags":"python,sql,apache-spark,pyspark","A_Id":62652857,"CreationDate":"2020-06-30T07:13:00.000","Title":"Do we must make a complex query in PySpark or a simple, and use .filter \/ .select?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a question. Suppose I run a python script on the server where my data are stored. What is the faster way to have a spark dataframe of my data between :\n\nMake a complex query with lot of conditions but it return me the exact dataframe I need or\nMake a simple query and make the dataframe I need with .filter \/ .select\n\nYou can also suppose that the dataframe I need is small enough to fit on my RAM.\nThanks","AnswerCount":3,"Available Count":3,"Score":0.0665680765,"is_accepted":false,"ViewCount":239,"Q_Id":62652101,"Users Score":1,"Answer":"The key points to mind is\n\nRestrict\/filter data to maximum possible level while loading into dataframe, so as only needed data resides in dataframe\nfor non file sources: filtering data at source by using native filter and fetching only needed columns (aim for minimum data transfer).\nfor file sources: restricting\/modifying data in file source is not feasible. so the first operation is to filter data once loaded\n\nIn complex operations first perform narrow transformations (filters, selecting only needed columns) and then perform wide transformations(joins, ordering) which involves shuffle towards the end, so that less data will be shuffled between worker nodes.\n\n\nThe less the shuffles the faster your end dataframe would be.","Q_Score":4,"Tags":"python,sql,apache-spark,pyspark","A_Id":62655260,"CreationDate":"2020-06-30T07:13:00.000","Title":"Do we must make a complex query in PySpark or a simple, and use .filter \/ .select?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using FB Prophet to do time-series forecast. I added two features--discount and promotion, and add holiday effect. The model fits well. But I want to get the feature importance to check how much contribution of 2 features. It seems FB Prophet does not have the feature importance function like other machine learning models \"model.feature_importances_\".\nIn FB Prophet, I can get the \"forecast\" dataframe, which contains :\ntrend\nyhat_lower\nyhat_upper\ntrend_lower\ntrend_upper\ndiscount_x\ndiscount_lower\ndiscount_upper\nextra_regressors_multiplicative\nextra_regressors_multiplicative_lower\nextra_regressors_multiplicative_upper\nholidays holidays_lower\nholidays_upper\nmultiplicative_terms multiplicative_terms_lower\nmultiplicative_terms_upper\npromotion_x\npromotion_lower\npromotion_upper\npromotion_Day\npromotion_Day_lower\npromotion_Day_upper\nweekly\nweekly_lower\nweekly_upper\nadditive_terms\nadditive_terms_lower\nadditive_terms_upper\nyhat\ny\nIn that case, how can I analyze the feature importance?\nTHANK YOU!","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":1345,"Q_Id":62654951,"Users Score":0,"Answer":"Use SHAP to get it. It will tell you what are the features and how much it is contributing on individual level as well.","Q_Score":3,"Tags":"python,machine-learning,time-series,facebook-prophet","A_Id":67316330,"CreationDate":"2020-06-30T10:04:00.000","Title":"How to get feature importance of FB prophet?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Suppose I have trained a neural network that takes some inputs and accurately calculates their value. This neural network was used to approximate a function that was hard to solve analytically or to simulate using other methods. It is a very accurate function approximator. Now I would like to know what the best inputs are that will return the highest value. I was thinking that I could do this with a genetic algorithm but is there a neural network method of doing this? Also is it possible to train the neural network and find the optimal inputs simultaneously? What kind of network architecture could do this?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":196,"Q_Id":62666620,"Users Score":1,"Answer":"Well, a direct solution would be to apply calculus to each of the layers and solve for any local minimums or maximums (assuming that you don't have that many variables). But I don't think this solution (or similar optimization methods) would be a proper use of neural networks.\nNeural networks are designed to copy-cat. Give input X and expected output Y, optimize a function that guesses \"close\" to Y. This is the nature of a neural network. An isolated optimization problem asks a fundamentally different question. Given a body of data that approximates some underlying function, find the single \"best\" solution. Such problem is looking for a single case (or isolated discrete cases) amoungst a collection of data.\nIf you want to phrase an optimization problem in terms of a neural network solution it would look like this. Given a collection of approximated functions (millions of trained neural networks) and known optimized solutions (the expected solutions for each one), train a new neural network that mimics this behavior. This can certainly be done, but the collection of functions of interest would need some kind of bounds; it would certainly not be possible to train a single neural network that applies \"universally\" to all possible optimization problems. That would solve the entire field of optimization theory.\nFor example, given a collection of functions of the form Asin(Bx+C)+D for a random distribution of A, B, C, and D; find the maximum. Or count the number of maximum and minimum. These are great examples of something a neural network could learn to do, on unseen functions from the dataset. The neural network, might even learn the underlying behavior so well that it works with coefficients outside the initial dataset too.\nOf course, one could start building a massive collection of optimization neural networks that applies in millions of different cases for all kinds of different problems. Such \"neural network zoo\" could solve all of optimization theory.","Q_Score":2,"Tags":"python,tensorflow,keras,deep-learning,neural-network","A_Id":62668130,"CreationDate":"2020-06-30T21:47:00.000","Title":"Neural network for optimization problems","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using RASA NLU (open source), but I am concerned about data privacy. I want my data to be private, and wanted to ensure that none of my data ever leaves my machine, connects to Rasa's servers (or any servers other than my own \u2014- only running locally), and nothing goes to the cloud. I want all my data to be private and local until deployment. Is this true of Rasa NLU?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":44,"Q_Id":62667655,"Users Score":0,"Answer":"Yes, this is true. If you spin up an NLU server on a machine you have control over, no NLU data will go to any cloud server. Rasa specifically supports deploying an assistant (or just an NLU server) either on premise, or in the cloud (which also, incidentally, will not share your data unless you choose to do so - it's just another place to spin up a server), so it is up to you. There are no \"Rasa servers\" in the sense of servers providing the Rasa service unless you bring one up.","Q_Score":0,"Tags":"python,nlp,artificial-intelligence,rasa-nlu","A_Id":62756008,"CreationDate":"2020-06-30T23:40:00.000","Title":"Data Privacy Rasa NLU","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"So I saved my trained machine learning model as pickle in github, but I can't find a way to access it yet? Anyone have a suggestion?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":262,"Q_Id":62669501,"Users Score":0,"Answer":"Clone the github repository it's in and run pickle.load to load the pickle file.","Q_Score":0,"Tags":"python,machine-learning,github,pickle,github-pages","A_Id":62669532,"CreationDate":"2020-07-01T04:03:00.000","Title":"Accessing Saved Pickle Model in github","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am currently following a tutorial for my project when it starts using the OneHotEncoder. When he inputs the following code:\ntype_one_hot = OneHotEncoder(sparse=False).fit_transform(\nreview_df.review_type.to_numpy().reshape(-1, 1))\nprint(type_one_hot[0])\nhe gets an output of:\narray([0., 1.])\nwhereas when I run the code I just get:\n[0. 1.]\nThis matters for later on as when I later input using this style it complains that my input is not a vector. Any ideas?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":21,"Q_Id":62680377,"Users Score":0,"Answer":"It is pretty clear that what you have is a list and the tutorial is producing an array but can you check what type the values in your list are and it would help to know what these variables hold: review_df.review_type","Q_Score":0,"Tags":"python,one-hot-encoding","A_Id":62681046,"CreationDate":"2020-07-01T15:37:00.000","Title":"OneHotEncoder input not working as an array","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am training a neural network in parallel on 2 GPUs using the Tensorflow MirroredStrategy. With a single GPU, each epoch takes 19 seconds to complete whereas with 2 GPUs, each epoch takes 13 seconds to finish. I am not surprised at this since I know the scaling is not perfect due to the all_reduce overhead for updating the variables during training.\nHowever, after each epoch of the distributed training, there is a pause of about 8 seconds. When using a single GPU, this pause is less than 1 second. Does anyone know why there is such a long pause after each epoch when training distributed?\nAlternatively, can anyone explain what happens differently in distributed training at the end of an epoch?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":102,"Q_Id":62683947,"Users Score":0,"Answer":"Apparently this had something to do with running TF in graph mode. By setting tf.compat.v1.enable_eager_execution() the problem went away. This also fixed a memory leak that was causing issues, so perhaps the pause was being caused by TF making copies of something that I wasn't expecting.","Q_Score":0,"Tags":"python,tensorflow2.0","A_Id":62717644,"CreationDate":"2020-07-01T19:17:00.000","Title":"Tensorflow distributed training pause after each epoch","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"AttributeError: Can't get attribute 'DeprecationDict' on \nShowing error in model = pickle.load(open('rf_regression_model.pkl', 'rb')) this line.","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":1663,"Q_Id":62702362,"Users Score":2,"Answer":"You used a new version of sklearn to load a model which was trained by an old version of sklearn.\nSo, the options are:\n\nRetrain the model with current version of sklearn if you have the\ntraining script and data\nOr fall back to the lower sklearn version\nreported in the warning message","Q_Score":0,"Tags":"python,machine-learning,scikit-learn,pickle","A_Id":63251293,"CreationDate":"2020-07-02T17:55:00.000","Title":"Getting 'AttributeError: Can't get attribute 'DeprecationDict' on and I installed that on my Ubuntu Server, but it gives me the AVX error. I tried the 1.5 version and it works but doesn't support Keras and the other commands I used. I am using python3.5. There are no errors in the code.\nOS: Ubuntu Server on a Server with 16GB ram\nPip: 19.0\nPython: 3.5.9","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":1814,"Q_Id":62747937,"Users Score":3,"Answer":"To fix this, you can install TensorFlow via anaconda and not pip. It work for me by doing this. If anybody knows why, they are welcome to explain.","Q_Score":2,"Tags":"python-3.x,linux,tensorflow,pip,avx","A_Id":62778317,"CreationDate":"2020-07-06T01:13:00.000","Title":"Tensorflow 2.2.0 support on non-AVX systems","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":1,"Web Development":0},{"Question":"In my case, I would like to weekly tune\/adjust the model parameters value.\nI have pre-trained the model by using the 100K data rows, Keras, and saved the model.\nThen, as the new data collection (10K data rows), I need to tune the model parameter but don't want to retrain the whole dataset (110K).\nHow can I just partially fit the data on the model? load model -> model.fit(10K_data)?","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":260,"Q_Id":62748756,"Users Score":2,"Answer":"Yes, that is correct you will train only on the new dataset (10k) model.fit(10K_data). I will recommend to change the learning rate for the retraining (reducing the learning rate) as you will just want to do a minor update to the parameters while keeping the earlier learning intact (or trying to leavarage the earlier learning).","Q_Score":1,"Tags":"python,tensorflow,keras","A_Id":62749453,"CreationDate":"2020-07-06T03:17:00.000","Title":"How to partial training on the additional data for pre-trained model?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I need to upload a csv file from my local to an existing project in Watson Studio using python.\nThanks in Advance.","AnswerCount":1,"Available Count":1,"Score":-0.3799489623,"is_accepted":false,"ViewCount":202,"Q_Id":62751319,"Users Score":-2,"Answer":"Go to Resource List > Click on Services > Db2 > Open Console > Click on Hand Burger Icon on right > Click on Load > Open Load Data > Upload your CSV File > using Drag n drop or browser","Q_Score":0,"Tags":"python,python-requests,ibm-watson,watson-studio","A_Id":62814372,"CreationDate":"2020-07-06T07:37:00.000","Title":"Upload asset(csv file) to watson studio project using python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":1},{"Question":"Have a flask api, everytime a endpoint is called triggers a job in Spark, open a Session which I close when it's done.\nThe job itself takes less than 2 Minutes.\nI start the session and close it everytime the method is called.\nIs it better to start a single Session and keep it always alive or just open and kill it everytime?\nThanks","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":114,"Q_Id":62753897,"Users Score":1,"Answer":"This will cause issue if you recieve bulk requests then multiple spark session will be created with the same resources.\nBetter keep the spark session running and serve the request using the same","Q_Score":1,"Tags":"python,apache-spark,pyspark","A_Id":62754480,"CreationDate":"2020-07-06T10:15:00.000","Title":"Best practices for Sparkessions Pyspark","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":1},{"Question":"I would like to connect the OLAP Cube through python.\n\n(First)Basically I would like to import data from OLAP Cube.\n(Second)And import columns through DAX is there any way to run DAX formula in Python.\n\nI'm ok if python doesn't have any option for DAX. However at least I would like to import data from OLAP Cube.\nPlease assist me with the code or guide me. Let me know if you need more information.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":244,"Q_Id":62760356,"Users Score":0,"Answer":"You can use Cubes. Cubes is a light-weight Python framework and set of tools for development of reporting and analytical applications, Online Analytical Processing (OLAP), multidimensional analysis and browsing of aggregated data.","Q_Score":0,"Tags":"python,data-connections","A_Id":62760894,"CreationDate":"2020-07-06T16:24:00.000","Title":"Python data connection OLAP\/Cube","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I don't know for what reasons I am getting this error while installing Numpy in Pycharm. Although I have already installed Numpy in my system which is Windows based with the help of command prompt. But still I am still getting this error and also I have latest version of Pycharm.\nRuntimeError: Broken toolchain: cannot link a simple C program\nCan somebody help me?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":82,"Q_Id":62763104,"Users Score":0,"Answer":"To properly install Numpy in Pycharm, you have to go to File\/Settings\/Project Interpreter click on add and search for numpy in the search bar.\nClick on install package, it should run and install with no problem","Q_Score":0,"Tags":"python,python-3.x,numpy,installation,pycharm","A_Id":62763168,"CreationDate":"2020-07-06T19:26:00.000","Title":"Problems in installing Numpy in Pycharm","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am doing a sparse-matrix multiplication A^-1@B in Python within scipy.sparse. Both A and B are stored in csc format. The size of A and B is around 1E+6 x 2E+5 and 1E+6 x 1E+6. My intuition tells me I shouldn't invert A but use scipy.sparse.spsolve alternatively. But spsolve(A,B) gives me memory issue. I also try iterative solver like gmres and cg. But since the result from such an iterative solver is usually dense, the memory issue still shows up. Does anybody know if there is an appropriate way to solve this large-scale problem? Many thanks to you guys!","AnswerCount":2,"Available Count":1,"Score":-0.0996679946,"is_accepted":false,"ViewCount":324,"Q_Id":62764490,"Users Score":-1,"Answer":"It is possible to multiply large matrices using a deep neural network which is designed to predict the result of essentially a matrix factorization-like model. Piecemeal computation is the benefit, making the memory size not a problem. Your labels for supervised will be computed dynamically because you can predict perfectly the exact result of each dot product. Maybe no learning per se is needed, not sure, because your problem is actually solved as soon as you compute the labels. Tensorflow2 is good for this.\nThere is probably something COTS that already does what you need if you look more, so you probably won't need to go through the effort of making the thing I described.","Q_Score":2,"Tags":"python,numerical-methods,scientific-computing","A_Id":62766537,"CreationDate":"2020-07-06T21:03:00.000","Title":"Solving large-scale sparse matrix equation","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"In cvxpy, I want to express a perspective of log function, which has the form: x*log(1 + y\/x). This can be easily implemented in cvx by using rel_entr(). But I found that rel_entr() is not supported in cvxpy. Is there any way to write this perspective?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":162,"Q_Id":62768324,"Users Score":0,"Answer":"I have figured it out. We can use kl_div() in cvxpy to transform, i.e., -kl_div(x, x+y) + y.","Q_Score":0,"Tags":"python,cvxpy","A_Id":62768555,"CreationDate":"2020-07-07T04:49:00.000","Title":"How to write a perspective of log function in cvxpy?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have my dataset in a TensorFlow Dataset pipeline and I am wondering how can I normalize it, The problem is that in order to normalize you need to load your entire dataset which is the exact opposite of what the TensorFlow Dataset is for.\nSo how exactly does one normalize a TensorFlow Dataset pipeline? And how do I apply it to new data? (I.E. data used to make a new prediction)","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":1604,"Q_Id":62772571,"Users Score":1,"Answer":"You do not need to normalise the entire dataset at once.\nDepending on the type of data you work with, you can use a .map() function whose sole purpose is to normalise that specific batch of data you are working with (for instance divide by 255.0 each pixel within an image.\nYou can use, for instance, map(preprocess_function_1).map(preprocess_function_2).batch(batch_size), where preprocess_function_1 and preprocess_function_2 are two different functions that preprocess a Tensor. If you use .batch(batch_size) then the preprocessing functions are applied sequentially on batch_size number of elements, you do not need to alter the entire dataset prior to using tf.data.Dataset()","Q_Score":1,"Tags":"python,tensorflow,machine-learning,keras,tensorflow-datasets","A_Id":62772780,"CreationDate":"2020-07-07T09:52:00.000","Title":"how does one normalize a TensorFlow `Dataset` pipeline?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Imagine, that I have a 28 x 28 size grayscale image.. Now if I apply a Keras Convolutional layer with 3 filters and 3X3 size with 1X1 stride, I will get 3 images as output. Now if I again apply a Keras Convolutional layer with only 1 filter and 3X3 size and 1X1 stride, so how will this one 3X3 filter convolute over these 3 images and then how will we get one image..\nWhat I think is that, the one filter will convolute over each of the 3 images resulting in 3 images, then it adds all of the three images to get the one output image.\nI am using tensorflow backend of keras. please excuse my grammar, And Please Help me.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":46,"Q_Id":62787503,"Users Score":0,"Answer":"Answering my own question:\nI figured out that the one filter convolutes over 3 images, it results in 3 images, but then these these images pixel values are added together to get one resultant image..\nYou can indeed check by outputting 3 images for 3 filters on 1 image. when you add these 3 images yourself (matrix addition), and plot it, the resultant image makes a lot of sense.","Q_Score":0,"Tags":"python-3.x,tensorflow,keras,conv-neural-network","A_Id":62828300,"CreationDate":"2020-07-08T04:22:00.000","Title":"How do we get the output when 1 filter convolutes over 3 images?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to convert a Pyspark dataframe to Python list with 140000 rows. I am doing it using toLocalIterator() but it is taking a lot of time. How do i fasten this process?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":95,"Q_Id":62788966,"Users Score":0,"Answer":"Using toLocalIterator() will eliminate parrallesim . It will work on one partition on driver node one by one. Based on use cases and size of data you can do collect or save file. If you add details can explore more options.","Q_Score":0,"Tags":"python,apache-spark,pyspark,apache-spark-sql,pyspark-dataframes","A_Id":62797531,"CreationDate":"2020-07-08T06:41:00.000","Title":"How to improve performance of toLocalIterator() in Pyspark","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm working on a dataset and the data is provided to us in a .data file. is there any direct function like read_csv or read_excel?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":47,"Q_Id":62791172,"Users Score":0,"Answer":"No. A .data file could be absolutely anything.\nUse the file utility to try to identify the file format, or better yet ask the party you got the data from what it is.","Q_Score":1,"Tags":"python,pandas,numpy,dataframe,machine-learning","A_Id":62791229,"CreationDate":"2020-07-08T09:00:00.000","Title":"Is there a python pandas function to directly read .data file?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm working on a neural network to predict scores on how \"good\" the images are. The images are the inputs to another machine learning algorithm, and the app needs to tell the user how good the image they are taking is for that algorithm.\nI have a training dataset, and I need to rank these images so I can have a score for each one for the regression neural network to train.\nI created a program that gives me 2 images from the training set at a time and I will decide which one wins (or ties). I heard that the full rank can be obtained from these comparisons using SVM Ranking. However, I haven't really worked with SVMs before. I only know the very basics of SVMs. I read a few articles on SVM Ranking and it seems like the algorithm turns the ranking problem to a classification problem, but the maths really confuses me.\nCan anyone explain how it works in simple terms and how to implement it in Python?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":126,"Q_Id":62792094,"Users Score":0,"Answer":"I did some more poking around on the internet, and found the solution.\nThe problem was how to transform this ranking problem to a classification problem. This is actually very simple.\nIf you have images (don't have to be images though, can be anything) A and B, and A is better than B, then we can have (A, B, 1). If B is better, then we have (A, B, -1)\nAnd we just need a normal SVM to take the names of the 2 images in and classify 1 or -1. That's it.\nAfter we train this model, we can give it all the possible pairs of images from the dataset and generating the full rank will be simple.","Q_Score":0,"Tags":"python,svm,ranking","A_Id":62813295,"CreationDate":"2020-07-08T09:52:00.000","Title":"How to rank images based on pairs of comparisons with SVM?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm testing Conv, GRU, LSTM and simple Dense and I don't get 70 to 80%\nMy network converges very fast and overfits in the first seasons, could it be the data?\nLayer (type) Output Shape Param #\nlstm_46 (LSTM) (None, 65, 32) 6272\n\ndropout_67 (Dropout) (None, 65, 32) 0\n\nbidirectional_20 (Bidirectio (None, 65, 64) 16640\n\ndropout_68 (Dropout) (None, 65, 64) 0\n\nlstm_48 (LSTM) (None, 32) 12416\n\ndropout_69 (Dropout) (None, 32) 0\n\nflatten_28 (Flatten) (None, 32) 0\n\ndense_73 (Dense) (None, 10) 330\n\nactivation_72 (Activation) (None, 10) 0\n\ndense_74 (Dense) (None, 1) 11\n\nactivation_73 (Activation) (None, 1) 0\nTotal params: 35,669\nTrainable params: 35,669\nNon-trainable params: 0","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":51,"Q_Id":62797061,"Users Score":0,"Answer":"It's hard to say without knowing more about the data. Some of the possible solutions can be -\n\nUse a shallower network\nGet more training data\nMake sure your training and validation set comes from the same distribution","Q_Score":1,"Tags":"python,machine-learning,deep-learning,nlp,lstm","A_Id":62797185,"CreationDate":"2020-07-08T14:26:00.000","Title":"What to do when overfitting does not improve using regularization and droppout?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"i am using tensorflow 2.2 in virtualenv, i tried to import imread, imresize from from scipy.misc but got this error\nfrom scipy.misc import imread, imresize\nwhen i checked for the reason online, i figured out that scipy.misc is deprecated with the version of scipy required in tf2.2.\nSo i tried using imageio but getting error of PIL\ndon't know what to do, can anyone of you help?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":859,"Q_Id":62801953,"Users Score":0,"Answer":"the answer to my question is quite simple. I needed to install all the required packages of tensorflow2.2 mentioned in the documentation and use python 64bits","Q_Score":0,"Tags":"python,tensorflow,scipy","A_Id":69963753,"CreationDate":"2020-07-08T19:05:00.000","Title":"ImportError: cannot import name 'imread' from 'scipy.misc' with tensorflow 2.2","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a program that retrieves image and return the RGB image as 3D np.ndarray. I want to return np.ndarray([[[]]]) when image is not available.\nCan we do it?","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":364,"Q_Id":62807699,"Users Score":0,"Answer":"simply return np.empty((10,10,10),object) because x=np.empty((10,10,10)) returns array with random values already stored in the memory buffer . x=np.empty((10,10,10),object) will return array with none values.\nHere (10,10,10) dimension is just for example. Use the dimensions favourable for you.","Q_Score":0,"Tags":"python,numpy,numpy-ndarray","A_Id":62807935,"CreationDate":"2020-07-09T04:57:00.000","Title":"How to return empty numpy array as np.ndarray([[[]]])","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I classify clients by many little xgboost models created from different parts of dataset.\nSince it is hard to support many models manually, I decided to automate hyperparameters tuning via Hyperopt and features selection via Boruta.\nWould you advise me please, what should go first: hyperparameters tuning or features selection? On the other hand, it does not matter.\nAfter features selection, the number of features decreases from 2500 to 100 (actually, I have 50 true features and 5 categorical features turned to 2 400 via OneHotEncoding).\nIf some code is needed, please, let me know. Thank you very much.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":395,"Q_Id":62811696,"Users Score":1,"Answer":"Feature selection (FS) can be considered as a preprocessing activity, wherein, the aim is to identify features having low bias and low variance [1].\nMeanwhile, the primary aim of hyperparameter optimization (HPO) is to automate hyper-parameter tuning process and make it possible for users to apply Machine Learning (ML) models to practical problems effectively [2]. Some important reasons for applying HPO techniques to ML models are as follows [3]:\n\nIt reduces the human effort required, since many ML developers spend considerable time tuning the hyper-parameters, especially for large datasets or complex ML algorithms with a large number of hyper-parameters.\n\nIt improves the performance of ML models. Many ML hyper-parameters have different optimums to achieve best performance in different datasets or problems.\n\nIt makes the models and research more reproducible. Only when the same level of hyper-parameter tuning process is implemented can different ML algorithms be compared fairly; hence, using a same HPO method on different ML algorithms also helps to determine the most suitable ML model for a specific problem.\n\n\nGiven the above difference between the two, I think FS should be first applied followed by HPO for a given algorithm.\nReferences\n[1] Tsai, C.F., Eberle, W. and Chu, C.Y., 2013. Genetic algorithms in feature and instance selection. Knowledge-Based Systems, 39, pp.240-247.\n[2] M. Kuhn, K. Johnson Applied Predictive Modeling Springer (2013) ISBN: 9781461468493.\n[3] F. Hutter, L. Kotthoff, J. Vanschoren (Eds.), Automatic Machine Learning: Methods, Systems, Challenges, 9783030053185, Springer (2019)","Q_Score":2,"Tags":"python-3.x,xgboost,feature-selection,hyperparameters,hyperopt","A_Id":63994784,"CreationDate":"2020-07-09T09:25:00.000","Title":"What should go first: automated xgboost model params tuning (Hyperopt) or features selection (boruta)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I checked multiple sources but couldn't pinpoint this particular problem although it probably has a very easy fix.\nLet's say I have some graph, g.\nI am able to print the vertices using g.vertices.show()\nBut I'm having a lot of trouble figuring out how to load all the vertices into a dataframe of some sort. I want to do a variety of tasks that are well supported on Pandas. Does anyone have a way to do this?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":402,"Q_Id":62825021,"Users Score":0,"Answer":"Just like how .show() will display the results of any query, you can do .toPandas() which will convert the output to a pandas DataFrame. As far as I can tell, this command couples any command that you can couple .show() with.\nSo for my specific question:\ng.vertices.toPandas() solves the problem.","Q_Score":1,"Tags":"python,pandas,apache-spark,graphframes","A_Id":62840761,"CreationDate":"2020-07-09T23:07:00.000","Title":"Convert GraphFrame output to a pandas DataFrame","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to read multiple tab delimited files (.tab) using pandas, and all files contain 250 rows and varying number of columns (more than 1). Some of the resulting data frames have expected number of rows and columns. However, in some of them all columns are recognized as a single column. Those data frames have expected number of rows, but only one column. I checked if the problematic documents have any unexpected line breaks or separators (or absence of thereof) and I wasn't able to find anything different from the 'good' documents. Does anyone have any ideas what could be happening?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":37,"Q_Id":62838552,"Users Score":0,"Answer":"Apparently, there was an extra line on the top of some documents I was trying to open. After checking all data frames and using a skiprow argument while reading files, everything worked fine.","Q_Score":0,"Tags":"python,pandas","A_Id":62962823,"CreationDate":"2020-07-10T16:28:00.000","Title":"Pandas doesn't recognize columns in a document","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to build a really simple tool in Python.\nI have a list, a very large list (about 5GB) in a .csv, of raffle numbers.\nFor whatever reason I cannot get Pandas or even regular SQL Databases to convert this list to a table and then randomly select a number (trying to select a random winner)\nSo it was suggested that I break up the .csv into chunks with code (so far I have no way to even open the list).\nThe main question is, how random will be effected if I do this? Lets say it breaks it into 5 chunks, and then I am asking it to select a random row of data from ANY of those five chunks. Does the random outcome actually show a 100% random row of data, or is this effected by having to run random on both levels.\nI.E. - Randomly select one of these five chunks, then randomly select a number from within them.\nIf I do it that way, isn't that effecting how truly random it is? Or am I just losing my mind thinking about the statistics around it?\n(Bonus question, I still have not even figured out a clear way to get it to break up the csv into manageable chunks, so any tips there would be extra awesome!)","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":28,"Q_Id":62840194,"Users Score":3,"Answer":"The following two scenarios are equivalent:\n\nPick a card from a deck at random\nPick a suit from {clubs,hearts,spades,diamonds} at random and then pick a card from that suit.\n\nBut, the following are not equivalent:\n\nPick a card at random\nPick a category from {face cards, non-face cards} at random and then pick a card from that category at random, since that would over-sample face cards.\n\nMoral of the story: you will be okay as long as the chunks are of equal size. Otherwise, you will over-sample the smaller chunks.","Q_Score":0,"Tags":"python,csv,random,large-files","A_Id":62840360,"CreationDate":"2020-07-10T18:21:00.000","Title":"How random is a random row from random chunks of data?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I need a data structure to store positive (not necessarily integer) values. It must support the following two operations in sublinear time:\n\nAdd an element.\nRemove the largest element.\n\nAlso, the largest key may scale as N^2, N being the number of elements. In principle, having O(N^2) space requirement wouldn't be a big problem, but if a more efficient option exists in terms of store, it would work better.\nI am working in Python, so if such a data structure exists, it would be of help to have an implementation in this language.","AnswerCount":3,"Available Count":1,"Score":0.1325487884,"is_accepted":false,"ViewCount":205,"Q_Id":62843016,"Users Score":2,"Answer":"There is no such data structure. For example, if there were, sorting would be worst-case linear time: add all N elements in O(N) time, then remove the largest element remaining N times, again in total O(N) time.","Q_Score":0,"Tags":"python,algorithm,data-structures","A_Id":62843062,"CreationDate":"2020-07-10T22:15:00.000","Title":"Insert and get max from structure in constant time","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have raster (.tif) files for every four days interval (e.g. LAI.Day.2015.10.24.tif, LAI.Day.2015.10.28.tif, LAI.Day.2015.11.01.tif, LAI.Day.2015.11.05.tif, LAI.Day.2015.11.09.tif, so on). Is there any way to get daily raster files (e.g. LAI.Day.2015.10.24.tif, LAI.Day.2015.10.25.tif, LAI.Day.2015.10.26.tif, so on) using bilinear interpolations on the raster files having temporal resolution of four days?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":152,"Q_Id":62863807,"Users Score":1,"Answer":"I do not think bilinear interpolation applies to time as it applies to space. But you can interpolate. In R, you could use raster::calc with approx. See the regression example in calc.","Q_Score":1,"Tags":"python,r,raster,gdal","A_Id":62863877,"CreationDate":"2020-07-12T16:44:00.000","Title":"Bilinear Interpolation on rasters to create daily raster files","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"GridSearchCV and RandomizedSearchCV has best_estimator_ that :\n\nReturns only the best estimator\/model\nFind the best estimator via one of the simple scoring methods : accuracy, recall, precision, etc.\nEvaluate based on training sets only\n\nI would like to enrich those limitations with\n\nMy own definition of scoring methods\nEvaluate further on test set rather than training as done by GridSearchCV. Eventually it's the test set performance that counts. Training set tends to give almost perfect accuracy on my Grid Search.\n\nI was thinking of achieving it by :\n\nGet the individual estimators\/models in GridSearchCV and RandomizedSearchCV\nWith every estimator\/model, predict on test set and evaluate with my customized score\n\nMy question is:\n\nIs there a way to get all individual models from GridSearchCV ?\nIf not, what is your thought to achieve the same thing as what I wanted ? Initially I wanted to exploit existing GridSearchCV because it handles automatically multiple parameter grid, CV and multi-threading. Any other recommendation to achieve the similar result is welcome.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":272,"Q_Id":62864193,"Users Score":1,"Answer":"You can use custom scoring methods already in the XYZSearchCVs: see the scoring parameter and the documentation's links to the User Guide for how to write a custom scorer.\nYou can use a fixed train\/validation split to evaluate the hyperparameters (see the cv parameter), but this will be less robust than a k-fold cross-validation. The test set should be reserved for scoring only the final model; if you use it to select hyperparameters, then the scores you receive will not be unbiased estimates of future performance.\nThere is no easy way to retrieve all the models built by GridSearchCV. (It would generally be a lot of models, and saving them all would generally be a waste of memory.)\nThe parallelization and parameter grid parts of GridSearchCV are surprisingly simple; if you need to, you can copy out the relevant parts of the source code to produce your own approach.\n\n\nTraining set tends to give almost perfect accuracy on my Grid Search.\n\nThat's a bit surprising, since the CV part of the searches means the models are being scored on unseen data. If you get very high best_score_ but low performance on the test set, then I would suspect your training set is not actually a representative sample, and that'll require a much more nuanced understanding of the situation.","Q_Score":0,"Tags":"python,scikit-learn,cross-validation,grid-search,gridsearchcv","A_Id":62938603,"CreationDate":"2020-07-12T17:19:00.000","Title":"Get individual models and customized score in GridSearchCV and RandomizedSearchCV","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have the following OF to minimize the cost of supply chain:\nmdl.minimize(mdl.sum((cs+ch+cf+cv*d[j])*q[j] for j in arcs) + mdl.sum(\u03b1*(eh+et*d[j])*q[j] for j in arcs) + mdl.sum(\u03b2*(gh+gt*d[j])*q[j] for j in arcs) + mdl.sum(X[f]*cjf for f in comb))\nWhere cs, ch, cf, cv, eh, et, gh, gt, cjf, \u03b1 and \u03b2 are a series of constant parameters.\nd[j] is the distance between origin iand destination j that are combined in a list of arcs or tuples.\nq[j] is the flow variable between origin i and destination j in arcs.\nX[f] is a binary variable to open a facility in destination j with capacity f, the possible combinations of j and f are listed in comb.\nThe first constraint 1 ensures the flow q[i,j] from origin i does not exceed its maximum availability of material dQ in i. D[(i, j)] is a binary parameter that is 1 if the distance between origin i and destination j is less or equal than a treshold value, else the value of D[(i, j)] is 0. (This parameter helps us to limit the transport distance.)\nfor i in I: mdl.add_constraint(mdl.sum(q[(i, j)]*D[(i, j)] for j in J) <= Qi[i])\nThe second constraint 2 ensures the flow q[i,j] to a destination j equals the capacity of the opened facility in destination j with capacity f.\nfor j in J: mdl.add_constraint(mdl.sum(q[(i, j)]for i in I) == mdl.sum(X[(j,f)] for f in F))\nBut then, we want another constraint 3 that ensures the sum of capacities f in the facilities opened at destinations j has to be as close as possible to the total demand of capacities E. Let's say there is an energy demand of 100 MW E = 100, then we want to reduce the cost in OF of the supply but also make sure we reach the demand E. Otherwise minimizing the cost would be 0. This constraint can be formulated like:\nmdl.add_constraint(mdl.sum(X[j,f]for j in J for f in F) == E)\nUnfortunately, this solution is never feasible. If we replace == by <= than it is feasible, but it is at minimal cost and the capacity is nowhere near maximal.\nWe don't need this to be a strict constraint but we do wanna get as close to E as possible, by opening multiple facilities at destinations j with different capacities f. (Eg. we could have one destination with 20 MW, one at 5 MW, two at 30 MW and another at 15 MW to reach 100 MW by opening 5 destinations)\nOne way is to force the model to open N number of locations j, however, we have a set of 128 locations. To find the minimum cost and maximum capacity from a ranges of scenarios from N=1 to N=128 means we need to run this model 128 times.\nOn top of the above-mentioned constraint we have 3 additional constraints:\n\nWe can only select destination j to built a facility and open it at only one capacity f.\nThe sum of destinations j to open is greater than 0.\nThere is no negative flow q between origins i and destinations j\n\nIs there a way to:\n\nMake constraint 3 less binding, but still try to reach E while keeping the cost minimal?\nReformulate the OF to combine the minimized cost with the maximized capacity?\n\nImportantly we do not want to run the model 128 times. We want to model to select the destinations j to open a facility and select the capacity f accordingly, to minimize the overall cost of supply and maximize the installed capacity. In our case,e it would also be very unlikely to open just one destination j to satisfy all demand E. Instead we would have multiple j with smaller f capacity that approach E when summed.","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":531,"Q_Id":62867607,"Users Score":0,"Answer":"This is 'multi-objective optimisation'. Two possible ways to achieve this are outlined below.\nFirst approach is to get a combined single objective function. This is easier if both terms are working in the same direction e.g. both are minimising terms. So for your 'constraint 3' try using a term in the objective for the shortfall relative to the demand, so the shortfall is something like:\nShortfall == E - mdl.sum(X[j,f]for j in J for f in F)\nThen add the shortfall into the objective, and use some weighting factors for the two terms, e.g.:\nw * Cost + (1-w) * Shortfall\nThen if w is one, you are just minimising the cost, while if w is zero, you are just minimising the shortfall. Of course, if you use a value for the weighting between zero and one, then you will get a balance of the two objectives. You will need to pay careful attention to the value of the weighting split between your two terms.\nA variation in this approach would be to give a much bigger weight to one term than the other, so that term dominates the objective. Then the solver will try to minimise that more important term (e.g. the shortfall), and the other term will help select the lower cost options for achieving that. In practice this often does NOT work as well as people expect - adding very large and very small terms in the objective can give rise to numerical issues in the solver, and often the real differences in the objective values of different solutions can get lost in the tolerances in the solver anyway. For example we have seen some people use relative weights of 1 million to one, while still using an optimality gap of 1e-6; in this case the second term effectively gets lost in the noise because many (perhaps very different) alternatives look almost the same to the solver and fall within the tolerances and so effectivley get ignored.\nThe second approach is 'lexical multi-objective' solving which is a little more complicated, but doesn't rely on some troublesome weighting factors. Effectively you need to solve your problem twice - once to find the maximum capacity that you can provide, and then fix that with a constraint in your second problem and minimise the cost of delivering that capacity.\nIn practice you might adjust this purist approach, and accept solutions in your second model that are close enough to achieving the maximum capacity. So for example you may fix the total capacity in your second model to be e.g. at least 99% of the calculated maximum capacity achievable from the first model. This reflects the cases where there are maybe only a few (expensive) ways to achieve the absolute maximum capacity, but there may be worthwhile savings if we explore solutions that are close to that maximum.\nNote that there are several solvers that provide ready-built support for multi-objective models using this 'lexical' approach which may avoid you explicitly solving the model twice for each case.","Q_Score":0,"Tags":"python,mathematical-optimization,cplex,docplex,docplexcloud","A_Id":62871035,"CreationDate":"2020-07-13T00:00:00.000","Title":"How to combine 2 constraints to minimise cost and maximise capacity using DOcplex.mp in Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":1},{"Question":"I'm looking to build a system that alerts me when there's a package at my front door. I already have a solution for detecting when there's a package (tflite), but I don't know how to get the array of detected objects from the existing tflite process and then pull out an object's title through the array. Is this even possible, or am I doing this wrong?\nAlso, the tflite model google gives does not know how to detect packages, but I'll train my own for that","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":99,"Q_Id":62868911,"Users Score":0,"Answer":"I've figured out a solution. I can just use the same array that the function that draws labels uses (labels[int(classes[i])) to get the name of the object in place i of the array (dunno if I'm using the correct terminology but whatever). hopefully this will help someone","Q_Score":0,"Tags":"python,python-3.x,tensorflow,object-detection,tensorflow-lite","A_Id":62883062,"CreationDate":"2020-07-13T03:40:00.000","Title":"how to get names of all detected models from existing tensorflow lite instance?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a pandas dataframe that effectively contains several different datasets. Between each dataset is a row full of NaN. Can I split the dataframe on the NaN row to make two dataframes? Thanks in advance.","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":680,"Q_Id":62869058,"Users Score":0,"Answer":"Use df[df[COLUMN_NAME].isnull()].index.tolist() to get a list of indices corresponding to the NaN rows. You can then split the dataframe into multiple dataframes by using the indices.","Q_Score":3,"Tags":"python,pandas,numpy,dataframe","A_Id":62869145,"CreationDate":"2020-07-13T03:59:00.000","Title":"Can split pandas dataframe based on row values?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using Flask as backend and React as frontend in my application. The application deals with large amounts of data (millions of rows).\nWhen I send the data from backend (stored in a dataframe in python) to frontend, it is in JSON format and is quite fast. But is JSON format stable enough to hold million rows of data?\nAre there any ideal data structures for large data like datatables or dataframes which makes it easier to access rows and columns similar to pandas dataframe in javascript or reactJS?","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":189,"Q_Id":62897005,"Users Score":0,"Answer":"try using lazyloading. It helps you get data on scroll","Q_Score":0,"Tags":"javascript,python,reactjs,flask,data-structures","A_Id":62898196,"CreationDate":"2020-07-14T14:03:00.000","Title":"Ideal data structure to hold a large tables in ReactJS","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":1},{"Question":"I am using Flask as backend and React as frontend in my application. The application deals with large amounts of data (millions of rows).\nWhen I send the data from backend (stored in a dataframe in python) to frontend, it is in JSON format and is quite fast. But is JSON format stable enough to hold million rows of data?\nAre there any ideal data structures for large data like datatables or dataframes which makes it easier to access rows and columns similar to pandas dataframe in javascript or reactJS?","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":189,"Q_Id":62897005,"Users Score":0,"Answer":"Sending millions of rows to frontend and doing analysis in the frontend is not very adequate. Instead you can apply your bi logic in the backend and send results to frontend.","Q_Score":0,"Tags":"javascript,python,reactjs,flask,data-structures","A_Id":62899647,"CreationDate":"2020-07-14T14:03:00.000","Title":"Ideal data structure to hold a large tables in ReactJS","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":1},{"Question":"I've used random.normal() in the past to generate a single number who, if called multiple times, in aggregate would create a bell curve distribution. What I'm trying to do now is to create the opposite \/ inverse, where the distribution is biased towards the extremes within a range? There are built in functions in excel that seem to do what I want. Is there a way to do it in python? Thank you","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":464,"Q_Id":62899379,"Users Score":0,"Answer":"It sounds like what you are wanting is to shift the distribution the the edge of the range, and wrap around?\nSomething like this could do what you're looking for:\nnum = (random.normal() + 0.5) % 1","Q_Score":0,"Tags":"python,random,normal-distribution,inverse","A_Id":62899580,"CreationDate":"2020-07-14T16:09:00.000","Title":"Inverse normal random number generation in python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Can anyone help with best practices for avoiding this type of problem?\nin: np.arrange(1, 2.2, .2)\nout: array([1. , 1.2, 1.4, 1.6, 1.8, 2. , 2.2])\nMust have something to do with binary\/base10 difficulties, as\nin: np.arrange(1, 2.2, .2)[6]\nout: 2.1999999999999997\npython version: 3.6.8 |Anaconda, Inc.| (default, Dec 29 2018, 19:04:46)\n[GCC 4.2.1 Compatible Clang 4.0.1 (tags\/RELEASE_401\/final)]\nnumpy version: : 1.16.3","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":90,"Q_Id":62905568,"Users Score":0,"Answer":"Okay, answered my own question (rly just wanted to post on stackoverflow).\nIt's best to use numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0), and just set num to (start - stop)\/spacing (+1 if endpoint=True).","Q_Score":0,"Tags":"python,numpy","A_Id":62905620,"CreationDate":"2020-07-14T23:45:00.000","Title":"numpy arrange oddly including endpoint when it shouldn't","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm dealing with a dataframe of dimension 4 million x 70. Most columns are numeric, and some are categorical, in addition to the occasional missing values. It is essential that the clustering is ran on all data points, and we look to produce around 400,000 clusters (so subsampling the dataset is not an option).\nI have looked at using Gower's distance metric for mixed type data, but this produces a dissimilarity matrix of dimension 4 million x 4 million, which is just not feasible to work with since it has 10^13 elements. So, the method needs to avoid dissimilarity matrices entirely.\nIdeally, we would use an agglomerative clustering method, since we want a large amount of clusters.\nWhat would be a suitable method for this problem? I am struggling to find a method which meets all of these requirements, and I realise it's a big ask.\nPlan B is to use a simple rules-based grouping method based on categorical variables alone, handpicking only a few variables to cluster on since we will suffer from the curse of dimensionality otherwise.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":773,"Q_Id":62917042,"Users Score":1,"Answer":"The first step is going to be turning those categorical values into numbers somehow, and the second step is going to be putting the now all numeric attributes into the same scale.\nClustering is computationally expensive, so you might try a third step of representing this data by the top 10 components of a PCA (or however many components have an eigenvalue > 1) to reduce the columns.\nFor the clustering step, you'll have your choice of algorithms. I would think something hierarchical would be helpful for you, since even though you expect a high number of clusters, it makes intuitive sense that those clusters would fall under larger clusters that continue to make sense all the way down to a small number of \"parent\" clusters. A popular choice might be HDBSCAN, but I tend to prefer trying OPTICS. The implementation in free ELKI seems to be the fastest (it takes some messing around with to figure it out) because it runs in java. The output of ELKI is a little strange, it outputs a file for every cluster so you have to then use python to loop through the files and create your final mapping, unfortunately. But it's all doable (including executing the ELKI command) from python if you're building an automated pipeline.","Q_Score":1,"Tags":"python,r,bigdata,cluster-analysis,mixed","A_Id":62917300,"CreationDate":"2020-07-15T14:18:00.000","Title":"Clustering on large, mixed type data","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a calculation that may result in very, very large numbers, that won fit into a float64. I thought about using np.longdouble but that may not be large enough either.\nI'm not so interested in precision (just 8 digits would do for me). It's the decimal part that won't fit. And I need to have an array of those.\nIs there a way to represent \/ hold an unlimited size number, say, only limited by the available memory? Or if not, what is the absolute max value I can place in an numpy array?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":1833,"Q_Id":62929222,"Users Score":2,"Answer":"Can you rework the calculation so it works with the logarithms of the numbers instead?\nThat's pretty much how the built-in floats work in any case...\nYou would only convert the number back to linear for display, at which point you'd separate the integer and fractional parts; the fractional part gets exponentiated as normal to give the 8 digits of precision, and the integer part goes into the \"\u00d710\u207f\" or \"\u00d7e\u207f\" or \"\u00d72\u207f\" part of the output (depending on what base logarithm you use).","Q_Score":0,"Tags":"python,numpy,python-3.7,numpy-ndarray","A_Id":62929416,"CreationDate":"2020-07-16T07:00:00.000","Title":"In NumPy, how to use a float that is larger than float64's max value?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Currently, I am working on creating datasets by using Twitter API. I have some question that you might be able to help me out. For example, the first dataset that I have to create is related to the early hashtag adopters, I mean, by using a specific hashtag as the search word in a certain timeframe, I will retrieve the first 50 users ID who have used the hashtag on their tweets.\nThe problem I'm facing is that it will show me the most recent tweets that match the query, but what I want is the other way round, I mean, in ascending order. So, I am wondering if this is possible to do it.\nPD: I am using searchtweets package in python.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":57,"Q_Id":62938338,"Users Score":1,"Answer":"Unfortunately, there isn't a way to make premium api return things in chronological order (it will always return newest first).","Q_Score":1,"Tags":"python,twitter","A_Id":62956049,"CreationDate":"2020-07-16T15:38:00.000","Title":"Retrieve tweets in ascending order with a defined timeframe","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a Pandas dataframe column that consists of several dictionaries in the format of:\ndf[students] = {u'51': [u'1592', u'1582', u'1272', u'459', u'1254', u'1267'], u'32': [u'1659', u'1322', u'1396', u'1315', u'1342', u'1661']} {u'51': [u'1592', u'1582', u'1272', u'459', u'1254', u'1267'], u'32': [u'1659', u'1322', u'1396', u'1315', u'1342', u'1661']}\n... and so on for several more entries.\nEach dictionary represents one entry in the dataframe. I would like to convert this column into 2 new columns where the keys (51 and 32) are the column headers, and the values go into each column accordingly. I used the df.to_list() and Pd.Series() methods which seemed to work at first, but when I replicated it, it didnt change the data at all. Is there something I'm missing here?","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":37,"Q_Id":62944256,"Users Score":0,"Answer":"Turns out that the above methods posted didn't work while the strings in question were in unicode.\nThis finally worked:\ndf['students'] = df['students'].map(eval)\ndf2 = pd.concat([df.drop('students', axis=1), pd.DataFrame(df['students'].tolist())], axis=1)\nI appreciate the answers posted, thanks a bunch everyone.","Q_Score":0,"Tags":"python,pandas,list,dataframe,dictionary","A_Id":62945479,"CreationDate":"2020-07-16T22:11:00.000","Title":"Converting a Dataframe Column of Dictionaries into New Columns based on Keys","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"While importing from kerastuner.engine.hyperparameters import Hyperparameters I am getting below error in the Jupyter Notebook. However while running import kerastuner as kt I am not getting any error. I am using tensorflow 2.2.","AnswerCount":1,"Available Count":1,"Score":0.537049567,"is_accepted":false,"ViewCount":328,"Q_Id":62949807,"Users Score":3,"Answer":"Try using this :\nfrom kerastuner.engine.hyperparameters import HyperParameters","Q_Score":0,"Tags":"python,keras,hyperparameters","A_Id":67977779,"CreationDate":"2020-07-17T08:11:00.000","Title":"ImportError: cannot import name 'Hyperparameters' from 'kerastuner.engine.hyperparameters'","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a dataset (Tiny ImageNet) where the images are 64 x 64 but I want to use the pre-trained model: InceptionResNetV2 since the accuracy on all other models is low.\nCan I double the dimensions in target_size to 128, 128 in the image_gen.flow_from_dataframe function and use the output in the InceptionResNetV2?\nWill doubling the target size influence the training? I mean will it stretch the images or add blank space around them.\nIs this way appropriate or is there a better way to train tiny images using InceptionResNetV2?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":183,"Q_Id":62953272,"Users Score":1,"Answer":"You can either define input image size in ImageDataGenerator (target_size=(224,224)) or in tf.keras.layers.Input( shape=input_shape ) part.","Q_Score":1,"Tags":"python,keras","A_Id":62953368,"CreationDate":"2020-07-17T11:44:00.000","Title":"Target_size image_gen.flow_from_dataframe InceptionResNetV2 (Keras) for smaller images","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"This is a bit idea hovering over my head.\nknn is a lazy eval algorithm, so the data in the backend must be stored with categories.\nI wanted to build a visual feedback where if we modify a point, any new prediction is based on the updated data. Is it possible to modify that information stored in backend?\nIs it possible for knn to reference data from an external database, or do we need to retrain the model from start","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":45,"Q_Id":62953376,"Users Score":1,"Answer":"You will have to re-generate the model if there is an update in the training data since the calculation for kth neighbor will change.","Q_Score":0,"Tags":"python,python-3.x,knn","A_Id":62953517,"CreationDate":"2020-07-17T11:51:00.000","Title":"knn realtime update based on feedback","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to train a Deep Neural Network (DNN) with labeled data. The labels are encoded in such a way that it only contains values 0 and 1. The shape of the encoded label is 5 x 5 x 232. About 95% of values in the label is 0and rests are 1. Currently, I am using binary_crossentroy loss function to train the network.\nWhat is the best technique to train the DNN in such a scenario? Is the choice of binary_crossentroy\nas the loss function is appropriate in this case? Any suggestion to improve the performance of the model.","AnswerCount":4,"Available Count":2,"Score":0.049958375,"is_accepted":false,"ViewCount":50,"Q_Id":62957768,"Users Score":1,"Answer":"You can try MSE loss. If you want to stick to binary cross-entropy (used in binary classification), consider using label smoothing.","Q_Score":0,"Tags":"python,tensorflow,deep-learning,conv-neural-network","A_Id":62958032,"CreationDate":"2020-07-17T16:06:00.000","Title":"How to perform supervised training of a deep neural network when the target label has only 0 and 1?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to train a Deep Neural Network (DNN) with labeled data. The labels are encoded in such a way that it only contains values 0 and 1. The shape of the encoded label is 5 x 5 x 232. About 95% of values in the label is 0and rests are 1. Currently, I am using binary_crossentroy loss function to train the network.\nWhat is the best technique to train the DNN in such a scenario? Is the choice of binary_crossentroy\nas the loss function is appropriate in this case? Any suggestion to improve the performance of the model.","AnswerCount":4,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":50,"Q_Id":62957768,"Users Score":0,"Answer":"In such scenarios where you have highly imbalanced data, I would suggest going with Random Forest with up-Sampling. This approach will up-sample the minority class and hence improve the model accuracy.","Q_Score":0,"Tags":"python,tensorflow,deep-learning,conv-neural-network","A_Id":62960030,"CreationDate":"2020-07-17T16:06:00.000","Title":"How to perform supervised training of a deep neural network when the target label has only 0 and 1?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"When I load the BERT pretrained model online I get this error OSError: Error no file named ['pytorch_model.bin', 'tf_model.h5', 'model.ckpt.index'] found in directory uncased_L-12_H-768_A-12 or 'from_tf' set to False what should I do?","AnswerCount":3,"Available Count":1,"Score":0.0665680765,"is_accepted":false,"ViewCount":4569,"Q_Id":62961627,"Users Score":1,"Answer":"These are the pretrained model files. You can download them from the repository, you have taken the code from if provided. If its HuggingFace you are using, you can get these on their site.","Q_Score":4,"Tags":"python,tensorflow,pytorch,bert-language-model","A_Id":62962289,"CreationDate":"2020-07-17T20:52:00.000","Title":"OSError: Error no file named ['pytorch_model.bin', 'tf_model.h5', 'model.ckpt.index']","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Per title. I do not understand why it is not valid. I understand that they mutate the object, but if you call the sort method, after it's done then you'd call the reverse method so it should be fine. Why is it then that I need to type lst.sort() then on the line below, lst.reverse()?\nEdit: Well, when it's pointed out like that, it's a bit embarrassing how I didn't get it before. I literally recognize that it mutated the object and thus returns a None, but I suppose it didn't register that also meant that you can't reverse a None-type object.","AnswerCount":3,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":198,"Q_Id":62963707,"Users Score":1,"Answer":"When you call lst.sort(), it does not return anything, it changes the list itself.\nSo the result of lst.sort() is None, thus you try to reverse None which is impossible.","Q_Score":0,"Tags":"python,python-3.x,list,function,methods","A_Id":62963730,"CreationDate":"2020-07-18T01:31:00.000","Title":"Why isn't lst.sort().reverse() valid?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a boolean numpy array which I need to convert it to binary, therefore where there is true it should be 255 and where it is false it should be 0.\nCan someone point me out how to write the code?","AnswerCount":4,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":1440,"Q_Id":62965151,"Users Score":0,"Answer":"Let x be your data in numpy array Boolean format.\nTry\nnp.where(x,255,0)","Q_Score":0,"Tags":"python,numpy","A_Id":62965290,"CreationDate":"2020-07-18T05:52:00.000","Title":"Converting numpy boolean array to binary array","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I an new to code and I would like to know whether it is possible to upload multiple excel documents into one dataset using python? If so, what is the code for this? All of the code I have seen is used for uploading one single excel document. Moreover, do I have to convert the data into CSV form first or I can use code to convert it into CSV after uploading it?\nI am using jupyter notebook in anaconda to run my python code.\nYour assistance is greatly appreciated.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":35,"Q_Id":62968420,"Users Score":1,"Answer":"By uploading, do you mean reading a file? If so, just create a list or dictionary, open the files and write them 1 by 1 into your list \/ dictionary. Also, it would be really helpful creating CSV files first. If you want to do it manually you can easily by saving the file as CSV in Excel.","Q_Score":0,"Tags":"python,csv","A_Id":62969927,"CreationDate":"2020-07-18T12:11:00.000","Title":"How to upload multiple excel documents into one dataset using python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I would like more info. on the answer to the following question:\n\ndf[\u2018Name\u2019] and 2. df.loc[:, \u2018Name\u2019], where:\n\ndf = pd.DataFrame(['aa', 'bb', 'xx', 'uu'], [21, 16, 50, 33], columns = ['Name', 'Age'])\nChoose the correct option:\n\n1 is the view of original dataframe and 2 is a copy of original\ndataframe\n2 is the view of original dataframe and 1 is a copy of\noriginal dataframe\nBoth are copies of original dataframe\nBoth are views of original dataframe\n\nI found more than one answer online but not sure. I think the answer is number 2 but when i tried x = df['name'] then x[0] = 'cc' then print(df) I saw that the change appeared in the original dataframe. So how the changed appeared in the original dataframe although I also got this warining:\nA value is trying to be set on a copy of a slice from a DataFrame\nI just want to know more about the difference between the two and weather one is really a copy of the original dataframe or not. Thank you.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":693,"Q_Id":62970683,"Users Score":0,"Answer":"Both are the views of original dataframe\nOne can be used to add more columns in dataframe and one is used for specifically getting a view of a cell or row or column in dataframe.","Q_Score":0,"Tags":"python,pandas,dataframe","A_Id":62970716,"CreationDate":"2020-07-18T16:00:00.000","Title":"df['colimn_name'] vs df.loc[:, 'colimn_name']","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm working on tensorflow and my dataset is composed only by Black and White images, so I thought that I could make my neural net (currently I am using Resnet50) less heavy and easier to train and test by changing the number of channels from 3 to 1,\nIs there a way to do so?\n(Ik I can treat b\/w images as rgb images but I don't want to do that)\nThanks in advance for the answer","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":3133,"Q_Id":62971655,"Users Score":0,"Answer":"The pretrained weights in keras.applications require a 3 channel input. You could one of two things:\n\nUse a different pretrained model that works on grayscale images.\nSet the R, G and B channels to replicate your BW input, then fine-tune the entire neural network on your own dataset. This probably won't work without the fine-tuning step.\n\nOn a side note, I must say this task will not help in your goal of making it 'less heavy and easier to train and test'. If you call model.summary() on keras Resnet50, you see that of the total trainable 23,534,592 parameters, only about 10K of them are in the initial layer. So at best you can reduce the number of parameters by an insignificant few thousand.\nI would instead suggest using a lighter model such as MobileNet that are also available in Keras.","Q_Score":2,"Tags":"python,tensorflow,keras,artificial-intelligence,conv-neural-network","A_Id":62972371,"CreationDate":"2020-07-18T17:33:00.000","Title":"How can I change number of channels on Resnet to make it work only on B\/W images?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a data frame in hand, now i want to add one more column in that data frame. that column will be a set of lists, ie, if the length of the data frame is 10, the column will be set of 10 lists. Each row associate with one list. How can i make this? And initially those lists will be blank list so that i can append objects further.","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":31,"Q_Id":62976640,"Users Score":0,"Answer":"I can give the answer of my question i think.\nSuppose i have a dataset called XYZ, It has @ column A,B. Now i want to add one more column C which is a set of lists ie, there are same number of lists as number of rows.\nXYZ = pd.read_csv('untitled.csv', usecols = ['A', 'B']) XYZ['C'] = pd.Series([]*len(XYZ), dtype = object) for i in range(len(XYZ)): XYZ['C'][i] = []","Q_Score":0,"Tags":"python-3.x,list,dataframe","A_Id":63017034,"CreationDate":"2020-07-19T05:28:00.000","Title":"How to make a column of set of lists in python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to create a matrix inside a for loop (one column at a time).\nWhich is the faster way to do it? creating a np.empty() array and using np.hstack() to append the columns, or creating a np.zeros() array of the desired shape and changing the columns of the array.\nTIA","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":178,"Q_Id":62976800,"Users Score":1,"Answer":"np.zeros() be faster when the size is big enough that the array operations are significant.\nThe reason for that is that numpy arrays are stored continuously in one big block of memory. Allocating memory for the array takes time. When using hstack you continuously need to grow the memory for the array, which means re-allocating the memory and copying all the data to the new place, making this essentially an O(n^2) operation. Pre-allocating with np.zeros saves you this time.","Q_Score":2,"Tags":"python,numpy","A_Id":62977201,"CreationDate":"2020-07-19T05:56:00.000","Title":"What is faster for creatin a matrix, using np.hstack (or np.vstack) inside a for loop, or changing the columns of a previously created np.zeros array?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am writing a rest api in flask to read data from some json files, turn them to pandas dataframes, read and\/or edit data from the data frames. When I turn the jsons into dataframes I want to make sure that any finite number of computers that access the api now has access to the same dataframes, and assuming computer A edits a data frame(maybe deletes a column called \"names\") , then when computers B-Z try to access the names column in tbe data frame it should also be gone for them. How do I achieve this in a flask emvironment. i already tried reading the files and declaring the dataframes at the start of the flask app but when i looked online for a bit i found that it's bad practice to use global varibles in flask. All the help i found siggested using sessions, but that would mean the changes computer A makes to the dataframe, will be visible to only computer A unless it saves back to the json file and all other computer B-Z re-read from the Json. Thanks for your help.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":54,"Q_Id":62980318,"Users Score":0,"Answer":"You should use a database to achieve that, if your project is not big, SQLite should be enough, and Flask-SQLAlchemy would be a good choice to make the persistent work easier.","Q_Score":0,"Tags":"python,session,flask","A_Id":62982003,"CreationDate":"2020-07-19T12:30:00.000","Title":"How to make a variable available accross all open flask sessions","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":1},{"Question":"Even after installing xlrd module, I am not able to read excel files using pandas, every time it's showing file directory not found. Please help!\nI am using \" import Pandas as pd\"\n\" data=pd.read_excel(\"notebook.xlsx\")\nIt shows error as file not found","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":34,"Q_Id":62988750,"Users Score":0,"Answer":"Pandas is not finding the excel file. Try to put the complete path on the read_excel function like read_excel(\"C:\/documents\/notebook.xlsx\").","Q_Score":0,"Tags":"excel,pandas,python-3.8","A_Id":62989065,"CreationDate":"2020-07-20T04:37:00.000","Title":"Query regarding pandas","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to cache a Pyspark based data frame with 3 columns and 27 rows and this process is taking around 7-10 seconds.\nIs there anyway to accelerate this job?\nThanks in advance!","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":70,"Q_Id":62998750,"Users Score":2,"Answer":"You could try any of the below approaches:\n\ncoalesce your dataframe into a single partition for eg. df.coalesce(1) and then cache it\nSince your dataframe is pretty tiny you could load it as a pandas dataframe, which will be in memory. toPandas() could help you in that regards. Don't forget use the arrow spark setting to make it faster.\nspark.conf.set(\"spark.sql.execution.arrow.pyspark.enabled\", \"true\")\nspark.conf.set(\"spark.sql.execution.arrow.enabled\", \"true\")","Q_Score":0,"Tags":"python,pyspark","A_Id":63000410,"CreationDate":"2020-07-20T15:25:00.000","Title":"Is there any way to accelerate the caching process in pyspark?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to convert the following ANTsR line to ANTsPy:\nseggm[seggm < 0.5 & tmp > 0.5] <- 2 (seggm and tmp are both 'ANTsImage's)\nI have tried:\nseggm[seggm.numpy() < 0.5 & tmp.numpy() > 0.5] = 2 but this is too slow.. Is there a faster way to perform this?\nThanks","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":13,"Q_Id":63000289,"Users Score":0,"Answer":"Whoops typed it differently in my code.. This works now!","Q_Score":0,"Tags":"python,numpy,numpy-ndarray","A_Id":63000930,"CreationDate":"2020-07-20T16:55:00.000","Title":"How do I convert ANTsR to ANTsPy image querying command?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am looking for a way to make n (e.g. 20) groups in a dataframe by a specific column by percentile. (data type is float). I am not sure if the group by quantile function can take care of this, and if it can, how the code should look like.\nThere are 3 rows a, b, c\ni.e. Data are sorted by column 'a', and make 20 groups\n\nGroup 1 = 0 to 5 percentile\nGroup 2 = 5 to 10 percentile\n.\n.\n.\nGroup 20 = 95 to 100 percentile.\n\nwould there also be a way to find the mean a, b, and c of each group, and sort them into another dataframe?","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":90,"Q_Id":63004139,"Users Score":1,"Answer":"You can create 20 equal size bins using this.\ndf['newcol'] = pd.qcut(df.a,np.linspace(.05, 1, 19, 0), duplicates='drop')\nThen you can groupby the newcol to find the summary stats of a,b and c columns\ndf.groupby(['newcol']).mean()","Q_Score":0,"Tags":"python,pandas","A_Id":63004943,"CreationDate":"2020-07-20T21:33:00.000","Title":"How to make a fixed number of groups by percentile from a dataframe in pandas","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have pyspark data frame with 3+ million of records and it's necessary to write it to Dynamo db. What is the best way to do it?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":188,"Q_Id":63004483,"Users Score":1,"Answer":"If you want to do this using python then you can do this as:\n\nsave the spark df with sufficient number of files i.e. if file size is 5 GB, generate 50 files of 100 mb.\nNow write python code with multiprocessing where your process pool will be equal to the number of CPU's available.\nWrite the files using dynamodb's boto3 batch_writer and process all files parallely.\n\nFor this you can use either glue python shell or create your own container and launch it on fargate.","Q_Score":0,"Tags":"python,amazon-web-services,dataframe,pyspark,amazon-dynamodb","A_Id":63012440,"CreationDate":"2020-07-20T22:05:00.000","Title":"How to write large Pyspark DataFrame to DynamoDB","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I wanted to convert my Date column (yyyy-mm-dd) into type datetime. I checked its dtype and it was object. On converting it as pd.to_datetime(data['Date']), the dtype changed to dtype('O'). I looked it up online and it had to something with numpy dtypes however I cannot find a concrete answer.\n\nCan someone help me with this?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":672,"Q_Id":63008833,"Users Score":0,"Answer":"Although I could not get why this was happening but when I tried data[\"Date\"] = pd.to_datetime(data[\"Date\"], errors='coerce') , the column changed into datetime type as it was required.","Q_Score":0,"Tags":"python,pandas,numpy,types","A_Id":63009103,"CreationDate":"2020-07-21T06:44:00.000","Title":"What is the difference between datatype \"object\" and dtype('O') in python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I tried to install Rasa, with the command: pip3 install rasa.\nHowever, I came up against an error about tensorflow, which is not automatically installed.\nThen I used command: pip3 install tensorflow, unfortunately, an error appeared:\nERROR: Could not find a version that satisfies the requirement tensorflow-addons<0.8.0,>=0.7.1 (from rasa) (from versions: none).\nSo how could I install Rasa, and Tensorflow as well?\nP\/s: Python --version: 3.8.3;\npip --version: 20.1.1","AnswerCount":5,"Available Count":2,"Score":0.0399786803,"is_accepted":false,"ViewCount":6867,"Q_Id":63011755,"Users Score":1,"Answer":"I've made the same mistake of installing the python version 3.8 when it says on the RASA installation notes that you've got to go for version 3.6 3.7 for now.\nAfter having the right version of Python in my venv (macOS zsh) the installation worked fine. From the python site you can find the right version to prepare for your environment. Also it was advised that you prepare the python version for the venv and not your entire system (which I think is at python 2.x)\nMaking sure that you have all the components you need and the right version was key for RASA to not have issues during the install.","Q_Score":3,"Tags":"python,tensorflow","A_Id":63299303,"CreationDate":"2020-07-21T09:45:00.000","Title":"ERROR: Could not find a version that satisfies the requirement tensorflow-addons<0.8.0,>=0.7.1 (from rasa) (from versions: none)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I tried to install Rasa, with the command: pip3 install rasa.\nHowever, I came up against an error about tensorflow, which is not automatically installed.\nThen I used command: pip3 install tensorflow, unfortunately, an error appeared:\nERROR: Could not find a version that satisfies the requirement tensorflow-addons<0.8.0,>=0.7.1 (from rasa) (from versions: none).\nSo how could I install Rasa, and Tensorflow as well?\nP\/s: Python --version: 3.8.3;\npip --version: 20.1.1","AnswerCount":5,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":6867,"Q_Id":63011755,"Users Score":0,"Answer":"I faced same problems and executed following commands:\n\nsudo apt-get update\nsudo apt-get upgrade\nsudo pip3 install --upgrade pip\npip3 install rasa\n\nNow My System is:\n\nUbuntu 18.04.5 LTS\nPython 3.6.9\npip 20.3.3\ntensorflow 2.3.1\ntensorflow_addons 0.12.0\n\nand rasa on my system is working fine.","Q_Score":3,"Tags":"python,tensorflow","A_Id":65488687,"CreationDate":"2020-07-21T09:45:00.000","Title":"ERROR: Could not find a version that satisfies the requirement tensorflow-addons<0.8.0,>=0.7.1 (from rasa) (from versions: none)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"First time posting so hopefully I can relate what I'm trying to ask.\nI have cpp code that records timestamps down to the nanosecond level from an fpga. It is writing this value to a csv. In the same csv I am calculating the difference between consecutive timestamps.\nWhen I export it to python and do the timestamp difference, I get mostly 1s (its based off a PPS), but also random impulse points. Any idea why I get all 1s in cpp but mostly 1s and occasionally 1 +- 3E-14?\nany info or guidance would be appreciated. From using search, it seems like it could be due to floating points? but shouldnt that happen for both?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":41,"Q_Id":63019871,"Users Score":0,"Answer":"@tdelaney's and user4581301's comments hit the nail on the head. It appears that it was due to the precision of python's floating type. I replaced it with the mentioned decimal.Decimal and it kept the original CSVs precision and calculated the data with no rounding.\nDecimal doesn't rely on binary fractions and the only downside is that it is slower (which in my case is fine).\nThe difference between my cpp and python code was that my cpp code was doing the math as uints and I was calculating it manually vs just A-B.","Q_Score":1,"Tags":"python,c++,precision","A_Id":63035268,"CreationDate":"2020-07-21T17:28:00.000","Title":"CPP and Python csv Precision","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"If I have two datasets d1 and d2, where the d1 columns are:\nd1_columns {X,Y,Z,T}\nand for d2 :\nd2_columns{X,Y,L,P}\nIs there a function f such that:\nf(d1,d2) = {Z,T} or equivalently: f(d1,d2) = {L,P} ?","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":33,"Q_Id":63021214,"Users Score":0,"Answer":"In this case first add both the dataframes and then subtract the other.\nEg : A = ( a,b,c,d ) , B = ( a,b,e,g ). Here I mean to say that a,b,c,d,e,f are the column names.\nSo , if you want column ( c,d ) only , then do\n\nC = A + B , then ,\nC = C - B and hence you will be left with columns ( c,d ) only.\n\nLikewise you can do for ( e,g ) columns.","Q_Score":0,"Tags":"python,pandas","A_Id":63021526,"CreationDate":"2020-07-21T18:51:00.000","Title":"Is there a way to get the element that belong only to a dataset d1 and not to another one d2, with pandas?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"If I have two datasets d1 and d2, where the d1 columns are:\nd1_columns {X,Y,Z,T}\nand for d2 :\nd2_columns{X,Y,L,P}\nIs there a function f such that:\nf(d1,d2) = {Z,T} or equivalently: f(d1,d2) = {L,P} ?","AnswerCount":2,"Available Count":2,"Score":1.2,"is_accepted":true,"ViewCount":33,"Q_Id":63021214,"Users Score":0,"Answer":"Refer the following Code -\ndf1 = pd.DataFrame({'A':[1,2,3,4,5],'B':[2,5,4,7,8],'C':[4,1,7,5,6],'D':[2,5,4,7,8]}) #First Dataframe\ndf2 = pd.DataFrame({'A':[1,2,3,4,5],'B':[2,5,4,7,8],'E':[5,6,7,4,4],'F':[5,7,8,9,4]}) #Second Dataframe\nnew_df = pd.concat([df1,df2],axis=1) # Concat the dataframes\nnew_df[list(set(new_df.columns).difference(df1.columns))] # Gives us Columns (E,F)\nnew_df[list(set(new_df.columns).difference(df2.columns))] # Gives us Columns (C.D)","Q_Score":0,"Tags":"python,pandas","A_Id":63073867,"CreationDate":"2020-07-21T18:51:00.000","Title":"Is there a way to get the element that belong only to a dataset d1 and not to another one d2, with pandas?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working on data set where there are four predictors. There is good linear relation with one of the predictors but with other three i think polynomial would fit. Is there any method in python where i can predict single variable combining linear regression on one predictors and polynomial or other non-linear regression on other three predictors?\nPlease help.","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":366,"Q_Id":63027352,"Users Score":1,"Answer":"You can fit one polynomial expression for all features which should take care of the linear one as well. The only difference is that the coefficient of the linear one will be of order 1.","Q_Score":0,"Tags":"python,machine-learning,regression","A_Id":63027504,"CreationDate":"2020-07-22T05:14:00.000","Title":"linear and nonlinear regression combined in python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Does anyone know how to feed in an initial solution or matrix of initial solutions into the differential evolution function from the Scipy library?\nThe documentation doesn't explain if its possible but I know that initial solution implementation is not unusual. Scipy is so widely used I would expect it to have that type of functionality.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":160,"Q_Id":63031913,"Users Score":0,"Answer":"Ok, after review and testing I believe I now understand it.\nThere are a set of parameters that the scipy.optimize.differential_evolution(...) function can accept, one is the init parameter which allows you to upload an array of solutions. Personally I was looking at a set of coordinates so enumerated them into an array and fed in 99 other variations of it (100 different solutions) and fed this matrix into the inti parameter. I believe it needs to have more than 4 solutions or your are going to get a tuple error.\nI probably didn't need to ask\/answer the question though it may help others that got equally confused.","Q_Score":0,"Tags":"python,scipy,initialization,scipy-optimize,differential-evolution","A_Id":63034841,"CreationDate":"2020-07-22T10:14:00.000","Title":"Scipy Differential Evolution initial solution(s) input","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have been having problems with dask.distributed. Everytime I run it, it always has memory issues and kills my workers, when running on my laptop. I have a laptop with 16GB and run 4 workers, when I try to run a computation it seems to straight away kill workers. Ive tried limiting the ram to 3.5 GB but that doesnt work. My chunk sizes are around 200MB. I am using a zarr file with a 3diim array stored. So I don't understand why I have this issue. I had it working a few months ago and took some time away from it when this problem occurred. I tired a smaller overall data set and the same issue occurs. Any thoughts?\nWhen I run this outside of distributed I don't have the same issue?\nHappy to show error reports and a minimum example if anyone has idea's?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":47,"Q_Id":63044326,"Users Score":0,"Answer":"I recommend looking at logs. KilledWorker errors can occur for many reasons. For example you might not have the same version of Dask everywhere or you might be launching workers someplace where they can't connect.","Q_Score":0,"Tags":"python,dask,dask-distributed","A_Id":63310776,"CreationDate":"2020-07-22T22:54:00.000","Title":"Dask.distributed kill workers Everytime I run","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":1,"Web Development":0},{"Question":"So, I have a dataframe with the name of all the states in the USA and a few cities for each state. However, I need to change the names of the states to its two letter acronyms (ex: Nevada becomes NV and Wyoming becomes WY).\nA have a dictionary with the name of the states\/territories and its respective acronym, as you can see bellow:\nstates = {'OH': 'Ohio', 'KY': 'Kentucky', 'AS': 'American Samoa', 'NV': 'Nevada', 'WY': 'Wyoming', 'NA': 'National', 'AL': 'Alabama' and on an on an on\nI was thinking about creating a new column, and once it was created, I'd drop the 'States' column. But my code bellow is filling the new column with NaN values\nstate_town_df['acronym'] = state_town_df['State'].map(states)\nIs there any simple way to solve it?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":85,"Q_Id":63044687,"Users Score":1,"Answer":"In the dictionary the key is acronym and the value is the state. I assume that State column is not an acronym. You may have to inverse the dictionary such as inv_map = {v: k for k, v in states.items()}","Q_Score":0,"Tags":"python,pandas","A_Id":63044722,"CreationDate":"2020-07-22T23:42:00.000","Title":"Replace the values of a given column in pandas with a dictionary","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have installed pandas in my venv. The import statement from pandas import DataFrame is not recognized in Pycharm. DataFrame is underlined with red line. When I run the code, it works fine. Why DataFrame is not recognized.\n\nAlso suddenly, relative paths of local packages stopped working in PyCharm but code runs fine though.\nAbsolute path also works fine.\n\n\nI have tried setting project as \"source code\" in settings but does not solve the problem.","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":51,"Q_Id":63053400,"Users Score":0,"Answer":"You might install the DataFrame on your default python environment.\nTo make sure you have installed on venv environment.\n1- Activate your venveither form terminal or command-prompt by execuitng: source ~\/envs\/venv\/bin\/activate\n2- Install pandas: pip install pandas\nNow If you have installed correctly you will have a warning. Otherwise the package will be installed on your venvenvironment.","Q_Score":0,"Tags":"python,pycharm","A_Id":63119146,"CreationDate":"2020-07-23T11:40:00.000","Title":"Cannot import DataFrame in PyCharm","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have installed pandas in my venv. The import statement from pandas import DataFrame is not recognized in Pycharm. DataFrame is underlined with red line. When I run the code, it works fine. Why DataFrame is not recognized.\n\nAlso suddenly, relative paths of local packages stopped working in PyCharm but code runs fine though.\nAbsolute path also works fine.\n\n\nI have tried setting project as \"source code\" in settings but does not solve the problem.","AnswerCount":2,"Available Count":2,"Score":0.0996679946,"is_accepted":false,"ViewCount":51,"Q_Id":63053400,"Users Score":1,"Answer":"File -> invalidate Caches\\Restart (did not work)\nRemoved .idea file and opened project again (did not work)\nPointed project to new venv with all installed dependencies (did not work)\n\nFinally, uninstalled PyCharm and installed again. It solved my problem.","Q_Score":0,"Tags":"python,pycharm","A_Id":63130139,"CreationDate":"2020-07-23T11:40:00.000","Title":"Cannot import DataFrame in PyCharm","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a dataframe with two columns, one column is medicine name of dtype object it contains medicine name and few of the medicine name followed by its mg(eg. Avil25 and other row for Avil50) and other column is Price of dtype int . I'm trying to convert medicine name column into a scipy csr_matrix using the following lines of code:\nfrom scipy.sparse import csr_matrix\nsparse_matrix = csr_matrix(medName)\nI am getting the following error message:\n\nTypeError: no supported conversion for types: (dtype('O'),)\n\nas an alternative way I tried to remove the integers using(medName.str.replace('\\d+', '')) from dataframe and tried sparse_matrix = csr_matrix(medName.astype(str)) . Still i am getting the same error.\n\nWhat's going on wrong here?\nWhat is another way to convert this dataframe to csr matrix?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":183,"Q_Id":63056536,"Users Score":0,"Answer":"you will have the encode strings to numeric data types for it to be made sparse. One solution ( probably not the most memory efficient) is to make a networkx graph, where the string-words will be the nodes, using the nodelist of the graph you can keep track of the word to numeric mapping.","Q_Score":0,"Tags":"python-3.x,pandas,scipy,sparse-matrix","A_Id":63061525,"CreationDate":"2020-07-23T14:23:00.000","Title":"converting a Object (containing string and integers) Pandas dataframe to a scipy sparse matrix","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"My dataset contains incorrect date of birth entries. How do I resolve this?,since this data is important to my analysis as it will help in segmentation. E.g: a customer has a date of birth entry of 1843-12-21, which is clearly not proper. Similar issues are also present.\nThanks in advance.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":65,"Q_Id":63057658,"Users Score":0,"Answer":"There are different ways to deal with it:\n\nTry to understand the reason of the error. Maybe in some cases people input data in the wrong fields.\n\nMake an educated guess - for example 1843 could be 1943.\n\nConsider these errors to be missing values.","Q_Score":0,"Tags":"python-3.x,data-science,data-cleaning,data-processing","A_Id":63097521,"CreationDate":"2020-07-23T15:21:00.000","Title":"How to resolve improper date of birth data","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I installed\/imported streamlit, numpy, and pandas but I do not know how I can see the charts I have made. How do I deploy it on repl.it?","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":230,"Q_Id":63058342,"Users Score":1,"Answer":"You can not deploy streamlit application within repl.it because\n\nIn order to protect against CSRF attacks, we send a cookie with each request.\nTo do so, we must specify allowable origins, which places a restriction on\ncross-origin resource sharing.\n\nOne solution is push your code from repl.it to GitHub. Then deploy from GitHub on share.streamlit.io.","Q_Score":0,"Tags":"python,repl.it,streamlit","A_Id":68072848,"CreationDate":"2020-07-23T15:56:00.000","Title":"How can I deploy a streamlit application in repl.it?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to install Tensorflow 1.14 for a package that I am trying to use. I tried:\npip3 uninstall tensorflow\nThen I tried to install Tensorflow 1.14 using:\npip3 install tensorflow==1.14\nand I get the following error\nERROR: Could not find a version that satisfies the requirement tensorflow==1.14 (from versions: 2.2.0rc3, 2.2.0rc4, 2.2.0, 2.3.0rc0, 2.3.0rc1, 2.3.0rc2) ERROR: No matching distribution found for tensorflow==1.14\nI also tried making a new virtual env and tried the following commands but it didn't work. Is there any way to install Tensorflow 1?","AnswerCount":5,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":8604,"Q_Id":63059979,"Users Score":0,"Answer":"I faced the same issue while installing tensorflow version 1.14.0. The best solution i tried is:\nNote that your Python version is 3.7.8\nSteps:\n\nOpen python 3.7.8 script folder C:\\Users\\mypc\\AppData\\Local\\Programs\\Python\\Python37\\Scripts folder and type \"cmd\" in above bar, which opens it in the command prompt.\nTo install tensorflow-1.14.0 type : pip install tensorflow==1.14.0\nTo install keras-2.2.4 type : pip install keras==2.2.4","Q_Score":13,"Tags":"python,tensorflow","A_Id":72236507,"CreationDate":"2020-07-23T17:33:00.000","Title":"Cannot install TensorFlow 1.x","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"For context, I'm currently working on a machine learning problem where there exists fairly large imbalances in our dataset, and we've been trying to find ways to work around our data imbalance to extract useful metrics\/measures of performance. One metric we've really wanted to use is a ROC curve plot for each of our classes, but we've found that since a large portion of our data is negative in nature (meaning that most of the time, our images don't contain anything in them), the False Positive Rate is basically getting \"squished\" close to 0 since our number of True Negatives is so large, so our ROC plots look basically perfect when in reality they are being heavily skewed by our high TN count.\nFor example, a given class can have as many as 30,000 Negative cases, but only 2,000 or so positive cases, so 90+% accuracy can be achieved if the model were to simply always predict negatively. Our problem is also a multi-class problem, so it's not feasible to simply remove negative cases from the data since removing a negative case could be inadvertently removing a positive case for another class in a given image. We've done what data thinning\/reduction we can by removing all images where there are no occurrences of any class in a given image, but there still exists a large data imbalance in our data after this thinning process.\nIn the meantime we've switched over to using precision-recall plots, and those have yielded more reasonable results since precision and recall don't depend on the True Negative count, but we've recently wanted to switch back to using ROC curves, and I'm trying to find a solution to address the skewed plots we were seeing prior.\nOne idea I had was simply plotting the #True Positives vs. #False Positives, and since doing this I've seen more reasonable looking curves. By doing this, I am able to avoid the issue of the False Positive Rate getting squished down due to the high TN count, and the plot essentially conveys the same information (the trade-off between True Positives and False Positives). What's wrong with this idea? Is there any other approach I can take to getting better results from my ROC plots?\nOne idea my colleague proposed was as follows:\n\" Do you think you can redo the ROC curves by removing most of these non-events from the statistics? Maybe keep about as much non-events as for the class with the highest number of events? \"\nI wasn't sure exactly what he meant, so I asked him for some clarification and he said this:\n\" You can still re-balance the data for your ROC analysis by randomly excluding most of the \"nothing\" events so that they do not dominate the statistics in your confusion matrix. Assuming your have enough random samples of the \"nothing events\" in your analysis, that smaller subset can be an accurate representation of the true \"nothing\" population \"\nI'm still not sure what exactly he means by this or how I am supposed to implement it, and I've asked him again for clarification, but in the mean time I was hoping I could get some more insight elsewhere.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":170,"Q_Id":63060554,"Users Score":0,"Answer":"No, plotting TP against FP does not make sense, in your case it would make more sense to use the precision\/recall curve. On one axis, you plot the precision (aka positive predictive value) and on the other axis you plot the recall (aka sensitivity).\nThe precision is given by TP\/(TP+FP) and recall is given by TP\/(TP+FN), where TP is true positives, FP is false positives and FN is false negatives.","Q_Score":0,"Tags":"python,roc,confusion-matrix,precision-recall","A_Id":63134949,"CreationDate":"2020-07-23T18:10:00.000","Title":"Could I make a ROC curve using TP vs. FP instead of TPR vs. FPR?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"The numpy function np.random.choice takes in an optional parameter called 'p' that denotes the probability distribution of the values it is sampling . So , my question is , even though the function generates random values , do values that have higher probability more likely to be sampled ? Meaning , does it randomly choose a value from a subset of \" Most probable values \" ?\nAm I right in perceiving it that way ? Or can someone please correct my assumption ?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":646,"Q_Id":63086570,"Users Score":0,"Answer":"It is an optional array of probabilities p with which respective elements of sampled array A are sampled. So A and p should have the same number of elements and all elements of p should add up to 1 (as all discrete probabilities should).","Q_Score":1,"Tags":"python,numpy,random,random-seed,probability-distribution","A_Id":63086602,"CreationDate":"2020-07-25T09:18:00.000","Title":"Probability distribution in np.random.choice","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have trained model with keras and saved in with the help of pytorch. Will it cause any problems in the future. As far as I know the only difference between them is Keras saves its model's weights as doubles while PyTorch saves its weights as floats.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":190,"Q_Id":63086902,"Users Score":1,"Answer":"You can convert your model to double by doing\n\nmodel.double()\n\nNote that after this, you will need your input to be DoubleTensor.","Q_Score":0,"Tags":"python,machine-learning,keras,pytorch","A_Id":63092605,"CreationDate":"2020-07-25T09:53:00.000","Title":"Saving model in pytorch and keras","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I Have an dataset folder of size 690Mo in my google drive, I would to copy the hole dataset on my google colab notebook to train my model, but the process of copying is very long, so how I can download the folder from Google drive with use of python script ?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":3011,"Q_Id":63088546,"Users Score":0,"Answer":"Maybe, you have too many files on the root directory of Google Drive or in the dataset folder.\n\nIf you have too many files and folders in root directory, then you\nshould clean up and sort it in less folders.\n\n\nIf you have many files in dataset folder, then try the following\nsolutions:\n\nMake a compressed file of your dataset folder and save it to drive. Then while running copy that compressed file (will take less than a\nminute for 690Mb) and extract it in Colab.\n\nUpload your dataset to any other platform (say OneDrive, Mega, etc.), get the link, and download on Colab using that link.","Q_Score":0,"Tags":"python,python-3.x,python-2.7,google-drive-api,google-colaboratory","A_Id":63088659,"CreationDate":"2020-07-25T12:54:00.000","Title":"Download folder from Google drive to colab notebook","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Say I have orthogonal vectors of dimension n. I have two questions:\n\nHow to create\/initialize n such orthogonal vectors in python using the existing packages (numpy, scipy, pytorch etc)? Ideally these basis vectors should be as random as possible given the constraints, that is avoiding values such as 1,0,-1 as much as possible.\nHow can I rotate them by an angle alpha so that they remain orthogonal in high dimensional space? Again, I would like to do this in python, preferably using existing implementation in some of the packages.","AnswerCount":3,"Available Count":1,"Score":0.0665680765,"is_accepted":false,"ViewCount":665,"Q_Id":63089387,"Users Score":1,"Answer":"You could do a QR decomposition of a random matrix, and set the R-component to zero. This will yield a random orthogonal matrix.\nVary one of the Givens angles in the Q components and you get a random rotation.","Q_Score":1,"Tags":"python,numpy,scipy,rotational-matrices,orthogonal","A_Id":63092682,"CreationDate":"2020-07-25T14:13:00.000","Title":"Rotating high dimensional orthogonal vectors in python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"VSCode, Python3.8.4 64-bit, first assignment with Jupyter notebooks. I have installed numpy but when I run import numpy as np I receive ModuleNotFoundError: No module named 'numpy'. I'm very new please be gentle.","AnswerCount":2,"Available Count":2,"Score":0.0996679946,"is_accepted":false,"ViewCount":109,"Q_Id":63092643,"Users Score":1,"Answer":"Write pip list in anaconda prompt or cmd and search for it if you don t find it then it s a problem of path","Q_Score":1,"Tags":"python-3.x,numpy,jupyter-notebook","A_Id":63093019,"CreationDate":"2020-07-25T19:27:00.000","Title":"Numpy not recognized even though it is installed","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"VSCode, Python3.8.4 64-bit, first assignment with Jupyter notebooks. I have installed numpy but when I run import numpy as np I receive ModuleNotFoundError: No module named 'numpy'. I'm very new please be gentle.","AnswerCount":2,"Available Count":2,"Score":0.0996679946,"is_accepted":false,"ViewCount":109,"Q_Id":63092643,"Users Score":1,"Answer":"I don't know why this worked but I changed my python interpreter in VSCode to 3.8.5 and now I'm all good.","Q_Score":1,"Tags":"python-3.x,numpy,jupyter-notebook","A_Id":63095482,"CreationDate":"2020-07-25T19:27:00.000","Title":"Numpy not recognized even though it is installed","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I trying to feed a keras model tensor with numpy array values. But the tensor is 4D and the array is 3D. How can I to convert this 3D numpy array (128, 128, 3) in a 4D (?, 128, 128, 3) tensor?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":863,"Q_Id":63094152,"Users Score":0,"Answer":"Just use np.expand_dims to extend the first dimension. The 4D tensor means that you are having a batch of some images with 3 channels. Since you have just one image, add into an array and give it to the model or use np.expand_dims(image_ref, axis=0).","Q_Score":0,"Tags":"python,tensorflow,keras","A_Id":63094470,"CreationDate":"2020-07-25T22:22:00.000","Title":"How do I feed a tensor in Keras model using a numpy array values?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I was able to mount Azure Blob Container to my Databricks DBFS and was able to read the data as well. While writing, I was able to see the files in the mount point from within databricks, however, it does not reflect in the blob storage. Can someone help?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":723,"Q_Id":63098954,"Users Score":0,"Answer":"Chances are that your path is incorrect.\nCheck the mounted path with dbutils.fs.mounts() and ensure it is in your saving path. Also check that your saving path starts with dbfs:\/ and not \/dbfs\/.\nDon\u2019t hesitate to share your script.","Q_Score":1,"Tags":"python,azure,azure-blob-storage,databricks,mount","A_Id":63100309,"CreationDate":"2020-07-26T10:31:00.000","Title":"Writing Data to Azure Blob Storage from Azure Databricks","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":1,"Web Development":0},{"Question":"I have a text file that has encoded strings.\nI am decoding them using urllib.parse.unquote(string_df.encoded_string) and storing it in a dataframe.\nI want to export this dataframe to a text file.\nHowever, it just adds garbage values.\nFor example:\nEncoded String: %D1%81%D0%BF%D0%B0%D1%81%D0%BE-%D0%BF%D1%80%D0...\nDecoded using urllib.parse.unquote : \u0441\u043f\u0430\u0441\u043e-\u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0441\u043a\u0438\u0439 \u0441\u043e\u0431\u043e\u0440\nExported value in text file: ?????-?????????????? ?????\nI have tried exporting in an excel file using to_excel but when I open the excel file, it gives illegal character error.\nAlso tried using numpy.savetxt but it gives the same ?????-?????????????? ?????.\nAnyway I can export it to a flat file and still have the desired \"\u0441\u043f\u0430\u0441\u043e-\u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0441\u043a\u0438\u0439 \u0441\u043e\u0431\u043e\u0440\" result?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":81,"Q_Id":63103778,"Users Score":1,"Answer":"This looks like a character-encoding problem, make sure your CSV file is opened as 'UTF-8' or other compatible encoding, not ASCII, as '\u0441\u043f\u0430\u0441\u043e-\u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0441\u043a\u0438\u0439 \u0441\u043e\u0431\u043e\u0440' are cyrillic and not latin characters.","Q_Score":0,"Tags":"python,python-3.x,pandas,numpy,decode","A_Id":63103890,"CreationDate":"2020-07-26T17:58:00.000","Title":"Python: to_csv for decoded dataframe","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Okay, so I recently upgraded Spyder to version 4.1.4 and ever since I have the issue that all plots are extremely slow in showing. I am plotting Outline with Qt5 (v. 5.9.2). I already tried downgrading spyder back to 4.1.3 as well as 4.1.2 but neither helped.\nSo when I plot some simple data the plot in the extra window takes a few seconds to actually show the data and when I want to switch between one plot or the other it takes 5-10 seconds to show me the other plot.\nHas anyone else experienced this issue? I could not find anything online so far. Any suggestions are welcome :)","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":207,"Q_Id":63111318,"Users Score":2,"Answer":"I am experiencing the same thing. All my Qt5 applications became extremely slow after upgrading to Spyder 4.1.4, did not find a solution yet, unfortunately.\n\/e Rolling back my entire Conda environment did 'solve' it for me though.","Q_Score":3,"Tags":"python,pyqt5,spyder","A_Id":63112159,"CreationDate":"2020-07-27T08:20:00.000","Title":"Plotting Outline with PyQt5 extremely slow","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":1,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"In a project I have to store a sequence of successive rotations of an object in python. I intend to store them using scipy.spatial.transform.Rotation objects.\nI have noticed that two options are available.\n\nI store a multitude of Rotation object in an array, each Rotation object containing a single rotation of my sequence.\n\nI store every rotation in the same Rotation object, effectively stacking them in a single object.\n\n\nI wondered what were the trade offs between the methods in terms of computational speed and data access speed. And ultimately which method should be preferred.\nIn my particular case:\n\nI have a fairly big set of rotations (around 2'000'000).\nI would like to speed up the accessing time for my data as much as possible.\nI am not concerned with memory usage so I am willing to trade space for speed.\nI don't intend to apply my rotations to anything. This is purely for storage use.\nI will have to access my rotations both as quaternions (.as_quat()) and as euler angles (.as_euler())\nI will have to split my data into smaller chunk at some point (And I am aware that if I use a single Rotation object I might have to re-create on per chunk in order to split my data correctly)\n\nWhat I am looking for:\n\nThe method that has the fastest access time\nThe method that is closer to good practice and coding convention in python\n\nThanks in advance.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":492,"Q_Id":63116277,"Users Score":1,"Answer":"Alright so I'll throw in the first elements I have.\nFor both you end up accessing an iterable and an object (just in a different order). Therefor there should not be any major difference in accessing speed.\nThe list of R is easier to access and manipulate afterwards. Hence if you are suceptible of changing anything in your rotation sequence it is the easier way. There for using a single object requires some extra-code for manipulation and might be slower.\nHowever it really depends on what you do and I have no data to prove that it is significantly slower.\nThe single object should take less memory space since there is only one instance, where as the list of object has nb_rotation times more.\nI already mentionned that this was not critical in my case it is not critical. Again I don't have any data to support this but I expect the difference to be significative since I have about 2'000'000 rotations.\nRegarding those facts I would make the decision as follow:\n\nIf you're just looking to use the object for storage then the single object is probably more efficient. (However that would apply very specific cases since you could also compute the resulting rotation and store a single quaternion or rotation object)\n\nIf you're looking to manipulate your data in any way then the list of object seems more indicated for that. The only real draw back is memory use how ever if you manipulate the data you would also have to unpack the single object at some point, leading to a similar problem, if not worse due to data duplication.\n\n\nIn my case I will be using the list of object.","Q_Score":2,"Tags":"python,performance,scipy,scipy-spatial","A_Id":63243054,"CreationDate":"2020-07-27T13:22:00.000","Title":"scipy.spatial.transform.Rotation Array of rotation vs Stack inside the same object","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to use the compare() function available in Pandas 1.1.0. I am doing an update in Anaconda to Pandas, but it just takes me to 0.25?","AnswerCount":3,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":9042,"Q_Id":63119244,"Users Score":0,"Answer":"Typing conda update pandas should do the job.","Q_Score":1,"Tags":"python,pandas,conda","A_Id":63119285,"CreationDate":"2020-07-27T16:13:00.000","Title":"How to update Pandas in Anaconda","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to use the compare() function available in Pandas 1.1.0. I am doing an update in Anaconda to Pandas, but it just takes me to 0.25?","AnswerCount":3,"Available Count":2,"Score":0.0665680765,"is_accepted":false,"ViewCount":9042,"Q_Id":63119244,"Users Score":1,"Answer":"Have you tried:\nconda install pandas=1.1.0.\nYou may need to add a channel that contains pandas 1.1.0.\nConda forge contains pandas 1.0.5\nconda config --add channels conda-forge","Q_Score":1,"Tags":"python,pandas,conda","A_Id":63119317,"CreationDate":"2020-07-27T16:13:00.000","Title":"How to update Pandas in Anaconda","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working on a project to find similarity among products. The model splits the excel data sheet into 90% training \/ 10% validation. When I check manually for validation the model works pretty well. But I am having trouble with the evaluation process. How should I find accuracy, precision, recall and F1 score to understand how well my model works?\nI am very new to machine learning, still learning, please give me some clues where to start.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":548,"Q_Id":63134913,"Users Score":3,"Answer":"Word2vec is an algorithm that's considered 'unsupervised' \u2013 it's not trained using specified 'correct' answers, but rather learns from the patterns in any data. As a result, there's no native-to-word2vec idea of 'accuracy', 'precision', etcetera \u2013 those concepts only have meaning in relation to a set of desired answers.\nSo to calculate those values, you have to use those word-vectors in some other downstream task, and devise your own evaluation for that downstream task. Then you can calculate accuracy & other values for that whole system (including the word2vec step). This may include applying your judgement, or that of other reviewers, about what the result \"should\" be in certain cases.\nWithout any examples of your data, it's not yet clear what your Word2Vec model is doing, and how products are represented in it. (What's the individual items in the customers_train list you've created? Where do product names\/identifiers come in? What kinds of similarity-questions or end-user operations do you need to be performing?)","Q_Score":0,"Tags":"python,cross-validation,word2vec,evaluation","A_Id":63146519,"CreationDate":"2020-07-28T13:08:00.000","Title":"How to find accuracy, precision, recall, f1 score for my word2vec model?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am attempting to calculate Kendall's tau for a large matrix of data stored in a Pandas dataframe. Using the corr function, with method='kendall', I am receiving NaN for a row that has only one value (repeated for the length of the array). Is there a way to resolve it? The same issue happened with Spearman's correlation as well, presumably because Python doesn't know how to rank an array that has a single repeated value, which leaves me with Pearson's correlation -- which I am hesitant to use due to its normality and linearity assumptions.\nAny advice is greatly appreciated!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":807,"Q_Id":63143659,"Users Score":0,"Answer":"I decided to abandon the complicated mathematics in favor of intuition. Because the NaN values arose only on arrays with constant values, it occurred to me that there is no relationship between it and the other data, so I set its Spearman and Kendall correlations to zero.","Q_Score":1,"Tags":"python,pandas,scipy,statistics,correlation","A_Id":63178640,"CreationDate":"2020-07-28T22:24:00.000","Title":"NaN values with Pandas Spearman and Kendall correlations","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am translating codes from Stata to R. The same random seed does not generate the same outputs. I am not sure if this is also the case in other languages (Python, Java etc.). How to generate identical random numbers in different languages?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":206,"Q_Id":63153166,"Users Score":3,"Answer":"R uses its own initialization method for the Mersenne-Twister (see help(\"set.seed\")), which differs from what other languages do. The easiest way to ensure the same PRNG is used (and to avoid implementing something subpar yourself), is simply interfacing R and Stata and using the PRNG from either of these.\nHowever, it's worth keeping in mind that achieving true reproducibility is impossible unless you are using exactly the same software on exactly the same hardware and OS. Thus, I wouldn't spent effort on trying to achieve the same PRNG streams with different software. Instead I would generate these numbers, store them and import them as needed.","Q_Score":0,"Tags":"java,python,r,random,stata","A_Id":63153666,"CreationDate":"2020-07-29T12:02:00.000","Title":"How to generate the same random numbers in one language as in another?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I created siamese model with triplet loss function.\nI tested it a little bit and notice that when object are small, like 2\/5 of the image space, model is matching images with similar background instead of object.\nSome of pictures were taken on the same background what is causing the issue as I think.\nIs there any way to maybe extract objects? train model to recognize those object, ignore background?\nShape of each image is (150, 150, 3).","AnswerCount":2,"Available Count":2,"Score":1.2,"is_accepted":true,"ViewCount":40,"Q_Id":63153619,"Users Score":1,"Answer":"the siamese model actually deepened on encoded data simply its match between tow encoded feature representation so it not know your object of intraset you have extract object than do the matching between them\nfor example if the model you built was for face matching\nuse opencv to extract the faces and than do the matching you want to make","Q_Score":0,"Tags":"python,image,tensorflow,image-processing,deep-learning","A_Id":63157792,"CreationDate":"2020-07-29T12:28:00.000","Title":"Model is recognizing background better than objects","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":1,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I created siamese model with triplet loss function.\nI tested it a little bit and notice that when object are small, like 2\/5 of the image space, model is matching images with similar background instead of object.\nSome of pictures were taken on the same background what is causing the issue as I think.\nIs there any way to maybe extract objects? train model to recognize those object, ignore background?\nShape of each image is (150, 150, 3).","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":40,"Q_Id":63153619,"Users Score":0,"Answer":"You can try to train with masks or do random croppings of the images as a data augmentation strategy or you can change your model for more finer convolutions. The easiest would be to do the random cropping and then, training; that will help the network to disentangle the object from the background.","Q_Score":0,"Tags":"python,image,tensorflow,image-processing,deep-learning","A_Id":63153804,"CreationDate":"2020-07-29T12:28:00.000","Title":"Model is recognizing background better than objects","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":1,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Can you not just use categorical variables like in R where you can feed factor variables into the model?","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":71,"Q_Id":63154361,"Users Score":1,"Answer":"The support is not there in scikit-learn (yet), no. Other python packages for tree models do support categorical variables though, e.g. H2O's tree models and LightGBM (and in a different way, CatBoost).","Q_Score":0,"Tags":"python,r,machine-learning,scikit-learn","A_Id":63194478,"CreationDate":"2020-07-29T13:08:00.000","Title":"In python, do you have to create dummy variables to train a model such as RandomForests?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Does anyone know if it is possible to use n_simulation = None in 'MarkovModel' algorithm in 'pychhatr' library in Python?\nIt throws me an error it must be an integer, but in docsting i have information like that:\n'n_simulations : one of {int, None}; default=10000'\nI`d like to do something like nsim = NULL in 'markov_model' in 'ChannelAttribution' package in R, these two algorithms are similarly implemented.\nI don`t know how does it works exactly, how many simulations from a transition matrix I have using NULL.\nCould anyone help with this case?\nRegards,\nSylwia","AnswerCount":3,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":216,"Q_Id":63155356,"Users Score":0,"Answer":"Out of curiosity I spent some minutes staring intensely at the source code of both pychattr module and ChannelAttribution package.\nI'm not really familiar with the model, but are you really able to call this in R with \"nsim=NULL\"? Unless I missed something if you omit this parameter it will use value 100000 as the default and if parameter exists, the R wrapper will complain if it's not a positive number.\nRegards,\nMaciej","Q_Score":0,"Tags":"python,r,markov","A_Id":63160750,"CreationDate":"2020-07-29T13:58:00.000","Title":"'pychattr' library in Python, 'n_simulations' parameter","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Does anyone know if it is possible to use n_simulation = None in 'MarkovModel' algorithm in 'pychhatr' library in Python?\nIt throws me an error it must be an integer, but in docsting i have information like that:\n'n_simulations : one of {int, None}; default=10000'\nI`d like to do something like nsim = NULL in 'markov_model' in 'ChannelAttribution' package in R, these two algorithms are similarly implemented.\nI don`t know how does it works exactly, how many simulations from a transition matrix I have using NULL.\nCould anyone help with this case?\nRegards,\nSylwia","AnswerCount":3,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":216,"Q_Id":63155356,"Users Score":0,"Answer":"I checked that 'pychattr' (Python) doesn`t support value None but it supports n_simulations = 0 and it sets n_simulations to 1e6 (1 000 000).\n'ChannelAttribution' (R) replaces nsim = NULL and nsim = 0 to nsim = 1e6 (1 000 000) too.\nIn latest version of 'ChannelAttribution' (27.07.2020) we have nsim_start parameter instead of nsim and it doesn`t support 0 or NULL value anymore.\nImportant: default value of nsim_start is 1e5 (100 000) and from my experience it`s not enough in many cases.\nRegards,\nSylwia","Q_Score":0,"Tags":"python,r,markov","A_Id":63175481,"CreationDate":"2020-07-29T13:58:00.000","Title":"'pychattr' library in Python, 'n_simulations' parameter","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to run a study, using the optimize function with the default sampler and Median pruner.\nevery run crashes, sometimes after 1 succefull trial sometimes without completing any.\nThe crash message is: Process finished with exit code 137 (interrupted by signal 9: SIGKILL)\nExpected behavior\nrunning a study\nEnvironment\n\nOptuna version:\n2.0.0\nPython version: 3.8\nOS:QubeOS with debian 10 VM\n(Optional) Other libraries and their versions:\nPytorch '1.5.0+cpu'\n\nError messages, stack traces, or logs\nProcess finished with exit code 137 (interrupted by signal 9: SIGKILL)\nwhat cause such an error?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":299,"Q_Id":63155994,"Users Score":0,"Answer":"One likely situation is that your process consumes a lot of memory and gets killed by the operating system's OOM killer. You can monitor the memory consumption of your process using a tool like top and see if it uses a lot of memory.\nYou can also run dmesg in the console and look for messages from the OOM killer in the output. The OOM killer will usually print there which process it killed. Check whether the process ID is the one of your process.\nIn case the process is indeed killed by the OOM killer then the only remedy probably is to reduce the memory consumption of the program (or get a bigger machine).","Q_Score":0,"Tags":"python,pycharm,pytorch,optuna","A_Id":63156511,"CreationDate":"2020-07-29T14:32:00.000","Title":"Getting SIGKILL when running study optimization with Optuna on PyCharm","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"How do you decide the critical values(alpha) and analyze with the p value\nexample: stats.ttest_ind(early['assignment1_grade'], late['assignment1_grade'])\n(2 series with score of their assignments)\nI understand the concept that if the p value is greater than the alpha value then the null hypothesis cant be neglected.\nIm doing a course and instructor said that the alpha value here is 0.05 but how do you determine it.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":151,"Q_Id":63157884,"Users Score":0,"Answer":"The alpha value cannot be determined in the sense that there were a formula to calculate it. Instead, it is arbitrarily chosen, ideally before the study is conducted.\nThe value alpha = 0.05 is a common choice that goes back to a suggestion by Ronald Fisher in his influential book Statistical Methods for Research Workers (first published in 1925). The only particular reason for this value is that if the test statistic has a normal distribution under the null hypothesis, then for a two-tailed test with alpha = 0.05 the critical values of the test statistic will be its mean plus\/minus 2 (more exactly, 1.96) times its standard deviation.\nIn fact, you don't need alpha when you calculate the p value, because you can just publish the p value and then every reader can decide whether to consider it low enough for any given purpose or not.","Q_Score":0,"Tags":"python-3.x,scipy","A_Id":63160949,"CreationDate":"2020-07-29T16:10:00.000","Title":"How to know the alpha or critical value of your t test analysis?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have 50 time series, each having at least 500 data points (some series have as much as 2000+ data points). All the time series go from a value of 1.089 to 0.886, so you can see that the resolution for each dataset comes close to 10e-4, i.e. the data is something like:\n1.079299, 1.078809, 1.078479, 1.078389, 1.078362,... and so on in a decreasing fashion from 1.089 to 0.886 for all 50 time-series.\nMy questions hence, are:\n\nCan LSTMs handle such dense data?\nIn order to avoid overfitting, what can be the suggested number of epochs, timesteps per batch, batches, hidden layers and neurons per layer?\n\nI have been struggling with this for more than a week, and no other source that I could find talks about this specific case, so it could also help others.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":74,"Q_Id":63167041,"Users Score":3,"Answer":"A good question and I can understand why you did not find a lot of explanations because there are many tutorials which cover some basic concepts and aspects, not necessarily custom problems.\n\nYou have 50 time series. However, the frequency of your data is not the same for each time series. You have to interpolate in order to reach the same number of samples for each time series if you want to properly construct the dataset.\nLSTMs can handle such dense data. It can be both a classification and a regression problem, neural networks can adapt to such situations.\nIn order to avoid overfitting(LSTMs are very prone to it), the first major aspect to take into consideration is the hidden layers and the number of units per layer. Normally people tend to use 256-512 by default since in Natural Language Processing where you process huge datasets they are suitable. In my experience, for simpler regression\/classification problems you do not need such a big number, it will only lead to overfitting in smaller problems.\n\nTherefore, taking into consideration (1) and (2), start with an LSTM\/GRU with 32 units and then the output layer. If you see that you do not have good results, add another layer (64 first 32 second) and then the output layer.\nAdmittedly, timesteps per batch is of crucial importance. This cannot be determined here, you have to manually iterate through values of it and see what yields you the best results. I assume you create your dataset via sliding window manner; consider this(window size) also a hyperparameter to alter before arriving at the batch and epochs ones.","Q_Score":2,"Tags":"python,keras,deep-learning,time-series,lstm","A_Id":63167865,"CreationDate":"2020-07-30T05:59:00.000","Title":"Can LSTMs handle incredibly dense time-series data?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm really confused as to when I should apply MinMaxScaler or scaling in general to my dataset, whether is before splitting into train_test_split or after splitting into training and validation split, then fit and transform on X_train and transform on X_test. Really confused about what the general rule of thumb is in applying this...","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":522,"Q_Id":63181857,"Users Score":0,"Answer":"You want to scale before training on the training set. After that, you scale the test and validation using the same mean and variance (i.e. train mean and variance) before inference.","Q_Score":0,"Tags":"python,validation","A_Id":63181913,"CreationDate":"2020-07-30T21:49:00.000","Title":"Is it best to apply MinMaxScaler to your dataset before splitting into training and Validation set or after splitting","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm really confused as to when I should apply MinMaxScaler or scaling in general to my dataset, whether is before splitting into train_test_split or after splitting into training and validation split, then fit and transform on X_train and transform on X_test. Really confused about what the general rule of thumb is in applying this...","AnswerCount":2,"Available Count":2,"Score":0.0996679946,"is_accepted":false,"ViewCount":522,"Q_Id":63181857,"Users Score":1,"Answer":"There is no rule of thumb, but generally, you definitely want to scale before splitting your dataset.\nI will tell you why. Logically, it would be confusing (for the model) while predicting if you have a dataset and split it into three subsets without assuring that the subset are more or less in the same distribution. Now if you are sure that the three subsets have the same distribution and not imbalanced (which is hard to prove) than I see no problem splitting before or after. I would never recommend it though.\nHence, the logical choice is to scale before and then do the splitting. An alternative approach for this is to use the StandardScaler instead of the MinMaxScaler. I find it less sensitive and from my experience, it is in most cases a better choice than the minmax.","Q_Score":0,"Tags":"python,validation","A_Id":63182093,"CreationDate":"2020-07-30T21:49:00.000","Title":"Is it best to apply MinMaxScaler to your dataset before splitting into training and Validation set or after splitting","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to convert my RGB image to Grayscale. While doing it, I came across the code:\nnp.dot(rgbImage[...,:3], [0.299, 0.587, 0.114])\nCan anyone please explain this line and values taken.?\n(Please don't provide any Wikipedia link)\nsearching for a simple explanation.","AnswerCount":1,"Available Count":1,"Score":0.537049567,"is_accepted":false,"ViewCount":34,"Q_Id":63190950,"Users Score":3,"Answer":"It is like converting into Grayscale using weighted or Luminosity method\nLuminosity = 0.299 \u00d7 R + 0.587 \u00d7 G + 0.114 \u00d7 B\nIt means 29.9% for RED, 58.7% for Green, and 11.4% Blue.","Q_Score":0,"Tags":"python,image-processing","A_Id":63191124,"CreationDate":"2020-07-31T11:23:00.000","Title":"Why are these particular values used to convert image to grayscale in python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm using Windows 10 with Spyder (Python 3.6). Everything seems fine, I leave my PC on for the training, but when I come back I find Spyder closed. I tried to uninstall and reinstall Tensorflow, updated everything, but it still happens. What should I do? I don't even get a crash message.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":53,"Q_Id":63199388,"Users Score":1,"Answer":"I had a similar problem. When I tried to train for longer than 30 epochs, Spyder stopped responding after some time (you had to close it). In my case the problem was solved by decreasing the (runtime) output.","Q_Score":0,"Tags":"python,neural-network,crash,spyder","A_Id":64059673,"CreationDate":"2020-07-31T21:36:00.000","Title":"Spyder closes while training a neural network","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working with the John Hopkins Covid data for personal use to create charts. The data shows cumulative deaths by country, I want deaths per day. Seems to me the easiest way is to create two dataframes and subtract one from the other. But the file has column names as dates and the code, e.g. df3 = df2 - df1 subtracts the columns with the matching dates. So I want to rename all the columns with some easy index, for example, 1, 2, 3, ....\nI cannot figure out how to do this?","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":113,"Q_Id":63205657,"Users Score":0,"Answer":"Thanks for the time and effort but I figured out a simple way.\nfor i, row in enumerate(df):\ndf.rename(columns = { row : str(i)}, inplace = True)\nto change the columns names and then\nfor i, row in enumerate(df):\ndf.rename(columns = { row : str( i + 43853)}, inplace = True)\nto change them back to the dates I want.","Q_Score":0,"Tags":"python,pandas,dataframe","A_Id":63208922,"CreationDate":"2020-08-01T13:20:00.000","Title":"Rename hundred or more column names in pandas dataframe","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a question about logistic regression. For my thesis I have to compare companies using different financial ratios using Python. The financial ratios should be balanced either by logistic regression or probit regression. I have already looked at some tutorials and these have worked with explanatory and dependent variables, but there are no dependent variables in my data set. I only need the regression to balance the different financial ratios and not to explain dependent variables. The goal is to calculate a score (\"Propensity Score\") for each company, from which I can then calculate the distance to the \"nearest\" company and thus get a proxy for comparability with other companies.\nUnfortunately, I completely lack the approach here and I can't find any instructions or examples. Does anyone of you have an idea how I can proceed here? I hope my problem becomes clear.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":59,"Q_Id":63209213,"Users Score":0,"Answer":"It sounds to me like regression models are not the right approach here. If I understand correctly and you want to find companies which are comparable based on different financial ratios you should use clustering algorithm like k-means or just just use a distance metric like euclidean distance to find the closest neighbor for each company.","Q_Score":0,"Tags":"python,regression","A_Id":63209931,"CreationDate":"2020-08-01T19:24:00.000","Title":"Balancing via Logistic Regression","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'll open with saying I'm not a data scientist or statistician so I've been trying to figure out the best way to score a set of given AI moves to help the computer determine which move path to choose. I've come up with the following and am asking if there is a better way to do this or if this will even work in the first place.\nFor any given player:\n\nNormal move +0\nCapture normal piece +1\nCapture king +2\nMove resulting in king +2\nWin game +10 (Should make AI highly prefer this path unless another provides a stronger and safer short term advantage.)\nDraw Game (Disregard path unless it's the only remaining option. Static 1 Goodness Point.)\nLose Game (Disregard path unless it's the only remaining option. Static 0 Goodness Points.)\n\nI'm also toying with the following:\n\nMove that ends against a wall +0.5\nMove that gains center control without threat +0.75\nMove that results in potential capture of multiple AI pieces (per piece) -0.25\nMove that results in piece getting \"stuck\" (within 1 turn) -0.5\n\nThe AI then runs through X levels (Let's say 4) of moves deep in the search tree and tallies points for both the player and opponent for each branch.\nI track the following (per branch):\n\nTotal points for AI\nTotal points for human opponent\nOpponent likelihood of choosing branch (see below)\nBranch \"Goodness\" (see below)\nTotal branches (move combinations)\n\nIn order to choose the best one, here is the algorithm I have developed but haven't determined if it will work well yet:\nBase Opponent Move Probability = 100 \/ Total Branches * (Human Opponent Points Gained + 1)\nPlayer Branch \"Goodness\" = Human Opponent Probability * Total Points for AI Player\nThe AI then chooses the move branch with the highest \"Goodness\" points or picks one at random in event of a tie.\nExample:\n4 Branches Available. In one of them, the human will king once and the AI will capture 2 pieces and king once.\n100 \/ 4 Moves * (1 Opponent Points + 1) = 50 Human Opponent Likelihood Score\n50 Human Opponent Likelihood * 5 AI Player Points Gained = 250 Move \"Goodness\" Points\nThe only other thing I can think to add would be to score the entire board's \"favorability\" at the end of each branch and multiply that by the \"Goodness\" Score. Favorability meaning the total point score for all pieces, kings, center\/wall control as a given end state. Though the more I expand on this the more it seems like I should pick one or the other. Either score as each of the moves in a branch are calculated or score the end board favorability result of each branch, not both.\nMaybe something like: (Board Favorability \/ 2) * Goodness = Final Branch Value\nRegardless, am I on the right track here? Will this approach work (not the favorability part, the general scoring and \"Goodness\" score for a given branch) or am I on the complete wrong track? Thanks for any assistance!","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":708,"Q_Id":63223136,"Users Score":1,"Answer":"You're on the right track, and another answer already has lots of details, but one thing I want to highlight is that you should focus on evaluating positions rather than evaluating moves. The value of a move is simply the value of the position it ends up in.\n\nInstead of awarding lots of points to a \"winning move\", you award lots of points to a won position.\nInstead of awarding some points for a capture, and some more points for a king capture, you can score positions according to material. The reason we consider a capture a good move is because it deprives the opponent of pieces. Acquiring a king improves our own material. Evaluating positions on material takes these things into consideration.\nLikewise your rules about control of the center, being against the wall, etc. are much easier to do (and work better) as evaluations of a position, rather than tallying up points for \"moves that result in X\".\n\nWin\/lose\/draw are \"hard\" conditions; if the game is over, it doesn't matter how much material you have left, or where it's placed, or anything else. You wouldn't choose a draw over a win just because the win sacrifices a piece. Evaluation rules for material, mobility, etc. are \"rules of thumb\" for how close a player is to winning, or how much ability they have to win, so you only really care about them when you don't have a forced win\/loss\/draw within your search horizon, and when you do use them, you want them to produce scores that are as similar as possible to the scores you would get if you could search every position until the end of the game.\nYou can start out assigning scores to your different evaluation rules by intuition, but to make them really good, you would simulate lots of games to the finish, and then run statistics on the winning and losing players' positions \u2014 then you would assign higher scores to the rules that most strongly correlate with positions that actually win.","Q_Score":0,"Tags":"python,artificial-intelligence","A_Id":63224987,"CreationDate":"2020-08-03T02:57:00.000","Title":"Will my AI algorithm for a python checkers game work and if not, what others should I consider?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a python virtual environment (conda) where I\u2019ve installed CUDA toolkit 10.1.243 and tensorflow-gpu 2.3.0rc0. My CUDA driver is 11.0.\nIn order to test if tensorflow was installed to GPU correctly, I ran a series of commands from within the venv:\ntf.test.is_built_with_cuda()\nTrue\ntf.config.list_physical_devices(\u2018GPU\u2019)\nFound device 0 with properties:\npciBusID: 0000:01:00.0 name: Quadro M2000M computeCapability: 5.0\n[PhysicalDevice(name=\u2019\/physical_device:GPU:0\u2019, device_type=\u2018GPU\u2019)]\npython -c \"import tensorflow as tf; print(tf.reduce_sum(tf.random.normal([1000,1000])))\"\ntensorflow.python.framework.errors_impl.InternalError: CUDA runtime implicit initialization on GPU:0 failed. Status: device kernel image is invalid\nI am not sure how to troubleshoot this. I have a feeling that it is related to modifying the compilation such that tensorflow supports the compute capability of my device (5.0), but I am not sure how to proceed. Thank you!!","AnswerCount":3,"Available Count":1,"Score":0.0665680765,"is_accepted":false,"ViewCount":6036,"Q_Id":63231021,"Users Score":1,"Answer":"i recommend pip install tensorflow-gpu==2.2","Q_Score":9,"Tags":"python,tensorflow,gpu,nvidia","A_Id":67192770,"CreationDate":"2020-08-03T14:10:00.000","Title":"Tensorflow-gpu issue (CUDA runtime error: device kernel image is invalid)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have Qubole connected to Azure data lake, and I can start a spark cluster, and run PySpark on it. However, I can't save any native Python output, like text files or CSVs. I can't save anything other than Spark SQL DataFrames.\nWhat should I do to resolve this?\nThank you in advance!","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":254,"Q_Id":63235683,"Users Score":0,"Answer":"If I understand your question correctly,I believe you are unable to download the result of pyspark command output into text or CSVs while you are able to do so for the spark sql command command output in a nice tabular format.\nUnfortunately, there is no direct field separator for the output text for a Python or Shell command outputs. You will need to get your output comma separated so you can download the raw output and save it as a csv.\nIf this is not what you meant, Please share more details as to what exactly are you trying to do along with screenshots details. As that will help us answer your question better.","Q_Score":0,"Tags":"python,azure,qubole","A_Id":63238287,"CreationDate":"2020-08-03T19:21:00.000","Title":"How to get Python in Qubole to save CSV and TXT files to Azure data lake?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am running the latest anaconda on ubuntu linux. Everything was working ok until this week. I can't import pandas on python3. I could last week using the same programs. I've tried it on python called from the bash and also from spyder and jupyter, and I get a message that it can't find pandas. I've tried reinstalling pandas using both pip and conda, and it said that it was correctly installed.\nAny suggestions?\nThank you.\nHoward","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":177,"Q_Id":63238530,"Users Score":0,"Answer":"You can create a new environment on Anaconda and then install pandas in that environment. Otherwise, try re-installing Anaconda.","Q_Score":0,"Tags":"python,pandas,conda","A_Id":63256430,"CreationDate":"2020-08-04T00:06:00.000","Title":"why does import pandas suddenly not work?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to implement a degree-3 noncausal moving average filter (in Python) to be applied to one of the signals. I do have an idea about moving average but I am new to signal processing. As of now, I know that a smoothing technique like an MA would reduce out the noise in the data but then it would make the sharp transitions in the data increasingly blunt. But then my question is how is this thing taken care of when we go to introduce non-causality in the system.\nFrom what I understand about non-causal system is a system whose output not only depends on past and present inputs but also future inputs. I am trying to understand things in depth here. But i think i am stuck due to knowledge gap. I would be grateful if there are any good references or resources which I could use for a better understanding.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":633,"Q_Id":63239658,"Users Score":0,"Answer":"If you have your dataset in memory, you are free to take make output[100] depend on input[105] if you so please. There's nothing about Python or signal processing that prevents you from mathematically doing that, as long as you recognize that you'll need to either truncate both edges or apply suitable padding.\nMathematically, you simply convolve with your desired impulse response. For example, a length-3 rectangular moving average impulse response centered about 0 (non-causally) would be represented by y[n] = x[n-1]\/3 + x[n]\/3 + x[n+1]\/3. We call the values [1\/3, 1\/3, 1\/3]the coefficients of the non-causal FIR filter we have chosen. Actually designing a filter by choosing the best coefficients is a [mathematically complex and rich problem](https:\/\/en.wikipedia.org\/wiki\/Finite_impulse_response#Filter_design), but you may always obtain a MATLAB license and utilize a tool such asfdatool` to build the filter to your frequency response specifications.\nFor a physical system or realtime sample-by-sample processing (e.g. on a microcontroller running CircuitPython), this cannot be realized of course. Assuming a discrete transformation and an otherwise stable system, the non-causality shows up in the Z-transform as elements of the form z^n for positive n. By adding delays (i.e. multiplying by z-1), you can make your non-causal response causal, at the expense of that added delay. Looking at our prior example, such a delay would correspond to making output[100] still depend on input[105], but making the 100th output sample only available to the following stage after the 105th input sample has been received.\nAs for making your data smoother or not smoother, an LTI smoothing filter will generally always blunt your edges. You can either design a filter with the appropriate characteristics to trade off the blunting of edges with smoothing requirements, or if the data is suitable, use a non-LTI processing approach.","Q_Score":0,"Tags":"python-3.x,signal-processing,smoothing","A_Id":63239683,"CreationDate":"2020-08-04T03:06:00.000","Title":"Why non-causal?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I installed snorkel using conda and when I try to run - from snorkel.labeling import labeling_function it throws the following error - ModuleNotFoundError: No module named 'snorkel.labeling'.\nI tried looking up for a solution on Github, but unfortunately, I couldn't follow through. I have also tried installing nb_conda_kernels, to make all your conda environments available in jupyterbut it didn't help. Also tried creating a separate env, installing snorkel and launching jupyter notebook from the snorkel's environment, and it didn't work either. Any form of help is much appreciated!\nThanks in advance!","AnswerCount":2,"Available Count":1,"Score":-0.0996679946,"is_accepted":false,"ViewCount":750,"Q_Id":63243522,"Users Score":-1,"Answer":"Please try the following:\nFor pip users\npip install snorkel\nFor conda users\nconda install snorkel -c conda-forge","Q_Score":0,"Tags":"python,jupyter,snorkel","A_Id":63243641,"CreationDate":"2020-08-04T09:04:00.000","Title":"ModuleNotFoundError: No module named 'snorkel.labeling'","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"Shannon's entropy from information theory measures the uncertainty or disorder in a discrete random variable's empirical distribution, while differential entropy measures it for a continuous r.v. The classical definition of differential entropy was found to be wrong, however, and was corrected with the Limiting density of discrete points (LDDP). Does scipy or other compute the LDDP? How can I estimate LDDP in python?","AnswerCount":1,"Available Count":1,"Score":0.537049567,"is_accepted":false,"ViewCount":429,"Q_Id":63254029,"Users Score":3,"Answer":"Since LDDP is equivalent to the negative KL-divergence from your density function m(x) to your probability distribution p(x), you might be able to use one of the many implementations of KL-divergence, for example from scipy.stats.entropy.\nAn appropriate procedure (assuming you have finite support) is to approximate the continuous distribution with a discrete one by sampling over its support, and calculating the KL divergence.\nIf this is not possible, then your only option that I can think of is probably to use numerical (or possibly analytic?) integration methods, of which you should have plenty. An easy first step would be to try monte-carlo methods.","Q_Score":2,"Tags":"python,entropy,information-theory","A_Id":63254307,"CreationDate":"2020-08-04T19:42:00.000","Title":"Limiting density of discrete points (LDDP) in python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am building a neural net with Keras for predicting the voltage output of a complicated electrical circuit based on known current injections at distinct input nodes. As of right now, the model is a simple ConvLSTM model, which produces fairly good predictions. The problem is that I need to predict several minutes of voltage output on a millisecond timescale based on the initial 50 ms of ground truth voltage and the known current injections, so as I move forward in time, the model starts to rely on it's own predictions, therefore the prediction error compounds. I can measure the behavior of the system to obtain training datasets, but it's really slow, hence the need for a NN.\nIn my current mdoel I can only predict the next voltage value in time as the current input changes every millisecond, therefore long-term forecasting is not feasible. What I want to do is to build a model which takes 50 ms of ground truth training voltage, 60 ms of current input (starting at the same time as the voltage values, but exceeding it by 10 ms), and 10 milliseconds of voltage as a target. This would potentially help me to strenghten the first prediction (51st datapoint).\nUnfortunately no matter how long I searched, I haven't found an architecture which was capable of handling this kind of input. Does anyone have any idea for a basic keras architecture?\nThanks!","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":139,"Q_Id":63254704,"Users Score":0,"Answer":"Viktor,\nI suggest to feed LSTM for training with combination of actual current (at t between 11 ms and 50 ms) and voltage from 10 ms ago (from 1 ms to 40 ms) then you have a rectangular input (2 x 40) for each training sample.","Q_Score":0,"Tags":"python,tensorflow,machine-learning,keras","A_Id":63255210,"CreationDate":"2020-08-04T20:36:00.000","Title":"Long-term time series forecasting using Keras with predictions relying on future inputs","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a task to perform classification on a data set in which the feature names are anonymous like var1,var2 etc. There is mixed continuous and one hot encoded features. I am bit stuck how to make new features out of the existing features and perform EDA on it.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":263,"Q_Id":63260282,"Users Score":1,"Answer":"There are many approaches to feature engineering, which could be also used on anonymized data:\n\ntransformation of continuous variables: log, power, normalization;\naggregations: `df.groupby(['cat_column']).agg({'continuous_column': ['min', 'max', 'mean', 'std'])\ninteractions of continuous variables: addition, subtraction, multiplications, division\nAnd so on.","Q_Score":1,"Tags":"python,jupyter-notebook,data-science,feature-selection,feature-engineering","A_Id":63262347,"CreationDate":"2020-08-05T07:23:00.000","Title":"How to do feature engineering on anonymous dataset?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Relatively simple question. Looking at the objective documentation for xgboost, I see \"multi:softmax\" and \"multi:softprob\", but both are mutliclass which will only output one class. Is there any way to predict multiple labels using xgboost or would I be better off simply training multiple models for each individual label. For example, on sklearn, multilabel is supported by RandomForestClassifier, where when fitting, your input for the target array can be of the shape n samples x n labels.\nTo clarify: multiclass would be when you want to predict whether a student gets an A,B, or C while multilabel would be something like predicting whether the student got question 1,2,3, or 4 on the test right. (they can only receive one grade but they can correctly answer any combination of those questions correctly)","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":840,"Q_Id":63271205,"Users Score":0,"Answer":"I haven't found anything which is supported natively by xgboost. The only solution is to wrap it around sklearn.multioutput.MultiOutputClassifier which does the same thing. But the downside of this method is that you cannot leverage load_model and save_model from xgboost itself and must use something like joblib to dump and load the model (which is not backward compatible in terms of xgboost version).","Q_Score":3,"Tags":"python-3.x,scikit-learn,xgboost,multilabel-classification,multiclass-classification","A_Id":68484221,"CreationDate":"2020-08-05T18:15:00.000","Title":"XGboost objectives: Is there a way to do Multi label (NOT multiclass ) classification?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using Pandas and SQLAlchemy to push data from CSVs into a MySQL database. When calling df.to_sql() thousands of lines of logs clutter the command line. Is there a way turn off\/stop the logging?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":264,"Q_Id":63273105,"Users Score":1,"Answer":"Don't think that is the standard behaviour of to_sql() but rather the parameter echo=True set in your sqlalchemy engine. Changing it back to echo=False or removing it since it is false as a default should stop it from printing out the logs.","Q_Score":0,"Tags":"python,pandas,sqlalchemy","A_Id":63273278,"CreationDate":"2020-08-05T20:33:00.000","Title":"Is there a way to turn off df.to_sql logs?","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am studying from my course book on Data Structures by Seymour Lipschutz and I have come across a point I don\u2019t fully understand..\n\nBinary Search Algorithm assumes that one has direct access to middle element in the list. This means that the list must be stored in some typeof linear array.\n\nI read this and also recognised that in Python you can have access to the middle element at all times. Then the book goes onto say:\n\nUnfortunately, inserting an element in an array requires elements to be moved down the list, and deleting an element from an array requires element to be moved up the list.\n\nHow is this a Drawback ?\nWon\u2019t we still be able to access the middle element by dividing the length of array by 2?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":191,"Q_Id":63277598,"Users Score":0,"Answer":"It seems that author compares array-like structures and linked list\nThe first (array, Python and Java list, C++ vector) allows fast and simple access to any element by index, but appending, inserting or deletion might cause memory redistribution.\nFor the second we cannot address i-th element directly, we need to traverse list from the beginning, but when we have element - we can insert or delete quickly.","Q_Score":1,"Tags":"algorithm,python-2.7,data-structures,binary-search","A_Id":63277814,"CreationDate":"2020-08-06T05:51:00.000","Title":"Binary Search-accessing the middle element drawback","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am currently working on my Bachelor Thesis. I want to predict the heartrate of people with video data. I build my network similar to the paper \"RhythmNet: End-to-End Heart Rate Estimation\nFrom Face via Spatial-Temporal Representation\".\nMy problem:\nMy network does not learn to predict the HR properly instead it learns the mean HR. Could you give me some tipps how to improve the variety of my Regression output? Do you have some general tipps how to improve the network performance?\nThx in advance","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":27,"Q_Id":63278659,"Users Score":0,"Answer":"According to Page 8 of the Paper, the output of the network is the mean Heart Rate. The output is computed with a mean pooling layer. Maybe you can get the single values from the single heart rates before the mean pooling layer?","Q_Score":0,"Tags":"python,tensorflow,regression","A_Id":63278785,"CreationDate":"2020-08-06T07:20:00.000","Title":"My Network is rather predicts the mean output instead of individual predictions","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using TPE sampler from optuna to optimize hyperparameters for Deep Learning vision models.\nI was wondering if optuna adapt search depending of the number of trials.\nIf I train for 1000 trials and stop at 500, I can see that many parameters were not tried by the algorithm.\nIf I reduce n_trials, does TPE explore faster (and less precisely) ?\nIn other terms, is interupting optuna at 500 with n_step=1000 the same as using n_trials = 500 and waiting until the end.\nI only have basic understanding of how TPE works.\nThanks.","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":247,"Q_Id":63282307,"Users Score":2,"Answer":"If I reduce n_trials, does TPE explore faster (and less precisely)?\n\nNo.\n\n... is interupting optuna at 500 with n_step=1000 the same as using n_trials = 500 and waiting until the end.\n\nYes.\nThis is because TPE (from Optuna) is not aware of the number of remaining (or total) trials.","Q_Score":1,"Tags":"python,hyperparameters,optuna","A_Id":63421727,"CreationDate":"2020-08-06T11:09:00.000","Title":"Does TPE (from Optuna) takes account of the number of trials?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"i am new to python opencv and i want to build a software that verifies if the uploaded image belongs to the same user or not but i in opencv you need to train the faces in order to get precised results, the problem is that the faces are likely random with only 1 photo as described above.\nAny help will be appreciated, thank you.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":92,"Q_Id":63284327,"Users Score":0,"Answer":"i am using google facenet for the implementation of face recognition system.","Q_Score":0,"Tags":"python,opencv","A_Id":63398253,"CreationDate":"2020-08-06T13:10:00.000","Title":"python-opencv face recogniton and verification without face training","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"In sklearn.cross_decomposition.PLSRegression, we can obtain the latent variables scores from the X array using x_scores_.\nI would like to extract the loadings to calculate the latent variables scores for a new array W. Intuitively, what I whould do is: scores = W*loadings (matrix multiplication). I tried this using either x_loadings_, x_weights_, and x_rotations_ as loadings as I could not figure out which array was the good one (there is little info on the sklearn website). I also tried to standardize W (subtracting the mean and dividing by the standard deviation of X) before multiplying by the loadings. But none of these works (I tried using the X array and I cannot obtain the same scores as in the x_scores_ array).\nAny help with this?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":260,"Q_Id":63288624,"Users Score":0,"Answer":"Actually, I just had to better understand the fit() and transform() methods of Sklearn. I need to use transform(W) to obtain the latent variables scores of the W array:\n1.Fit(): generates learning model parameters from training data\n2.Transform(): uses the parameters generated from fit() method to transform a particular dataset","Q_Score":0,"Tags":"python,scikit-learn,pls","A_Id":63299943,"CreationDate":"2020-08-06T17:12:00.000","Title":"Python PLSRegression : obtaining the latent variables scores using loadings","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"In linear algebra, vectors are normalized when they are divided by their norm, that is, the squared sum of their components.\nYet, sklearn.preprocessing.normalize method does not accept vectors, only matrices of at least two columns:\n\"ValueError: Expected 2D array, got 1D array instead\"\nWhy?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":244,"Q_Id":63291969,"Users Score":0,"Answer":"According to the documentation for sklearn.preprocessing.normalize, the parameter x is the data to normalize, element by element, and has the shape [n_samples, n_features]. The function normalize perform this operation on a single array-like dataset, either using the L1 or L2 norms.","Q_Score":1,"Tags":"python,scikit-learn,linear-algebra","A_Id":63292027,"CreationDate":"2020-08-06T21:25:00.000","Title":"Normalize function in Sklearn requires 2D array","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I tried using Scikit Learn's classification_report() to find other details why I got a certain score but instead I got an error.\n\nValueError: continuous is not supported\n\nI just want to know what it is and how to resolve it?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":152,"Q_Id":63294425,"Users Score":1,"Answer":"Probably you are trying to classify a continuous value. When the values are continuous you need to perform a regression. If you want to perform a classification you then perform a classifier in which you assign the features to a class (group).","Q_Score":0,"Tags":"python,scikit-learn","A_Id":63294585,"CreationDate":"2020-08-07T02:43:00.000","Title":"ValueError: continuous is not supported. What is this error?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Hello StackOverflow community:\nI trained a 4 layer DNN using Tensorflow 2.0. Using a new batch of data, I wish to retrain the model weights starting from layer 2 to the output layer, while keeping the weights from earlier layers, (i.e., those attached to the inputs and layer 1) frozen. I tried to lookup in the documentation of Tensorflow 2.0, but I can't seem to find what I am looking for. What could be the setup for the codes here? Or, if there is a documentation, could please someone link me to?\nThanks.\nPS: I am new to Tensorflow. I am tempted to solve this problem from scratch. But not ensuring first whether the package actually handles the job would be unwise and inefficient.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":50,"Q_Id":63308156,"Users Score":0,"Answer":"Thanks for the response. I am using Tensorflow 2.0. I know that Keras has been embedded in this new version. I was actually able to solve this problem by intuition. Turns out that each layer has an attribute where we can set trainable=False. So what I did is that I collected the layers of the original model, and then set those layers I want frozen as non-trainable, leaving the weights in the later layers for fine-tuning during the retraining step.","Q_Score":0,"Tags":"python,tensorflow,machine-learning,deep-learning,tensorflow2.0","A_Id":63316820,"CreationDate":"2020-08-07T19:33:00.000","Title":"How to retrain a DNN keeping the weights in the hidden layers frozen in Tensorflow 2.0","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a dataframe and when I do df.dtypes in shows the column is an object\nI do df[\"column_name\"] = df[\"column_name\"].astype(str)\nand again check df.dtypes it still shows the column type as object. Any idea bow to fix this.\nWhen I do df['column_name'].to_string().dtype\nI get an error\nAttributeError: 'unicode' object has no attribute 'dtype'","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":194,"Q_Id":63308956,"Users Score":1,"Answer":"In Pandas, there are only these datatypes: boolean, integer, float, datetime and object. Objects are almost always strings but can be any Python object. This is the reason why df.dtypes shows an object.","Q_Score":0,"Tags":"python,pandas,dataframe","A_Id":63309089,"CreationDate":"2020-08-07T20:48:00.000","Title":"Pandas change column to string","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Using Scikit-Learn's RandomizedSearchCV module, how do you guarantee a certain set of hyper-parameter settings will all be tested?\nMy goal is to guarantee that, using a randomized search for optimal estimator hyper-parameters, all available activation functions for sklearn MLPClassifier are tested. Still, I would also like an answer that applies to Python machine learning models\/estimators in general. I believe I could test which activation function was the best by running RandomizedSearchCV or GridSearchCV using 3 different instances of MLPClassifier. The problem is, what if I want to test all available activation functions and all weight \"solvers\" among other parameters such as the number of neurons and layers? Is there any way to do this using a Python library?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":104,"Q_Id":63313134,"Users Score":0,"Answer":"I am only posting this answer since the comment below the question is the best answer for me.\nComment by desertnaut on Aug. 08, 2020:\n\nYou cannot; RandomizedSearchCV provides absolutely no such guarantees. You should revert to GridSearchCV if you want to be sure that certain combinations will be tested.\n\nThe best solution for now is to use a combination of both RandomizedSearchCV and GridSearchCV.","Q_Score":0,"Tags":"python,scikit-learn,hyperparameters","A_Id":63608321,"CreationDate":"2020-08-08T08:06:00.000","Title":"Using Scikit-Learn's RandomizedSearchCV module, how do you guarantee a certain set of hyper-parameter settings will all be tested?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to create a CNN, but using the SIFT algorithm instead of any pooling layers.\nProblem is I can't seem to find any Python implementation of the algorithm in Tensorflow or PyTorch. The only implementation I have seen of it is with opencv.\nIs it possible to use the opencv SIFT implementation as a layer in a Tensorflow CNN Model?\nIf so, how would you go about creating it?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":637,"Q_Id":63313842,"Users Score":2,"Answer":"While this is an interesting idea, I believe it has numerous issues that make it highly impracticable to impossible.\nLayers of a network have to be differentiable with regards to their input to allow any gradients to be calculated, which are then used to update the weights.\nWhile I think it might be possible to write a fully differentiable sift implementation, this alone will be impractical.\nFurther SIFT does not have a constant number of outputs and takes a long time to compute, which would slow down the training a lot.\nThe only practical way to use SIFT with neural networks would be to first run SIFT and then use the top N detected keypoints as input for the first layer. However, I'm not sure this would be successful.","Q_Score":1,"Tags":"python,tensorflow,pytorch,sift","A_Id":63313979,"CreationDate":"2020-08-08T09:33:00.000","Title":"Can you integrate opencv SIFT with a tensorflow model?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am creating a deep ensemble, and I need to keep track of which inference results came from which neural network. However, enabling versioning via the Kedro catalog only organizes my inference results by datetime, with each file having an identical name.\nWhat is the best practice for organizing results by model ID? For example, is it possible to customize the versioned folder names, or the versioned file? E.g. data\/07_model_output\/model_predictions.json\/2020-08-09T20.55.57.237Z-Model-04\/model_predictions.json or ...\/2020-08-09T20.55.57.237Z\/model_predictions-Model-04.json","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":50,"Q_Id":63331325,"Users Score":0,"Answer":"Versioning is intended for keeping track of the versions of a single dataset, not to disambiguate between multiple datasets.\nIf I understand your question correctly, I think you can use multiple output datasets to keep track of your predictions, i.e. nn1_predictions.json, nn2_predictions.json, etc.","Q_Score":0,"Tags":"python,machine-learning,devops,inference,kedro","A_Id":63338094,"CreationDate":"2020-08-09T21:06:00.000","Title":"How to organize inference results by model ID that produced it?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Recently I trained my model on google colab and saved weights in google drive automatically by ModelCheckPoint.\nWhen I use these saved weights on google colab the prediction performs great, but when I download the weights and run them locally on my laptop, the prediction is extemely terrible.\nThe GPU of my laptop is GeForce RTX 1060 with Max-Q design 12GB. Could anyone tell me what leads to the different performance between my laptop and google colab?\nBy the way, I tried to save the whole model and then load it, the saving process runs smoothly but when I load model, there is a ValueError says \"There is a cyclic-dependency between functions\", still have no idea how to solve it.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":246,"Q_Id":63332507,"Users Score":0,"Answer":"I solved this problem by changing tensorflow-gpu==2.2.0 to tensorflow==2.3.0, which is extactly the same as the version in google colab.","Q_Score":0,"Tags":"python,tensorflow,google-colaboratory","A_Id":63332722,"CreationDate":"2020-08-10T00:02:00.000","Title":"Why model weights trained on google colab cannot perform locally as in colab","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm writing Rasa source code for my chatbot, using Python 3.7.7, pip 20.1.1 and conda 4.5.12.\nI use the command: conda install tensorflow to install this framework, version 2.1.0.\nHowever when trying to execute rasa train to train my chatbot, I came up against an error with process of importing tensorflow.\nThe Error: ImportError: DLL load failed: The specified module could not be found.\nI still find the tensorflow folder, so what I need to do to fix this problem?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":252,"Q_Id":63335258,"Users Score":0,"Answer":"You can Use pip install tensorflow","Q_Score":1,"Tags":"python,tensorflow,rasa","A_Id":63335375,"CreationDate":"2020-08-10T06:37:00.000","Title":"Tensorflow: ImportError: DLL load failed: The specified module could not be found","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I cannot install PyTorch on python 3.7. This error occurs for others but the suggested fixes did not work. I have tried instaling wheel, and importing tools but neither work.\nGot error: ModuleNotFoundError: No module named 'tools.nnwrap'\nran command pip install --pre torch torchvision -f https:\/\/download.pytorch.org\/whl\/nightly\/cu102\/torch_nightly.html\nfull output: Looking in links: https:\/\/download.pytorch.org\/whl\/nightly\/cu102\/torch_nightly.html Collecting torch Using cached torch-0.1.2.post2.tar.gz (128 kB) Collecting torchvision Using cached torchvision-0.2.2.post3-py2.py3-none-any.whl (64 kB) Requirement already satisfied: pyyaml in c:\\users\\lv7682\\documents\\repos\\security_patch\\spms\\webapp\\securitypatchmanagementsystem\\venv\\venv\\lib\\site-packages (from torch) (5.3.1) Collecting pillow>=4.1.1 Using cached Pillow-7.2.0-cp37-cp37m-win32.whl (1.8 MB) Collecting numpy Using cached numpy-1.19.1-cp37-cp37m-win32.whl (10.9 MB) Collecting six Using cached six-1.15.0-py2.py3-none-any.whl (10 kB) Using legacy 'setup.py install' for torch, since package 'wheel' is not installed. Installing collected packages: torch, pillow, numpy, six, torchvision Running setup.py install for torch ... error ERROR: Command errored out with exit status 1: command: 'c:\\users\\lv7682\\documents\\repos\\security_patch\\spms\\webapp\\securitypatchmanagementsystem\\venv\\venv\\scripts\\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[ 0] = '\"'\"'C:\\\\Users\\\\LV7682\\\\AppData\\\\Local\\\\Temp\\\\pip-install-4b80gt33\\\\torch\\\\setup.py'\"'\"'; __file__='\"'\"'C:\\\\Users\\\\LV7682\\\\AppData\\\\Local\\\\Temp\\\\pip-install-4b80gt33\\\\torch\\\\setup .py'\"'\"';f=getattr(tokenize, '\"'\"'open'\"'\"', open)(__file__);code=f.read().replace('\"'\"'\\r\\n'\"'\"', '\"'\"'\\n'\"'\"');f.close();exec(compile(code, __file__, '\"'\"'exec'\"'\"'))' install --reco rd 'C:\\Users\\LV7682\\AppData\\Local\\Temp\\pip-record-z5_fy7cc\\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\\users\\lv7682\\documents\\repos\\security _patch\\spms\\webapp\\securitypatchmanagementsystem\\venv\\venv\\include\\site\\python3.7\\torch' cwd: C:\\Users\\LV7682\\AppData\\Local\\Temp\\pip-install-4b80gt33\\torch\\ Complete output (23 lines): running install running build_deps Traceback (most recent call last): File \"\", line 1, in File \"C:\\Users\\LV7682\\AppData\\Local\\Temp\\pip-install-4b80gt33\\torch\\setup.py\", line 265, in description=\"Tensors and Dynamic neural networks in Python with strong GPU acceleration\", File \"c:\\users\\lv7682\\documents\\repos\\security_patch\\spms\\webapp\\securitypatchmanagementsystem\\venv\\venv\\lib\\site-packages\\setuptools\\__init__.py\", line 163, in setup return distutils.core.setup(**attrs) File \"C:\\Users\\LV7682\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\distutils\\core.py\", line 148, in setup dist.run_commands() File \"C:\\Users\\LV7682\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\distutils\\dist.py\", line 966, in run_commands self.run_command(cmd) File \"C:\\Users\\LV7682\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\distutils\\dist.py\", line 985, in run_command cmd_obj.run() File \"C:\\Users\\LV7682\\AppData\\Local\\Temp\\pip-install-4b80gt33\\torch\\setup.py\", line 99, in run self.run_command('build_deps') File \"C:\\Users\\LV7682\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\distutils\\cmd.py\", line 313, in run_command self.distribution.run_command(command) File \"C:\\Users\\LV7682\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\distutils\\dist.py\", line 985, in run_command cmd_obj.run() File \"C:\\Users\\LV7682\\AppData\\Local\\Temp\\pip-install-4b80gt33\\torch\\setup.py\", line 51, in run from tools.nnwrap import generate_wrappers as generate_nn_wrappers ModuleNotFoundError: No module named 'tools.nnwrap' ---------------------------------------- ERROR: Command errored out with exit status 1: 'c:\\users\\lv7682\\documents\\repos\\security_patch\\spms\\webapp\\securitypatchmanagementsystem\\venv\\venv\\scripts\\python.exe' -u -c 'import sys , setuptools, tokenize; sys.argv[0] = '\"'\"'C:\\\\Users\\\\LV7682\\\\AppData\\\\Local\\\\Temp\\\\pip-install-4b80gt33\\\\torch\\\\setup.py'\"'\"'; __file__='\"'\"'C:\\\\Users\\\\LV7682\\\\AppData\\\\Local\\\\Temp\\\\p ip-install-4b80gt33\\\\torch\\\\setup.py'\"'\"';f=getattr(tokenize, '\"'\"'open'\"'\"', open)(__file__);code=f.read().replace('\"'\"'\\r\\n'\"'\"', '\"'\"'\\n'\"'\"');f.close();exec(compile(code, __file__, '\"'\"'exec'\"'\"'))' install --record 'C:\\Users\\LV7682\\AppData\\Local\\Temp\\pip-record-z5_fy7cc\\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\\user s\\lv7682\\documents\\repos\\security_patch\\spms\\webapp\\securitypatchmanagementsystem\\venv\\venv\\include\\site\\python3.7\\torch' Check the logs for full command output.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":2364,"Q_Id":63345212,"Users Score":1,"Answer":"Fixed: needed to use python 64-bit not 32-bit","Q_Score":1,"Tags":"python,python-3.x,installation,pip,pytorch","A_Id":63345384,"CreationDate":"2020-08-10T17:34:00.000","Title":"Cant install pytorch - ModuleNotFoundError: No module named 'tools.nnwrap'","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've been working with some face detection in OpenCV. I have a couple projects I've done - one does face detection which uses a pre-built model. Some others do different things where I collect my own images and train my own models. When I do the latter, it's generally with much smaller datasets that what you'd use for face training.\nOn my face recognizer - many of the common faces I work with do not get detected properly (due to odd properties like masks, hats, goggles, glasses, etc). So I want to re-train my own model - but grabbing the gigantic \"stock\" datasets, adding my images to it may take a VERY long time.\nSo the question is: is there a way to start with an existing model (XML file) and run the trainer in a way that would just add my images to it?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":86,"Q_Id":63347621,"Users Score":0,"Answer":"This is called \"Transfer Learning\". Tenserflow (Keras) has a lot of support for this. It basically consists of taking a pre-existing model with pre-existing weights, \"freezing\" weights on certain layers, adding new layers in or below existing ones, and then retraining only the un-frozen layers.\nit can't be used to readily just \"continue\" learning, but can be used to add additional things into the training - for newer aspects (like potentially, adding masked people to an already trained model of unmasked people, as in my original question)","Q_Score":0,"Tags":"opencv,machine-learning,computer-vision,face-detection,opencv-python","A_Id":67290842,"CreationDate":"2020-08-10T20:32:00.000","Title":"\"Incremental\" face training in OpenCV","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am loading 10-15MB numpy arrays saved in .npy format in a loop, and each load takes about 1.5s in Google Colab. Is that an acceptable speed? Its by far the slowest part of my loop. Also, the second time I run the loop its faster (presumably because the loaded files were saved to RAM?) but then eventually it slows back down again (runs out of RAM?).\nHere is the code I am using to load the arrays:\ndata = np.load('\/content\/drive\/My Drive\/Share\/Daily Data\/Processed\/' + str(fileName))\nAny advice to speed this up would be greatly appreciated, right now I have load 1500 arrays per loop so each loop takes around 25 minutes. The arrays must be loaded separately (please don't suggest I append them all and load it all at once, I can't).","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":441,"Q_Id":63350586,"Users Score":0,"Answer":"As an approximate test,\nI can load a .npy file with 1_000_000 elements (int64) in 6 milliseconds (from my local disk).\n\nAre your files (\/content\/drive\/...) in a Google data center, or on your own storage?\nIn the latter case, can you copy to files, so they're at Google, along with the compute?","Q_Score":0,"Tags":"python,numpy,load","A_Id":63387495,"CreationDate":"2020-08-11T02:19:00.000","Title":"Using Numpy.Load - is this the fastest method? It seems slow","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"Matplotlib created a temporary config\/cache directory at \/var\/www\/.config\/matplotlib because the default path (\/tmp\/matplotlib-b33qbx_v) is not a writable directory; it is highly recommended to set the MPLCONFIGDIR environment variable to a writable directory, in particular to speed up the import of Matplotlib and to better support multiprocessing.\nThis is the message I'm getting in error.log file and 504 Gateway Time out error on browser .\nSomeone please help to resolve this issue.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":11684,"Q_Id":63356808,"Users Score":0,"Answer":"import os\nos.environ['MPLCONFIGDIR'] = os.getcwd() + \"\/configs\/\"\nbefore\nimport matplotlib\nworks for me","Q_Score":5,"Tags":"python-3.x,django,matplotlib,django-wsgi","A_Id":68589747,"CreationDate":"2020-08-11T11:00:00.000","Title":"Matplotlib created a temporary config\/cache directory","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"Using scipy.sparse is very efficient both in storing and doing computations on sparse matrices. What if it is used for non-sparse matrices? More specifically, It is clear that we cannot exploit the sparsity benefits of that data structure, however, is it worse (in storage and computation complexity) than using an ordinary numpy array?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":36,"Q_Id":63361442,"Users Score":1,"Answer":"Yes, it is worse in both storage and performance, let alone cognitive load for whoever reads your code.","Q_Score":0,"Tags":"python,arrays,python-3.x,numpy,scipy","A_Id":63361873,"CreationDate":"2020-08-11T15:29:00.000","Title":"Is it good to use scipy sparse data structure for non-sparse matrices?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm performing hyperparameter tuning with grid search and I realized that I was getting overfitting... I tried a lot of ways to reduce it, changing the \"gamma\", \"subsample\", \"max_depth\" parameters to reduce it, but I was still overfitting...\nThen, I increased the \"reg_alpha\" parameters value to > 30....and them my model reduced overfitting drastically. I know that this parameter refers to L1 regularization term on weights, and maybe that's why solved my problem.\nI just want to know if it has any problem using high values for reg_alpha like this?\nI would appreciate your help :D","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":3721,"Q_Id":63368841,"Users Score":1,"Answer":"reg_alpha penalizes the features which increase cost function. Meaning it finds the features that doesn't increase accuracy. But this makes prediction line smoother.\nOn some problems I also increase reg_alpha > 30 because it reduces both overfitting and test error.\nBut if it is a regression problem it's prediction will be close to mean on test set and it will maybe not catch anomalies good.\nSo i may say you can increase it as long as your test accuracy doesn't begin to fall down.\nLastly when increasing reg_alpha , keeping max_depth small might be a good practise.","Q_Score":3,"Tags":"python,xgboost","A_Id":65459006,"CreationDate":"2020-08-12T02:22:00.000","Title":"\"reg_alpha\" parameter in XGBoost regressor. Is it bad to use high values?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I had implemented a CNN with 3 Convolutional layers with Maxpooling and dropout after each layer\nI had noticed that when I trained the model for the first time it gave me 88% as testing accuracy but after retraining it for the second time successively, with the same training dataset it gave me 92% as testing accuracy.\nI could not understand this behavior, is it possible that the model had overfitting in the second training process?\nThank you in advance for any help!","AnswerCount":2,"Available Count":2,"Score":0.1973753202,"is_accepted":false,"ViewCount":222,"Q_Id":63371731,"Users Score":2,"Answer":"It is quite possible if you have not provided the seed number set.seed( ) in the R language or tf.random.set_seed(any_no.) in python","Q_Score":1,"Tags":"python,tensorflow,keras,neural-network","A_Id":63371848,"CreationDate":"2020-08-12T07:22:00.000","Title":"Retrain your CNN model successifely with two different datasets","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I had implemented a CNN with 3 Convolutional layers with Maxpooling and dropout after each layer\nI had noticed that when I trained the model for the first time it gave me 88% as testing accuracy but after retraining it for the second time successively, with the same training dataset it gave me 92% as testing accuracy.\nI could not understand this behavior, is it possible that the model had overfitting in the second training process?\nThank you in advance for any help!","AnswerCount":2,"Available Count":2,"Score":1.2,"is_accepted":true,"ViewCount":222,"Q_Id":63371731,"Users Score":1,"Answer":"Well I am no expert when it comes to machine learning but I do know the math behind it. What you are doing when you train a neural network you basicly find the local minima to the loss function. What this means is that the end result will heavily depend on the initial guess of all of the internal varaibles.\nUsually the variables are randomized as a initial estimation and you could therefore reach quite different results from running the training process multiple times.\nThat being said, from when I studied the subject I was told that you usually reach similar regardless of the initial guess of the parameters. However it is hard to say if 0.88 and 0.92 would be considered similar or not.\nHope this gives a somewhat possible answer to your question.\nAs mentioned in another answer, you could remove the randomization, both in the parameter initialization of the parameters and the randomization of the data used for each epoch of training by introducing a seed. This would insure that when you run it twice, everything will get \"randomized\" in the exact same order. In tensorflow this is done using for example tf.random.set_seed(1), the number 1 can be changed to any number to get a new seed.","Q_Score":1,"Tags":"python,tensorflow,keras,neural-network","A_Id":63371852,"CreationDate":"2020-08-12T07:22:00.000","Title":"Retrain your CNN model successifely with two different datasets","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am generating a large array of random numbers, totaling more than half the available memory on a GPU. I am doing this in a loop.\nWhen I call cupy.random the second time (or third time...), assigning to the same variable name, it does not free the memory for the first array. It tries to allocate more memory, which causes an out of memory error.\nExplicitly freeing the memory before generating a new random array is very slow, and seems inefficient.\nIs there a way to generate a new set of numbers, but in the same memory space?\nEdit: cupy.random.shuffle() is letting me work around the problem, but I wonder if there is a better way?\nEdit 2: on further review, shuffle() does not address the problem, and appears to need even more memory than allocating a second block (before freeing the first) of memory... I am back to restricting ndarray size to less than half the remaining memory, so two ndarrays can be allocated alternately","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":281,"Q_Id":63371771,"Users Score":0,"Answer":"As user2357112 suggests, cupy.random.random() does not appear to support \u201cre-randomizing\u201c an existing ndarray, even though cuRand does. Writing C to modify an existing cupy array somewhat defeats the point of using python \/ cupy in the first place.\nCuriously, having an array about 1\/3rd the size of available memory, while increasing the number of loops, is faster in total execution time (versus larger arrays\/fewer loops). I was not able to determine when cupy (or python or cuda?) does garbage collection on the disused array, but it seems to happen asynchronously.\nIf GPU garbage collection uses cuda cores (I presume it does?), it does not appear to materially effect my code execution time. Nvidia-smi reports \u201cP2\u201d GPU usage when my code calculations are running, suggesting there are still cores available for cupy \/ cuda to free memory outside of my code?\nI don\u2019t like answering my own question... just sharing what I found in case it helps someone else","Q_Score":0,"Tags":"python,cupy","A_Id":63437375,"CreationDate":"2020-08-12T07:25:00.000","Title":"CuPy random - how to generate new random set in same memory?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have to download .parqeat file from Azure storage and have to analyze the Data.\nSo I started using python codes with azure-storage-blob library and Pandas to store DataFrames and flask to create API on response.\nBut now file size in the Azure storage is getting increased up to 30MB(a day file) and as tested it takes 6min to download 20MB file into my local which I can't afford because I have to analyse files of each days in a month, which will have 20 MB each. That's almost 3020MB size.\nAny suggestion?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":43,"Q_Id":63376871,"Users Score":0,"Answer":"Did you find your answer? Without a code snippet it would be hard to diagnos your problem. Azure Blob Storage supports read in parallel. If you have BatchServiceClient service that would be straightforward. Otherwise, try Multiprocessing module. Kr.","Q_Score":0,"Tags":"python,azure,blob,azure-storage,data-analysis","A_Id":65569711,"CreationDate":"2020-08-12T12:48:00.000","Title":"Python: azure-storage-blob takes 6 min to download a 20MB file to local","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":1,"Web Development":0},{"Question":"I want to extract Medical Equipment part names from the list of sentences.\nThese sentences are recorded actions taken on a support request which might include replacement of a part or acknowledging a part is in a bad state.\nHere are the sample sentences-\n\nFound [Some equipment part] on both side not working.\nNarrowed problem down to the [Some equipment part].\nNeeded a [Some equipment part] replacement.\nAssisted with troubleshooting, found [Some equipment part] is most likely bad.\n[Some equipment part] won't go down, will order part.\n\nI want to extract \"[Some equipment part]\" from the above sentences.\nThings I've already tried-\nFirst, I've filtered the sentences using Sentiment Analysis. Considering only the ones which have a negative sentiment or have \"replace\" text in them.\n\nUsing NLTK, After POS tagging using RegexpParser on a defined grammer = \"NP : {++|+}\"\nUsing Spacy, After POS tagging and dependency, filtering based on Verb, Noun relationship - token.dep_ in ['dobj'] and token.pos_ == 'NOUN'\n\nThe above approaches gives me a lot of meaningless output.\nPlease, let me know if there is anything which can be of help.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":433,"Q_Id":63378487,"Users Score":0,"Answer":"It sounds like you would benefit from looking at Named Entity Recognition (NER). I would be curious if SpaCy would be able to pick these out as PRODUCT entities.","Q_Score":0,"Tags":"python,nlp,nltk,data-science,spacy","A_Id":63379092,"CreationDate":"2020-08-12T14:17:00.000","Title":"How to extract particular word(s) from the list of sentences using Python NLP. These word(s) are Parts of Medical equipments","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am about creating a regression model but I wonder what would be the best way to handle nan values for both numerical and categorical data:\nI know that for the numerical columns the next solutions could be useful:\n1- Replace it with 0: df.fillna(0, inplace=True)\n2- Replace it with mean: df.fillna(df.mean(), inplace=True)\n3- Replace it with median df.fillna(df.median(), inplace=True)\n4- delete each row, in my target column, has nan value\nIs it possible to have overfitting after adopting 2 or 3.\nWhat is the best way to handle both categorical and numeric values in columns\nHowever, I wonder what could be the best choice for categorical data is it after using the one hot encoding ?\nAny help could be appreciated !","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":755,"Q_Id":63380017,"Users Score":4,"Answer":"For usual practice, it is preferred to use df.fillna(df.mean(), inplace=True) for columns having continuous values and df.fillna(df.mode()[0], inplace=True) for categorical values.","Q_Score":1,"Tags":"python,pandas,regression,nan,categorical-data","A_Id":63380122,"CreationDate":"2020-08-12T15:38:00.000","Title":"What would the best way to handle NaN values for both numerical and categorical data","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a dataset which I transformed to CSV as potential input for a keras auto encoder.\nThe loading of the CSV works flawless with pandas.read_csv() but the data types are not correct.\nThe csv solely contains two colums: label and features whereas the label column contains strings and the features column arrays with signed integers ([-1, 1]). So in general pretty simple structure.\nTo get two different dataframes for further processing I created them via:\nlabels = pd.DataFrame(columns=['label'], data=csv_data, dtype='U')\nand\nfeatures = pd.DataFrame(columns=['features'], data=csv_data)\nin both cases I got wrong datatypes as both are marked as object typed dataframes. What am I doing wrong?\nFor the features it is even harder because the parsing returns me a pandas.sequence that contains the array as string: ['[1, ..., 1]'].\nSo I tried a tedious workaround by parsing the string back to an numpy array via .to_numpy() a python cast for every element and than an np.assarray() - but the type of the dataframe is still incorrect. I think this could not be the general approach how to solve this task. As I am fairly new to pandas I checked some tutorials and the API but in most cases a cell in a dataframe rather contains a single value instead of a complete array. Maybe my overall design of the dataframe ist just not suitable for this task.\nAny help appreacheated!","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":102,"Q_Id":63394131,"Users Score":0,"Answer":"The input csv was formatted incorrectly, therefore the parsing was accurate but not what i intended. I expanded the real columns and skipped the header to have a column for every array entry - now panda recognize the types and the correct dimensions.","Q_Score":0,"Tags":"python,pandas,dataframe,csv","A_Id":63399489,"CreationDate":"2020-08-13T11:25:00.000","Title":"Loading CSV with Pandas - Array's not parsed correctly","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a csv file encoded in utf-8 (filled with information from website through scraping with a python code, with str(data_scraped.encode('utf-8') in the end for the content)).\nWhen I import it to excel (even if I pick 65001: Unicode UTF8 in the options), it doesn't display the special characters.\nFor example, it would show \\xc3\\xa4 instead of \u00e4\nAny ideas of what is going on?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":60,"Q_Id":63399685,"Users Score":0,"Answer":"I solved the problem.\nThe reason is that in the original code, I removed items such as \\t \\n that were \"polluting\" the output with the replace function. I guess I removed too much and it was not readable for excel after.\nIn the final version, I didn't use\nstr(data_scrapped.encode('utf-8') but\ndata_scrapped.encode('utf-8','ignore').decode('utf-8')\nthen I used split and join to rempove the \"polluting terms\":\nstring_split=data_scrapped.split()\ndata_scrapped=\" \".join(string_split)","Q_Score":0,"Tags":"python,excel,web-scraping,encoding","A_Id":63502540,"CreationDate":"2020-08-13T16:45:00.000","Title":"Cannot read imported csv file with excel in UTF-8 format after python scraping","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"In theory, linear interpolation can be done with any triangulation (not just a Delaunay triangulation).\nI am trying to use scipy.interpolate.LinearNDInterpolator with a pre-computed 3D triangulation which is not of class scipy.spatial.Delaunay. However, this won't work because the SciPy code checks the class of the triangulation (if isinstance(points, qhull.Delaunay)...). I tried to create a 'fake' Delaunay triangulation with the correct class by changing the 'points' and 'simplices' attributes of a Delaunay object, but I received the error AttributeError: can't set attribute.\nIs there a way around this, or another library for linear interpolation?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":156,"Q_Id":63404041,"Users Score":0,"Answer":"It looks like matplotlib.tri.LinearTriInterpolator might be a good alternative. I will update this post when I have tested this.\nEdit: This is not a solution to my problem because it is only implemented in 2-D.","Q_Score":1,"Tags":"python,class,scipy,interpolation","A_Id":63404055,"CreationDate":"2020-08-13T22:27:00.000","Title":"3-D linear interpolation in SciPy with non-Delaunay triangulation","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'd like to understand what happens under the hood of scikitlearn OneVsRestClassifier when we use LinearRegression as estimator. Does it create one LinearRegressor per class and apply a softmax function to return an output class? Documentation is not clear in this aspect. Even fit() source code seems is clear enough.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":110,"Q_Id":63405239,"Users Score":0,"Answer":"OvR is used for classification not for regression so using LinearRegression would not work at all.\nThe one-versus-the-rest(OvR) strategy is used for multiclass classification with multiple binary classifiers. Take the MNIST digit dataset as an example where you would want to create a system that can classify the digit images into 10 classes (from 0 to 9) using OvR you would train 10 binary classifiers, one for each digit (a 0-detector, a 1-detector, a 2- detector, and so on). Then when you want to classify an image, you get the decision score from each classifier for that image and you select the class whose classifier outputs the highest score.","Q_Score":0,"Tags":"python,machine-learning,scikit-learn,classification","A_Id":63405948,"CreationDate":"2020-08-14T01:21:00.000","Title":"What happens if you use LinearRegression with OneVsRestClassifier","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm using LassoCV in sklearn. There's always a lot of ConvergenceWarnings. I checked the results and they look good. So I was wondering if it is safe to simply ignore those warnings. A few thoughts I have are:\n\nDoes the warning happens because the magnitude of my response is too big? It will make the loss bigger, too.\nIn most cases, would it be solved when I increase the number of iterations? I'm hesitating to do it because sometimes it takes longer to run but the results didn't improve.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":318,"Q_Id":63419118,"Users Score":0,"Answer":"tl;dr It is fine almost always, to be sure watch learning curve.\nSo, LassoCV implements Lasso regression, which parameters are optimized via some kind of gradient descent (coordinate descent to be more precise, which is even simpler method) and as all gradient methods this approach requires defining:\n\nstep size\nstop criterion\n\nprobably most popular stop criteria are:\na) fixed amount of steps (good choice time-wise, since 1000 steps takes exactly x1000 time compare to 1 step, so it is easy to manage the time spent on training).\nb) fixed delta (difference) between values of a loss function during step n and n-1 (possibly better classification\/regression quality)\nThe warning you observe is because LassoCV uses the the first criterion (fixed amount of steps), but also checks for the second (delta), once number of fixed steps is reached the algorithm stops, default value of delta is too small for most real datasets.\nTo be sure that you train your model long enough you could plot a learning curve: loss value after every 10-20-50 steps of the training, once it goes to a plateau you are good to stop.","Q_Score":0,"Tags":"python,scikit-learn,lasso-regression","A_Id":63419986,"CreationDate":"2020-08-14T19:39:00.000","Title":"Is it safe to ignore the \"ConvergenceWarning\" in sklearn?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"How do I tune the parameters for a neural network such as the amount of layers, the types of layers, the width, etc.? Right now I simply guess for good parameters. This becomes very expensive and time consuming for me as I will tune a network and then find out that it didn't do any better than the previous model. Is there better way to tune the model to get a good test and validation score?","AnswerCount":2,"Available Count":2,"Score":1.2,"is_accepted":true,"ViewCount":88,"Q_Id":63421907,"Users Score":0,"Answer":"It is totally hit and trail method. You have to play around it. There is no particular method to do that. Try to use GPU instead to CPU to compute fast such as \"Google Colab\". My suggestion is note down all the parameters that can be tunned.\neg:\n\n\nOptimizer: Try to use different optimizer such as Adam,SGD,many more\nlearning rate : This is a very crucial parameter, try to change it from .0001 to 0.001 step by 0.0001.\nNumber of hidden layers : Try to increase no. of hidden layers.\nTry to use Batch Normalization or Drop out or both if required.\nUse correct Loss funtion.\nChange Batch size and Epoch.","Q_Score":0,"Tags":"python-3.x,machine-learning,optimization","A_Id":63422098,"CreationDate":"2020-08-15T02:04:00.000","Title":"How do I properly tune parameters for a neural network?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"How do I tune the parameters for a neural network such as the amount of layers, the types of layers, the width, etc.? Right now I simply guess for good parameters. This becomes very expensive and time consuming for me as I will tune a network and then find out that it didn't do any better than the previous model. Is there better way to tune the model to get a good test and validation score?","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":88,"Q_Id":63421907,"Users Score":0,"Answer":"Hidden layers, Epochs, batch-size: Try different numbers.\nOptimizers: Adam (gives better results), Rmsprop\nDropout: 0.2 works well in most case\nAlso as a plus, you should also try different activation functions ( like you can use ReLu in the hidden layers and for output layer use sigmoid for binary class classification and softmax for multiclass classification.","Q_Score":0,"Tags":"python-3.x,machine-learning,optimization","A_Id":63422228,"CreationDate":"2020-08-15T02:04:00.000","Title":"How do I properly tune parameters for a neural network?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have to generate a matrix with of shape 10^4 x 10^4 with 100 integer items randomly chosen 1 and 30 and the rest of the elements equals to 0. Can anybody help me? :pray","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":60,"Q_Id":63424797,"Users Score":0,"Answer":"Create the matrix with zeros, and then add the random numbers, or create an empty matrix, add the random numbers, and fill the empty values with 0.","Q_Score":0,"Tags":"python,numpy,matrix,random","A_Id":63424819,"CreationDate":"2020-08-15T10:03:00.000","Title":"How can I generate in Python a matrix with n random elements between 1 and 30 and the rest of the elements equal to zeros?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"What is the time complexity of operations in SortedList implementation of sortedcontainers module?\nAs I understand, the underlying data structure is an array list. So does insertion takes O(n) time since the index can be found in O(logn) and then insert the element at the correct location is O(n)?\nSimilarly, popping an element from an index must be O(n) as well.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":1479,"Q_Id":63430867,"Users Score":0,"Answer":"Insert, remove, get index, bisect right and left, find element inside list, are all log(n) operations. Its similar to treeset and multiset in java and c++, implemented with AVL tree or red black tree.","Q_Score":1,"Tags":"python,sortedlist,sortedcontainers","A_Id":72413340,"CreationDate":"2020-08-15T21:15:00.000","Title":"Time complexity of operations in SortedList - Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"When I try to import geopandas package in \"Google Colaboratory\" I got the error \"ModuleNotFoundError: No module named 'geopandas'\".\nI will appreciate your help. Thanks in advance.","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":5719,"Q_Id":63433405,"Users Score":0,"Answer":"Try running !pip install geopandas in a new cell.\nDon't forget the ! Exclamation mark.\nNote:\nThis method works for other libraries too.\nSimply !pip install 'package_name'\nIf you are running Python on your local machine, then open up Command Line and type pip install 'package_name' to install a package.","Q_Score":1,"Tags":"python,google-colaboratory,geopandas","A_Id":63433559,"CreationDate":"2020-08-16T05:15:00.000","Title":"Colab error : ModuleNotFoundError: No module named 'geopandas'","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have an LSTM that utilizes binary data, ie the labels are all 0's or 1's.\nThis would lead me to use a sigmoid activation function, but when I do it significantly underperforms the same model with a tanh activation function with the same data.\nWhy would a tanh activation function produce a better accuracy even though the data is not in the (-1,1) range needed for a tanh activation function?\nSigmoid Activation Function Accuracy:\nTraining-Accuracy: 60.32 %\nValidation-Accuracy: 72.98 %\nTanh Activation Function Accuracy:\nTraining-Accuracy: 83.41 %\nValidation-Accuracy: 82.82 %\nAll the rest of the code is the exact same.\nThanks.","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":330,"Q_Id":63438191,"Users Score":1,"Answer":"In the interval of (0, 1] if gradient is diminishing over time t, Then sigmoid gives better result. If gradient is increasing then tanh activation function.","Q_Score":0,"Tags":"python,tensorflow,keras","A_Id":63438468,"CreationDate":"2020-08-16T14:41:00.000","Title":"Keras Activation Functions Tanh Vs Sigmoid","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have trained a image classification model using keras which gives training acc of 98%, validation acc of 98% testing acc of 90%, but performs very poor on new input images. I don't know the why??","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":28,"Q_Id":63439218,"Users Score":0,"Answer":"You write that you trained an image classification model. Let's say that you want to write an app which lets people photograph their dinner and it returns a prediction on which food it is.\nIf you train your model with \"perfect\" images, i.e. high-quality images that are sharp, but now you let your model predict a \"real-life\" which was taken in a dark restaurant, then you have the problem: You let model predict sth it basically didn't learn. That might be the issue.\nI think it would be great if you could provide us with some typical images of your training-dataset and the dataset you are predicting on. Maybe the ones you took for predictions are not typical for the whole training dataset.","Q_Score":0,"Tags":"python,keras,deep-learning,image-classification","A_Id":63441964,"CreationDate":"2020-08-16T16:19:00.000","Title":"Keras model performs well in training, validation and also in evaluating but performs poor when predicting a new image","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a python script using the scapy 2.4.3 sniff() fuction, running in a thread:\nsniff(iface=self.iface, store=0, filter=\"(ip and not src net %s) and (udp dst port %s)\" % (self.ip_src, str(self.dport)), prn=self.handle_someip_packet)\nIt came to my attention that the execution of this sniffing thread is take too much time.\nI would like to set the conf.layers.filter([UDP]), but I get the error:\nAttributeError: 'LayersList' object has no attribute 'filter'\nWhat am I doing wrong?\nAny other ideas to speed the scapy sniffing?\nThanks in advance,","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":490,"Q_Id":63447758,"Users Score":0,"Answer":"You are probably using an older version of scapy without realizing. Try using 2.4.4rc2 (pip3 install scapy --pre)\nYou can check the version using scapy.__version__","Q_Score":1,"Tags":"python,multithreading,performance,filter,scapy","A_Id":63449833,"CreationDate":"2020-08-17T09:02:00.000","Title":"Scapy speed up sniff performance","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Out of meterological data with 3 dimensions (lat, lon and time) I selected a subset and aggregated values of two different timespans\/years into monthly means.\nSo at the end I have a DataSet where the dimension are the months (1-12) and there are two variables... Mean Values of timespan 1 and Mean Values of timespan 2.\nNow I just want to plot these two variables on a simple Line chart to compare them. I already spent hours and days to find any advice on this, but it seems, that xarray isn't made for plotting multiple variables over each other? (Can't find anything useful for this)","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":524,"Q_Id":63448843,"Users Score":1,"Answer":"So, you have one DataSet with two climatologies? And if you run data.clim1 or data.clim1 in the console, you see the the data sets and your climatologies are different? (Just to make sure, that you do not plot the same thing over each other.)\nYou should be able to plot them with:\n\nimport matplotlib.pyplot as plt \nplt.figure() \ndata.clim1.plot() \ndata.clim2.plot()\n\nHope that works. :)","Q_Score":0,"Tags":"python,plot,python-xarray","A_Id":63486658,"CreationDate":"2020-08-17T10:17:00.000","Title":"Plot multiple variables of a 1-Dimensional xarray DataSet","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"For a current project, I am planning to merge two very large CSV files with Dask as an alternative to Pandas. I have installed Dask thorough pip install \"dask[dataframe]\".\nWhen running import dask.dataframe as dd, I am however receiving the feedback ModuleNotFoundError: No module named 'dask.dataframe'; 'dask' is not a package.\nSeveral users seem to have had the same problem and were recommneded to install the module via Conda, which has not helped either in my case.\nWhat is the reason for the module not being found?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":2058,"Q_Id":63452968,"Users Score":4,"Answer":"As user John Gordon mentioned, the reason for the error notification is that a file within the same folder was named dask.py. Renaming the file solved the situation within seconds.\nAs a general rule\/conclusion: is as advisable to not use .py file names that directly relate to Python modules.","Q_Score":2,"Tags":"python,pandas,dask,dask-dataframe","A_Id":63456511,"CreationDate":"2020-08-17T14:30:00.000","Title":"ModuleNotFoundError: No module named 'dask.dataframe'; 'dask' is not a package","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I was reading a Machine Learning book and came across this in the CNN chapter.\n\nThe weights of a convolutional layer are represented as a 4D tensor of\nshape [fh, fw, fn\u2032, fn]. The bias terms of a convolutional layer are\nsimply represented as a 1D tensor of shape [fn]. Where fh is the heigher of the receptive field and fw is the width of the receptive field. fn' is the number of feature maps in the previous layer and fn is the number of feature maps in the current layer.\n\nI am trying to understand what each number in the given order signifies. Is it creating a rank 4 matrix where each entry represents the weight connecting an output neuron from the previous layer with specified feature map and location in the receptive field to the current ouput neuron?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":388,"Q_Id":63455361,"Users Score":3,"Answer":"fn':\nIt represents number of channels in previous layer which also indirectly specifies depth(or channels) of each kernels in current layer.\nfn:\nIt represents number of feature maps in current layer i.e. number of different kernels in current layer. Because each kernel outputs single channel.\nfw:\nIt represents kernel width.\nfh:\nIt represents kernel height.\nSuppose [fh, fw, fn\u2032, fn] = [3, 3, 10, 20] then layer(weight) will be of size 20x10x3x3. Each kernel will be of size 10x3x3 (where 3x3 is spacial and 10 is depth) and there will be 20 such kernels. These kernels operate on previous 20 feature maps to output 10 feature maps.\nAnd each entry in this 4d matrix representing weight will be shared. It doesn't connect neurons one to one because of convolution. Convolution's main advantages itself is parameter sharing and receptive field\/local connectivity.","Q_Score":0,"Tags":"python,tensorflow","A_Id":63455927,"CreationDate":"2020-08-17T16:58:00.000","Title":"4D Tensor Shape","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"After updating macOS to Catalina, I can no longer import modules like Pandas, Numpy or Scipy--I get a ModuleNotFoundError. Interestingly, import os and import sys do not throw this error.\nDoes anyone know why this is and how to fix it?\nThanks","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":144,"Q_Id":63468915,"Users Score":0,"Answer":"Probably after update you have another default Python interpreter.\nYou either should find where \"the old one\" is located or install again all libraries needed (e.g. pip install pandas)","Q_Score":1,"Tags":"python-3.x,macos,python-import,python-module,macos-catalina","A_Id":63469530,"CreationDate":"2020-08-18T12:44:00.000","Title":"Python modules not working after macOS Catalina update","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":1,"Web Development":0},{"Question":"Say I have two arrays\n[1, 3 , 5] and\n[2, 4, 6],\nwhat's the best way of merging them to yield [1, 2, 3, 4, 5, 6] without using loops or recursion and just numpy?","AnswerCount":5,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":301,"Q_Id":63469749,"Users Score":0,"Answer":"You can do it without numpy:\nJust add them, a = [1,3,5]+[2,4,6] and then sort them sorted(a)","Q_Score":1,"Tags":"python,numpy,concatenation,numpy-ndarray","A_Id":63469780,"CreationDate":"2020-08-18T13:31:00.000","Title":"Merge two arrays in a zipper pattern","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"So I'm currently completing my Udacity Nanodegree and there is this one point that i'm not able to understand.\nIn the input layer we're taking 784 because the pixel of MNIST dataset is 28x28, but i don't understand why are they taking 256 hidden layer. Where did this 256 number came from?","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":58,"Q_Id":63481752,"Users Score":0,"Answer":"The 256 hidden layer represent the 0 to 255 value given to each pixel to represent saturation of color for that pixel.","Q_Score":0,"Tags":"python,deep-learning","A_Id":63483155,"CreationDate":"2020-08-19T07:11:00.000","Title":"Hidden Layer in a Neural Network","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"So I'm currently completing my Udacity Nanodegree and there is this one point that i'm not able to understand.\nIn the input layer we're taking 784 because the pixel of MNIST dataset is 28x28, but i don't understand why are they taking 256 hidden layer. Where did this 256 number came from?","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":58,"Q_Id":63481752,"Users Score":0,"Answer":"The number of units in hidden layers is an hyperparameter of the network, so just like any other hyperparameter (like the learning rate, regularization factor and so on) it is initially chosen arbitrarily, then its value is \"tuned\" by assessing the model's performances on the validation set.\nSometimes though, especially in small and contrived examples like MNIST, some hyperparameters are fixed once and for all and never tuned, given how simple the task at hand is. So yeah, chances are that the number 256 was chosen arbitrarily.","Q_Score":0,"Tags":"python,deep-learning","A_Id":63483349,"CreationDate":"2020-08-19T07:11:00.000","Title":"Hidden Layer in a Neural Network","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Suppose I have a tabular dataset of fixed dimension (N x M). I receive a stream of updates from Kafka updating entries in this table. Ultimately, I'd like to have a pandas dataframe with a recent version of the table, and I'm considering a few options for doing that:\n\nMaintain it in memory as a table \/ dataframe. My concern here, is I don't know if I can avoid multithreading, since one process will perpetually be in a for loop of receiving messages.\n\nMaintain it in an external structure, and have a separate process independently read from it. Choices of external data stores:\na) SQLite - Might have concurrency issues, and updates for arbitrary rows are probably a bit messy.\nb) Redis - Easy to maintain, but hard to query \/ read the whole table at once (which is how I would generally be accessing the data).\n\n\nI'm a bit of a Kafka beginner, so any advice here would be appreciated. How would you approach this problem? Thanks!\nEDIT: I guess I could also just maintain it in memory and then just push the whole thing to SQLite?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":339,"Q_Id":63495473,"Users Score":1,"Answer":"My initial approach would be to ask: can I create a \"good enough\" solution to start with, and optimize it later if needed?\nUnless you need to worry about very sensitive information (like healthcare or finance data), or data that is going to definitely going to scale up very quickly, then I would suggest trying a simple solution first and then see if you hit any problems. You may not!\nUltimately, I would probably go with the SQLite solution to start with, as it's relatively simple to set up and it's a good fit for the use case (i.e. \"transactional\" situations).\nHere are some considerations I would think about:\nPros\/cons of a single process\nUnless your data is high-velocity \/ high-volume, your suggestion of consuming and processing the data in the same process is probably fine. Processing data locally is much faster than receiving it over the network (assuming your Kafka feed isn't on your local computer), so your data ingest from Kafka would probably be the bottleneck.\nBut, this could be expensive to have a Python process spinning indefinitely, and you would need to make sure to store your data out to a file or database in order to keep it from being lost if your process shut down.\nRelational database (e.g. SQLite)\nUsing a relational database like SQLite is probably your best bet, once again depending on the velocity of the data you're receiving. But relational databases are used all the time for transactional purposes (in fact that's one of their primary intended purposes), meaning high volume and velocity of writes\u2014so it would definitely make sense to persist your data in SQLite and make your updates there as well. You could see about breaking your data into separate tables if it made sense (e.g. third normal form), or you could keep it all in one table if that was a better fit.\nMaintain the table in memory\nYou could also keep the table in memory, like you suggested, as long as you're persisting it to disk in some fashion (CSV, SQLite, etc.) after updates. For example, you could:\n\nHave your copy in memory.\nWhen you get an update, make the update to your in-memory table.\nWrite the table to disk.\nIf your process stops or restarts, read the table from memory to start.\n\nPandas can be slower for accessing and updating individual values in rows, though, so it might actually make more sense to keep your table in memory as a dictionary or something and write it to disk without using pandas. But if you can get away with doing it all in pandas (re: velocity and volume), that could be a fine way to start too.","Q_Score":0,"Tags":"python,apache-kafka,redis,producer-consumer","A_Id":63496093,"CreationDate":"2020-08-19T21:55:00.000","Title":"Best data structure to maintain a table from a stream of Kafka update messages in Python","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"System\n\nmacbook pro\nOSX 10.15.5(Catalina)\nDocker version 19.03.12, build 48a66213fe\n\nLibrary\n\nuvicorn==0.11.8\nfastapi==0.61.0\ntorch==1.6.0\ntransformers==3.0.2\nsentence-transformers==0.3.2\nscikit-learn==0.20.0\nscipy==1.4.1\npandas==0.23.4\njupyter==1.0.0\n\nDetail\nI used Colaboratory to fine-tune Setence BERT and save that model.\nThen I went local and built an environment with Docker that included jupyter and FastAPI, and in that environment I was able to confirm that the model I saved with Jupyter, launched in Docker, returned the same estimation results as in the Collaboratory.\nWhen I used that model, I got different results when I used FastAPI started in the same Docker environment as Jupyter.\nAll the text entered in this flow is the same.\nThe analysis showed that the SentenceTransformer loaded the model and then encoded it, and found that it calculated completely different embedding.\nThanks to your advice.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":125,"Q_Id":63497635,"Users Score":0,"Answer":"sorry, I use Japanese model but I forgat translate default BertTokenizer to BertJapaneseTokenizer.\nChange default Tokenizer fixed this problem.","Q_Score":0,"Tags":"python,docker,jupyter-notebook,bert-language-model,fastapi","A_Id":63498106,"CreationDate":"2020-08-20T02:53:00.000","Title":"Encoding sentences with Setenece BERT's model in FastAPI changes the result from the results with Jupyter and python scripts","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to find or create a region growing algorithm which takes in an array of seeds and a sort of \"cost\" array so that when regions are created, they do so in a way which can be controlled by a threshold put on cost.\nFor example, I want to input seed locations and population counts in 2D numpy arrays of the same size. The final result would ideally be a set of regions associated with the seeds which are constrained by the population array so that no one region would have a much higher population count than others.\nI have looked into skimage.segmentation.watershed and have created a basic region segmentation using inverse distance weighting with numpy, but I'm unsure of where to go from here.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":299,"Q_Id":63512671,"Users Score":0,"Answer":"similar to k-mean clustering where the candidate pixel is classified based on the distance that is closest to the mean of the cluster. On the other hand, region growing based segmentation analyzes the neighboring pixels to determine whether or not to add the pixel to the seed region. and similar to the k-means, the process is iterated over all the pixels. First threshold the image and input some seed values usually through mouse clicks and finally iteratively use the 4\/8-neighborhood connectivity.","Q_Score":0,"Tags":"python,numpy","A_Id":63521734,"CreationDate":"2020-08-20T20:25:00.000","Title":"Region Growing Algorithm with threshold or bounds","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working with features extracted from pre-trained VGG16 and VGG19 models. The features have been extracted from second fully connected layer (FC2) of the above networks.\nThe resulting feature matrix (of dimensions (8000,4096)) has values in the range [0,45]. As a result, when I am using this feature matrix in gradient based optimization algorithms, the value for loss function, gradient, norms etc. take very high values.\nIn order to do away with such high values, I applied MinMax normalization to this feature matrix and since then the values are manageable. Also, the optimization algorithm is behaving properly. Is my strategy OK i.e. is it fair enough to normalize features that have been extracted from a pre-trained models for further processing.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":132,"Q_Id":63518308,"Users Score":0,"Answer":"From experience, as long as you are aware of the fact that your results are coming from normalized values, it is okay. If normalization helps you show gradients, norms, etc. better then I am for it.\nWhat I would be cautious about though, would be any further analysis on those feature matrices as they are normalized and not the true values. Say, if you were to study the distributions and such, you should be fine, but I am not sure what is your next step, and if this can\/will be harmful.\nCan you share more details around \"further analysis\"?","Q_Score":0,"Tags":"python,feature-extraction,gradient-descent,vgg-net,batch-normalization","A_Id":63518474,"CreationDate":"2020-08-21T07:23:00.000","Title":"Can we normalize features extracted from pre-trained models","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"When running a PyTorch training program with num_workers=32 for DataLoader, htop shows 33 python process each with 32 GB of VIRT and 15 GB of RES.\nDoes this mean that the PyTorch training is using 33 processes X 15 GB = 495 GB of memory? htop shows only about 50 GB of RAM and 20 GB of swap is being used on the entire machine with 128 GB of RAM. So, how do we explain the discrepancy?\nIs there a more accurate way of calculating the total amount of RAM being used by the main PyTorch program and all its child DataLoader worker processes?\nThank you","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":1819,"Q_Id":63522955,"Users Score":1,"Answer":"Does this mean that the PyTorch training is using 33 processes X 15 GB = 495 GB of memory?\n\nNot necessary. You have a worker process (with several subprocesses - workers) and the CPU has several cores. One worker usually loads one batch. The next batch can already be loaded and ready to go by the time the main process is ready for another batch. This is the secret for the speeding up.\nI guess, you should use far less num_workers.\nIt would be interesting to know your batch size too, which you can adapt for the training process as well.\n\nIs there a more accurate way of calculating the total amount of RAM being used by the main PyTorch program and all its child DataLoader worker processes?\n\nI was googling but could not find a concrete formula. I think that it is a rough estimation of how many cores has your CPU and Memory and Batch Size.\nTo choose the num_workers depends on what kind of computer you are using, what kind of dataset you are taking, and how much on-the-fly pre-processing your data requires.\nHTH","Q_Score":18,"Tags":"python,python-3.x,ubuntu,deep-learning,pytorch","A_Id":68578695,"CreationDate":"2020-08-21T12:29:00.000","Title":"Understanding Memory Usage by PyTorch DataLoader Workers","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"So right now I'm using keras and training my model works perfectly fine, but I have to pass my data as numpy ndarray. So I have to convert my list of data to numpy ndarray first and then pass it to keras for training. When I try to pass my python list\/array, even tho it's the same shape as numpy array I get back errors. Is there any way to not use numpy for this or am I stuck with it?","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":737,"Q_Id":63527536,"Users Score":2,"Answer":"Can you further explain your problem. What is the error message you are getting and are you getting this error during training or predicting?\nAlso if you could post some code samples that would help to","Q_Score":2,"Tags":"python-3.x,tensorflow,keras","A_Id":63527609,"CreationDate":"2020-08-21T17:33:00.000","Title":"Passing a python list to keras model.fit","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to install sklearn for Python, however whenever I attempt to install something which has files from it as a requirement (such as scikit-neuralnetwork) or I attempt to import sklearn in a Python file, I get errors. In the first scenario I receive the error message below marked A, and for the second I receive an error saying I have no module named sklearn.utils (I've already commented out the correct install check). I've tried reinstalling the libraries but the issue remains the same.\n\nERROR: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: 'C:\\Users\\Charles\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python38\\site-packages\\sklearn\\datasets\\tests\\data\\openml\\292\\api-v1-json-data-list-data_name-australian-limit-2-data_version-1-status-deactivated.json.gz'","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":54,"Q_Id":63528167,"Users Score":0,"Answer":"Download Anaconda. It has all the libraries already downloaded.","Q_Score":0,"Tags":"python,import,scikit-learn,libraries","A_Id":63528596,"CreationDate":"2020-08-21T18:19:00.000","Title":"How can I fix an failed install of sklearn for python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"Cannot use df.iplot. The error it generates is Mime type rendering requires nbformat>=4.2.0. Any help?","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":1922,"Q_Id":63533424,"Users Score":2,"Answer":"Simply update your jupyter notebook version with pip install notebook, restart kernel and you should be fine. Had this issue myself and this solved the problem.","Q_Score":3,"Tags":"python-3.x","A_Id":66232443,"CreationDate":"2020-08-22T06:56:00.000","Title":"Mime type rendering requires nbformat>=4.2.0","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I see that I have both version of tensorflow in anaconda2\/lib\/python2.7\/site-packages:\n\ntensorflow-1.14.0.dist-info\/\ntensorflow-2.1.0.dist-info\/\n\nBut when I start anaconda2\/bin\/jupyter qtconsole, I always get 1.14. How do I use 2.1?\nThe history may be something like this:\n\n1.14 comes with conda\nI did pip install for 2.1\nI tried to do \"pip install tensorflow-datasets', it didn't work.\nGoogling suggested \"conda install -c anaconda tensorflow-datasets\". It looks this set tensorflow back to 1.14\nI tried different ways of 'pip install' 'conda install' 'conda update', but can't get tensorflow to 2.1.\n\nThanks.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":60,"Q_Id":63539835,"Users Score":0,"Answer":"anaconda 2 can't install tensorflow 2.x using conda install, I had to re-install anaconda 2, then install tf 2.x using pip install","Q_Score":0,"Tags":"python,tensorflow,anaconda","A_Id":63549256,"CreationDate":"2020-08-22T18:39:00.000","Title":"using different version of package within python anaconda","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a GaussianHMM that I have fitted using hmmlearn.fit function. I also have a bunch of sequences of observations and I want to compute the probability of each sequence happening given my fitted model. I looked into hmmlearn's documentation and I couldn't quite find a method that does what I want. In this case, do I just have to code the forward-backward algorithm? In case I code the forward-backward, I would also need the emission matrix, which is not given by hmmlearn.\nAnyone has an advice regarding this? thank you!","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":285,"Q_Id":63542312,"Users Score":1,"Answer":"I also have a bunch of sequences of observations and I want to compute the probability of each sequence happening given my fitted model\n\n\nWhat you might be looking for is the score function, to evaluate the probability of sequence (ie. model.score(X)). Note that this is the log probability, as hmmlearn adjusts for underflow error.\n\n\nIn case I code the forward-backward, I would also need the emission matrix, which is not given by hmmlearn.\n\n\nWhile the GaussianHMM does not have an emission matrix, you can choose to discretize your emissions and utilize MultinomialHMM, which allows you to specify and also later extract the emission matrix model.emissionprob_.","Q_Score":0,"Tags":"python-3.x,hmmlearn","A_Id":64174760,"CreationDate":"2020-08-23T00:24:00.000","Title":"Is there a function that computes the probability of a sequence T of observations given a hidden Markov model on hmmlearn?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I know it's important to apply Gaussian blur to an image before using Canny to detect edges. My question is: does cv2.Canny() do Gaussian blur on its own or it is necessary to apply cv2.GaussianBlur() before cv2.Canny()? The documentation isn't clear on this point.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":2587,"Q_Id":63543033,"Users Score":0,"Answer":"The aperture argument of Canny controls the size of the Sobel filter (from 1 to 7 ?), which in fact applies a lowpass filter before taking the derivative. Unfortunately, the documentation is not explicit about that lowpass filter, though Gaussian is cited.\nI bet that a binomial filter is in fact used (which is a close approximation to a Gaussian).","Q_Score":2,"Tags":"python,opencv,image-processing,edge-detection,canny-operator","A_Id":63594236,"CreationDate":"2020-08-23T03:15:00.000","Title":"Does cv2.Canny() perform a Gaussian blur?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"My question is: Is there a way to extract the flexray singals from Mf4 using dbc\/arxml file and save to MDF format","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":103,"Q_Id":63548369,"Users Score":0,"Answer":"Not until somebody releases a reliable parser for the Fibex and Arxml database formats for Flexray.","Q_Score":0,"Tags":"python-3.x,asammdf","A_Id":63622037,"CreationDate":"2020-08-23T14:52:00.000","Title":"Cannot extract Flexray signals from MF4 using dbc file","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to train a model with Yolo v5 to detect multiple objects on sales flyers. each image in the dataset used in training contains only one object and obviously a single bounding box.\nI'm wondering if that will affect the performance of the model in a bad way? because what I'm trying to do at the end is detecting multiple objects on each sale flyer.\nThank you for your help.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":648,"Q_Id":63554029,"Users Score":1,"Answer":"It probably will lower your AP if you work like this, but give it a try. It really depends on your training images and your data augmentations. I dont know about YOLOv5 but YOLOv4 has its Mosaic Data Augmentation which will adress your problem in a way i guess.","Q_Score":1,"Tags":"python,deep-learning,dataset,object-detection,yolov5","A_Id":63558389,"CreationDate":"2020-08-24T02:36:00.000","Title":"Train A Custom Object Detection Model with YOLO v5","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am always getting confused while preprocessing the dataset , whethere to use min max scaler or standard scaler, so basically my question is when to use standard scaler and in which situation can I use MinMax scaler ?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":972,"Q_Id":63572758,"Users Score":1,"Answer":"MinMaxScaler say (feature_range = (0, 1)) will transform each value in the column proportionally within the range [0,1]. Use this as the first scaler choice to transform a feature, as it will preserve the shape of the dataset (no distortion).\nStandardScaler() will transform each value in the column to range about the mean 0 and standard deviation 1, ie, each value will be normalised by subtracting the mean and dividing by standard deviation. Use StandardScaler if you know the data distribution is normal.\nIf there are outliers, use RobustScaler(). Alternatively you could remove the outliers and use either of the above 2 scalers (choice depends on whether data is normally distributed)\nAdditional Note: If scaler is used before train_test_split, data leakage will happen. Do use scaler after train_test_split","Q_Score":0,"Tags":"python,machine-learning,dataset,preprocessor","A_Id":63572819,"CreationDate":"2020-08-25T05:51:00.000","Title":"What is the main Difference between Standard Scaler and MinMax Scaler in machine learning while preprocrssing the dataset?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working on bayer raw(.raw format) image domain where I need to edit the pixels according to my needs(applying affine matrix) and save them back .raw format.so There are two sub-problems.\n\nI am able to edit pixels but can save them back as .raw\nI am using a robust library called rawpy that allows me to read pixel values as numpy array, while I try to save them back I am unable to persist the value\n\nrawImage = rawpy.imread('Filename.raw') \/\/ this gives a rawpy object\nrawData = rawImage.raw_image \/\/this gives pixels as numpy array\n.\n.\/\/some manipulations performed on rawData, still a numpy array\n.\nimageio.imsave('newRaw.raw', rawData)\n\n\n\nThis doesn't work, throws error unknown file type. Is there a way to save such files in .raw format.\nNote: I have tried this as well:-\n\nrawImageManipulated = rawImage\nrawImageManipulated.raw_image[:] = rawData[:] \/\/this copies the new\ndata onto the rawpy object but does not save or persists the values\nassigned.\n\n\nRotating a bayer image - I know rawpy does not handle this, nor does any other API or Library acc to my knowledge. The existing image rotation Apis of opencv and pillow alter the sub-pixels while rotating. How do I come to know? After a series of small rotations(say,30 degrees of rotation 12 times) when I get back to a 360 degree of rotation the sub-pixels are not the same when compared using a hex editor.\n\nAre there any solutions to these issues? Am I going in the wrong direction? Could you please guide me on this. I am currently using python i am open to solutions in any language or stack. Thanks","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":454,"Q_Id":63574377,"Users Score":0,"Answer":"As far as I know, no library is able to rotate an image directly in the Bayer pattern format (if that's what you mean), for good reasons. Instead you need to convert to RGB, and back later. (If you try to process the Bayer pattern image as if it was just a grayscale bitmap, the result of rotation will be a disaster.)\nDue to numerical issues, accumulating rotations spoils the image and you will never get the original after a full turn. To minimize the loss, perform all rotations from the original, with increasing angles.","Q_Score":0,"Tags":"python,image-processing,rotation,edit,raw","A_Id":63574600,"CreationDate":"2020-08-25T07:55:00.000","Title":"Raw image Editing, Rotating and Saving back as Raw","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"When using cv2.HOGDescriptor().detectMultiScale, what is the starting size of the detection window used? Is it the same size as my training data?\nFor example, if my training data are all 64*128 images then the detection window starts at 64*128?\nand how is the scaling factor used? For example, If I want to detect humans on an image of size 640*512, and I set scale=1.05, how is this 1.05 used?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":68,"Q_Id":63580023,"Users Score":1,"Answer":"The detection window is always 64 x 128 by default. To accommodate for the multiscale, the image is progressively scaled to create an image pyramid while keeping the detection window of 64 x 128 the same. This achieves the effect of searching for humans at larger sized search windows in order to keep the search window the same size. The image pyramid is constructed by progressively decreasing the image size by the scale factor until the 64 x 128 search window can no longer fit inside the rescaled image. Therefore, if your search images already consist of 64 x 128 images then there will only be one scale.\nThis moves to your next question where if scale=1.05, we produce an image pyramid by progressively resizing the input image rows and columns by rows \/ (scale ** i) and cols \/ (scale ** i) where i = 0, 1, 2, ... to provide an image pyramid. For each image in the pyramid, we use the 64 x 128 search window to look for the object of interest.","Q_Score":1,"Tags":"python,opencv,image-processing,computer-vision,object-detection","A_Id":63584964,"CreationDate":"2020-08-25T13:32:00.000","Title":"What is the starting size of the detection window?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have an array of log values temp= [4,4.05......9]\nThese are actually from 10^4 to 10^9\nfor example, log(10^4)=4 and so on\nI need to take the antilog of temp array to get these numbers from 10^4 to 10^9 but when I calculate np.exp(6.89) it gives me 991\nSo how to take antilog correctly?\nenter code hereEve_gradual_mr24_23=np.exp(np.mean(new_q3[340:350]))","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":390,"Q_Id":63580907,"Users Score":2,"Answer":"np.exp is the exponential in base e. If you want the exponential in base 10, you could use scipy.special.exp10 or simply 10.0**your_array","Q_Score":0,"Tags":"python,numpy,math","A_Id":63582039,"CreationDate":"2020-08-25T14:19:00.000","Title":"calculate antilog in python? np.exp \/ math.exp doesn't work","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"How to filter a specific type of image from the rest of the type of image.\nConsider i have a data set consisting of images of dogs only. I need the classifier to differentiate between dogs and all the other types of images in the world that are not dogs.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":16,"Q_Id":63583207,"Users Score":0,"Answer":"I will suggest you use pre trained deep learning models like vgg16, resnet50 which are available in Keras frame work. Train the model on images having only 2 category , i.e with dog and with out dogs. Than run the model on the existing dataset you will definately get your result.","Q_Score":0,"Tags":"python,machine-learning,deep-learning,computer-vision,artificial-intelligence","A_Id":63583320,"CreationDate":"2020-08-25T16:26:00.000","Title":"Cclassification of 1 vs infinite set","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"When using Keras recurrent layers, such as an LSTM layer, your input data is supposed to be in the 3-dimensional form of [samples,timesteps,features]. The problem here is that I can't get any reliable information on the order of the timesteps dimension in the input matrices. As a concrete example, would the first element\/row, for a given sample, be the most recent known row of features or the most distant row of features?\nI would suspect that the order would matter since the model is recurrent, and indeed when flipping the order of the timesteps column you end of getting different training results (when you have appropriately set seeds which would yield reproducibility.)\nIf someone would force me to guess, I would assume that the first row (for one sample) would be the most distant features in the sequence, but is there a definite answer here?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":405,"Q_Id":63598509,"Users Score":0,"Answer":"It's easier to picture 3D arrays in Keras as an array of 2D arrays. The first dimension is the samples.\nYour array must be of the shape [samples, timesteps, features]. Picture this as an array of length samples, where each element is itself a 2D array of shape [timesteps, features]. So, to be clear, each element in this array is a 2D array with timesteps number of rows and features number of columns.\nThe first row (index 0) in each of these 2D arrays is the first timestep, i.e., oldest as you say. The last row in each of these 2D arrays is the last timestep, i.e., most recent. For each timestep row, you have features along the columns.\nIt helps to unroll the array as done above to picture it easily and with more clarity.\nHope this helped.","Q_Score":2,"Tags":"python,keras,lstm","A_Id":63599590,"CreationDate":"2020-08-26T13:16:00.000","Title":"Order of timesteps in Keras LSTM training and validation data","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a parquet file which contains list of structs and I cannot seem to read it with any of the available python parquet libraries. Some of them return an error noting that 'list of structs' is not yet supported and the others just make a pandas dataframe with None objects. If anyone has any experience with this it would help a lot. I have been banging my head with this for the last few days. Is there any other way to programmatically read the file somehow or convert that file to some other format and then read it ?\nI want a python native support or c library can be called using Python that does not involving calling or starting other services like Spark.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":446,"Q_Id":63603023,"Users Score":0,"Answer":"Try uninstalling pyarrow and install fastparquet. This worked for me. I was trying to convert it to CSV using pandas.","Q_Score":1,"Tags":"python,parquet,pyarrow,fastparquet","A_Id":63703221,"CreationDate":"2020-08-26T17:42:00.000","Title":"How to read nested struct Parquet files in Python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using matplotlib to plot a KDE. The issue with this is I'm using ax.imshow, which only takes in a grid and an extent. Meaning it will linearly space the data from the grid using the minimum value in the extent to the maximum.\nI need to flip the y axes (doable), but then I also need to arbitrarily scale every y point by a function, not just a simple factor. As an example, if the y value is 5, I need it to be mapped to f(5)=13 and 6 should be mapped to f(6)=22. The point is, it's not a simple scale.\nIs there any way of modifying these y values after they have been plotted, or am I forced to modify these values before-hand.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":37,"Q_Id":63608699,"Users Score":1,"Answer":"I couldn't find a way to modify the y values, but I could find a way to modify the labels of the yaxis.\nBy scaling the yaxes with the desired function and its inverse, using the following:\nax.set_yscale('function', **{'functions':[forward, inverse]})\nThen scaling the axes ytick values by the desired function and setting the ytick labels to be the scaled yticks, you effectively scale the y values:\nax.set_yticklabels(forward(ax.get_yticks()))","Q_Score":0,"Tags":"python,matplotlib,kde-plasma","A_Id":63716562,"CreationDate":"2020-08-27T03:23:00.000","Title":"Modify matplotlib y values after plotting","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a image and I want to do HE or CLAHE on specific area of the image.\nI already have a mask for the image.\nIs there any possible way to do so?","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":566,"Q_Id":63608938,"Users Score":0,"Answer":"You can simply crop the area that you want to apply CLAHE on it and then process the cropped image","Q_Score":3,"Tags":"python,opencv","A_Id":63609101,"CreationDate":"2020-08-27T03:56:00.000","Title":"How to do Histogram Equalization on specific area","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a conda env with tensorflow 2.2.0 But now I want to create a new env with tensorflow 1.14.0.\nI used conda create --name tensorflow1_14 tensorflow-gpu==1.14.0 to create a new env.\nBut when I tried checking the tensorflow version in this env it still gives me 2.2.0\nand when I use conda list it shows the tensorflow-gpu version as 1.14.0\nBecause of this I cannot use the tf 1.14.0 Where am I going wrong?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":1836,"Q_Id":63616215,"Users Score":0,"Answer":"If someone is wondering what went wrong! here is the solution.\nThere was an overlap of pip and conda install. Steps followed:\n\nconda uninstall tensorflow-gpu==2.2.0\npip uninstall tensorflow-gpu==2.2.0\nconda install tensorflow-gpu==1.14.0","Q_Score":0,"Tags":"python,tensorflow,anaconda,version,conda","A_Id":63632866,"CreationDate":"2020-08-27T12:40:00.000","Title":"Anaconda new environment with tensorflow 1.14 version","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"For a data science project I used to calculate the week numbers through this code:\ndf['Week_Nr'] = df['Date'].dt.week\nAs this function is now depreciated I changed to\ndf['Week_Nr'] = df['Date'].dt.isocalendar().week\nYet my output used to be in int64 and now is in UInt32\nAnd this is causing an error in a following calculation: \"ValueError: DataFrame.dtypes for data must be int, float or bool.Did not expect the data types in fields Week_Nr\"\nSo my question is how I can modify the isocalendar().week to give me a int64 output or how to transform the column to int64 as I have not been successful in finding the right code.\nThis code did not work: df['Week_Nr'] = pd.to_numeric(df['Week_Nr'],errors='coerce')","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":422,"Q_Id":63634630,"Users Score":2,"Answer":"try .astype(numpy.int64) or .astype(\"int64\")","Q_Score":0,"Tags":"python,python-3.x,pandas,dataframe,integer","A_Id":63634663,"CreationDate":"2020-08-28T13:22:00.000","Title":"Change UInt32 to int64 for dt.isocalendar().week calculations","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to load a XBGClassifier model with joblib and pickle.\nWhen using joblib loaded_model = joblib.load('trained_model.sav') I'm getting the following error: AttributeError: module 'xgboost.compat' has no attribute 'XGBoostLabelEncoder'\nAnd with pickle loaded_model = pickle.load(open('trained_model.sav', 'rb')) I get AttributeError: Can't get attribute 'XGBoostLabelEncoder' on \nI installed xgboost again but it doesn't work, what might be the issue?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":1841,"Q_Id":63634910,"Users Score":0,"Answer":"Make sure that the xgboost versions in the saved and loaded environments are the same. You need to change the version of xgboost in the environment that you try to load model.","Q_Score":5,"Tags":"python,pickle,xgboost,joblib","A_Id":64227604,"CreationDate":"2020-08-28T13:38:00.000","Title":"joblib.load and pickle.load error \"No attribute 'XGBoostLabelEncoder'\"","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to generate a ndArray to compare it with an existing one, which is structured as follow:\n\nthe first column dtype is 'datetime' (Timestamp('2020-08-29 00:00:00))\nall the other n columns dtype are 'float' (nan)\n\nThe way I found till now is to define the array as:\ndataset = np.array((timestamp_vector, nan_vector, nan_vector, ...), dtype=object)\nI do not want to repeat 'nan_vector' n-time. Do you have some advice?","AnswerCount":1,"Available Count":1,"Score":-0.1973753202,"is_accepted":false,"ViewCount":69,"Q_Id":63647869,"Users Score":-1,"Answer":"To improve the above ndarray construction, I made a for loop where I used the concatenate function to add a new nan array, previously created with the same length of timestamp vector.","Q_Score":0,"Tags":"python,numpy,timestamp,numpy-ndarray","A_Id":64303183,"CreationDate":"2020-08-29T14:07:00.000","Title":"Python ndArray Generation [Different Data Type Columns]","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I was looking at the TensorFlow 2.0 Detection Zoo recently and found the SSD MobileNet V2 FPNLite 320x320 pre-trained model and was wondering what the FPN part in \"FPNLite\" means\/stands for.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":5266,"Q_Id":63653903,"Users Score":0,"Answer":"A Feature Pyramid Network, or FPN, is a feature extractor that takes a single-scale image of an arbitrary size as input, and outputs proportionally sized feature maps at multiple levels, in a fully convolutional fashion. This process is independent of the backbone convolutional architectures.","Q_Score":5,"Tags":"python,tensorflow,tensorflow2.0,tensorflow-lite,mobilenet","A_Id":69140926,"CreationDate":"2020-08-30T04:16:00.000","Title":"What does FPN in SSD MobileNet V2 FPNLite 320x320 stand for?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I can upload files to Azure, but sometimes the files I send to Azure are empty or not even present. I use iothub_client (from azure-iothub-device-client).\nFirst I create a series of csv and json files from an SQL database which I temporarily store on my pc. These files are then processed by the upload client and uploaded asynchronously to a storage blob.\nBasically the structure is:\n-- ID\n---- csv file\n---- csv file\n---- json file\nMost of the time this functions without any problems, however sometimes something doesn't work correctly and one csv file is containing only the header row - but never all of them - and\/or the json file is even missing. The order of uploading is:\n\ncsv file one\njson file\ncsv file two\n\nThe files are however always correctly created and stored on my pc. The code does not give any errors, so the iothub_client seems to be happy with what it's getting as input.\nI can't figure out why this goes wrong, as I have not been able to reproduce the error. Retrying to upload the same files results in a correctly executed upload procedure.\nAny clues about what can be the cause would be very much appreciated!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":270,"Q_Id":63661288,"Users Score":0,"Answer":"I run into this a lot. My best guess something has a lock on the file. I team into this with a logic app that scanned a SharePoint directory every five minutes. It would grab an Excel file and move it to blob storage. But I kept getting 0k files. I haven't seen this issue since changing the logic app too check every ten minutes. This increases the odds that a user will not be in the file.","Q_Score":0,"Tags":"python,azure","A_Id":63664736,"CreationDate":"2020-08-30T19:21:00.000","Title":"Uploaded files to azure blob storage are empty or not even present","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have months(Jan, Feb, Mar etc) data in my dataset and I am generating dummy variable using pandas library.\npd.get_dummies(df['month'],drop_first=True)\nI want to understand whether I should use drop_first=True or not in this case?\nWhy is it important to use drop_first and for which type of variables?","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":11653,"Q_Id":63661560,"Users Score":0,"Answer":"What is drop_first=True\ndrop_first=True drops the first column during dummy variable creation. Suppose, you have a column for gender that contains 4 variables- \"Male\", \"Female\", \"Other\", \"Unknown\". So a person is either \"Male\", or \"Female\", or \"Other\". If they are not either of these 3, their gender is \"Unknown\".\nWe do NOT need another column for \"Uknown\".\nIt can be necessary for some situations, while not applicable for others. The goal is to reduce the number of columns by dropping the column that is not necessary. However, it is not always true. For some situations, we need to keep the first column.\nExample\nSuppose, we have 5 unique values in a column called \"Fav_genre\"- \"Rock\", \"Hip hop\", \"Pop\", \"Metal\", \"Country\" This column contains value\nWhile dummy variable creation, we usually generate 5 columns. In this case, drop_first=True is not applicable. A person may have more than one favorite genres. So dropping any of the columns would not be right. Hence, drop_first=False is the default parameter.","Q_Score":8,"Tags":"python,linear-regression","A_Id":71984203,"CreationDate":"2020-08-30T19:17:00.000","Title":"drop_First=true during dummy variable creation in pandas","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"For an exploratory semester project, I am trying to predict the outcome value of a quality control measurement using various measurements made during production. For the project I was testing different algorithms (LinearRegression, RandomForestRegressor, GradientBoostingRegressor, ...). I generally get rather low r2-values (around 0.3), which is probably due to the scattering of the feature values and not my real problem here.\nInitially, I have around 100 features, which I am trying to reduce using RFE with LinearRegression() as estimator. Cross validation indicates, I should reduce my features to only 60 features. However, when I do so, for some models the R2-value increases. How is that possible? I was under the impression that adding variables to the model always increases R2 and thus reducing the number of variables should lead to lower R2 values.\nCan anyone comment on this or provide an explanation?\nThanks in advance.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":80,"Q_Id":63665684,"Users Score":0,"Answer":"It depends on whether you are using the testing or training data to measure R2. This is a measure of how much of the variance of the data your model captures. So, if you increase the number of predictors then you are correct in that you do a better job predicting exactly where the training data lie and thus your R2 should increase (converse is true for decreasing the number of predictors).\nHowever, if you increase number of predictors too much you can overfit to the training data. This means the variance of the model is actually artificially high and thus your predictions on the test set will begin to suffer. Therefore, by reducing the number of predictors you actually might do a better job of predicting the test set data and thus your R2 should increase.","Q_Score":0,"Tags":"python,regression,feature-selection","A_Id":63665753,"CreationDate":"2020-08-31T06:14:00.000","Title":"Why does R2-value increase after feature-reduction with RFE?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using skmultilearn library to solve a multi-label machine learning problem. There are 5 labels with binary data (0 or 1). Sklearn logistic regression is being used as base classifier. But I need to set label specific features for each classifier. The label data of one classifier to be used as feature of another classifier.\nI am not able to figure out on how to do that.\nAny help appreciated.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":59,"Q_Id":63683533,"Users Score":0,"Answer":"One-vs-Rest is the method of solving the multi-label problem you are trying to address, it is the transformation type. You just need to generate a different training set for each simple classifier so that you have all the combinations between the original attributes and each of the labels. Pandas can be useful for the manipulation of the data and the generation of the different datasets for each simple classifier. Note that using this strategy in its original form ignores the relationships between the tags.","Q_Score":0,"Tags":"python,multilabel-classification,skmultilearn","A_Id":63690540,"CreationDate":"2020-09-01T07:54:00.000","Title":"How to use skmultilearn to train models on label specific data","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am relatively new to Machine Learning and Tensorflow, and I want to try and implement mini-batch gradient descent on the MNIST dataset. However, I am not sure how I should implement it.\n(Side note: the training images (28px by 28px) and labels are stored in Numpy arrays)\nAt the moment, I can see 2 different ways to implement it:\n\nMy training images are in a Numpy array of [60000,28,28]. Reshape this into a [25 (num batches), 2400 (num images in batch), 28,28] and then use a for loop to call each batch and pass it the model.compile() method. The only thing that I am worried about with this method is that for loops are inherently slow, and a vectorised implementation would be much quicker.\n\nCombine the images and labels into a tensorflow dataset object, and then call the Dataset.batch() method and Dataset.prefetch() method, and then pass the data to the model.compile() method. The only problem with this is that my data doesn't remain as a Numpy array, which I feel have more flexibility than tensorflow dataset objects.\n\n\nWhich of these 2 methods would be best to implement, or is there a third way that is best that I am not aware of?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":1681,"Q_Id":63687295,"Users Score":2,"Answer":"Keras has an inbuilt batch_size argument to its model.fit method (since you tagged this question with keras I assume that you're using it). I believe that this will probably be the best optimised method to achieve what you're looking for.","Q_Score":1,"Tags":"python,numpy,tensorflow,keras,tensorflow-datasets","A_Id":63687640,"CreationDate":"2020-09-01T12:04:00.000","Title":"How to implement mini-batch gradient descent in Tensorflow 2?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm reading spark the definitive guide in which it is said :\n\nPython\/R DataFrames exist on one machine rather than multiple machines... this limits what you can do with a given DataFrame to resources that exist on that specific machine..\n\ntherefore, I wonder why Python's dataFrame can't spand to multiple machines ? and if that means that python's are not distributed ?\nUpdate\ndoes Python\/R have an equivalent distributed DataFrame like Spark scala\/java??DataFrame","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":71,"Q_Id":63690443,"Users Score":0,"Answer":"For example, pandas DataFrame is not distributed.\nThe statements say that the DataFrame is not unique, there were several DataFrame concepts. Even though there are many concepts, the spark DataFrame is the distributed one, but the others, i.e. python and R are not.\nIt does not mean for the pyspark DataFrame.","Q_Score":1,"Tags":"python,dataframe,apache-spark,pyspark,apache-spark-dataset","A_Id":63699596,"CreationDate":"2020-09-01T15:09:00.000","Title":"why does python dataFrames' are localted only in the same machine?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm reading spark the definitive guide in which it is said :\n\nPython\/R DataFrames exist on one machine rather than multiple machines... this limits what you can do with a given DataFrame to resources that exist on that specific machine..\n\ntherefore, I wonder why Python's dataFrame can't spand to multiple machines ? and if that means that python's are not distributed ?\nUpdate\ndoes Python\/R have an equivalent distributed DataFrame like Spark scala\/java??DataFrame","AnswerCount":2,"Available Count":2,"Score":0.1973753202,"is_accepted":false,"ViewCount":71,"Q_Id":63690443,"Users Score":2,"Answer":"Pandas doesnt allow you to distribute the datframe to mulitple machine at it own. It is good to us when you have data that\n\nFit in Memory (RAM)\nFits in Disk\n\nSo, it works well when you can have data that can be handled with single machine. But when the data and processing needs grows, you want to move to libraries that store and handle distributed\/parallel processing of dataframes. The concept of dataframe is common in these libraries, but implementation differs to provide distributed processing power. Two good examples are\n\nDask, it is typically used on a single machine utilising multiple cores\/thread by multiprocessing\/multitasking, but can also runs well on a distributed cluster.\nApache spark is mainly used in cluster mode on multiple node, hence distributed data processing framework. (but it can be used on single standlone machine as well)\n\nUpdate:\nYou asked that\n\nDataFrame CONCEPT is the one that is not distributed, however R and\nPython have other concept to do distributed computation\n\nDataframe don't needs to be non-distributed or distributed, it is a concept , DataFrame is a 2-dimensional data structure with columns that can have different types and it is so easy and efficient to query,summarise and manipulate that it was adopted in many Data-oriented Programming Paradigms and libraries. So, utilising and manipulating these dataframes can be done in distributed manner as well to handle Big data. Spark is just an example of Distributed data processing framework, which can be used with many languages including R and Python","Q_Score":1,"Tags":"python,dataframe,apache-spark,pyspark,apache-spark-dataset","A_Id":63699990,"CreationDate":"2020-09-01T15:09:00.000","Title":"why does python dataFrames' are localted only in the same machine?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a column which has entry like :\n'TURBINE, STEAM ; MAKE: ABB ; MODEL: CF-4GSS ; RATING: OUT PUT 1175 BHP ; SPEED: 2975 MIN -1'\nThere is some modifications I need to do after reading this into python. String MUST be of the form :\nITEM : TURBINE ; COMBUSTION : STEAM ; MAKE : XYZ ; MODEL : XYZ and so on.\nHow can I format it so that the column is of the specified format ?\n(Also since im reading this with pandas i think this column will be a series object)","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":55,"Q_Id":63704203,"Users Score":0,"Answer":"You could use the .split method on your original string:\nnew_string = original_string.split()\nWhich would give you a list of separate objects for each category in your string like this, ['TURBINE,', 'STEAM', ';', 'MAKE:', 'ABB', ';', 'MODEL:', 'CF-4GSS', ';', 'RATING:', 'OUT', 'PUT', '1175', 'BHP', ';', 'SPEED:', '2975', 'MIN', '-1']\nThen start a new string for your item final_string = \"ITEM :\"\nThen concatenate individual items from your list using indexing, final_string += new_string[0]\nThis would give you final_string == \"ITEM : TURBINE\". For a different item to add to your string you simply use a different index position from 0. Remember that python indexes from 0 onwards, and each individual item in the list is considered an object so the semi colons would be considered an individual object and you'd need to count them in your indexing. You will also want to add punctuation while you're concatenating.\nYou could remove all the semi colons from the string by using those to split the original string by inserting it into the .split method original_string.split(';'), but that would split the items only when it reaches semi colons, which would give you this, ['TURBINE, STEAM ', ' MAKE: ABB ', ' MODEL: CF-4GSS ', ' RATING: OUT PUT 1175 BHP ', ' SPEED: 2975 MIN -1']","Q_Score":0,"Tags":"python,python-3.x,pandas","A_Id":63704786,"CreationDate":"2020-09-02T11:07:00.000","Title":"Python : String Manipulation","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I was just looking into Tensorflow for Python, and they say they support python version 3.5-3.8. What I can't understand is, does \"3.8\" mean strictly 3.8.0 OR 3.8.x(so 3.8.5 works)?\nI know it can vary for different software.\nI just want to make sure that IF 3.8.5 is supported, that I use that since it's a newer version.\nThanks in advance!","AnswerCount":2,"Available Count":2,"Score":1.2,"is_accepted":true,"ViewCount":422,"Q_Id":63712637,"Users Score":1,"Answer":"Yes, it does. I'm on Python 3.8.5 and using tensorflow==2.3.0.\nUsually when a version is given as \"3.5-3.8\", it includes the patch versions as well. (Sometimes there could be issues that pop up but it's intended to include all patch version of the 'from' & 'to', inclusive.)","Q_Score":1,"Tags":"python,python-3.x,tensorflow,version,tensorflow2.0","A_Id":63712790,"CreationDate":"2020-09-02T19:48:00.000","Title":"Does Tensorflow support Python 3.8.5?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I was just looking into Tensorflow for Python, and they say they support python version 3.5-3.8. What I can't understand is, does \"3.8\" mean strictly 3.8.0 OR 3.8.x(so 3.8.5 works)?\nI know it can vary for different software.\nI just want to make sure that IF 3.8.5 is supported, that I use that since it's a newer version.\nThanks in advance!","AnswerCount":2,"Available Count":2,"Score":-0.0996679946,"is_accepted":false,"ViewCount":422,"Q_Id":63712637,"Users Score":-1,"Answer":"I would think it works in 3.8.5, but it would be safer to use 3.8.0.","Q_Score":1,"Tags":"python,python-3.x,tensorflow,version,tensorflow2.0","A_Id":63712671,"CreationDate":"2020-09-02T19:48:00.000","Title":"Does Tensorflow support Python 3.8.5?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I created a bidirectional seq2seq endcoder-decoder network, which aims at formating different datetypes to a german datetime format as: day_written_out, day.month.year\nSo as an example I have the string 12-27-1992 and I expect the model to predict Sunday, 27.12.1992.\nAfter training, the model reaches a valid_accuracy of 98%. Further investigation showed, that the model nearly always predicted the date itself correct, but the model is not able to extract the correct day. So instead of predicting Sunday, 27.12.1992 it predicts Wednesday, 27.12.1992.\nOnly 5% of the days are predicted correctly.\nI think, that the issues lies in the LSTM I use, even though its bidirectional, but since the day is the first element that is predicted, the model does not have alot of information for predicting the correct day, since at timestep 0 the model hasnt seen any date values yet. Is this correct?\nSo my question is, why is this model not capable of predicting the correct day? And would a tranformer architecture, which is capable of reading the whole sequence at a time, be able to solve this issue?\nThank you","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":85,"Q_Id":63722187,"Users Score":0,"Answer":"I think, that the issues lies in the LSTM I use, even though its bidirectional, but since the day is the first element that is predicted, the model does not have alot of information for predicting the correct day, since at timestep 0 the model hasnt seen any date values yet.\n\nTry generate 27.12.1992 - Wednesday instead to see if that does anything.\nHonestly i don't think any model can predict correctly with that data","Q_Score":0,"Tags":"python,tensorflow,lstm,autoencoder,transformer","A_Id":63723410,"CreationDate":"2020-09-03T10:56:00.000","Title":"Tensorflow: Getting LSTM to 100% in converting date time formats","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"So I just started using tweepy and I want to know, is there a way to get the likes of the tweet that was retweeted? Currently, I am storing the tweets inside of a dataframe, but when tweepy gets a retweet the favorite_count method returns 0 because you are not able to like a retweet. What I am wondering is if there is a way to track the original tweets likes, retweets, etc.?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":167,"Q_Id":63726639,"Users Score":0,"Answer":"TLDR; tweet.retweeted_status.favorite_count\nThe reason you cannot obtain the likes of the tweet that was retweeted is because of the way that the Tweepy API is set up. Consider this from the Tweepy Documentation.\n\nWhen using extended mode with a Retweet, the full_text attribute of the Status object may be truncated with an ellipsis character instead of containing the full text of the Retweet. However, since the retweeted_status attribute (of a Status object that is a Retweet) is itself a Status object, the full_text attribute of the Retweeted Status object can be used instead.","Q_Score":0,"Tags":"python,twitter,tweepy","A_Id":65331960,"CreationDate":"2020-09-03T15:15:00.000","Title":"Get the Likes of a retweet with tweepy","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am building a heat map for my company from a generated csv. After a lot of reading I built it using jupyter notebooks (online) using the gmaps API. I've never done anything like this before and jupyter\/python\/gmaps made it easy to accommodate my requirements (allows for zooming, hovering over a point displays data, easy data cleaning).\nNow I've reached the point where I need to share what I have built (with non-programmers). Right now the user can hit a button and a csv generates, I then take that csv and manually place it in my jupyter notebook folder, my code reads it in via pandas and generates the heatmap. I've seen a lot of resources pointing to github, nbviewer, Colaboratory and others but can't seem to find anything that allows user input. Ideally users would be able to click the button and a heatmap would appear (online or not). Security is also an issue so I am not able to make this project public.\nIs there a way to make jupyter notebooks (with gmaps) into an executable that allows input? Or another way to securely share my project that automates the csv upload? Am I looking at this from completely the wrong angle and need to change my technology?\nThank you very much in advanced! I am new to this kind of project and appreciate any help :)\nMore Info:\nWindows 10,\nGeneral environment: visual studio 2019 C#,\nCurrent project: python 3","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":230,"Q_Id":63730494,"Users Score":2,"Answer":"I decided I was thinking about jupyter notebooks in the wrong way and that that technology is more for research\/data science. I decided to just make a website that launches when the user clicks the button and have the data auto upload. I changed my technology to google maps javascript api and this seems to do everything I need it to do. I changed my data from csv to json but otherwise I think this is the right answer for me.","Q_Score":3,"Tags":"python,jupyter-notebook,exe,heatmap,jupyterhub","A_Id":63766221,"CreationDate":"2020-09-03T19:32:00.000","Title":"How to Share a Jupyter Notebook with a CSV Input","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have trained my model (.fit()) and satisfied with the performance on test split making prediction (.predict()). So I save my model to the disk (.save('model.h5')).\nNow I'm given new unseen dataset and asked to evaluate my already saved model on this dataset for performance. I am required to not only report accuracy but stuff line precision\/recall, confusion matrix etc...\nI then loaded my saved model (.load_model('model.h5')).\nQuestion:\nWhat the appropriate function that I should use to prepare report of the model performance on this new dataset. I should I use .predict() function or .evaluate().","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":319,"Q_Id":63755812,"Users Score":1,"Answer":"If you want to get loss\/accuracy or whatever other metrics you had during training - you need .evaluate() method. If all you need is actual probabilities or regression values - you need .predict() method.","Q_Score":2,"Tags":"python,python-3.x,machine-learning,keras,deep-learning","A_Id":63755900,"CreationDate":"2020-09-05T15:52:00.000","Title":"Evaluating my model in new unseen dataset","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to train an object detection model from tensorflow 1 detection model zoo using python, version 3.7, and when I'm executing it throws all these errors. I'm still learning about this so I haven't any idea about how to solve this problem. Have anyone had the same issue about the different dimensions?\nI have checked different questions from this web, like looking for 0 height or width into my csv files and things like that, but It seems like that is not the problem.\n\ntensorflow.python.framework.errors_impl.InvalidArgumentError: Shape\nmismatch in tuple component 16. Expected [1,?,?,3], got\n[1,1,242,640,3]","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":102,"Q_Id":63756857,"Users Score":0,"Answer":"Finally I checked my dataset and my csv file. The problem was almost all of the images had the same shape, but 3 of them not. So I changed those images and regenerate the csv files and the tfrecord files and now is running. The thing with the shape mismatch threw me off, but finally that was the problem","Q_Score":0,"Tags":"python-3.x,tensorflow","A_Id":64283197,"CreationDate":"2020-09-05T17:44:00.000","Title":"Shape mismatch in tuple component 16. Expected [1,?,?,3], got [1,1,242,640,3]","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using Open CV2 face detection in Python. It works very well, but often finds faces that, although they really are faces, are so blurry as to be useless. It succeeds in finding faces that can't be recognized as male or female, adult or child, but still clearly human faces.\nDetecting a face that can't be recognized is not a useful result, but I don't know how to programmatically block these results, or determine that they should be ignored.\nThe only approach I currently have is to ignore any face smaller than a certain threshold, but I still get some large blurry faces.\nAny suggestions? I am using the haarcascade_frontalface_alt_tree.xml for detection.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":313,"Q_Id":63761605,"Users Score":0,"Answer":"If your problem is to detect faces of Male , female or child you need to feed the images of the genders and train your program . It involves a lot of programming , but can be solved easily with opencv. You need to train your model(project) with thousands of images for accuracy.\nIf you want to detect certain faces only, you need to do the same but train your model with the images of faces you want to detect.....","Q_Score":0,"Tags":"python,cv2,facial-identification","A_Id":63762542,"CreationDate":"2020-09-06T07:06:00.000","Title":"Blurry faces in open CV2 face detection","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm using an RPyC Service to make some calculations on a remote machine and then want to return the result, which is a numpy array to the user - the rpyc client.\nThe return value of the service method is Netref to a numpy array, and therefore, when it returns to the client, he can not use operations such as np.mean(return_arr) on the returned array (even after using 'allow_all_attr':True).\nI am aware that I can obtain the return_arr using the rpyc obtain method on the client side, but I want to leave the client code (almost) empty for internal project reasons.\nSo, is there a way to configure the Service\/ method to return the numpy arrays by value instead of netref?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":321,"Q_Id":63762335,"Users Score":0,"Answer":"Possible solution:\nSend the client's numpy library to the service and save it as self.client_np.\nThen, whenever you want to return numpy array from a servive method to the client just use:\nreturn self.client_np.array(return_arr)","Q_Score":0,"Tags":"python,rpyc","A_Id":63765906,"CreationDate":"2020-09-06T08:48:00.000","Title":"Return object by value (not as Netref) from RPyC service exposed method","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Case I: In some cases, I use the library name to call some set of function i.e, np.median(). \nCase II: And in some cases, I use the variable name and library name to call another set of function i.e, np.mean(heights) or heights.mean().\nIn case II, I am able to use both library name and variable name. In case I, only library name works.\nMy doubt is how to differentiate these tow sets of functions.\nIf I am wrong in anyway, please clear my thoughts.\n(here i am referring to python language)\nthank you.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":192,"Q_Id":63764180,"Users Score":0,"Answer":"In the first case you\u2019re calling a method (function) of the library. Libraries are usually class instances or collections of functions within a module.\nIn the second example instead, you\u2019re again calling a function from the module but in this case it returns a ndarray (a numpy list basically) which itself has some methods that can be called on it.","Q_Score":0,"Tags":"python,pandas,function,numpy,libraries","A_Id":63764228,"CreationDate":"2020-09-06T12:31:00.000","Title":"Calling library functions in python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"My independent variable is a datetime object and my dependent variable is an float. Currently, I have a keras model that predicts accurately, but I found out that model.predict() only returns predictions for the values that are already known. Is there a method I can call to tell the program to use the model to predict unknown values? If there isn't please give me instructions about how to predict these unknown values.","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":181,"Q_Id":63768722,"Users Score":1,"Answer":"Currently, I have a Keras model that predicts accurately, but I found out that model.predict() only returns predictions for the values that are already known\n\nThat is incorrect. A predict statement doesn't just 'search and return' results from training data. That's not how machine learning works at all. The whole reason that you build models and have a train and test dataset is to ensure you have a model that is generalizable (i.e. can be used to make predictions on unseen data, assuming the observation is coming from the same underlying distribution that the model is trained on)\nIn your specific case, you are using a DateTime variable an independent, which means you should refrain from using variable such as year, which are non-recurring since you can use it to make predictions about the future (model learns patterns in 2019 but 2020 may be out of its vocabulary and thus years after that are not feasible to use for predictions.)\nInstead, you should engineer some features from your DateTime variable and use recurring variables which may show reveal some patterns in the dependent variable. These variables are like days of the week, months, seasons, hours of the day. Depending on what your dependent variable is, you can surely find some patterns in these.\nAll of this totally depends on what you are trying to model and what is the goal of the model.predict() w.r.t your problem statement. Please elaborate if possible so that people can give you more specific answers.","Q_Score":0,"Tags":"python,tensorflow,keras","A_Id":63768797,"CreationDate":"2020-09-06T20:41:00.000","Title":"How do I predict data using a trained keras model","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"After a lot of research, it seems like there is no good way to properly stop and resume training using a Tensorflow 2 \/ Keras model. This is true whether you are using model.fit() or using a custom training loop.\nThere seem to be 2 supported ways to save a model while training:\n\nSave just the weights of the model, using model.save_weights() or save_weights_only=True with tf.keras.callbacks.ModelCheckpoint. This seems to be preferred by most of the examples I've seen, however it has a number of major issues:\n\nThe optimizer state is not saved, meaning training resumption will not be correct.\nLearning rate schedule is reset - this can be catastrophic for some models.\nTensorboard logs go back to step 0 - making logging essentually useless unless complex workarounds are implemented.\n\n\nSave the entire model, optimizer, etc. using model.save() or save_weights_only=False. The optimizer state is saved (good) but the following issues remain:\n\nTensorboard logs still go back to step 0\nLearning rate schedule is still reset (!!!)\nIt is impossible to use custom metrics.\nThis doesn't work at all when using a custom training loop - custom training loops use a non-compiled model, and saving\/loading a non-compiled model doesn't seem to be supported.\n\n\n\nThe best workaround I've found is to use a custom training loop, manually saving the step. This fixes the tensorboard logging, and the learning rate schedule can be fixed by doing something like keras.backend.set_value(model.optimizer.iterations, step). However, since a full model save is off the table, the optimizer state is not preserved. I can see no way to save the state of the optimizer independently, at least without a lot of work. And messing with the LR schedule as I've done feels messy as well.\nAm I missing something? How are people out there saving\/resuming using this API?","AnswerCount":3,"Available Count":1,"Score":0.0665680765,"is_accepted":false,"ViewCount":1495,"Q_Id":63775936,"Users Score":1,"Answer":"tf.keras.callbacks.BackupAndRestore can take care of this.","Q_Score":8,"Tags":"python,tensorflow,keras,tensorflow2.0,tf.keras","A_Id":72065560,"CreationDate":"2020-09-07T10:39:00.000","Title":"Keras - no good way to stop and resume training?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am experimenting with different methods of binning a continuous variable. two methods that I used - qcut and entropy_based_binning method bin_sequence. For testing I created a data with 100 values. I made the data skewed by putting value = 1 for first 50 records, 2 for next few records, 5, 12 for few records and then randomly few numbers.\nWhen I tried to run it with number of bins = 6 it created only 3 bins with qcut method. from pandas documentation it is not clear how it behaves with skewed data. Also, there is very limited information available on entropy based binning. Would appreciate if someone can share details. Pros and cons of each method\nage\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n12\n12\n12\n12\n12\n12\n12\n12\n12\n5\n5\n5\n5\n5\n5\n5\n5\n20\n20\n20\n20\n20\n20\n20\n25\n26\n27\n93\n50\n54","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":147,"Q_Id":63803037,"Users Score":0,"Answer":"When using qcut(), it will sort the array, and create bin boundaries based on the values at positions data[(len(data)*index \/ bin].\nIn your case, a lot of those values are equal. You should have gotten a warning about that, unless you explicitly told it to \"drop\" duplicate values by calling pd.qcut(age, q=6, duplicates='drop').\nFor entropy-based binning, you need a class label. You get bins with boundaries based on age, such that the class in each bin is (ideally) as uniform as possible. In your example, we only have age, so we can't use entropy-based binning.\nFor your particular setting, I would use qcut(), set the number of bins high enough, tell it to drop duplicates, and see what bins come out of it. One of the bins will have a lot of data in it (the first one), but that can't be helped, since our data is so highly skewed.","Q_Score":0,"Tags":"python-3.x,binning","A_Id":63803169,"CreationDate":"2020-09-09T00:06:00.000","Title":"Panda.qcut inside logic of binning","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've installed matplotlib through pip, and it runs perfectly when I use it in PyCharm. However, when I run my Python file through cmd, I get the following error message:\n\nModuleNotFoundError: No module named 'matplotlib'\n\nI have installed other modules the same way, and those have no problems running in PyCharm or in cmd.\nMatplotlib is installed under:\n\nC:\\Users\\David\\appdata\\local\\programs\\python\\python38-32\\lib\\site-packages\n\nSomething I noticed - perhaps the root of the problem - Is that Python seems to be installed in 2 places:\n\nC:\\Users\\David\\AppData\\Local\\Programs\\Python\\Python38-32\\python.exe\n\nThe path above is also the path to my Python Interpreter on PyCharm.\nand\n\nC: \\Users\\David\\AppData\\Local\\Microsoft\\WindowsApps\\python.exe\n\n\nPython version 3.8.5\nWindows 10\n\nThanks in advance!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":47,"Q_Id":63822177,"Users Score":0,"Answer":"try running the command pip install matplotlib in your cmd. It works for me.","Q_Score":0,"Tags":"python,matplotlib,cmd,pycharm","A_Id":63823096,"CreationDate":"2020-09-10T02:58:00.000","Title":"Matplotlib works in my IDE, but not through cmd?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"If i change one value of a column in csv file then whole column values are changed for example i have a column type int64 and i change one item from any integer to string then whole items types are changed to string by default when we read file like df = pandas.read_csv(filename). Actually i have to find item\/items in a df column who have different datatypes from others like if i have column type int64 and there is one value of datatype object or float64 types in that column then i have to fetch that value as well as the row number of that value.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":75,"Q_Id":63827084,"Users Score":0,"Answer":"Column inside any data frame can only have one data type for all the cells of those columns. You can see it using:\ndf.describe() or df.info()","Q_Score":0,"Tags":"python,pandas,csv","A_Id":63827373,"CreationDate":"2020-09-10T09:48:00.000","Title":"Can a column in dataframe contains different datatypes items?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm using a transfert-style based deep learning approach that use VGG (neural network). The latter works well with images of small size (512x512pixels), however it provides distorted results when input images are large (size > 1500px). The author of the approach suggested to divide the input large image to portions and perform style-transfert to portion1 and then to portion2 and finally concatenate the two portions to have a final large result image, because VGG was made for small images... The problem with this approach is that the resulting image will have some inconsistent regions at the level of areas where the portions were \"glued\".\nHow can I correct these areas ?\nIs the an alternative approach to this dividing method ?","AnswerCount":1,"Available Count":1,"Score":0.6640367703,"is_accepted":false,"ViewCount":809,"Q_Id":63829340,"Users Score":4,"Answer":"Welcome to SO, jeanluc. Great first question.\nWhen you say VGG, I expect you're referring to VGG-16. This architecture uses fully connected layers in the end which means you can only use it with images of a certain size. I believe the ImageNet default is 224x224 pixels.\nIf you want to use VGG-16 without modifications, you MUST use images of this size. However, many people remove the fully connected layers in the end (especially in the context of style transfer) in order to feed in any size they want.\nAny size? Well, you probably want to make sure that the images are multiples of 32 because VGG-16 comes with 5 MaxPooling operations that half the dimensions every time.\nBut just because the network can now digest images of any size doesn't mean the predictions will be meaningful. VGG-16 learned what 1000 different objects look like on a scale of 224px. Using a 1500px of a cat might not activate the cat related neurons. Is that a problem?\nIt depends on your use case. I wouldn't trust VGG-16 to classify these high resolution images in the context of ImageNet but that is not what you're after. You want to use a pretrained VGG-16 because it should have learned some abilities that may come in handy in the context of style transfer. And this is usually true no matter the size of your input. It's almost always preferred to start out with a pretrained model in comparison to starting from scratch. You probably want to think about finetuning this model for your task because A) style transfer is quite different from classification and B) you're using a completely different scale of images.\nI've never found this recommended patch based approach to help because of precisely the same problems you're experiencing. While CNN learn to recognize local pattern in an images, they will also learn global distributions which is why this doesn't work nicely. You can always try to merge patches using interpolation techniques but personally I wouldn't waste time on that.\nInstead just feed in the full image like you mentioned which should work after you removed the fully connected layers. The scale will be off but there's little you can do if you really want high resolution inputs. Finetune VGG-16 so it can learn to adapt to your use case at hand.\nIn case you don't want to finetune, I don't think there's anything else you can do. Use the transformation\/scale the network was trained on or accept less than optimal performance when you change the resolution.","Q_Score":5,"Tags":"python,deep-learning,vgg-net","A_Id":63832438,"CreationDate":"2020-09-10T12:06:00.000","Title":"Strategy to put and get large images in VGG neural networks","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a python dataframe with a column populated with strings of the same length like 0302000C0AABGBG , 0407020B0AAAGAG, 040702040BGAAAC\nI want to filter to identify all values that contain 'AA' but it must be at position _________AA ____ i.e. do not include 040702040BGAAAC in results.\nHow do I achieve that?\nCurrent searches yield str.contains but I can't find how to specify the position of the substring.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":32,"Q_Id":63835528,"Users Score":0,"Answer":"Append to your regex \\w{4}$ (requiring that four word characters occur at end of line) in str.contains call","Q_Score":0,"Tags":"python,pandas,string","A_Id":63835560,"CreationDate":"2020-09-10T18:18:00.000","Title":"Filter a list of strings but the filter must appear at a certain place","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"as I use the holoviews library in conjunction with the bokeh backend, I would like to create a 3D surface plot, too. In the documentation I only found matplotlib and plotly backends.\nCan somebody share a code snippet how to use holoviews\/bokeh for 3D surface plots?\nThank you","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":412,"Q_Id":63837347,"Users Score":0,"Answer":"Bokeh is a 2d plotting library, there is no built-in support for 3d plots. It's possible to wrap third-party 3d JS plotting tools as Bokeh custom extensions, but AFAIK Holoviews has not done this.","Q_Score":0,"Tags":"python,3d,bokeh,surface,holoviews","A_Id":63837495,"CreationDate":"2020-09-10T20:36:00.000","Title":"3d surface plot with holoviews and \"bokeh\"","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a datetime variable date_var=datetime(2020,09,11,0,0,0 ) and i am trying to populate a dataframe column for each row with this value. So i did something like df['Time']=date_var first this show 'Time' field datatype as datetime64 [ns] and not datetime and this populates Time field with value 2020-09-11 instead of 2020-09-11 00:00:00. Am i doing something incorrect ?\nThanks","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":357,"Q_Id":63846064,"Users Score":1,"Answer":"You've done nothing wrong. The fact that it prints as the date without time is just a convention in Pandas for simpler output. You can use df['Time'].dt.strftime('%F %T') if you want the column printed with the time part as well.\nStoring datetimes as the Pandas type (datetime64[ns]) is better than storing them as the Python type, because it is more efficient to manipulate (e.g. to add offsets to all of them).","Q_Score":0,"Tags":"python,pandas,dataframe,datetime","A_Id":63846217,"CreationDate":"2020-09-11T11:20:00.000","Title":"Assigning datetime variable to a pandas dataframe column","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Recently i came across a requirement where i tried to change python re with pyspark regexp_extract, the reason behind change re to pyspark regexp_extract is spark is more faster. by comparing the process speed with pyspark and re process I concluded like re is faster than pyspark regexp_extract. Is there any specific reason that cause pyspark regexp_extract is slow.\nThanks in advance","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":239,"Q_Id":63850472,"Users Score":0,"Answer":"Probably more context is needed to give an specific answer, but what I can infer from what you said is the following:\nI would think that it depends on the size of the data and how are the partitions in spark. As spark is parallelizing, probably in not huge amounts of data, regular python functions will work faster, but not in huge amounts of data were parallelization is more handy.","Q_Score":0,"Tags":"python-3.x,pyspark,apache-spark-sql,python-re","A_Id":63850526,"CreationDate":"2020-09-11T15:57:00.000","Title":"Why spark regexp_extract too slow when we compare with python re","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm building a text analysis program that extract dates from a text document. The dates are in several formats so I have written several extract lines like below.\ndf_new_1 = dfnew['text'].str.extract(r'(?P\\d{1,2})\/-\/-')\ndf_new_7 = dfnew['text'].str.extract(r'(?P\\d{1,2})\/-')\ndf_new_8 = dfnew['text'].str.extract(r'(?P\\d{4})')\nWhen running these lines in PyCharm, they work as expected. But, when running these in Jupyter Notebook, the last line (df_new_8) doesn't show the Grouped Name.\nOutput PyCharm of df_new_8.tail():\nYear\n495 1979\n496 2006\n497 2008\n498 2005\n499 1980\nOutput Jupyter Notebook of df_new_8.tail() No column title!!:\nOut[1]\n495 1979\n496 2006\n497 2008\n498 2005\n499 1980\nName: Year, dtype: object\nTo illustrate, when running df_new_1.head() in Jupyter it outputs (as expected):\nOut[3]\nMonth Day Year\n0 03 25 93\n1 6 18 85\n2 7 8 71\n3 9 27 75\n4 2 6 96\nAt the end of the program I 'concatenate' all df_new* dataframes together using fillna.\ndf_out = df_new_1.fillna(df_new_2).fillna(df_new_3).fillna(df_new_4).fillna(df_new_5).fillna(df_new_6).fillna(df_new_7).fillna(df_new_8).fillna(1)\nThat's when the real problem appears in Jupyter Notebook. Obviously df_new_8 wasn't processed, probably because of the missing Named Group. Again, this works fine in PyCharm. So, instinctly I say there's a problem with the line:\ndf_new_8 = dfnew['text'].str.extract(r'(?P\\d{4})')\nCan't figure out what though.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":24,"Q_Id":63858716,"Users Score":0,"Answer":"Turns out that Pycharm returns df_new_8 = dfnew['text'].str.extract(r'(?P\\d{4})') as a DataFrame, where Jupyter notebook returns it as a Series.","Q_Score":0,"Tags":"python,jupyter-notebook,regex-group","A_Id":63858908,"CreationDate":"2020-09-12T09:12:00.000","Title":"Jupyter Notebook Named Groups issue on extract() function","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"My data set has datetime data, I want to iterate over each day and run some function on one of the attributes for each day.\nHow do i iterate over each day in datetime series?\nSo, I am iterating using groupby(Date)\nIndex Date Time\n1 2-12-2018 13:22:27 \\n\nI need a way to tell if the time is between 12am to 6 am or other time intervals.\nTime is an object here. I am new to python and pandas\nThanks,","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":67,"Q_Id":63863409,"Users Score":0,"Answer":"I used,\nset_index('DateTime').between_time('00:00', '06:00', include_end=False).reset_index()\nto further classify my dataframe into required data frame.","Q_Score":0,"Tags":"python,pandas,datetime","A_Id":63892119,"CreationDate":"2020-09-12T18:06:00.000","Title":"Python pandas datetime attribute extraction","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to install TensorFlow via pip in the command line. I have satisfied all the requirements but all I get when executing pip install tensorflow is\nERROR: Could not find a version that satisfies the requirement tensorflow (from versions: none)\nERROR: No matching distribution found for tensorflow\nI also tried to install manylinux2010 but I get the same output. I'm running Windows 10 on a laptop with Python v. 3.8.5 installed. Pip version is 20.2.3 If you could help me that'd be great. Thanks!","AnswerCount":5,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":647,"Q_Id":63867489,"Users Score":0,"Answer":"Tensorflow as of Aug-13-2018 supports, Python 3.6.x, and only the 64 bit version.","Q_Score":2,"Tags":"python,tensorflow","A_Id":63867517,"CreationDate":"2020-09-13T05:28:00.000","Title":"Can't Install TensorFlow Via Pip","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to use Lasso regression in order learn a coefficient matrix, B. The problem I'm trying to solve is:\n\nmin{||y-xB|| +lambda{P X B}_1}\n\nWhere P is some penalty matrix: P_ij gives B_ij penalty p (the bigger P_ij the smaller B_ij)\nHow can I do this using python (didn't find anything useful in sklearn)?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":88,"Q_Id":63868994,"Users Score":0,"Answer":"Your problem is very specific, people usually don't train models like this, that's why there's nothing like that in sklearn. It's even incorrect to call lasso regression, but that's a question of terminology. But you can actually write the subdifferential of this loss and write subgradient descent yourself in python.","Q_Score":0,"Tags":"python,machine-learning,regression,lasso-regression","A_Id":63872979,"CreationDate":"2020-09-13T09:05:00.000","Title":"Lasso regression in python with differential penalties","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"When I read in a file (whether it'd be in .csv or .txt format) I tend to use the pandas.read_csv() method to read them. I was wondering if there is any difference with using this method and using with open(file). And if so, is there any advantages using one over another?\nAny insights on this will be greatful. :)","AnswerCount":2,"Available Count":2,"Score":1.2,"is_accepted":true,"ViewCount":35,"Q_Id":63876479,"Users Score":0,"Answer":"If you are going use pandas methods, then you need to read it in as a pandas dataframe.\nOtherwise, you can read in data with open(file) if you are not using pandas methods.\nAdvantages to doing this would be case specific, but for example one advantage could be that you don't need to use an additional library. For example, if you were to later automate a python script by building an executable that runs daily, you could avoid using pandas and build an executable file that is much smaller, since the pandas library uses a lot of space for building executables.","Q_Score":0,"Tags":"python,pandas","A_Id":63876523,"CreationDate":"2020-09-13T23:29:00.000","Title":"Reading in data into jupyter notebook","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"When I read in a file (whether it'd be in .csv or .txt format) I tend to use the pandas.read_csv() method to read them. I was wondering if there is any difference with using this method and using with open(file). And if so, is there any advantages using one over another?\nAny insights on this will be greatful. :)","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":35,"Q_Id":63876479,"Users Score":0,"Answer":"The advantage of using pandas, is that you have to write minimal\ncode, but also you probably load alot of stuff that you dont need.\n\nThe advantage of using open() is that you have more control, and\nyou program is gonna be significantly more minimalistic","Q_Score":0,"Tags":"python,pandas","A_Id":63876514,"CreationDate":"2020-09-13T23:29:00.000","Title":"Reading in data into jupyter notebook","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have 2 tables - customers and purchases\nI've used faker to create 100 entries for the customer table with various details of which one is customer_numbers that are unique 5 digits.\nI now want to create a table of 100 purchases that reuses the list of customer_numbers but to ensure that there is at least 25% duplicate records.\nI am not sure the best way to do this to ensure the 25% requirement.\nI initially created a custom function that resamples my original list (using faker.random_elements()) and just takes the first 100 records in the new list but that doesn't ensure a minimum of 25% overlap.\nIs there a built in function I can use? If not, what would be the math behind recreating a list with 25% overlaps from an existing list.\nCode seems less relevant here but let me know if you need samples.\nSolution I went with(not the only one to the problem):\n\nCalculated the number of samples to drop list_size-(list-size\/(1*repeat rate))\nDropped the no of samples from the customer list and resampled from the reduced list the number of samples I dropped (with replacement)\nMerged the shortened and resampled list\n\nThis solution ensures that len(original list) = len(set((new list)))*1.25","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":121,"Q_Id":63885052,"Users Score":0,"Answer":"A solution I can think of is as follows:\n\nRandomly selecting a number for your 'guarantee' overlapping between 25 and 100\nRandomly picking the 'guarantee' number of records from the existing list\nRandomly picking the rest of the required records (without considering the existence of the existing list)\n\nThis is because your customer_numbers consist of 5 digits, therefore picking these 5 digits randomly for 100 times will generally not create any duplicates with the existing list which has only 100 items. So I think using a way to 'guarantee' the overlapping percentage would work reasonably well. Also, I think it would not be difficult to implement the above steps in Python.","Q_Score":0,"Tags":"python,faker","A_Id":63888018,"CreationDate":"2020-09-14T13:11:00.000","Title":"Creating sample data (with faker) that has a % overlap in Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to create a column that identifies English and Spanish tweets from a dataframe with several rows of tweets. Ideally tweets in English would be categorized as a 1 and those in Spanish would be marked as 0.\nThe end goal is to be able to filter out Spanish tweets from my dataframe to save English tweets in a new CSV. I looked at using Textblob, langdetect, and also fastText, but everything I've found gives instructions for just running the code on 1 string of text at a time.\nIs there an easy way to categorize by language (English\/Spanish) for a whole dataframe using Python?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":189,"Q_Id":63889664,"Users Score":0,"Answer":"I think there are two ways.\ni) to train a model to determine the text is Spanish or English using\n(NLP).\nii) just trow the sentences to a list and use if condition with\nSpanish Character to give 1 or 0 on the bases of conditions.\nHope it is helpful.","Q_Score":1,"Tags":"python,twitter,nlp","A_Id":63889990,"CreationDate":"2020-09-14T18:09:00.000","Title":"How to identify Spanish vs. English Text from a csv of tweets?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Looking to extract only 7 digit numbers from this list that starts with the distance matrix, nothing after the underscore\nThe list:\n['data_train_3366094.dump','agile_234444.pkl','distanceMatrix_1517144.dump', 'distanceMatrix_3366094_1.dump']\nexpecting output: 1517144 , 3366094","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":22,"Q_Id":63892907,"Users Score":0,"Answer":"My guess is to explode(), separating with _ and .\nThen match for numeric value","Q_Score":0,"Tags":"python,python-3.x,regex,list","A_Id":63893029,"CreationDate":"2020-09-14T23:09:00.000","Title":"Python regular expression (matching in list)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have an array of 2k elements and i am trying to sort it.\nWhen i call sorted(arr) it takes very less time, i.e 3-4 sec to sort an array.\nbut when i am building my own sorting function(merge sort) with time complaxity nlogn it is taking more then a min to sort it.\nI also tried with quick sort and bubble sort but none of the algo is able to reduce the time to this extent.\nI am not able to understand that how builtin function works and how it is taking so less time. what is the logic behind it?","AnswerCount":2,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":640,"Q_Id":63897845,"Users Score":2,"Answer":"Python's sorted () is written in C and compiled to native code. When you write your own sort, it's run entirely in the python interpreter, which is at least an order of magnitude slower - nearly two. It's hard to say without seeing your code, but there's also a chance that your Python sort is doing a bunch of allocation behind the scenes...","Q_Score":0,"Tags":"python-3.x,sorting","A_Id":63898488,"CreationDate":"2020-09-15T08:19:00.000","Title":"logic behind sorted() function in python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have to create a 50 X 50 matrix in python at runtime using NumPy. The entries of the matrix will be a result of a data query from a website. The query return Pandas. So, how can I create a matrix using data from pandas at runtime?","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":467,"Q_Id":63900843,"Users Score":0,"Answer":"Almost everything you do in Python is on runtime. If your response is a pandas.DataFrame you can just access it's values attribute to get the underlying numpy array. No need to create it by hand.","Q_Score":0,"Tags":"python,pandas,numpy,matrix,numpy-ndarray","A_Id":63900911,"CreationDate":"2020-09-15T11:27:00.000","Title":"How to create a 50 X 50 matrix in Python at runtime?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"When I'm trying to read a feather file I got this Error:\n\nArrowInvalid: Column 0: In chunk 0: Invalid: Buffer #1 too small in array of type int64 and length 14712: expected at least 117696 byte(s), got 3450","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":1059,"Q_Id":63901347,"Users Score":4,"Answer":"This file was created with another pyarrow version. I had version 0.17.0 and file was created by version 1.0.0. So updating my pyarrow to new version solved the problem.","Q_Score":0,"Tags":"python,pandas,feather","A_Id":63901348,"CreationDate":"2020-09-15T11:57:00.000","Title":"pandas read feather ArrowInvalid","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have written some scrip in python using windows and want to run it in my raspberry with Ubuntu.\nI am reading a csv file with line separator new line. When I load the df I use the following code:\ndfaux = pd.read_csv(r'\/home\/ubuntu\/Downloads\/data.csv', sep=';') \nwhich loads a df with just one row. I have also tried including the argument lineterminator = '\\n\\t' which throws this error message:\nValueError: Only length-1 line terminators supported\nIn windows I see the line breaks in the csv file, whereas when I open it with mousepad in ubuntu I don't see the line breakers, but I see the columns color coded.\nHow could I read properly the csv?\nThanks!","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":1073,"Q_Id":63904101,"Users Score":1,"Answer":"Well, at then end I solved it by changing the explorer I was using to download the csv file with webdriver from Firefox to Chrome, not sure what\u00b4s the reason behind but maybe this will help if you have the same issue in the future","Q_Score":1,"Tags":"python,pandas,dataframe,csv,raspberry-pi4","A_Id":63916205,"CreationDate":"2020-09-15T14:31:00.000","Title":"Reading a CSV file to pandas works in windows, not in ubuntu","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm try to plot a decision trees of Xgboost models from different datasets.\nWhich worked fine for most of them, but for one dataset the plot_tree just shows only one leaf.\nIt's weird for me, once the max_depth of that model is 5.\nCould anyone give me a tip?\nThanks for considering my question. :) !","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":392,"Q_Id":63910030,"Users Score":0,"Answer":"I am glad to share that I figured out the reason for my problem :)\nXGBoost is a technique which works on the principle of ensemble, so XGBClassifier creates multiple trees and some trees can ended in only one leaf. I realised that the functions used to plot export_graphviz or plot_tree plotted the first tree of my model as default and not the best interaction. To do that I must set the parameter \"num_trees\":\n\n\"num_trees (int, default 0) \u2013 Specify the ordinal number of target\ntree\"\n\nSo, I have to find the ordinal number of the target tree.\nFortunately, there are two functions that set it for us .get_booster () and .best_iteration.\nSee below the code to plot the tree with the best interaction.\nplot_tree (model, ax = ax, num_trees = model.get_booster().best_iteration)","Q_Score":0,"Tags":"python,decision-tree,xgboost,xgbclassifier","A_Id":64353741,"CreationDate":"2020-09-15T21:22:00.000","Title":"Xgboost - Decision Tree - Only one leaf","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I asked our data support team to share data for 12 months, they sent me 12 different files with 3 sheets in each file. I need to combine all of that data into another datasheet, I have the following questions?\n\nWould excel be able to cram in all the data into one large file, limitations?\nIs R a good solution, can one share any easy code and libraries needed for such operation, seen multiple videos on youtube but all are not working.\nI heard that in Python Pandas is helpful but my past experience is bad that Python being very slow.\nI have no idea of VB codes\n\nPlease could anyone help.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":22,"Q_Id":63912986,"Users Score":0,"Answer":"may my answer can help you:\n\nExcel has limit 1.048.576 rows\nYou just need package to import excel file (readxl...). You can use for loop to import all file, and merge all file to dataframe and export to excel.\nIn VBA, i think logic is same in R","Q_Score":0,"Tags":"python,r,excel,pandas","A_Id":63914326,"CreationDate":"2020-09-16T04:09:00.000","Title":"Data Merging in R for 12 excel workbooks (each containing 3 worksheets)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I\u2019m trying to modify Yolo v1 to work with my task which each object has only 1 class. (e.g: an obj cannot be both cat and dog)\nDue to the architecture (other outputs like localization prediction must be used regression) so sigmoid was applied to the last output of the model (f.sigmoid(nearly_last_output)). And for classification, yolo 1 also use MSE as loss. But as far as I know that MSE sometimes not going well compared to cross entropy for one-hot like what I want.\nAnd specific: GT like this: 0 0 0 0 1 (let say we have only 5 classes in total, each only has 1 class so only one number 1 in them, of course this is class 5th in this example)\nand output model at classification part: 0.1 0.1 0.9 0.2 0.1\nI found some suggestion use nn.BCE \/ nn.BCEWithLogitsLoss but I think I should ask here for more correct since I\u2019m not good at math and maybe I\u2019m wrong somewhere so just ask to learn more and for sure what should I use correctly?","AnswerCount":1,"Available Count":1,"Score":0.537049567,"is_accepted":false,"ViewCount":965,"Q_Id":63914849,"Users Score":3,"Answer":"MSE loss is usually used for regression problem.\n\nFor binary classification, you can either use BCE or BCEWithLogitsLoss. BCEWithLogitsLoss combines sigmoid with BCE loss, thus if there is sigmoid applied on the last layer, you can directly use BCE.\n\nThe GT mentioned in your case refers to 'multi-class' classification problem, and the output shown doesn't really correspond to multi-class classification. So, in this case, you can apply a CrossEntropyLoss, which combines softmax and log loss and suitable for 'multi-class' classification problem.","Q_Score":2,"Tags":"python,pytorch,loss-function,cross-entropy","A_Id":65332656,"CreationDate":"2020-09-16T07:07:00.000","Title":"Using sigmoid output for cross entropy loss on Pytorch","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to subset anndata on basis of clusters, but i am not able to understand how to do it.\nI am running scVelo pipeline, and in that i ran tl.louvain function to cluster cells on basis of louvain. I got around 32 clusters, of which cluster 2 and 4 is of my interest, and i have to run the pipeline further on these clusters only. (Initially i had the loom file which i read in scVelo, so i have now the anndata.)\nI tried using adata.obs[\"louvain\"] which gave me the cluster information, but i need to write a new anndata with only 2 clusters and process further.\nPlease help on how to subset anndata. Any help is highly appreciated. (Being very new to it, i am finding it difficult to get)","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":1582,"Q_Id":63916137,"Users Score":3,"Answer":"If your adata.obs has a \"louvain\" column that I'd expect after running tl.louvain, you could do the subsetting as\nadata[adata.obs[\"louvain\"] == \"2\"]\nif you want to obtain one cluster and\nadata[adata.obs['louvain'].isin(['2', '4'])]\nfor obtaining cluster 2 & 4.","Q_Score":2,"Tags":"python,rna-seq,scanpy","A_Id":64331620,"CreationDate":"2020-09-16T08:31:00.000","Title":"subsetting anndata on basis of louvain clusters","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am generating dotplots using scanpy and unable to change the font size. Is there a way to do so?\nFor example, how would I edit this line of code?\nsc.pl.dotplot(df, [\"gene\"], 'CellType', dendrogram=True, save = name)","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":1124,"Q_Id":63925267,"Users Score":0,"Answer":"Turns out you can do this directly using scanpy with the following:\nsc.set_figure_params(scanpy=True, fontsize=14)\nHowever, I am still unsure how to change the y axis specifically...","Q_Score":0,"Tags":"python,python-3.x,matplotlib,scanpy","A_Id":63944122,"CreationDate":"2020-09-16T17:36:00.000","Title":"How to change font size in scanpy","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've been playing around with automatic gradients in tensorflow and I had a question. If we are updating an optimizer, say ADAM, when is the momentum algorithm applied to the gradient? Is it applied when we call tape.gradient(loss,model.trainable_variables) or when we call model.optimizer.apply_gradients(zip(dtf_network,model.trainable_variables))?\nThanks!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":32,"Q_Id":63926218,"Users Score":0,"Answer":"tape.gradient computes the gradients straightforwardly without reference to an optimizer. Since momentum is part of the optimizer, the tape does not include it. AFAIK momentum is usually implemented by adding extra variables in the optimizer that store the running average. All of this is handled in optimizer.apply_gradients.","Q_Score":0,"Tags":"python,tensorflow,adam","A_Id":63935102,"CreationDate":"2020-09-16T18:47:00.000","Title":"When is Momentum Applied in Tensorflow Gradient Tape?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to install package inside a docker container(python:rc-slim).\nAs of now I see that most recent azureml-core wheel uploaded to PyPI is:\n\nazureml_core-1.13.0-py3-none-any.whl\n\nbut when I run pip install azureml-core==1.13.0 I get following error:\n\nERROR: Could not find a version that satisfies the requirement\nazureml-core==1.13.0 (from versions: 0.1.50, 0.1.57, 0.1.58, 0.1.59,\n0.1.65, 0.1.68, 0.1.74, 0.1.80, 1.0rc83, 1.0rc85, 1.0.2, 1.0.6, 1.0.8, 1.0.10, 1.0.15, 1.0.17, 1.0.17.1, 1.0.18, 1.0.21, 1.0.23, 1.0.30, 1.0.33, 1.0.33.1, 1.0.39, 1.0.41, 1.0.41.1, 1.0.43, 1.0.43.1, 1.0.45, 1.0.48, 1.0.53, 1.0.55, 1.0.57, 1.0.57.1, 1.0.60, 1.0.62, 1.0.62.1, 1.0.65, 1.0.65.1, 1.0.69, 1.0.72, 1.0.74, 1.0.76, 1.0.76.1, 1.0.79, 1.0.81, 1.0.81.1, 1.0.83, 1.0.85, 1.0.85.1, 1.0.85.2, 1.0.85.3, 1.0.85.4, 1.0.85.5, 1.0.85.6, 1.1.0rc0, 1.1.1rc0, 1.1.1.1rc0, 1.1.1.2rc0, 1.1.2rc0, 1.1.5, 1.1.5.1, 1.1.5.2, 1.1.5.3, 1.1.5.4, 1.1.5.5, 1.1.5.6, 1.1.5.7)\n\nWhen installing packages from 'apt-get' I usually have to update the index first but I can't find a comparable command to do that with pip.","AnswerCount":2,"Available Count":1,"Score":-0.0996679946,"is_accepted":false,"ViewCount":166,"Q_Id":63927086,"Users Score":-1,"Answer":"Two possibilities:\n\nthe package needs you to use an underscore (since hyphens don't behave) so pip can download it: so run pip install azureml_core==1.13.0\nRun with the --no-cache-dir argument, so pip install --no-cache-dir azureml_core==1.13.0. This argument forces pip to refresh it's package cache.","Q_Score":0,"Tags":"python,docker,pip","A_Id":63927228,"CreationDate":"2020-09-16T19:51:00.000","Title":"pip using out of date package index","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":1,"Web Development":0},{"Question":"It gives that memory error but memory capacity is never reached. I have 60 GB of ram on the SSH and the full dataset process consumes 30\nI am trying to train an autoendcoder with k-fold. Without k-fold the training works fine. The raw dataset contains 250,000 data in hdf5.\nWith K-fold it works if I use less than 100000 of total data.\nI have converted it to float32 but still does not work.\nI have tried echo 1 as well but that kill the python program automatically","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":15477,"Q_Id":63932913,"Users Score":2,"Answer":"Taking into account the dimensions of the dataset you provided (725000 x 277 x 76) and its data type (float64 - 8 bytes), it seems that you need (at minimum) around 114 GB to have the dataset loaded\/stored in RAM.\nA solution to overcome this limitation is to: 1) read a certain amount of the dataset (e.g. a chunk of 1 GB at the time) through a hyperslab selection and load\/store it in memory, 2) process it, and 3) repeat the process (i.e. go to step 1) until the dataset is completely processed. This way, you will not run out of RAM memory.","Q_Score":5,"Tags":"python-3.x,memory-management,out-of-memory,hdf5,k-fold","A_Id":63978734,"CreationDate":"2020-09-17T07:06:00.000","Title":"MemoryError: Unable to allocate 30.4 GiB for an array with shape (725000, 277, 76) and data type float64","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"i am trying to find anomalies in my dataset of 1000+ documents. I'm using LIME ML Interpreter to be able to explain the model (Isolation Forest) predictions. In one parameter \"mode\" i am able to choose between Classification and Regression. I do not have a set of documents with a known anomaly.\nSince Isolation Forest is a unsupervised learning method and classifcation is a type of supervised learning which is used to clasify observations into two or more classses i ended up using regression. On the other side i have the outcome anomaly or no anomaly.\nWhat is right to use here?\nBest Regards,\nElle","AnswerCount":3,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":508,"Q_Id":63933188,"Users Score":0,"Answer":"The other option I see to this is to hold out 10-20% of the data set during IsoForest tree building. On this holdout to score the model and get the anomaly score (or avg tree depth) and build the explainer on this. Then in scoring new data, LIME will treat it as a regression problem...I am not sure how well this will work though...","Q_Score":0,"Tags":"python,regression,classification,anomaly-detection,lime","A_Id":64208801,"CreationDate":"2020-09-17T07:27:00.000","Title":"LIME ML Interpreter mode Classification or Regression for Isolation Forest (Anomaly Detection)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"i am trying to find anomalies in my dataset of 1000+ documents. I'm using LIME ML Interpreter to be able to explain the model (Isolation Forest) predictions. In one parameter \"mode\" i am able to choose between Classification and Regression. I do not have a set of documents with a known anomaly.\nSince Isolation Forest is a unsupervised learning method and classifcation is a type of supervised learning which is used to clasify observations into two or more classses i ended up using regression. On the other side i have the outcome anomaly or no anomaly.\nWhat is right to use here?\nBest Regards,\nElle","AnswerCount":3,"Available Count":2,"Score":0.0665680765,"is_accepted":false,"ViewCount":508,"Q_Id":63933188,"Users Score":1,"Answer":"For us, what we have done is as follows:\n\nUse Isolation Forest to get anomalies.\nTreat 1 and -1 returned by Isolation Forest as class labels and build a Random Forest classifier.\nPass this Random Forest classifier to LIME to get explanation of anomalous points.\n\nWe are also trying to find a better option instead of building second level Random Forest classifier.","Q_Score":0,"Tags":"python,regression,classification,anomaly-detection,lime","A_Id":63933865,"CreationDate":"2020-09-17T07:27:00.000","Title":"LIME ML Interpreter mode Classification or Regression for Isolation Forest (Anomaly Detection)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Facing issues when trying to downgrade python version from 3.7.3 to 3.6.5_1. I have did lot of research before reaching to stackoverflow family and all of them were suggesting the same resolution steps that i have tried as below, but found no luck. I looking for the python 3.6.5_1 version because Python 3.7 is unsupported by Keras\/TensorFlow and thus are not a good choice for OpenCV either:\nOption 1:\nbrew unlink python\nbrew install --ignore-dependencies https:\/\/raw.githubusercontent.com\/Homebrew\/homebrew-core\/f2a764ef944b1080be64bd88dca9a1d80130c558\/Formula\/python.rb\nError: Calling Installation of python from a GitHub commit URL is disabled! Use 'brew extract python' to stable tap on GitHub instead.\nOption 2:\nbrew switch python 3.6.5\nError: python does not have a version \"3.6.5\" in the Cellar.\nafter couple of tries I realized that it is problem with the git url that homebrew has it to get python 3.6.5_1 version and that would have changed or the commit url might not be the latest.\nmacOS version : Catalina 10.15.6\nSo seeking your guidance and suggestions on how to solve this problem. Also please let me know if missed any info that is required to post here(which could've helped in solving the problem)\nThanks in advance","AnswerCount":2,"Available Count":1,"Score":1.0,"is_accepted":false,"ViewCount":2982,"Q_Id":63948556,"Users Score":10,"Answer":"using brew install sashkab\/python\/python@3.6 works. credit to @Jean-Pierre Matsumoto.","Q_Score":1,"Tags":"python,python-3.x,macos,opencv,homebrew","A_Id":65308770,"CreationDate":"2020-09-18T02:35:00.000","Title":"Unable to downgrade python version in macos using Homebrew","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":1,"Web Development":0},{"Question":"While Anaconda is nice, my experience trying to use Visual Studio through Anaconda is a mess. I have just ended up using Spyder which is great but I'd preferably use visual studio.\nCouple of issues:\nI select base conda interpreter in visual studio and proceed to try to import pandas or numpy. This results in an error (AttributeError: module 'tokenize' has no attribute 'Name').\nA couple of days ago it randomly worked and now it's not. running print('hello') works just fine.\nI have no issues with any imports in Spyder but I've started using Flask and it'd be much easier to have it all in one workspace.\nAny understanding why I cannot import pandas.\nEdit: Did a clean reinstall of both and now am able to install numpy. However, I get the error when trying to install pandas. Using 3.8.3. Pandas works in Spyder, not in VS Code.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":77,"Q_Id":63951291,"Users Score":0,"Answer":"Ok so it started working for no apparent reason. I just restarted VS Code through Anaconda and this time it had no issues. As I said, I feel like VS Code is all over the place through Anaconda and not very reliable.","Q_Score":0,"Tags":"python,import,anaconda","A_Id":63952091,"CreationDate":"2020-09-18T07:40:00.000","Title":"Problems using Visual Studio through Anaconda","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"t-test between two numbers (0.85,0.18) getting p-value as Nan along with the following error:\n\nGetting this error also\n_,p_value=stats.ttest_ind(a=Max,b=Max_1,equal_var=False)\nC:\\Users\\NehaBhakat\\Anaconda31\\lib\\site-packages\\numpy\\core\\fromnumeric.py:3584: RuntimeWarning: Degrees of freedom <= 0 for slice\n**kwargs)\nC:\\Users\\NehaBhakat\\Anaconda31\\lib\\site-packages\\scipy\\stats_distn_infrastructure.py:903: RuntimeWarning: invalid value encountered in greater\nreturn (a < x) & (x < b)\nC:\\Users\\NehaBhakat\\Anaconda31\\lib\\site-packages\\scipy\\stats_distn_infrastructure.py:903: RuntimeWarning: invalid value encountered in less\nreturn (a < x) & (x < b)\nC:\\Users\\NehaBhakat\\Anaconda31\\lib\\site-packages\\scipy\\stats_distn_infrastructure.py:1912: RuntimeWarning: invalid value encountered in less_equal\ncond2 = cond0 & (x <= _a)","AnswerCount":2,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":353,"Q_Id":63957849,"Users Score":2,"Answer":"A t-test is for finding out whether two distributions are in fact coming from the same population. You cannot test for two single values. Hence, getting NaN is correct.\nA distribution means, that you have a vector with values that you measured. To have a meaningful t-test, you should usually have at least 30 values.","Q_Score":0,"Tags":"python,statistics,t-test","A_Id":63957952,"CreationDate":"2020-09-18T14:40:00.000","Title":"T test between two numbers(0.85,0.18) getting p value as Nan","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to train my model with 2 GPU(id 5, 6), so I run my code with CUDA_VISIBLE_DEVICES=5,6 train.py. However, when I printed torch.cuda.current_device I still got the id 0 rather than 5,6. But torch.cuda.device_count is 2, which semms right. How can I use GPU5,6 correctly?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":552,"Q_Id":63967302,"Users Score":0,"Answer":"you can check the device name to verify whether that is the correct name of that GPU. However, I think when you set the Cuda_Visible outside, you have forced torch to look only at that 2 gpu. So torch will manually set index for them as 0 and 1. Because of this, when you check the current_device, it will output 0","Q_Score":0,"Tags":"python,pytorch,gpu,multi-gpu","A_Id":63969178,"CreationDate":"2020-09-19T09:36:00.000","Title":"Pytorch Multi-GPU Issue","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Say if I have a df with columns A,B,C,D.\nI wanted to copy df to df1 columns A and B only based on a condition column C = 1.\nThanks for your help!!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":194,"Q_Id":63970543,"Users Score":0,"Answer":"Thanks Scott for your reply.\nThe first option worked!!!\nThe second option is giving error 'expr must be a string to be evaluated, given\nCode : temp1 = df[['Music', 'Pop', 'Rock']].query(df.Rock == '1.0')","Q_Score":0,"Tags":"python,pandas,dataframe","A_Id":63970708,"CreationDate":"2020-09-19T15:42:00.000","Title":"How to copy selected columns from a dataframe to another based on a column condition","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Basically I know in Python axis = 0 means row, and axis = 1 means the column.\ndf.isnull().sum(axis = 0) summarize the number of missing values in a column, but\ndf.drop(column, axis = 1) means to drop out a column.\nSo I am quite confused that when does axis = 0 means the rows and why does the second code not using axis = 0?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":647,"Q_Id":63971263,"Users Score":0,"Answer":".sum() is applied along an axis whereas .drop() is applied to an axis.\ndf.isnull().sum(axis = 0) returns the sum of all null cells along axis 0 (rows\/indices), meaning one value per column.\ndf.drop(column, axis = 1) drops column belonging to axis 1.","Q_Score":0,"Tags":"python,pandas","A_Id":63971589,"CreationDate":"2020-09-19T16:54:00.000","Title":"Pandas Question about axis = 0 and axis = 1","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Will python automatically parallelize sorting across all cores?\nSorting a list of objects based on an integer property, which sorts a list of size 2M in ~1.7s. My machine has 16 logical cores and 4 GPUs which I would like to leverage to speedup the sort. I found a couple parallel merge sort implementations online but none seemed popular which is surprising given the parallel hardware available today. Would these implementations be better on machines with 8-16 cores?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":232,"Q_Id":63975543,"Users Score":0,"Answer":"Will python automatically parallelize sorting across all cores?\n\nThere is nothing in the Python Language Specification (or more precisely, the Python Standard Library Specification) that would prevent an implementor from parallelizing either list.sort() or sorted(). There is, however, also nothing in the Python Language Specification or the Python Standard Library Specification that would force an implementor to parallelize either list.sort() or sorted().\nTherefore, it is completely up to each implementation whether they implement them serial, parallel, or print out the list, fax it to Malaysia, and have it hand-sorted in a sweat shop. Also, an implementation is free to change the implementation strategy at any time without warning, as long as it does not violate the invariants guaranteed by the Library Specification. (Which is basically only that the result must be sorted and that the sort must be stable.)\nOr, to answer the question succinctly:\n\nWill python automatically parallelize sorting across all cores?\n\nYou can't know.","Q_Score":0,"Tags":"python,sorting","A_Id":63975955,"CreationDate":"2020-09-20T04:36:00.000","Title":"Is python's builtin sort parallelized?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to export HMM model because training it every time takes time. My method is to save all matrices in file. I want to know is there any tensorflow way I can do it? Also is it possible to export it with api to other languages like C++.","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":276,"Q_Id":63975768,"Users Score":1,"Answer":"you can iterate over and save the weights from the model variables by calling variables attribute of tfp.distributions.HiddenMarkovModel()","Q_Score":0,"Tags":"python,tensorflow,tensorflow-probability","A_Id":63984048,"CreationDate":"2020-09-20T05:20:00.000","Title":"Exporting Tensorflow probability's Hidden Markov Model","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have already trained 85 models using ExtraTreeClassifiers and saved them (TO be honest, I cannot remember the python version or Sci-kit version or Anaconda version I was using while training the models). Due to some disk issues I had to replace hard disk and install OS(Windows10) again and installed Anaconda3 2020.07(Python 3.8.3 64 bit) now.\nBut now when I try to use this models for prediction purpose I am getting the following warning:\n\nquote\nC:\\Users\\DELL\\anaconda3\\lib\\site-packages\\sklearn\\base.py:313: UserWarning: Trying to unpickle estimator ExtraTreesClassifier from version 0.22.2.post1 when using version 0.23. This might lead to breaking code or invalid results. Use at your own risk.\n\nSo I uninstalled sklearn version 0.23 and installed version 0.22.2. If I do this I get the following warning\n\nquote\nC:\\Users\\DELL\\anaconda3\\lib\\site-packages\\sklearn\\base.py:313: UserWarning: Trying to unpickle estimator ExtraTreesClassifier from version 0.22 post1 when using version 0.22.2. This might lead to breaking code or invalid results. Use at your own risk.\n\nSo I uninstalled sklearn version 0.22.2 and installed version 0.22. If I do this I get the following error:\n\nquote\nERROR: Could not install packages due to an EnvironmentError: [WinError 5] Access is denied: 'C:\\Users\\DELL\\anaconda3\\Lib\\site-packages\\~-learn\\.libs\\vcomp140.dll'\nConsider using the --user option or check the permissions.\n\nBut still it gives me the needed output without any error. If I check the version of sklearn it shows me 0.22 even if there was error installing it.\n\nquote\nC:\\Users\\DELL\\anaconda3\\lib\\site-packages\\sklearn\\base.py:313: UserWarning: Trying to unpickle estimator ExtraTreesClassifier from version 0.22.2 post1 when using version 0.22. This might lead to breaking code or invalid results. Use at your own risk.\n\nAnd this process is going on vice-versa(0.22.2 to 0.22 and 0.22 to 0.22.2) if I install or uninstall accordingly.\nThough that I have seen various answers regarding this warning on Stackoverflow and worked upon as above, somehow I am unable to fix it and keep on getting this warning again and again or may be I am missing something. Even if I install Anaconda 2019.10 (Python 3.7.4 64 bit) this incompatibility issue still persist. I get the required output but at the back of my mind I am doubtful what if the output generated is not correct because of such warnings and incompatible versions. It is not possible to train all these models again due to time constraints or should I forget about warnings and go ahead and do the predictions with the trained models that I have. Please help. Thanks a lot.","AnswerCount":1,"Available Count":1,"Score":0.537049567,"is_accepted":false,"ViewCount":4713,"Q_Id":63976719,"Users Score":3,"Answer":"pip install scikit-learn==0.22.2.post1 resolved a similar issue for me.","Q_Score":4,"Tags":"python,scikit-learn,anaconda,warnings,prediction","A_Id":66484196,"CreationDate":"2020-09-20T07:49:00.000","Title":"UserWarning: Trying to unpickle estimator ExtraTreesClassifier from version 0.22.2.post1 when using version 0.22","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to plot ROC curve for my problem which has 4 classes. I created True and Predicted class lists after training and prediction. Here are my lists.\ntrue_class list :\n[0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0,1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 2, 3, 1, 0, 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3,2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 2, 2, 0, 0, 0, 3, 3, 3, 3, 3, 2]\npredicted_class list :\n[0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0,\n1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 2, 3, 1, 0, 1, 2, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3,\n2, 3, 2, 3, 2, 3, 2, 3, 3, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 2, 2, 0, 0, 0, 3, 3, 3, 3, 3, 2]","AnswerCount":3,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":243,"Q_Id":63977453,"Users Score":0,"Answer":"ROC curves are normally plotted with non-thresholded data, see the sklearn implementation for a binary roc curve. There are also some extensions to multi-class roc curves (which also are normally used with non-thresholded predictions) but there are better metrics out there than that.","Q_Score":0,"Tags":"python,python-3.x,keras,scikit-learn,roc","A_Id":63977740,"CreationDate":"2020-09-20T09:31:00.000","Title":"How To Plot Multi Class Roc Curve From True and Predicted Classes","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to plot ROC curve for my problem which has 4 classes. I created True and Predicted class lists after training and prediction. Here are my lists.\ntrue_class list :\n[0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0,1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 2, 3, 1, 0, 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3,2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 2, 2, 0, 0, 0, 3, 3, 3, 3, 3, 2]\npredicted_class list :\n[0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0,\n1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 2, 3, 1, 0, 1, 2, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3,\n2, 3, 2, 3, 2, 3, 2, 3, 3, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 2, 2, 0, 0, 0, 3, 3, 3, 3, 3, 2]","AnswerCount":3,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":243,"Q_Id":63977453,"Users Score":0,"Answer":"Maybe use a different metric than ROC curves as they don't fit well with the use case.","Q_Score":0,"Tags":"python,python-3.x,keras,scikit-learn,roc","A_Id":63978600,"CreationDate":"2020-09-20T09:31:00.000","Title":"How To Plot Multi Class Roc Curve From True and Predicted Classes","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I\u2018m new to tensorflow have a general question:\nI have a certain amount of training data and want to do a time series prediction.\nThe intervals on my training data is one minute and I want to do a prediction for the following minutes based on the new input data which is provided via a REST API\nWhat I don\u2018t understand is this:\nLet\u2018s say I train the model with all the data till yesterday and this means I can predict the first values of today by a certain amount. But the new values of today have not been observed by the model that has been build yesterday.\nHow would you solve this problem?\nThanks","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":50,"Q_Id":63981716,"Users Score":0,"Answer":"Djboblo,\nI assume that you need to predict whole next day values on per minute basis.\nIn that case your options are:\n\nrecursive prediction, i.e. using predicted data as input for the next prediction\nstructuring the model to provide you with prediction for the whole next day\n\nIf it is just a matter of predicting for a single minute forward and your model is trained on reasonably large amount of data - don't worry, just feed it with the values up to the prediction minute. Periodically you may re-train the model using new data.","Q_Score":1,"Tags":"python,tensorflow,time-series,training-data","A_Id":63984134,"CreationDate":"2020-09-20T17:20:00.000","Title":"Tensorflow continous training from input data","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"My goal is to apply GA to find optimum locations to place a number of circles (equal dia) in a 2D plane such that no two circles are closer than a certain distance. I account for the proximity constrain by setting the fitness function to -1 if the constraint is broken but the problem is none of the initial population randomly generated follows the proximity constraint thus making the fitness of all the members -1.\nBy googling, I found that if the plane is separated in to grids with the size of clearance I won't have this problem, but I'm afraid it will miss a lot of potential solution. Is there a method to incorporate the proximity constraint or should I go with the grid?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":194,"Q_Id":63982198,"Users Score":1,"Answer":"Instead of just random, start with a random solution with constraints. Generate one circle, then find the feasible space for next circle, create second circle and continue until you generate entire generation.","Q_Score":1,"Tags":"python,optimization,genetic-algorithm","A_Id":63988925,"CreationDate":"2020-09-20T18:12:00.000","Title":"How to deal with a constraint in Genetic Algorithm when none of the population members obeys it?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a set of co-ordinates(latitudes and longitudes) of different buildings of a city. The sample size is around 16,000. I plan to use these co-ordinates as the central point of their locality\/neighbourhood, and do some analysis on the different neighbourhoods of the city. The \"radius\/size\" for each neighbourhood is still undecided as of now.\nHowever, a lot of these co-ordinates are too close to each other. So, many of them actually represent the same locality\/neighbourhood.\nAs a result, I want to select a smaller sample(say, 3-6k) of co-ordinates that will be more evenly spread out.\nExample:- If two of the co-ordinates are representing two neighbouring buildings, I don't want to include both as they pretty much represent the same area. So we must select only one of them.\nThis way, I was hoping to reduce the population to a smaller size, while at the same time being able to cover most of the city through the remaining co-ordinates.\nOne way I was imagining the solution is to plot these co-ordinates on a 2D graph(for visualisation). Then, we can select different values of \"radius\" to see how many co-ordinates would remain. But I do not know how to implement such a \"graph\".\nI am doing this analysis in Python. Is there a way I can obtain such a sample of these co-ordinates that are evenly distributed with minimal overlap?\nThanks for your help,","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":18,"Q_Id":64012695,"Users Score":0,"Answer":"It seems like for your use case, you might need clustering instead of sampling to reduce your analysis set.\nGiven that you'd want to reduce your \"houses\" data to \"neighborhoods\" data, I'd suggest exploring geospatial clustering to cluster houses that are closer together and then take your ~3-4K clusters as your data set to begin with.\nThat being said, if your objective still is to remove houses that are closer together, you can obviously create an N*N matrix of the geospatial distance between each house vs. others and remove pairs that are within (0, X] where X is your threshold.","Q_Score":0,"Tags":"python,analytics,sample","A_Id":64181614,"CreationDate":"2020-09-22T15:16:00.000","Title":"Select a smaller sample of \"uniformly\" distributed co-ordinates, out of a larger population of co-ordinates","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to create datapoints which form non overlapping circle shapes; so far I was able to generate randomly distributed circles but without considering the non-overlapping feature.\nHow can I implement that these circles do not overlap while creating for example 2 (number_circles = 2) of them?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":455,"Q_Id":64018272,"Users Score":1,"Answer":"Draw N centers randomly. For every center compute the distance to the nearest neighbor and assign half that distance as the radius (or a little less). This will ensure no overlap.\n\nNote that you said nothing about the desired distribution of radii and this answer only fulfills the non-overlap constraint.","Q_Score":0,"Tags":"python,image,numpy,geometry","A_Id":64022738,"CreationDate":"2020-09-22T22:03:00.000","Title":"Random circles without overlap in python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I understand how gradient descent works and that a user can manually define a gradient descent function to minimize some cost function. My question is very general that where does GD appear in scikitlearn codes when we train and test machine learning models such as linear regression or random forest? Is GD simply embedded in the .fit() function? Or do we need to include it as a parameter to the model?","AnswerCount":3,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":62,"Q_Id":64020722,"Users Score":1,"Answer":"Short answer: most of the sklearn models use the stochastic gradient descent for optimization\/fitting. And you never need to specify that. Some functions allow you to specify optimizer (booster in plain language) like adam.","Q_Score":1,"Tags":"python,gradient-descent","A_Id":64020844,"CreationDate":"2020-09-23T03:42:00.000","Title":"Where does gradient descent appear in machine learning libraries (e.g. scikitlearn)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have kind a of weird problem where I have a .mat file that comes in a a 10x10 array where each index is a 20x20 array representing a gray image. So I have 10 trials and each trial are a time series with 10 intervals and each interval is tracked as a 20x20 image. In order to run tensor regression on this using tensorly this needs to be formatted as a (trails, time series, x-dim, y-dim) tensor. Is there a clean way to do this? I tried np.reshape on the mat file but that won't work cause the mat file dimensions are 10x10, cause like I said each cell of the array is the 20x20.\nSo for example let's say the mat file is variable name 'mat_var.' Then mat_var[0,0] will be a 20x20 array and mat_var will be a 10x10 array\nGoal is to reshape a 10x10 array where each index is a 20x20 array into a 10x10x20x20 array.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":117,"Q_Id":64023391,"Users Score":0,"Answer":"so apparent if you do tensor = np.full((10,10,20,20),0) then you can set each cell accordingly like\ntensor[x,y] = mat[x,y]\nand it'll just fill the 20x20 if the size of the array is also 20x20","Q_Score":0,"Tags":"python,numpy,tensorly","A_Id":64024496,"CreationDate":"2020-09-23T07:52:00.000","Title":"Python & Numpy - reshape 10x10 array where each cell is 20x20 array into a 10x10x20x20","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"My deep learning topic is classifying images into 5 different categories. I used the ImageDataGenerator library to split my dataset into train and test. I've successfully developed a model architecture following the CNN method and evaluated the performance of my model on a test dataset, which gave me an accuracy of 83%.\nIs it possible to apply sklearn evaluation metrics such as precision, recall, f1_score, etc. to evaluate my test results? If yes, how can I do it?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":74,"Q_Id":64025656,"Users Score":1,"Answer":"Yes you can do it as long as your model is giving out either the class labels or probabilities as it predictions.\nIf your model is predicting the encoded (integer) labels then you can use\nsklearn.metrics.precision_score(y_true, model.predict(test_x))\nOn the other hand if the model is predictiong the probabilies which is norammly the case then you have to fist convert them into class labels using argmax. So if you have a batch of test_x data then you can use\nsklearn.metrics.precision_score(y_true, np.argmax(model.predict(test_x), axis=1))","Q_Score":0,"Tags":"python,scikit-learn,image-classification","A_Id":64025740,"CreationDate":"2020-09-23T10:11:00.000","Title":"Is it possible to apply sklearn evaluation metrics such as precision, recall, f1_score on my problem?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using bokeh server to plot the result from my streaming frames of a video. I see Bokeh provide add_periodic_callback as an auto-update on the server, but I don't know how to pause it. Any suggestion?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":85,"Q_Id":64026596,"Users Score":0,"Answer":"I have solved by passing some global value to track the result of each update. If the global values don't change, then I will pause the update","Q_Score":0,"Tags":"python,bokeh,pandas-bokeh","A_Id":64040027,"CreationDate":"2020-09-23T11:07:00.000","Title":"How to pause bokeh server updating plot based on some condition","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I had a DataFrame whose memory usage was 159.7 MB. When I used .to_csv method to write it in storage the written file was about 400 MB. And when I loaded this file its memory usage was 159.7 MB. Is there an explanation for this difference in sizes and how to write it so that it takes less space in the hard drive ? Thank you for your help","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":460,"Q_Id":64030576,"Users Score":0,"Answer":"The easiest way to reduce the size of the csv is to compress it when writing, using the compression parameter in to_csv. For example df.to_csv(compression='gzip').\nThere are a variety of reasons the memory usage could be so different from the size of the csv on disk, it's a little hard to say without knowing any specifics about the data you're working with.\nOne generic recommendation is to check the precision of any floating point values in your dataframe, if you're writing a bunch of numbers with 15 decimal points of precision or something that will take up a lot of space. Try truncating these values to the precision you need.","Q_Score":0,"Tags":"python,pandas,dataframe,csv","A_Id":64031232,"CreationDate":"2020-09-23T14:49:00.000","Title":"Pandas .to_csv takes more space than memory usage","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"How can I run TPOT to give me suggestions on what algorithm to use for a multi-label text classification? My data is already cleaned and divided into training and testing sets.","AnswerCount":1,"Available Count":1,"Score":-0.3799489623,"is_accepted":false,"ViewCount":154,"Q_Id":64034340,"Users Score":-2,"Answer":"Yes, you can use TPOT for multi-label text classification.","Q_Score":1,"Tags":"python,machine-learning,artificial-intelligence,automl,tpot","A_Id":67609475,"CreationDate":"2020-09-23T18:38:00.000","Title":"Does TPOT support multi-label text classification?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've got two DataFrames, count, and percentage with the same columns. count has a multi-level index. I want to use percentage.set_index(....) to make the index of percentage match the index of count. How do I do this?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":49,"Q_Id":64034517,"Users Score":1,"Answer":"You can use\npercentage.set_index(['col1', 'col2'])\nto make the same columns be the index, but the two tables won't nessecarily have the same index values or sorting. If you if you want to make sure percentage has exactly the same index as count, then after that you can also do\npercentage.reindex(count.index)\nbut note that you'll end up with null values in your data for any index values that are in count but not percentage, and you'll throw away any rows of percentage where the index value doesn't show up in `count.\nEdit:\nIf you want to do this but don't already know the names of the index columns, you can get them with count.index.names.","Q_Score":0,"Tags":"python,pandas","A_Id":64034714,"CreationDate":"2020-09-23T18:51:00.000","Title":"Match multi-index in parallel dataframe","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am still getting used to PVLIB and figuring out how to use the methods associated with it. I'd like to be able to model the growth of localised hotspots in a PV module due to current mismatch that results from partial shading.\nI'd be surprised if I was the first person to do this, so I'm wondering what other solutions exist to do this in a straightforward way from PVLIB.","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":92,"Q_Id":64044030,"Users Score":1,"Answer":"You can use the single-diode model functions from pvlib to build up the electrical simulation for this scenario, and thereby determine how much electrical power the affected cell absorbs.\nThere isn't a thermal model in pvlib to tell you how hot it would get, but as a first approximation you could adapt one of the existing module\/cell temperature functions quite easily. There is a local variable called heat_input to which you can add the electrical power.","Q_Score":1,"Tags":"python,pvlib","A_Id":64059837,"CreationDate":"2020-09-24T09:57:00.000","Title":"Can PVLIB be used for hotspot modelling?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a list of 30 data frames (each of length 53x3) named arr. Now I have to bind all these dataframes into 1 dataframe along row. So the new length of Data frame will be (53x30=1590).\nHow to do it in Python?\nIn R, I use rbind function.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":29,"Q_Id":64046655,"Users Score":0,"Answer":"Only thing was concat\nA = pd.concat(arr)","Q_Score":0,"Tags":"python,pandas,dataframe","A_Id":64058144,"CreationDate":"2020-09-24T12:40:00.000","Title":"Bind a list of some dataframe into 1 dataframe in Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a column in a dataframe that has some blanks (which appear as 'nan'). How do I replace those blanks with the string 'none'?","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":36,"Q_Id":64047421,"Users Score":2,"Answer":"You should use fillna: df[col].fillna('none')","Q_Score":0,"Tags":"python,dataframe","A_Id":64047500,"CreationDate":"2020-09-24T13:23:00.000","Title":"How to replace the blanks in a column of a dataframe with another value?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a pandas dataframe which has a column called filenames which contains the names which will be used to save certain objects into csv files. However, many of them contain illegal characters like \u201c?\u201d Or \u201c\/\u201c, is there a quick way to remove all of them ?\nI tried dataframe['filenames'] = dataframe['filenames'].str.strip('?\/') but nothing happens. The characters are still there, what\u2019s the more efficient and safe way to do this?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":275,"Q_Id":64059429,"Users Score":2,"Answer":"I will do this. You can add as many characters as you want.\ndataframe['filenames'] = dataframe['filenames'].str.replace('?|\/', '', regex=True)\nYou need to separate characters you want to remove by '|'.","Q_Score":1,"Tags":"python,regex,pandas,dataframe,strip","A_Id":64059593,"CreationDate":"2020-09-25T07:08:00.000","Title":"Remove illegal file name characters from pandas dataframe column using python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying out the TensorFlow 2.0 Object Detection API, while I am trying to export the inference graph I get an error stating tensorflow.python.framework.errors_impl.NotFoundError: Failed to create a NewWriteableFile: .\\exported-models\\my_mobilenet_model\\checkpoint\\ckpt-0_temp_8cca890901704d9b9c1a0c5e959235fc\/part-00000-of-00001.data-00000-of-00001.tempstate144711528486123721 : The system cannot find the path specified. ; No such process [Op:SaveV2] \nI run the command: python .\\exporter_main_v2.py --input_type image_tensor --pipeline_config_path .\\models\\my_ssd_mobilenet_v2_fpnlite\\pipeline.config --trained_checkpoint_dir .\\models\\my_ssd_mobilenet_v2_fpnlite\\ --output_directory .\\exported-models\\my_mobilenet_model\nI do have a folder name exported-models in the directory I am running the command","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":1242,"Q_Id":64065110,"Users Score":5,"Answer":"There is a limitation on the whole path length (<260). Pls. check your path to save the model, and you can manually try if you can create a folder as shown above, if not, pls. try to change the output_directory to another short path.","Q_Score":3,"Tags":"python,tensorflow,deep-learning,object-detection","A_Id":65030911,"CreationDate":"2020-09-25T13:29:00.000","Title":"Python Failed to create a NewWriteableFile (tensorflow.python.framework.errors_impl.NotFoundError: Failed to create a NewWriteableFile: )","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"My dataset contains columns describing abilities of certain characters, filled with True\/False values. There are no empty values. My ultimate goal is to make groups of characters with similar abilities. And here's the question:\n\nShould i change True\/False values to 1 and 0? Or there's no need for that?\nWhat clustering model should i use? Is KMeans okay for that?\nHow do i interpret the results (output)? Can i visualize it?\n\nThe thing is i always see people perform clustering on numeric datasets that you can visualize and it looks much easier to do. With True\/False i just don't even know how to approach it.\nThanks.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":1359,"Q_Id":64077136,"Users Score":2,"Answer":"In general there is no need to change True\/False to 0\/1. This is only necessary if you want to apply a specific algorithm for clustering that cannot deal with boolean inputs, like K-means.\nK-means is not a preferred option. K-means requires continuous features as input, as it is based on computing distances, like many clustering algorithms. So no boolean inputs. And although binary input (0-1) works, it does not compute distances in a very meaningful way (many points will have the same distance to each other). In case of 0-1 data only, I would not use clustering, but would recommend tabulating the data and see what cells occur frequently. If you have a large data set you might use the Apriori algorithm to find cells that occur frequently.\nIn general, a clustering algorithm typically returns a cluster number for each observation. In low-dimensions, this number is frequently used to give a color to an observation in a scatter plot. However, in your case of boolean values, I would just list the most frequently occurring cells.","Q_Score":2,"Tags":"python,dataset,data-science,cluster-analysis","A_Id":64153006,"CreationDate":"2020-09-26T11:28:00.000","Title":"How to perform clustering on a dataset containing TRUE\/FALSE values in Python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to create my training, validation and testset from one dataframe with\na proportion of 6:2:2.\nBut additionally within each set, I'd like to have a proportion\nof 6:4 between the 2 labels. Among the original dataframe this 6:4 proportion is\nnot given, one label is massively overrepresented.\nMaybe I should adjust that in advance?\nI think sklearns train_test_split() might be an option but to be honest\nits documentation did not make me any wiser...\nAre there any best practices for this kind of problem?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":111,"Q_Id":64090601,"Users Score":0,"Answer":"When you have an imbalanced dataset, you can use the parameter 'stratify' in the train_test_split(). This will make the dataset be split into training and test sets in such a way that the ratio of the class labels in the variable specified is constant i.e. both train and test set will have the same ratio of class labels.","Q_Score":0,"Tags":"python,pandas,dataframe,scikit-learn,dataset","A_Id":64099220,"CreationDate":"2020-09-27T16:12:00.000","Title":"Splitting dataframe into multiple ones according to proportion of samplesize and labels","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to understand the behavior of cache in pyspark\n\nIs df.cache() anyway different that df = df.cache() ?\n\nIs it absolutely necessary to unpersist the cached dataframe at the end of program execution, I understand its cleared by spark based on (Least Recently used mechanism),and what can be negative impacts if I don't unpersist a dataframe, I can think of out of memory issues but need inputs\n\nIs it possible that when I use df = df.cache(), the re-execution of the program uses the old cached data, rather than recalculating and overriding the cached dataframe ?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":141,"Q_Id":64092149,"Users Score":1,"Answer":"No need to unpersist at the end. stopping spark will clear the cached dataframes.\nYou cannot persist from one spark execution to another one. If you want to \"persist\" from one Spark to another, the only solution is to physically save your data (write) and read them again at the next execution.","Q_Score":1,"Tags":"python,apache-spark,pyspark","A_Id":64120980,"CreationDate":"2020-09-27T18:53:00.000","Title":"Pyspark:Need to understand the behaviour of cache in pyspark","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a fully functioning jupyter notebook (.ipynb) file that can find and import both pandas and numpy. I also have that same exact code saved as a .py file in the same exact folder.\nWhen I try to run the .py file with VSCode or Python Shell, I get an error message saying that numpy and pandas can't be found and aren't on path.\nNot sure how the .ipynb file right next to it can find these modules but the .py file can't.\nAny help would be much appreciated. (The .ipynb file runs through anaconda)","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":40,"Q_Id":64095062,"Users Score":0,"Answer":"Since you are hosting jupyter notebook from conda it can easily use the same environment and able to find the pandas and numpy. Try import the same py file in jupyter notebook you will be able to execute the code. You need to specify python path to environment variables which is pointing towards the one which jupyter is pointing.","Q_Score":0,"Tags":"python,python-3.x,pandas,numpy,path","A_Id":64095221,"CreationDate":"2020-09-28T02:02:00.000","Title":"Pandas and Numpy missing from path - Python\/Pyinstaller","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"Here is the error below that keeps appearing after I run the python script:\n\nThe MATPLOTLIBDATA environment variable was deprecated in Matplotlib 3.1 and will be removed in 3.3.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":146,"Q_Id":64098145,"Users Score":0,"Answer":"That's not an error. It's just a warning message.","Q_Score":0,"Tags":"python","A_Id":64098505,"CreationDate":"2020-09-28T08:00:00.000","Title":"MATPLOTLIBDATA environment variable was deprecated","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to read a file in pandas where the longitude column is of the format like this- 10559E53 (105 degrees 59 minutes East 53 seconds).\nWhen I print this data frame, python converts this to an exponent, something like 1.0559e+57. How can I stop this conversion?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":23,"Q_Id":64100246,"Users Score":1,"Answer":"The dtype parameter to read_csv should be useful. Probably something like dtype={'longitude': str} (not tested).","Q_Score":0,"Tags":"python,pandas","A_Id":64100847,"CreationDate":"2020-09-28T10:17:00.000","Title":"Stop conversion of Longitude column to exponent while reading a file with pandas","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using sklearnIntentClassifier in Rasa for intent classification. I want to check how this classifier has built the boundaries for different classes(here intents) using matplotlib with my training data.\nI could not see any inbuilt functionality for such task in Rasa.\nPlease help!\nThanks","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":44,"Q_Id":64100317,"Users Score":0,"Answer":"great idea, however calculating the decision boundaries are not always simple. Enabling this is something we're currently working on. Unfortunately, I cannot give a timeline when this feature will become available.","Q_Score":0,"Tags":"python,machine-learning,multiclass-classification,rasa-nlu,rasa","A_Id":64116439,"CreationDate":"2020-09-28T10:22:00.000","Title":"How to visualise boundaries created by sklearnIntentClassifier using matplotlib in Rasa","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am going to try to keep this as specific as possible but it is kind of a general question as well. I have a heavily skewed dataset in the order of { 'Class 0': 0.987, 'Class 1':0.012 }\nI would like to have a set of classifiers that work well on such datasets and then create an ensemble learner of those models. I do not think I want to oversample or undersample. I definitely dont want to SMOTE because they don't scale well for high dimensional data\/ or result in a very large number of data points. I want to use a cost sensitive approach to creating my classifiers and hence came across the class_weight=balanced parameter in the scikit-learn library. However, it doesn't seem to be helping me much because my F1 scores are still very terrible (in the range of 0.02 etc.) I have also tried using sklearn.utils.class_weight.compute_class_weight to manually calculate the weights, store them in a dictionary and pass it as a parameter to the class_weight parameter, however I see no improvement in F1 score and my False Positives are still very high(around 5k) and everything else quite low(less than 50). I don't understand what I am missing. Am I implementing something wrong? What else can I do to tackle my problem? When I change my evaluation metric from f1_score(average='binary') to f1_score(average='weighted') the F1 score increases from ~0.02 to ~98.66, which I think is probably wrong. Any kind of help including references to how I could tackle this problem will be very helpful.\nI am trying to implement XGBOOST, CATBoost, LightGBM, Logistic Regression,SVC('linear'),Random Forest Classifiers","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":371,"Q_Id":64104692,"Users Score":0,"Answer":"I realized that this question arose due to pure naivete. I resolved my problem by using the imbalanced-learn Python library. Algorithms like imblearn.ensemble.EasyEnsembleClassifier are a godsend when it comes to heavy imbalanced classification where the minority class is more important than the majority class. For anyone having troubles like this I suggest trying to find a different algorithm other than your usual favorites that will help you solve your problem.","Q_Score":0,"Tags":"python,scikit-learn,classification,data-science,imbalanced-data","A_Id":64209326,"CreationDate":"2020-09-28T14:59:00.000","Title":"Cost Sensitive Classifier fails for heavily imbalanced datasets","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am doing a simple binary text classification, and my label data are already in the format 0 and 1. I am wondering if I still need to perform a one-hot encoding so that they're in a [0,1] and [1,0] format?\nWhen I feed the labels into my Keras Sequential() model as , it works for the model and I get decent accuracy. But I still wonder if I should one-hot encode them beforehand?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":175,"Q_Id":64118767,"Users Score":3,"Answer":"It should not be helpful for binary cases because a binary column already has two values. If you encode a binary to two columns, you will add one more extra binary column to columns that is not informative.\nTherefore, it is not meaningful to hot-encode a binary column and causes a not useful redundancy in your context.","Q_Score":0,"Tags":"python,machine-learning,keras,nlp,one-hot-encoding","A_Id":64120117,"CreationDate":"2020-09-29T11:34:00.000","Title":"One-hot encoding labels for binary text classification that are already 0s and 1s?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm doing a hierarchical cluster-analysis of a dataframe with python Scipy, and was wondering if the clustering is column-wise-oriented or row-wise-oriented? I get different results depending on whether I transpose the dataframe or not before calculating the distance matrix.\nI read somewhere that the \"standard\" for clustering is to do it column-wise, however I can't seem to find anything about this in the scipy-documentation.\nAnyone who knows?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":122,"Q_Id":64120443,"Users Score":0,"Answer":"For anyone who's wondering the same thing; basic testing with a simple dataframe showed that it is row-wise","Q_Score":0,"Tags":"python,scipy,hierarchical-clustering","A_Id":64126386,"CreationDate":"2020-09-29T13:17:00.000","Title":"Column- or row-wise hierarchical clustering using Scipy","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I know stock['long_entry'] is creating a new column and stock.Close and stock.high are existing columns but I don't understand how the 'greater than' is being used here","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":20,"Q_Id":64125198,"Users Score":0,"Answer":"The boolean from evaluation of stock.Close > stock.high is stored in stock['long_entry']","Q_Score":0,"Tags":"python,pandas,dataframe","A_Id":64125247,"CreationDate":"2020-09-29T18:05:00.000","Title":"What does this mean from pandas in python: stock['long_entry'] = stock.Close > stock.high","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am currently trying to run a program with Scipy, and I want to use the load_npz module.\nWhenever I tried to run it, the compiler would say that that module doesn't exist.\nI ran scipy.__version__ and got 0.13.0b1, which makes sense as to why it couldn't find the module as it doesn't exist in that version, but I am confused as I have 1.5.2 installed in both pip and brew yet it keeps defaulting to the oldest version which is very frustrating.\nDoes anybody know how to get rid of this version? I have tried uninstalling from pip and brew, along with finding the path of the imported scipy with the outdated version yet it still is causing issues.\nI do have a lot of packages installed (numpy, matplotlib, etc.) so could it be a dependency that keeps reinstalling an old version?\nStrangely, even if I delete scipy from both brew and pip, it will still show the old version but throw an error on a different local file that also uses scipy saying the module does not exist (which is expected as I deleted it).","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":21,"Q_Id":64130416,"Users Score":0,"Answer":"I figured it out, I just deleted all my possible scipy locations and then just downloaded Anaconda and I'm using that as my python interpreter.","Q_Score":0,"Tags":"python,visual-studio-code,scipy","A_Id":64148403,"CreationDate":"2020-09-30T03:28:00.000","Title":"How to remove hidden utdated scipy file so it won't import with python in VS Code OSX","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to train neural network to indentify the colors. But issue is that when i use keras.utils.to_categorical for OneHotEncoding of color names, the colab is crashing and restarting. I tried this around 20 to 25 times but same problem persist.\nPlease help me","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":328,"Q_Id":64135978,"Users Score":1,"Answer":"May the data is not stored in a matrix or ma ythe numebr of categories is very high","Q_Score":2,"Tags":"python,keras,deep-learning,google-colaboratory,conv-neural-network","A_Id":64136020,"CreationDate":"2020-09-30T10:47:00.000","Title":"colab is crashing while using keras.utils.to_categorical","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have 120 txt files, all are around 150mb in size and have thousands of columns. Overall theres definitely more than 1million columns.\nWhen I try to concatenate using pandas I get this error: \" Unable to allocate 36.4 MiB for an array with shape (57, 83626) and data type object\"... I've tried Jupyter notebook and Spyder, neither work\nHow can I join the data? Or is this data not suitable for Pandas.\nThanks!","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":38,"Q_Id":64139668,"Users Score":0,"Answer":"Saying you want to concat in pandas implies that you just want to merge all 150 files together into one file? If so you can iterate through all the files in a directory and read them in as lists of tuples or something like that and just combine them all into one list. Lists and tuples are magnitudes less memory than dataframes, but you won't be able to perform calculations and stuff unless you throw them in as a numpy array or dataframe.\nAt a certain point, when there is too much data it is appropriate to shift from pandas to spark since spark can use the power and memory from a cluster instead of being restricted to your local machine or servers resources.","Q_Score":0,"Tags":"python,sql,pandas,bigdata","A_Id":64141398,"CreationDate":"2020-09-30T14:24:00.000","Title":"Is Panda appropriate for joining 120 large txt files?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Thank you for taking the time to check this question.\nI am interested in creating a profile for customers buying pattern.\nOnce I created a profile for everyone, we take unseen data and check with the profile to see if the customers followed their profile if not raise a flag. In this manner we do not create a set alert for all buyers but we can detect anomaly based on individual buyers to benchmark against their profile.\nAny thoughts or inputs to how to approach this problem.\nIf you have a course or tutorial on this matter please feel free to suggest it.\nThanks in advance.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":120,"Q_Id":64140562,"Users Score":1,"Answer":"You can either go by supervised learning method, basically machine learning. Also, buying pattern, I would suggest to explore more about RFM rule i.e. recency, frequency and monetary value. This will help you in creating features for model or profile customers.","Q_Score":0,"Tags":"python,pandas,classification,profiling,profile","A_Id":64140842,"CreationDate":"2020-09-30T15:10:00.000","Title":"Customer profiling and Anomaly detection -Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to train a model which takes a mixture of numerical, categorical and text features.\nMy question is which one of the following should I do for vectorizing my text and categorical features?\n\nI split my data into train,cv and test for purpose of features vectorization i.e using vectorizor.fit(train) and vectorizor.transform(cv),vectorizor.transform(test)\nUse vectorizor.fit transform on entire data\n\nMy goal is to hstack( all above features) and apply NaiveBayes. I think I should split my data into train_test before this point, inorder to find optimal hyperparameter for NB.\nPlease share some thought on this. I am new to data-science.","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":182,"Q_Id":64142447,"Users Score":0,"Answer":"If you are going to fit anything like an imputer or a Standard Scaler to the data, I recommend doing that after the split, since this way you avoid any of the test dataset leaking into your training set. However, things like formatting and simple transformations of the data, one-hot encoding should be able to be done safely on the entire dataset without issue, and avoids some extra work.","Q_Score":0,"Tags":"python,machine-learning,data-science,countvectorizer,train-test-split","A_Id":64142504,"CreationDate":"2020-09-30T17:04:00.000","Title":"What is right time to perform train_test_split when building a model with text and categorical features?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to train a model which takes a mixture of numerical, categorical and text features.\nMy question is which one of the following should I do for vectorizing my text and categorical features?\n\nI split my data into train,cv and test for purpose of features vectorization i.e using vectorizor.fit(train) and vectorizor.transform(cv),vectorizor.transform(test)\nUse vectorizor.fit transform on entire data\n\nMy goal is to hstack( all above features) and apply NaiveBayes. I think I should split my data into train_test before this point, inorder to find optimal hyperparameter for NB.\nPlease share some thought on this. I am new to data-science.","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":182,"Q_Id":64142447,"Users Score":0,"Answer":"I think you should go with the 2nd option i.e vectorizer.fit_transform on entire data because if you split the data before, it may happen that some of the data which is in test may not be in train so in that case some classes may remain unrecognised","Q_Score":0,"Tags":"python,machine-learning,data-science,countvectorizer,train-test-split","A_Id":64143264,"CreationDate":"2020-09-30T17:04:00.000","Title":"What is right time to perform train_test_split when building a model with text and categorical features?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am applying sklearn.preprocessing.MinMaxScaler() to a DataFrame and using the DataFrame for machine learning. After training I have a separate code and DataFrame to do a prediction. In the prediction code I do a MinMaxScaler() on the DataFrame I want to use to predict. The Training DataFrame and Prediction DataFrame will have different Min and Max values. My question is should the Training DataFrame and Prediction DataFrame use the same Min and Max values in order to get an accurate prediction?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":25,"Q_Id":64143779,"Users Score":1,"Answer":"Yes, you should use the same MinMaxScaler() on the train and test.\nExplanation: Assume your training dataset has some features with min=10 and max=20 and your test dataset has features with min=1 and max=10. If a separate scaler is trained on test, the test data values will be lower in comparison to the training dataset.","Q_Score":0,"Tags":"python,dataframe,tensorflow,scikit-learn,sklearn-pandas","A_Id":64143866,"CreationDate":"2020-09-30T18:36:00.000","Title":"Should the same Min and Max be applied for Training and Prediction on a DataFrame?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"The healpy.query_disc() function takes an argument vec which is a three-component unit vector defining the center of the disc. What coordinate system is being used here - why is there a third dimension for a 2-d projection? What point is the \"tail\" of this vector llocated at?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":142,"Q_Id":64144487,"Users Score":0,"Answer":"Solved. Used the output of ang2vec() to give the vector.","Q_Score":1,"Tags":"python,physics,astronomy,healpy","A_Id":64976754,"CreationDate":"2020-09-30T19:28:00.000","Title":"Coordinate system used for healpy.query_disc()","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am following a tutorial on Neural_Networks and it uses python2.7 and the line of code I am confused with is the if statement '''\nif test_data: n_test = len(test_data)\n''' and I ever came across this syntax in python 3.8 and please explain me what does test_data: n_test means. Thank You","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":196,"Q_Id":64148247,"Users Score":2,"Answer":"This is a if statement in python, it checks if test_data exists and if exists then sets the value of the variable n_data to the string length of test_data variable.","Q_Score":1,"Tags":"python,if-statement","A_Id":64148274,"CreationDate":"2020-10-01T02:26:00.000","Title":"Meaning of \"test_data: n_test\" in python 3.8","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a DataFrame with 57 columns. Columns 1 through 21 are dimensions. 22 through 57 are metrics. Column 1 is a date column. Column 21 is a bad column that is causing me to have duplicative data.\nWhat I am looking to do is remove column 21 and then take the min of 22 to 57 when 1 through 20 are the same.","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":813,"Q_Id":64162721,"Users Score":0,"Answer":"Just needed to drop the column and then drop duplicates. Sorry all.\ndf.drop(columns=\"lineItemBudget\", inplace=True)\ndf.drop_duplicates(inplace=True)","Q_Score":0,"Tags":"python,pandas","A_Id":64162928,"CreationDate":"2020-10-01T20:26:00.000","Title":"Pandas DataFrame: How to remove column and perform calculations on select columns","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"If I have a multivariable function such as\nF= lambda x,y: x**2+y**2\nand if I need to use the input x0=np.array([1,1])\nMay I know how I should use x0 to get the value from F?\nI understand that I could use something like F(x0[0],x0[1])\nBut I would like to know whether there is a way that I can directly use x0 rather than calling each cordinate manually\nAppreciate your help","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":59,"Q_Id":64165261,"Users Score":4,"Answer":"Python lets you do this by doing F(*x0), which expands the array into the parameters. In other languages this is sometimes called \"splatting\".","Q_Score":2,"Tags":"python,numpy","A_Id":64165360,"CreationDate":"2020-10-02T01:47:00.000","Title":"Using an array as an input for a multivariable function","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"If there are 10 features and 1 output class (sigmoid activation) with a regression objective:\nIf I use only 5 neurons in my first dense hidden layer: will the first error be calculated solely based on half of the training feature set? Isn't it imperative to match the # of features with the neurons in hidden layer #1 so that the model can see all the features at once? Otherwise it's not getting the whole picture? The first fwd propagation iteration would use 5 out of 10 features, and get the error value (and train during backprop, assume batch grad descent). Then the 2nd fwd propagation iteration would see the remaining 5 out of 10 features with updated weights and hopefully arrive at a smaller error. BUT its only seeing half the features at a time!\nConversely, if I have a convolutional 2D layer of 64 neurons. And my training shape is: (100, 28,28,1) (pictures of cats and dogs in greyscale), will each of the 64 neurons see a different 28x28 vector? No right, because it can only send one example through the forward propagation at a time? So then only a single picture (cat or dog) should be spanned across the 64 neurons? Why would you want that since each neuron in that layer has the same filter, stride, padding and activation function? When you define a Conv2D layer...the parameters of each neuron are the same. So is only a part of the training example going into each neuron? Why have 64 neurons, for example? Just have one neuron, use a filter on it and pass it along to a second hidden layer with another filter with different parameters!\nPlease explain the flaws in my logic. Thanks so much.\nEDIT: I just realized for Conv2D, you flatten the training data sets so it becomes a 1D vector and so a 28x28 image would mean having an input conv2d layer of 724 neurons. But I am still confused for the dense neural network (paragraph #1 above)","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":88,"Q_Id":64166258,"Users Score":1,"Answer":"What is your \"first\" layer?\nNormally you have an input layer as first layer, which does not contain any weights.\nThe shape of the input layer must match the shape of your feature data.\nSo basically when you train a model with 10 features, but only have a input layer of shape (None,5) (where none stands for the batch_size), tensorflow will raise an exception, because it needs data for all inputs in the correct shape.\nSo what you said is just not going to happen. If you only have 5 features, the next 5 features wont be fit into the net in the next iteration but, the next sample will be send to the model instead. (Lets say no exception is thrown) So of the next sample also only the first 5 features would be used.\nWhat you can do instead, use a input_layer as first layer with the correct shape of your features. Then as secodn layer, you can use any shape you like, 1,10,100 dense neurons, its up to you (and what works well of course). The shape of the output again must match (this time) the shape of your label data.\nI hope this makes it more clear","Q_Score":2,"Tags":"python,tensorflow,machine-learning,deep-learning,neural-network","A_Id":64168073,"CreationDate":"2020-10-02T04:43:00.000","Title":"Neural network hidden layer vs. Convolutional hidden layer intuition","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am attempting to do a two-fold task. The input is an image and based on the input I want to pick another image from a set of images (classification task) and then use both the images to obtain an output tensor. Clearly, I can train both the models separately if I know the ground truth of which image I should pick from that set. But, I only have the output tensor ground truth.\nThe problem, as it appears to me, is that if we employ a classification layer, the gradients will not be differentiable anymore. How do I deal with this problem? Is there literature which uses this kind of architecture for any application? TIA\nMore details: I have multiple images of an object\/scene and I want to use two of those images for some kind of reconstruction problem. To maximize the performance of reconstruction, I want to smartly choose the second image if I am given the first image. For eg., I have three images A, B, C and using AC gives the best result. I need a model which given A predicts C and then using AC I can achieve the reconstruction. Is the task clear now? I do not have ground truth which says AC is better than AB. Is the task clear now?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":49,"Q_Id":64169569,"Users Score":1,"Answer":"So basically, you want to do a classification task followed by a reconstruction task.\nHere is what I suggest (I do not pretend this the absolute best solution, but it's how I would approach this problem) :\nYou can create a single task that does Classification--> Reconstruction with a single loss. Let's still separate this network in two and call net_class the part that does classification , and net_reconstruct the part performing reconstruction.\nLet's say your classification network predicts {'B': 0.1, 'C': 0.9). Instead of using only image 'C' for reconstruction, I would feed both pairs (A-B and A-C) to the second network and compute a reconstruction loss L (I'm not an expert in reconstruction, but I guess there are some classical losses in this).\nTherefore, you would compute two losses L(A-B) and L(A-C).\nMy total loss would be 0.1 * L(A-B) + 0.9 L(A-C). This way, you would train net_class to choose the pairing that minimizes the reconstruction loss and you would still train net_reconstruct to minimize both losses, and the loss is continuous (and therefore, differentiable according to AI experts ;) ).\nThe idea behind this loss is three-fold :\n1 - Improving the reconstructor makes the loss go down (since both L(A-B) and L(A-C) would decrease. therefore, this loss should make your reconstructor converge towards something you want.\n2 - Let's imagine your reconstructor is pretty much trained (L(A-B) and L(A-C) are relatively low). Then, your classifier has an incentive to predict the class which has the lowest reconstruction loss.\n3 - Now, your reconstructor and your classifier will train at the same time. You can expect, at the end of the training, to have a classifier that would output pretty much binary results (like 0.998 vs 0.002). AAt that point, your reconstructor will almost only train on the scene associated with the 0.998 ouput. This should not be a problem, since, if I understood correctly your problem, you want to perform the reconstruction part only for the top classified scene.\nNote that this method also works if you're not performing deep learning for the reconstruction part.\nIf you want some inspiration on this kind of topic, I recommend you read some blog posts about GANs (Generative Adversarial Networks). They use the same two stage - one loss trick (with some slight differences of course, but the ideas are very close).\nGood luck !","Q_Score":1,"Tags":"python,tensorflow,machine-learning,computer-vision,data-science","A_Id":64173696,"CreationDate":"2020-10-02T09:51:00.000","Title":"Train a cascaded network with a classifier in between","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working with Carla 0.9.9 in Unreal 4.24 (Windows10\/RTX2080) right now in order to get some basic autonomous driving functions going. So far it seems to be working fine, but I have a weird problem and I'm quite confident that it's not caused by my code. I've googled around and this problem seems to be quite unique, but maybe one of you guys can point me in the right direction:\nI am displaying a few steps of my lane detection algorithm in different windows (e.g. ROI, detected lines...), and every few seconds, depending on the current framerate, the image will randomly flip to being upside down in some of the windows (only one at a time and only for a single\/few frames), except for the main window where I am controlling the car (manually for now). I've tried setting the Unreal Editor to different framerates, and there is definitely a connection between the output framerate (server side) and the amount of these \"flips\" happening, to the point where it's almost never happening if I run it at 15-20fps. There is also some \"tearing\" going on (e.g. only roughly the upper half of the image is flipped, like Vsynch is switched off) sometimes, which leads me to believe that the root cause is somewhere in the rendering part and not the python scripts. The point is: when the image is upside down, my lane detection is seeing the \"lane\" in the wrong place, which could lead to all sorts of trouble down the line.\nTo be honest I'm not that familiar with the whole Unreal Engine\/DirectX(?)-rendering pipeline, so I am a little lost what might be causing this issue. I'm grateful for any ideas on how to fix this, thanks in advance!","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":52,"Q_Id":64169887,"Users Score":0,"Answer":"Okay, in case anybody ever has the same problem, here's what I found out:\nthe client was running too fast in relation to the server. I limited the client side to 30fps now and that fixed it. This issue will only occur if the tick rate of the client is so high that it has trouble keeping up while running the calculations in the background.\nI still can't figure out why the image is upside down in that case, but hey...","Q_Score":0,"Tags":"python,image-processing,unreal-engine4,carla","A_Id":64222796,"CreationDate":"2020-10-02T10:14:00.000","Title":"Random image flipping in CARLA\/UE4","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":1,"Web Development":0},{"Question":"I have a problem with Tensorflow after import tensorflow\nTwo errors backwards I get :\n\n2020-10-02 15:13:07.794919: W\ntensorflow\/stream_executor\/platform\/default\/dso_loader.cc:59] Could\nnot load dynamic library 'libcudart.so.10.1'; dlerror:\nlibcudart.so.10.1: cannot open shared object file: No such file or\ndirectory 2020-10-02 15:13:07.794937: I\ntensorflow\/stream_executor\/cuda\/cudart_stub.cc:29] Ignore above cudart\ndlerror if you do not have a GPU set up on your machine.\n\nMy System:\n\nOS: Debian 10.6 AMD Ryzen 3 3300X Radeon XFX RX 590\npython 3.7\ntensorfolow 2.3.1\nIDE PyChram 2020.2\n\nI read that the GPU and CPU version of Tensorflow are together? Can I use this with my graphics card?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":272,"Q_Id":64172834,"Users Score":1,"Answer":"You say \"I get two errors\". But the second message says \"Ignore above cudart dlerror\". You only get a single error, and the second part says that the error really should have been a warning.\nThis is just a bad warning message. The real warning is that your GPU won't work with Tensorflow, but the CPU code will.","Q_Score":2,"Tags":"python","A_Id":64173300,"CreationDate":"2020-10-02T13:58:00.000","Title":"Problems with Tensorflow module","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Tensorboard fails to launch. I get the following error messages. Can somebody guide. I have reinstalled conda and Tensorflow multiple times. I also looked online for similar issues, have not found anything.\nPython 3.7.4 and Tensforflow version 2.1\nERROR: Failed to launch TensorBoard (exited with 1).\nContents of stderr:\nTraceback (most recent call last):\nFile \"C:\\ProgramData\\Anaconda3\\Scripts\\tensorboard-script.py\", line 9, in \nsys.exit(run_main())\nFile \"C:\\ProgramData\\Anaconda3\\lib\\site-packages\\tensorboard\\main.py\", line 65, in run_main\ndefault.get_plugins() + default.get_dynamic_plugins(),\nFile \"C:\\ProgramData\\Anaconda3\\lib\\site-packages\\tensorboard\\default.py\", line 125, in get_dynamic_plugins\n\"tensorboard_plugins\"\nFile \"C:\\ProgramData\\Anaconda3\\lib\\site-packages\\tensorboard\\default.py\", line 124, in \nfor entry_point in pkg_resources.iter_entry_points(\nFile \"C:\\ProgramData\\Anaconda3\\lib\\site-packages\\pkg_resources_init_.py\", line 2442, in load\nself.require(*args, **kwargs)\nFile \"C:\\ProgramData\\Anaconda3\\lib\\site-packages\\pkg_resources_init_.py\", line 2465, in require\nitems = working_set.resolve(reqs, env, installer, extras=self.extras)\nFile \"C:\\ProgramData\\Anaconda3\\lib\\site-packages\\pkg_resources_init_.py\", line 786, in resolve\nraise DistributionNotFound(req, requirers)\npkg_resources.DistributionNotFound: The 'typing-extensions>=3.7.4; python_version < \"3.8\"' distribution was not found and is required by yarl","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":317,"Q_Id":64186811,"Users Score":0,"Answer":"You need to install typing-extensions.","Q_Score":0,"Tags":"python,tensorflow,anaconda3,tensorflow2.x","A_Id":64191514,"CreationDate":"2020-10-03T17:01:00.000","Title":"Tensorboard fails to Launch","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to write a report on my Computer Vision project that uses OpenCV's (Python) boundingRect function. However, I am not allowed to say that I used this function, but rather the algorithm\/equation that this function uses. I have tried to find this online, but am not particularly good at identifying what it is I'm looking for. Would someone be able to suggest which algorithm the boundingRect equation uses? Thanks\nUtilised by: cv2.boundingRect(contour).","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":339,"Q_Id":64189496,"Users Score":2,"Answer":"In Python\/OpenCV, the axes aligned bounding rectangle is defined as X,Y,W,H, where X,Y are the coordinates of the minimum X,Y corner and W,H are the width and height of the box. Those values are found by testing every point (x,y) on the contour to find (the minimum and maximum of x and y each) minX, maxX, minY, maxY. The bounding rectangle values are then X=minX, Y=minY, W=(maxX-minX), H=(maxY-minY). You find the min and max values by looping over each x (or y) and testing it against the previous min or max value. If the current value is lower or higher, respectively, replace the old min or max with the current value.\nIn other systems, the bounding box is defined by the minimum and maximum diagonally opposite corners (minX,minY) and (maxX,maxY)","Q_Score":0,"Tags":"python,opencv","A_Id":64189992,"CreationDate":"2020-10-03T22:13:00.000","Title":"OpenCV Bounding Rectangle (Python)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm working on a project on recommender systems written by python using the Bayesian Personalized Ranking optimization. I am pretty confident my model learns the data I provided well enough, but now it's time I found out the exact model hyperparameters and try to avoid overfitting. Since the movielens dataset only provided me with 5-fold train-test datasets without validation sets, I want to split the original dataset by myself to validate my model.\nSince the movielens dataset holds 943 user data with each user guaranteed to have ranked at least 20 movies, I'm thinking of splitting the data so that both TRAIN and TEST datasets contain the same number of users(e.g. 943), and distributing 80% of the implicit feedback data to TRAIN, and the other to TEST. After training validation will take place using the mean value of Recall at k precision through all 943 users.\nIs this the right way to split the dataset? I am curious because the original movielens test dataset doesn't seem to contain test data for all 943 users. If a certain user doesn't have any test data to predict, how do I evaluate using recall@k -- when doing so would cause a zero division? Should I just skip that user and calculate the mean value with the rest of the users?\nThanks for the lengthy read, I hope you're not as confused as I am.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":630,"Q_Id":64189820,"Users Score":1,"Answer":"How I would split it is the whole data set on 80% (train)- 10% (validation) - 10% (test). It should work out :)","Q_Score":0,"Tags":"python,bayesian,precision-recall,recommender-systems","A_Id":64190100,"CreationDate":"2020-10-03T23:17:00.000","Title":"Splitting movielens data into train-validation-test datasets","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to replace a Noun in a sentence with its pronoun. I will be using this to create a dataset for a NLP task. for example if my sentences are -->\n\n\"Jack and Ryan are friends. Jack is also friends with Michelle.\"\n\nThen I want to replace the second Jack(in italics and bold ) with \"He\".\nI have done the POS tagging to find the Nouns in my sentences. But I do not know how to proceed from here.\nIf I have a list of all possible pronouns that can be used, Is there a corpus or system that can tell me the most appropriate pronoun for the word?","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":376,"Q_Id":64190127,"Users Score":2,"Answer":"You can almost do this with tools in Stanford CoreNLP. If you run the \"coref\" annotator, then it will attempt to determine the reference of a pronoun to other entity mentions in the text. There is also a \"gender\" annotator, which can assign a (binary) gender to an English name (based just on overall frequency statistics). (This gender annotator can at present only be accessed programmatically; its output doesn't appear in our standard output formats.)\nHowever, both coreference resolution and automated gender assignment are tasks with mediocre accuracy, and the second has further assumptions that make it generally questionable. I find it hard to believe that doing this automatically will be a useful strategy to automatically produce data for an NLP task.","Q_Score":5,"Tags":"python,python-3.x,nlp,stanford-nlp,coreference-resolution","A_Id":64199169,"CreationDate":"2020-10-04T00:21:00.000","Title":"Changing a Noun to its Pronoun in a sentence","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to define a number of learnable parameters in my model that are multiplied by the feature map in feedforward and updated when backpropagation.\nHow can i implement this in the chainer framework?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":44,"Q_Id":64192930,"Users Score":0,"Answer":"I read a little and found my answer.\nIf you need to define a number of parameters in chainer that need to be learned, you should use chainer.links.Scale() function.\nfor example chainer.links.Scale(axis=1,W_shape=(8,8))\nW are the same parameters that are learnable in the network. If the feature map is x, W is multiplied by x and its updated in backpropagation.","Q_Score":0,"Tags":"python,deep-learning,implementation,backpropagation,chainer","A_Id":64193805,"CreationDate":"2020-10-04T09:18:00.000","Title":"Define a number of learnable parameters in Chainer","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've been trying to unpack this like a dictionary or json in python pandas but it's not giving me an output into a dataframe. Can anyone point me in the right direction?\n0 [{'JournalLineID': 'XXX', 'AccountID': 'XXX', 'AccountCode': '200', 'AccountType': 'XXX', 'AccountName': 'XXX', 'Description': '', 'NetAmount': -428.0, 'GrossAmount': -428.0, 'TaxAmount': 0.0, 'TrackingCategories': [{'Name': 'Location', 'Option': 'SG', 'TrackingCategoryID': 'XXX', 'TrackingOptionID': 'XXX', 'Options': []}, {'Name': 'Sales Rep\/Dept', 'Option': 'HQ', 'TrackingCategoryID': 'XXX', 'TrackingOptionID': 'XXX', 'Options': []}]}, {'JournalLineID': 'XXX2', 'AccountID': 'XXX', 'AccountCode': 'XXX', 'AccountType': 'EXPENSE', 'AccountName': 'Subscriptions - Software', 'Description': 'XXXX', 'NetAmount': 400.0, 'GrossAmount': 428.0, 'TaxAmount': 28.0, 'TaxType': 'INPUT', 'TaxName': 'Purchases 7%', 'TrackingCategories': [{'Name': 'Location', 'Option': 'SG', 'TrackingCategoryID': 'XXX', 'TrackingOptionID': 'XXX', 'Options': []}, {'Name': 'Sales Rep\/Dept', 'Option': 'HQ', 'TrackingCategoryID': 'XXX', 'TrackingOptionID': 'XXX', 'Options': []}]}]\nWhen i try pd.DataFrame.from_records(df), it gives me an output that splits by the letter\n0 [ { ' J o u r n a l ... s ' : [ ] } ] } ]\nWhen i try pd.DataFrame(df),\nthis is the output:\n0 [{'JournalLineID': 'XXX', 'AccountID': 'XXX', 'AccountCode': '200', 'AccountType': 'XXX', 'AccountName': 'XXX', 'Description': '', 'NetAmount': -428.0, 'GrossAmount': -428.0, 'TaxAmount': 0.0, 'TrackingCategories': [{'Name': 'Location', 'Option': 'SG', 'TrackingCategoryID': 'XXX', 'TrackingOptionID': 'XXX', 'Options': []}, {'Name': 'Sales Rep\/Dept', 'Option': 'HQ', 'TrackingCategoryID': 'XXX', 'TrackingOptionID': 'XXX', 'Options': []}]}, {'JournalLineID': 'XXX2', 'AccountID': 'XXX', 'AccountCode': 'XXX', 'AccountType': 'EXPENSE', 'AccountName': 'Subscriptions - Software', 'Description': 'XXXX', 'NetAmount': 400.0, 'GrossAmount': 428.0, 'TaxAmount': 28.0, 'TaxType': 'INPUT', 'TaxName': 'Purchases 7%', 'TrackingCategories': [{'Name': 'Location', 'Option': 'SG', 'TrackingCategoryID': 'XXX', 'TrackingOptionID': 'XXX', 'Options': []}, {'Name': 'Sales Rep\/Dept', 'Option': 'HQ', 'TrackingCategoryID': 'XXX', 'TrackingOptionID': 'XXX', 'Options': []}]}]","AnswerCount":3,"Available Count":1,"Score":0.0665680765,"is_accepted":false,"ViewCount":143,"Q_Id":64193825,"Users Score":1,"Answer":"Remove the leading 0 and call pd.DataFrame() on the remaining part.","Q_Score":0,"Tags":"python,json,pandas","A_Id":64193880,"CreationDate":"2020-10-04T11:05:00.000","Title":"Unpack list of dictionary into Pandas dataframe","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am running a long ODE-integration in Python using scipy.integrate.solve_ivp. Is it possible to access the status of the integration or check at which integration step the routine is, while it is running? My integration is taking longer than expected and I would like to know whether the integrator is stuck at some step or whether the individual steps just take really long.\nFor future tasks; if I split the integration with solve_ivp into sub-intervals to print status messages in between, could this mess with the step-size adaptivity of certain solvers?\nThanks for any feedback!","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":299,"Q_Id":64194348,"Users Score":4,"Answer":"There was a GitHub pull request to add a verbose option to solve_ivp, but this has not yet been done. You can either implement it yourself by modifying scipy's solve_ivp function (should be easy), or just print the time t that is given by the solver to your ODE function. That's what I do. If your system is not too small, then you don't loose much time because of the printing.\nSplitting the integration the way you suggest can work, however if you split every few time steps, you will lose time as the solver restarts each tile. The impact is related with implicit algorithms, as they compute the Jacobian of your system anew at each start.","Q_Score":1,"Tags":"python,scipy","A_Id":64943101,"CreationDate":"2020-10-04T12:01:00.000","Title":"SciPy: status of solve_ivp during integration","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"How can I write a Python function that can takes n dimensional vectors and return boolean if vectors are linearly dependent? Can it be done using dot or do I need to write a full calculation?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":1337,"Q_Id":64201090,"Users Score":1,"Answer":"You can check for the determinant of the matrix , if the determinant is zero then it's linearly dependent.\nYou can use the function np.linalg.det(Mat)","Q_Score":1,"Tags":"python,numpy","A_Id":64211143,"CreationDate":"2020-10-05T00:20:00.000","Title":"Python linear independence using numpy","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a DataFrame with 1M+ rows. I'm trying to run pivot table using pivot_table method from pandas on Anaconda. However, it has been running over 15+ min without result.\nI've tried to install modin, and vaex on Anaconda with no luck as both libraries are not accepted by Anaconda.\nNot sure if this matters, I'm using vs code to run Anaconda.\nAnyone has suggestions? Thank you,","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":260,"Q_Id":64201815,"Users Score":1,"Answer":"I don't have the issue by following the steps:\n\nconvert data type from 'str' to 'float' for the column I meant to sum through pivot_table; this is the calculation that I had problem with.\nconvert DataFrame to numpy array\ncalculate sum of the sliced numpy array (column). It tool less than 5 sec to return the total.\n\nAll good.","Q_Score":0,"Tags":"python,pandas,visual-studio-code,anaconda","A_Id":64202151,"CreationDate":"2020-10-05T02:37:00.000","Title":"Slow to run a pivot table of a DataFrame with over 1,000,000 rows by using pandas on Anaconda. Any suggestions to improve efficiency?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Have been trying to access Cuda within Tensorflow 2.3.1 (through PyCharm) to access my compatible GPU for object detection. TensorFlow was working previously, but when I installed Cuda I realised that it was 11.1 - where TensorFlow has a pre-requisite of Cuda 10.1. I had both versions on my computer, and tried to uninstall all the 11.1 toolkit using the Windows add\/remove tool (which is recommended). This seemed to work in removing 11.1, however, when I try to re-install the TensorFlow package into the Project Interpreter Setting (within PyCharm) it comes up with the following error:\n\n\nUnsatisfiableError: The following specifications were found to be incompatible with the existing python installation in your\nenvironment:\nSpecifications:\ntensorflow -> python[version='3.5.|3.6.|3.7.*']\nYour python: python=3.8\nIf python is on the left-most side of the chain, that's the version you've asked for. When python appears to the right, that indicates\nthat the thing on the left is somehow not available for the python\nversion you are constrained to. Note that conda will not change your\npython version to a different minor version unless you explicitly\nspecify that.\nThe following specifications were found to be incompatible with your system:\nfeature:\/win-64::__cuda==11.1=0\nYour installed version is: 11.1\n\n\nEDIT - this the the same when I try to install into the Conda Environment through Anaconda.\nSystem setup:\nWindows 10 (64bit)\nTensorflow 2.3.1\nCuda 10.1 (previously 11.1 installed - but I thought uninstalled)\ncdnn 64_7\nPython 3.8\nGraphics: 2070Super (driver:456.55)\nI understand that PyCharm is unable to install TensorFlow because this has a pre-requisite of Cuda 10.1, but I can't find any references to where it's still pointing to the older (newer 11.1) version. All my path environment variables point to the 10.1 directory. I wonder if there isn't a text\/init file somewhere that hard-sets the Cuda version, but haven't found anything on the NVidia site.\nSorry for the noob question, but I am hoping someone can point out where this reference to the newer 11.1 version might be lingering.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":377,"Q_Id":64203247,"Users Score":0,"Answer":"So I feel somewhat embarrassed - it turns out despite the Tensorflow website indicating that TensorFlow2.0 was compatible with Python3.8, once I reverted back to an earlier 3.7 it seems to have at least resolved that problem. I was fixated on the fact that it was falsely reporting Cuda v11.1. I think this is now resolved.","Q_Score":0,"Tags":"python,tensorflow,pycharm","A_Id":64218556,"CreationDate":"2020-10-05T06:10:00.000","Title":"Problem reverting to older Cuda version for TensorFlow in PyCharm (Windows 10)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working with a dataframe that was 20 columns. When I try to display output using .show() after manipulations, due to the large number of columns its not very easy to read. What's the best way to get a compact view of all columns?\nThanks\nSS","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":187,"Q_Id":64208484,"Users Score":0,"Answer":"the display() function is what you want.\nIf your dataframe is named df, you'll call the function as such:\ndisplay(df) .","Q_Score":0,"Tags":"python,pyspark","A_Id":64234981,"CreationDate":"2020-10-05T12:18:00.000","Title":"show() for large number of columns in pyspark","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am building a CNN with a similar architecture as VGG16. I know in VGG16 u do rescale u also center around 0. Now I train mine from scratch, does it make a difference and should I do it or no? Anyone who can help?\ndatagen = ImageDataGenerator(rescale=1. \/ 255)\nThanks a lot guys! <3","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":1092,"Q_Id":64215709,"Users Score":2,"Answer":"Rescaling to 0-1 in general is always a good choice when training neural networks, so yes go for it. The reason behind this is that neural networks tend to yield better results when the inputs are normalised. You could run the same exact experiment with pixel rescaling and without pixel rescaling and see for yourself the results!","Q_Score":0,"Tags":"python,tensorflow,keras,conv-neural-network,image-classification","A_Id":64216427,"CreationDate":"2020-10-05T20:24:00.000","Title":"do I use \"rescale=1. \/ 255\" or not? Building VGG-like CNN","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm looking for a solution at the following problem:\nI have my neural network with 8 features and 6 outputs.\nThe network predicts some info on a graph, where a record is related to a node in the graph.\nIt works perfectly when I have all the examples (nodes) with the same degree of neighbours.\nNow I would need it to work also for nodes with less neighbours, but on a general form, meaning that I do not know a priori how many they are.\nThus I tried putting a zero when the the neighbour does not exist, but the predictions where all strange, not correct at all.\nSo my questions is: is there a way such that during training I can switch off some input neurons looking at how many effective features I have on that example?\nTo be more precise: the first example taken by the NN has the full neighbour, thus I have 8 values; the second has 6 values, so I would like to switch off 2 input neurons and so on.\nAny ideas ?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":77,"Q_Id":64225655,"Users Score":1,"Answer":"A simple solution which might work would be to declare a feature as non relevant. So you simply specify a value, which makes the model learn that it should not be used in this iteration. So when you set the values to zero, the model wll just think that its a zero, so the meaning is ambiguus. However if you set it to -1 e.G. but -1 does not occur in your data at all, the model might be able to learn that -1 represents a non existent feature and puts more attention on the others.","Q_Score":1,"Tags":"python,tensorflow,deep-learning,neural-network,feature-selection","A_Id":64227403,"CreationDate":"2020-10-06T12:17:00.000","Title":"turn off features during training in deep network","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a Dataframe of which one column contains several missing values, which are printed as NaN. I want to replace the missing values with the number 0. How can I do that with the fillna() function?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":37,"Q_Id":64229976,"Users Score":0,"Answer":"does using data.fillna(0) work for you?","Q_Score":0,"Tags":"python,pandas","A_Id":64230053,"CreationDate":"2020-10-06T16:24:00.000","Title":"How can I fill in missing values (NaN) at a particular column in a data frame?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am confused about tsfresh input format. Can I give a dataframe with missing values for different ids? For example, timeseries 1 {t0: 1, t2: 4, t5: 1} and timeseries 2 {t1: 5, t2: 2}. Should I fill missing values(t1, t3 etc.) with 0?\nthanks in advance","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":175,"Q_Id":64238345,"Users Score":2,"Answer":"tsfresh does not \"care\" about the time entries of your data. Most of its feature calculators do not need to have fixed time intervals (e.g. the mean of a timeseries is still the same, no matter which time stamps we are talking about). So yes, technically it is possible to have different times for different ids.\nThat being said, some feature calculators do rely on the time stamp and having proper time intervals (e.g. Fourier transformation). However, there exist many different ways on how to fill these missing values which need a lot of domain knowledge. That is why tsfresh does not do this \"automatically\". However, many libraries (e.g. pandas), give many possibilities for this, e.g. using resampling methods.","Q_Score":1,"Tags":"python,time-series,tsfresh","A_Id":65476168,"CreationDate":"2020-10-07T06:25:00.000","Title":"tsfresh timeseries missing values","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using xlsxwriter to export pandas dataframe to excel file. I need format a range of cells without using worksheet.write function as the data is already present in cells.\nIf I am using set_row or set_column, it is adding the format to entire row or column.\nPlease help me find a solution.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":408,"Q_Id":64239147,"Users Score":1,"Answer":"I need format a range of cells without using worksheet.write function as the data is already present in cells.\n\nIn general that isn't possible with XlsxWriter. If you want to specify formatting for cells then you need to do it when you write the data to the cells.\nThere are some options which may or may not suit your needs:\n\nRow and Column formatting. However that formats the rest of the row or column and not just the cells with data.\nAdd a table format via add_table().\nAdd a conditional format via conditional_format().\n\nHowever, these are just workarounds. If you really need to format the cells then you will need to do it when using write().","Q_Score":0,"Tags":"python,python-3.x,pandas,xlsxwriter","A_Id":64239595,"CreationDate":"2020-10-07T07:21:00.000","Title":"Cell Format for a range of cells using xlsxwriter","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have dataframe with columns(issue_id,summary, source_id). The source_id has values ranging from 1 to 3.\nI want to create multiple dataframes having name df_1, df_2,df_3 as per the values in source_id.\nI tried groupby and it gave a dict. but converting dict to dataframe is giving only 1 dataframe.\ndata_dict={'df'+str(i): grp for i , grp in df.groupby('Source_sys')}\npd.DataFrame.from_dict(data_dict,orient = 'index')\noutput:\n0\ndf1 Issue ...\ndf2 Issue ...\ndf3 Issue ...","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":61,"Q_Id":64247027,"Users Score":0,"Answer":"The simple way is delete other columns and assign different name. @krishna","Q_Score":0,"Tags":"python,pandas,dataframe","A_Id":64247086,"CreationDate":"2020-10-07T15:11:00.000","Title":"create multiple dataframes from unique values of a cloumn","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to generate a Dataframe which involves three industries, 100 investors, and 2000 firms in 50000 different deals. So, I have 50000 rows and four columns, including deal's date.\nI randomly assigned 100 investors and 2000 firm in this dataset for all deals.\nMy problem is that I need to determine the industry for each deal by considering a couple of conditions that should hold for this process. 1) If a firm randomly assigned to an industry, this firm should hold in the same industry in the whole dataset. 2) All investors invest at least in one industry, 15 investors invest at least in two industries, and four investors invest in all three industries. I don't know how I can do this.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":29,"Q_Id":64247853,"Users Score":0,"Answer":"This seems like 2 separate questions\nFor 1, one idea is to just hash the firm name and then that will give you a deterministic way of setting which firm goes to which industry.\nFor 2, one idea is to use a permutation function. For example, you can use numpy.shuffle where the first 4 belong to all 3, then the next 15 belong to a random subset of 2... etc, etc.\nYou could then generate tables off of all this information and use joins to concatenate your final table, where you initially start off with just trade dates, firms, and deal info.\n(This is just a starting idea)","Q_Score":1,"Tags":"python,python-3.x,dataframe","A_Id":64258036,"CreationDate":"2020-10-07T15:57:00.000","Title":"Adding random values between one to three to a column of a DataFrame conditional on some conditions","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working to calculate similarities of labels of materials. Where each label might have 1-10 words in it. I am using gensim word2vec to find cosine similarities.\nMy approach is simply to treat each label as a 'sentence' and tokenize each word.\nexample:\nlabels = ['wooden desk cherry', 'long sleeve shirt cotton',..]\nsentences = [['wooden', 'desk', 'cherry'], ['long', 'sleeve', 'shirt', 'cotton'],..]\nMy question is does word2vec take neighboring sentences into its context. for example if i am using a window = 2, when looking at words around 'long', will 'cherry' be included or only 'sleeve'.\nIf neighboring sentences are considered is there a way to only consider words within the target words sentence.\nThanks for any help. I have read the Word2Vec documentation and couldn't find any information about this.","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":97,"Q_Id":64267811,"Users Score":2,"Answer":"Gensim's Word2Vec works on whatever chunks of text you provide to it. So, when you supply ['wooden', 'desk', 'cherry'] and ['long', 'sleeve', 'shirt', 'cotton'] as separate items in the training corpus, no training windows will blend them together.\n(Separately: in sufficiently-large training sets, it'd be unlikely for such 'bleed-over' to make much difference, even if it did happen. It'd be a little bit of random-interference, since the source data doesn't truly imply those words appeared together. But the curve-balls it throws the training should be swamped out by the 'real signal' in true co-occurrences.)","Q_Score":1,"Tags":"python,machine-learning,nlp,gensim,word2vec","A_Id":64269938,"CreationDate":"2020-10-08T17:32:00.000","Title":"does gensim Word2Vec include neighboring sentences in context?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a dataset that contains many binary columns. In the first half, each row has at least a 1; on the second half, each row has all zeros across all columns.\nIs there a function to randomize rows so that they are not grouped by rows that have at least one 1 and rows that have all zeros?\nThank you!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":194,"Q_Id":64269183,"Users Score":0,"Answer":"You can use .sample(n) on your pandas dataframe to view a random sample of n items if that is all you need...","Q_Score":0,"Tags":"python,pandas,dataframe,data-cleaning","A_Id":64269244,"CreationDate":"2020-10-08T19:11:00.000","Title":"How mix rows around in a Pandas DataFrame?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a PYTHON script that uses multiprocessing to extract the data from DB2\/Oracle database to CSV and ingest to Snowflake. When I run this script, performance is good (extracts the source table that is large dataset in 75 seconds). So I made a copy of this python script and changed the input parameters (basically different source tables). When I run all these python scripts together, performance gets an impact (for the same table, it extracts in 100 seconds) and sometimes i see an error 'Cannot allocate memory'.\nI am using Jupyter Nootebook and all these different python scripts extracts different source tables to CSV files and saves it in same server location.\nI am also checking on my own. But any help will be appreciated.\nThanks\nBala","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":41,"Q_Id":64286754,"Users Score":0,"Answer":"If you are running multiple scripts that use multiprocessing and write to the same disk at the same time, you will eventually hit a bottleneck somewhere.\nIt could be concurrent access to the database, writing speed of the disk, amount of memory used or CPU cycles. What specifically is the problem here is impossible to say without doing measurments.\nBut e.g. writing things to a HDD is very slow compared to current CPU speeds.\nAlso, when you are running multiple scripts that use multiprocessing you could have more worker processes than the CPU has cores. In which case there will be some worker processes waiting for CPU time all the time.","Q_Score":0,"Tags":"python-3.x,multiprocessing,subprocess,pool","A_Id":64287348,"CreationDate":"2020-10-09T20:17:00.000","Title":"Python - Running multiple python scripts that uses multiprocessing affects performance and errors out sometimes","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"Large Sparse Matrix Data Saved To \/ Loaded From SQL vs. Numpy File Data\nI am using a large sparse matrix (~20k x 100k) and vector(s) (~20K x 1) in my python application with great speed and success.\nOver time, my large sparse matrix will grow. Growth management is easy and fast while the matrix is in memory.\nI am wanting to find the fastest method to save and load my matrix when my app closes and opens, respectively.\nI had planned to save and load using numpy save and load functions. SQL Server through pyodbc is lightning fast, but I have not ever thought to use SQL to manage and maintain sparse matrices before.\nIs it crazy to think of managing long term storage of sparse matrices in a SQL Server DataBase table? I would store each column of the sparse matrix as a column in the sparse matrix SQL table, and each row would represent a shared aspect amongst the columns. I do believe that updating the SQL table would be faster than storing the whole sparse matrix as a numpy data object to file. I am more worried about loading the matrix into memory when the app starts. Would numpy always be faster at this?\nLoading the matrix would be as simple as\nSELECT * FROM SPARSE_MATRIX.\nThose query results would then need to be formatted correctly and converted to a numpy sparse matrix. I am also open to some other SQL storage approach, but I cannot conceive of one yet.\nMotivation for asking this? Management of my sparse matrix for my particular app would be VERY elegant in SQL with regard to saving, growing and maintaining the matrix.\nIF I do not get an answer, I will likely do a speed test comparison and answer this question myself for members in the greater community that might have this same question, BUT I am hoping someone has had some experience with this.\nThis might all be more practical if I run things through pandas or dask between python and SQL. Eager to find an answer to this one way or another.","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":211,"Q_Id":64287189,"Users Score":2,"Answer":"Use Parquet\nHave you considered using the parquet file format? It stores tabular data really efficient and is very fast on reads and decently fast on writes. With Apache Drill or Spark you can directly use it with the SQL language. Dask and all major data processing frameworks support it, too.\nTo update a parquet file you would need to overwrite the whole file.\nDon\u2019t use a SQL server\nI would not recommend using an SQL server database as they have different goals:\n\nlow latency\noperation on just a subset of the data\n\nIn your case these don\u2019t apply.","Q_Score":1,"Tags":"python,sql-server,pandas,dask,pyodbc","A_Id":64289256,"CreationDate":"2020-10-09T20:54:00.000","Title":"Large Sparse Matrix Data Saved To \/ Loaded From SQL vs. Numpy File Data","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Given a 2D plane and N points (n1=(x1,y1), n2=(x2,y2)..., nN=(xN,yN)), what is a fast (O(n) or better) algorithm that will find the closest neighbor of any point (e.g. n1 closest neighbor is n3, n2 closest neighbor is n4). I was thinking about storing it in a dictionary where the keys are the points, and the values are the neighbors.\nThere seem to be quite a lot of similar questions on SO, but I couldn't find any code in Python or answers that are not in other languages.","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":554,"Q_Id":64287756,"Users Score":0,"Answer":"For a given a point P, simple solution:\n\nCalculate P's distance from all other points, this is done with O(n) time complexity.\nSave them as list of tuples (or similar data structure), the tuples of (point, distance from P).\nOne walk over the list can yield you the top K closest points, in O(n) time complexity.\n\nA second solution that will cost more in space complexity (O(n^2)) and maintenance over time, but will shorten finding the K nearest neighbors:\n\nKeeping a dictionary from each point to a ordered list (or similar data structure) of points by their distance - building this table once is O(n^2 * log(n)).\nFinding K closest points is O(k) - dictionary access + copying k elements from ordered list.\nOverhead in time complexity would be in adding a new point or removing an old one in a manner that will keep this data structure valid - O(n*log(n)) in both.\n\nThe solution you choose should be on what you want to optimize","Q_Score":0,"Tags":"python,distance,nearest-neighbor","A_Id":64288054,"CreationDate":"2020-10-09T21:52:00.000","Title":"Closest neighbor to any point (other than itself) in a 2D plane","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"Given a 2D plane and N points (n1=(x1,y1), n2=(x2,y2)..., nN=(xN,yN)), what is a fast (O(n) or better) algorithm that will find the closest neighbor of any point (e.g. n1 closest neighbor is n3, n2 closest neighbor is n4). I was thinking about storing it in a dictionary where the keys are the points, and the values are the neighbors.\nThere seem to be quite a lot of similar questions on SO, but I couldn't find any code in Python or answers that are not in other languages.","AnswerCount":2,"Available Count":2,"Score":1.2,"is_accepted":true,"ViewCount":554,"Q_Id":64287756,"Users Score":0,"Answer":"A simple solution that can yield better results than O(n) on average is using a k-d tree for storing the points. building the tree has a worst case complexity O(nlogn). after that searching is on average O(logn) and worst case O(n) (usually for points away from all the other data).\nAlso you might be interested in LSH or locality sensitive hashing while it is an approximation approach meaning you won't always get the right answer, for high dimensional data it provides an important speedup with complexity being closely related to the parameters chosen.","Q_Score":0,"Tags":"python,distance,nearest-neighbor","A_Id":64288117,"CreationDate":"2020-10-09T21:52:00.000","Title":"Closest neighbor to any point (other than itself) in a 2D plane","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"If the dependent variable has both positive and negative values, the model.score of any regression models are not accurate when train and test score are compared. I tried converting the target column into log but since there are negative values as well, it seems this is not right. Please advise","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":355,"Q_Id":64292762,"Users Score":0,"Answer":"I can't think of any machine learning algorithms that can't handle both positive and negative values. The scoring should still be accurate. If you would like to take the log transform of a column with negative values, then you can add some large constant to the column that makes all values positive and then take the log.","Q_Score":0,"Tags":"python,regression,artificial-intelligence","A_Id":64292943,"CreationDate":"2020-10-10T11:12:00.000","Title":"If the dependent variable has both positive and negative values, how to approach any machine learning algorithm?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"im using django for a face recogntion app and i need to save face descriptor in djangomodel and then retreive them and compare with the vectors of a new image and get the model in the database that have the nearest distance with the new vectore.\nso in short\n\ni have a model of persons\neach model have a textfield that represent a vector\ni have a function compare(vec1,vec2) that take two vectors as\nstrings and return the distance between them\ni have a new vector (not in the database)\ni need to apply the compare function on the model and retrieve the\nperson that his vector field have the minimum distance with the new\nvector","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":348,"Q_Id":64306630,"Users Score":0,"Answer":"RDBMS is not for storing the vectors, you need to use either elastic search or opensearch to store the vectors and perform the similarity checks.","Q_Score":0,"Tags":"python,django,django-models","A_Id":68935121,"CreationDate":"2020-10-11T16:49:00.000","Title":"searching in a django models of vectors with a custom function","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":1},{"Question":"I have a structure, looking a lot like a graph but I can 'sort' it. Therefore I can have two graphs, that are equivalent, but one is sorted and not the other. My goal is to compute a minimal dominant set (with a custom algorithm that fits my specific problem, so please do not link to other 'efficient' algorithms).\nThe thing is, I search for dominant sets of size one, then two, etc until I find one. If there isn't a dominant set of size i, using the sorted graph is a lot more efficient. If there is one, using the unsorted graph is much better.\nI thought about using threads\/multiprocessing, so that both graphs are explored at the same time and once one finds an answer (no solution or a specific solution), the other one stops and we go to the next step or end the algorithm. This didn't work, it just makes the process much slower (even though I would expect it to just double the time required for each step, compared to using the optimal graph without threads\/multiprocessing).\nI don't know why this didn't work and wonder if there is a better way, that maybe doesn't even required the use of threads\/multiprocessing, any clue?","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":38,"Q_Id":64308739,"Users Score":0,"Answer":"Sounds like you're not doing what you describe. Possibly you're waiting for BOTH to finish somehow? Try doing that, and seeing if the time changes.","Q_Score":0,"Tags":"python,multithreading,recursion,graph,multiprocessing","A_Id":64312566,"CreationDate":"2020-10-11T20:33:00.000","Title":"Simultaneous recursion on equivalent graphs using Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a structure, looking a lot like a graph but I can 'sort' it. Therefore I can have two graphs, that are equivalent, but one is sorted and not the other. My goal is to compute a minimal dominant set (with a custom algorithm that fits my specific problem, so please do not link to other 'efficient' algorithms).\nThe thing is, I search for dominant sets of size one, then two, etc until I find one. If there isn't a dominant set of size i, using the sorted graph is a lot more efficient. If there is one, using the unsorted graph is much better.\nI thought about using threads\/multiprocessing, so that both graphs are explored at the same time and once one finds an answer (no solution or a specific solution), the other one stops and we go to the next step or end the algorithm. This didn't work, it just makes the process much slower (even though I would expect it to just double the time required for each step, compared to using the optimal graph without threads\/multiprocessing).\nI don't know why this didn't work and wonder if there is a better way, that maybe doesn't even required the use of threads\/multiprocessing, any clue?","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":38,"Q_Id":64308739,"Users Score":0,"Answer":"If you don't want an algorithm suggestion, then lazy evaluation seems like the way to go.\nSetup the two in a data structure such that with a class_instance.next_step(work_to_do_this_step) where a class instance is a solver for one graph type. You'll need two of them. You can have each graph move one \"step\" (whatever you define a step to be) forward. By careful selection (possibly dynamically based on how things are going) of what a step is, you can efficiently alternate between how much work\/time is being spent on the sorted vs unsorted graph approaches. Of course this is only useful if there is at least a chance that either algorithm may finish before the other.\nIn theory if you can independently define what those steps are, then you could split up the work to run them in parallel, but it's important that each process\/thread is doing roughly the same amount of \"work\" so they all finish about the same time. Though writing parallel algorithms for these kinds of things can be a bit tricky.","Q_Score":0,"Tags":"python,multithreading,recursion,graph,multiprocessing","A_Id":64312443,"CreationDate":"2020-10-11T20:33:00.000","Title":"Simultaneous recursion on equivalent graphs using Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"This area is still very new to me, so forgive me if I am asking dumb questions. I'm utilizing MCTS to run a model-based reinforcement learning task. Basically I have an agent foraging in a discrete environment, where the agent can see out some number of spaces around it (I'm assuming perfect knowledge of its observation space for simplicity, so the observation is the same as the state). The agent has an internal transition model of the world represented by an MLP (I'm using tf.keras). Basically, for each step in the tree, I use the model to predict the next state given the action, and I let the agent calculate how much reward it would receive based on the predicted change in state. From there it's the familiar MCTS algorithm, with selection, expansion, rollout, and backprop.\nEssentially, the problem is that this all runs prohibitively slowly. From profiling my code, I notice that a lot of time is spent doing the rollout, likely I imagine because the NN needs to be consulted many times and takes some nontrivial amount of time for each prediction. Of course, I can probably stand to clean up my code to make it run faster (e.g. better vectorization), but I was wondering:\n\nAre there ways to speed up\/work around the traditional random walk done for rollout in MCTS?\nAre there generally other ways to speed up MCTS? Does it just not mix well with using an NN in terms of runtime?\n\nThanks!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":600,"Q_Id":64309511,"Users Score":0,"Answer":"I am working on a similar problem and so far the following have helped me:\n\nMake sure you are running tensorflow on you GPU (You will have to install CUDA)\nEstimate how many steps into the future your agent needs to calculate to still get good results\n(The one I am currently working on) parallelize","Q_Score":0,"Tags":"python,tensorflow,monte-carlo-tree-search","A_Id":68473168,"CreationDate":"2020-10-11T22:13:00.000","Title":"Ways to speed up Monte Carlo Tree Search in a model-based RL task","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a huge distance matrix.\nExample: (10000 * 10000)..\nIs there an effective way to find a inverse matrix?\nI've tried numpy's Inv() but it's too slow.\nIs there a more effective way?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":153,"Q_Id":64315047,"Users Score":0,"Answer":"You probably don't actually need the inverse matrix.\nThere are a lot of numeric techniques that let people solve matrix problems without computing the inverse. Unfortunately, you have not described what your problem is, so there is no way to know which of those techniques might be useful to you.\nFor such a large matrix (10k x 10k), you probably want to look for some kind of iterative technique. Alternately, it might be better to look for some way to avoid constructing such a large matrix in the first place -- e.g., try using the source data in some other way.","Q_Score":0,"Tags":"python,math,matrix,3d,distance","A_Id":64322480,"CreationDate":"2020-10-12T09:22:00.000","Title":"how to get the inverse of distance matrix?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to find eigenvalues and eigenvector in python without Numpy but I don't know how to calculate det(A-lemda*I) for finding eigenvalue.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":850,"Q_Id":64316637,"Users Score":0,"Answer":"If you really want to avoid using numpy.linalg (why? This must be some sort of a learning problem, surely), you can e.g. implement a variant of a qr algorithm: factorize A into the product of Q@R, multiply R@Q, repeat until convergence.\nHowever, if it's indeed a learning exercise, your best bet is to pick a textbook on numerical linear algebra.\nAnd if it is not, then keep in mind that you are very unlikely to outperform (in any definition of performance) the tried-and-tested lapack routines that numpy.linalg wraps.","Q_Score":0,"Tags":"python,numpy,matrix,scipy,linear-algebra","A_Id":64326240,"CreationDate":"2020-10-12T11:06:00.000","Title":"How to find eigenvalues and eigenvector in python without Numpy library?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to generate 50 random coordinates in an unit square such that each point has minimum Euclidian distance of 0.1 from other points. How can I generate such in python? Actually I need to know how to put condition in random number. But I could not find any way. One way I was using if command with that condition in it. But I need to generate 50 such points. Thanks for any help.","AnswerCount":3,"Available Count":2,"Score":0.2605204458,"is_accepted":false,"ViewCount":531,"Q_Id":64319946,"Users Score":4,"Answer":"A cheap solution would be to keep generating random points in the square. If the generated point is not too close to the other points, then keep it, otherwise throw it away. Once you've reached 50 points, you can stop generating random points.","Q_Score":1,"Tags":"python","A_Id":64320161,"CreationDate":"2020-10-12T14:35:00.000","Title":"generate 50 points with minimum distance between them is 0.1","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to generate 50 random coordinates in an unit square such that each point has minimum Euclidian distance of 0.1 from other points. How can I generate such in python? Actually I need to know how to put condition in random number. But I could not find any way. One way I was using if command with that condition in it. But I need to generate 50 such points. Thanks for any help.","AnswerCount":3,"Available Count":2,"Score":0.1325487884,"is_accepted":false,"ViewCount":531,"Q_Id":64319946,"Users Score":2,"Answer":"you could pick 50 points from the regular grid (0.1*i, 0.1*j) for i=0..10 and j=0..10","Q_Score":1,"Tags":"python","A_Id":64320254,"CreationDate":"2020-10-12T14:35:00.000","Title":"generate 50 points with minimum distance between them is 0.1","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"In OpenCV with Python, when the fps of the webcam and a video file in the directory are same, why does the video file play in fast forward whereas the webcam continues to show the frames at a normal rate? What role does the cv2.waitKey() function play here","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":87,"Q_Id":64322569,"Users Score":2,"Answer":"The fps of a video file means how it was encrypted, how many frames contain within a second as the name reveals. For example, if extracted 1 second of this video will produce only that number of frames (images).\nThe corresponding fps of the web camera means how many frames that camera can capture in a second. If saved to a video file that would mean how many frames are contained within each 1-second span.\nThere is a third (probably hidden to you) concept here though. How fast the opencv can read a video file. Normally, and for typical resolutions on a modern computer this fps is larger than the actual video. So, your computer seem to playback the video in fast forward mode because it reads (and displays) frames in a faster pace than the video file's fps.\nTheoretically, you can calculate the delay you should import to the video playback to force it to displayed with normal pace. I am not sure how easily you can accomplish that (in a scientific way and not trial and error mode).\nHope this clarifies the issue.","Q_Score":0,"Tags":"python,opencv,webcam,frame-rate","A_Id":64323662,"CreationDate":"2020-10-12T17:26:00.000","Title":"Why opencv video reading fps is not same with video encrypted fps?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I just installed alpha_vantage using pip and tried it on IDLE but I'm more used to working on Spyder so when I tried importing it there, I got the No module named 'alpha_vantage'.\nI thought the problem was that i used pip instead of conda but when I tried 'conda install alpha_vantage' I got a PackagesNotFoundError: The following packages are not available from current channels: alpha_vantage","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":634,"Q_Id":64324018,"Users Score":0,"Answer":"First all, to use conda you need: conda activate .\nTo know conda env name: conda env list\nWhen you stay in env conda : pip install alpha_vantage","Q_Score":0,"Tags":"python,pip,anaconda,spyder","A_Id":64324098,"CreationDate":"2020-10-12T19:12:00.000","Title":"I get a 'No module named 'alpha_vantage'' error when i try importing alpha_vantage on Spyder","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am new in the NLP community and need more light on something.\nI saw that Keras has an Embedding layer that is generally used before the LSTM layer. But what algorithm hides behind it? Is it Word2Vec, Glove or something else?\nMy task is a supervised text classification problem.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":128,"Q_Id":64331013,"Users Score":1,"Answer":"The embedding layer is a randomly initialized matrix, with the dimension of (number_of_words_in_vocab * embedding_dimension). The embedding_dimension is custom defined dimension, and an hyper-parmeter that we will have to choose.\nHere, the embeddings are updated during back-propagation, and are learnt from your task and task-specific corpus.\nHowever, pre-trained embeddings such as word2vec, glove are learnt in an unsupervised manner on huge corpus. Pre-trianed embeddings provides a good initialization for this embedding layer. Thus, you can use the pre-trained embeddings to initialize this embedding layer, and also choose if you want to freeze these emebeddings or update these embeddings during the back-propagation.","Q_Score":0,"Tags":"python,keras,nlp,embedding","A_Id":64331286,"CreationDate":"2020-10-13T07:58:00.000","Title":"Word Embedding for text classification","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to set some values in one column (col_2) coming from another column (col_3) when values in col_1 fulfill a condition.\nI'm doing that with the .loc operator as after all my research looking for alternatives it looks as the best practice.\ndata.loc[data.col_1.isin(['A','B']),col_2]=data[col_3]\nNevertheless this stills trigger the 'SettingWithCopyWarning:'.\nIs there any other way to do this operation without raising that warning?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":19,"Q_Id":64331870,"Users Score":0,"Answer":"Following the advice of Cameron,the line of code was part of a function, where data was passed as argument.\nStarting the function with data = data.copy() solves the issue","Q_Score":0,"Tags":"python,pandas","A_Id":64332146,"CreationDate":"2020-10-13T08:53:00.000","Title":"Avoid 'SettingWithCopyWarning:' when setting values with loc and conditions (inside a function)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I just built a price prediction model with LSTM and the RMSE was approximately 0.12. The price range is from 0 to 3. Does it mean the model is accurate? Are there any other ways to measure LSTM's accuracy?\nThank you!","AnswerCount":3,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":3211,"Q_Id":64334704,"Users Score":0,"Answer":"It would be easier if you measure MAE instead of RMSE, as it is the L1 is a more \"natural metric\".\nIf you want to estimate how good is your model, you need to build baselines. You could check for example how does the error change it you predicted always the average, or if you predicted always the last available data point.\nThat said, once you compute that, you could calculate relative metrics, for example the MAE of your model divided by the MAE of one of those Benchmarks. This builds upon the idea of the MASE metric from Rob Hyndman. I recommend you to have a look at it.","Q_Score":0,"Tags":"python,lstm,metrics","A_Id":64335026,"CreationDate":"2020-10-13T11:51:00.000","Title":"About accuracy of LSTM","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I just built a price prediction model with LSTM and the RMSE was approximately 0.12. The price range is from 0 to 3. Does it mean the model is accurate? Are there any other ways to measure LSTM's accuracy?\nThank you!","AnswerCount":3,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":3211,"Q_Id":64334704,"Users Score":0,"Answer":"One 'easy' way to test whether this performance is good, is to calculate the RMSE of a naive forecast. A naive forecast is forecasting the value from the previous step.\nSo if your series has the values [0, .2, .8, 2.2, 1.1], then the next predicted value would be '1.1'.\nThe RMSE from your LSTM should be smaller than the RMSE from your naive forecast, but even a smaller RMSE is no guarantee that your model is good.","Q_Score":0,"Tags":"python,lstm,metrics","A_Id":64335094,"CreationDate":"2020-10-13T11:51:00.000","Title":"About accuracy of LSTM","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am new to OpenCV and I do not understand how to traverse and change all the pixels of black with colour code exact RGB(0,0,0) to white colour RGB(255,255,255).\nIs there any function or way to check all the pixel and if RGB(0,0,0) the make it to RGB(255,255,255).","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":6288,"Q_Id":64336516,"Users Score":0,"Answer":"Subtract 255 from each Pixel and get the positive values only\nFor grayscale and black and white images\nsub_array = 255*np.ones(28, dtype = int)\nimg_Invert = np.abs(np.subtract(img,sub_array))","Q_Score":1,"Tags":"python,opencv,colors,rgb","A_Id":71540957,"CreationDate":"2020-10-13T13:50:00.000","Title":"How to change all the black pixels to white (OpenCV)?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am creating a line chart on superset which is being plotted against some aggregates function and time column. I am getting null when at that specific time no event is there due to this I am getting broken charts. Is there a way to replace these nulls with 0?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":1051,"Q_Id":64347576,"Users Score":1,"Answer":"If you are on the chart explore, click on the 3 dots next to dataset name, and click on \"Edit Dataset\". Go into \"Calculated columns\" tab and in there click on \"Add item\". In the SQL field you can then define your condition that will be applied to the column. So you can write SQL like IF(my_column IS NULL, 0, my_column) and label for this calculated column. On your chart, use this calculated column then. You can use any SQL statement you need in the box (format transformation, CASE WHEN, IF, etc.)","Q_Score":0,"Tags":"python,apache-superset","A_Id":64449173,"CreationDate":"2020-10-14T06:12:00.000","Title":"Replace null with zero in superset","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm a beginner at Python, and I would like to read multiple csv file and when i encode them with encoding = \"ISO-8859-1\",I get this kind of characters in my csv file : \"D\u00c2\u00b0faut\". So I tried to encode in utf-8, I get this error : 'utf-8' codec can't decode byte 0xb0 in position 14: invalid start byte'.\nCan someone help me please ?\nThank you !","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":2112,"Q_Id":64355933,"Users Score":2,"Answer":"If you decode with utf-8 you should also encode with utf-8.\nDepending on the unicode character you want to display (basically everything except for basic latin letters, digits and the usual symbols) utf-8 needs multiple bytes to store it. Since the file is read byte by byte you need to know if the next character needs more than a byte. This is indicated by the most significant bit of the byte. 0xb0 translates to 1011 0000 in binary and as you can see, the first bit is a 1 and that tells the utf-8 decoder that it needs more bytes for the character to be read. Since you encoded with iso-8859-1 the following byte will be part of the current character and encoding fails.\nIf you want to encode the degree symbol (\u00b0), it would be encoded as 0xC2 0xB0.\nIn any case: Always encode with the same encoding as you want to decode. If you need characters outside the code page, use utf-8. In general using any of the utf encodings is a good advice.","Q_Score":0,"Tags":"python,python-3.x,utf-8,character-encoding,encode","A_Id":64356118,"CreationDate":"2020-10-14T14:49:00.000","Title":"Error : 'utf-8' codec can't decode byte 0xb0 in position 14: invalid start byte","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've developed a model which uses several large, 3-dimensional datasets on the order of (1e7, 10, 1e5), and makes millions of read (and thousands of write) calls on slices of those datasets. So far the best tool I've found for making these calls is numpy.memmap, which allows for minimal data to be held in RAM and allows for clean indexing and very fast recall of data directly on the hard drive.\nThe downside of numpy.memmmap seems to be that performance is pretty uneven - the time to read a slice of the array may vary by 2 orders of magnitude between calls. Furthermore, I'm using Dask to parallelize many of the model functions in the script.\nHow is the performance of Dask DataFrames for making millions of calls to a large dataset? Would swapping out memmaps for DataFrames substantially increase processing times?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":150,"Q_Id":64356376,"Users Score":1,"Answer":"You would need to use Dask Array not Dask Dataframe. The performance is generally the same as Numpy, because Numpy does the actual computation.\nOptimizations can speed up the calculation depending on the use case.\nThe overhead of the scheduler decreases performance. This is only applicable if you split the data into many partition and can usually be neglected.","Q_Score":0,"Tags":"python,numpy,dask","A_Id":64389636,"CreationDate":"2020-10-14T15:12:00.000","Title":"Dask DataFrames vs numpy.memmap performance","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a Database with 13 columns(both categorical and numerical). The 13th column is a categorical variable SalStat which classifies weather the person is below 50k or above 50k. I am using Logical Regression for this case and want to know which columns (numerical and categorical) are redundant that is, dont affect SalStat, so that I can remove them. What function should I use for this purpose?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":27,"Q_Id":64375681,"Users Score":0,"Answer":"In my opinion you can study the correlation between your variables and remove the ones that have high correlation since they in a way give the same amount of information to your model\nyou can start with something like DataFrame.corr() then draw a heatmap using seaborn for better visualization seaborn.heatmap() or a more simple one with plt.imshow(data.corr()) plt.colorbar();","Q_Score":0,"Tags":"python,classification,logistic-regression","A_Id":64375987,"CreationDate":"2020-10-15T16:15:00.000","Title":"Identification of redundant columns\/variables in a classification case study","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm toying with a problem modelled by a linear system, which can be written as a square block-tridiagonal matrix. These blocks are of size b = 4n+8, and the full matrix is of size Nb; N could be arbitrarily large (reasonably, of course) while n is kept rather small (typically less than 10).\nThe blocks themselves are sparse, the first diagonal being only identity matrices, and the second diagonals having only n+1 non-zero columns (so 3n+7 columns of zeroes) per block. These columns are contiguous, either zeroes then non-zeroes or the other way around.\nBuilding all these blocks in memory results in a 3N-2 x b x b array that can be turned into a sparse matrix with scipy.sparse.bsr_matrix, then cast to CSR format and trimmed of the excess zeroes. It works nicely but I'd rather skip this temporary large and sparse array (for N = 1e4, n = 5 it's 5.6 zeros for every relevant entry!) altogether.\n\nI had a look at scipy.sparse.dok_matrix, recommended for slicing and incremental building. Creating my entries fits in a tidy loop but the process is ~10 times longer than using bsr_matrix with my unnecessary dense array, which will be detrimental to the future use cases.\nIt doesn't seem like bsr_matrix can be used directly with scipy sparse matrices as input.\nUsing bsr_matrix without including the diagonal blocks, then adding a sparse eye greatly reduces the number of zeros (3.5 per relevant entry in my test configuration) and speeds up the process by a third compared to the original solution. Score!\n\nAny clue on things that I could do to further reduce the original imprint of this matrix? The obvious goal being to give me more freedom with the choice of N.\nEDIT\nI managed to improved things a tad more by constructing the three block-diagonals separately. By doing so, I need less padding for my 2nd diagonals (n+3 instead of 3n+7; 1.3 zeroes per relevant entry), dividing my original blocks into two vertical blocks (one full of zeroes) and I only need it one diagonal at a time, cutting the memory cost in half on top of that. The main diagonal remains constructed with the eye method. The icing on the cake: a speed up of 25% compared to my 3rd bullet point, probably because separating the two 2nd diagonals saves some array reshaping operations needed before using bsr_matrix. Compared to the original method, for my (N, n) = (1e4, 5) test case it's ~20M zeroes saved when comparing matrices before trimming. At 128 bits each, it's a decent gain already!\nThe only possible improvement that I can picture now is building these diagonals separately, without any padding, then inserting columns of zeros (probably via products with block-matrices of identities) and finally adding everything together.\nI also read something about using a dict to update an empty dok_matrix, but in my case I think I would need to expand lists of indices, take their Cartesian product to construct the keys and each element of my blocks would need to be an individual value as one apparently cannot use slices as dictionary keys.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":87,"Q_Id":64382589,"Users Score":0,"Answer":"I ended up implementing the solution I proposed in my last paragraph.\nFor each 2nd diagonal, I construct a block sparse matrix without any padding, then I transform it into a matrix of the proper shape by a right-hand side product with a block matrix whose blocks are identity. I do need to store zeroes here to use bsr_matrix (I first gave a try to the method scipy.sparse.block_diag, but it was extremely slow), but less of them compared to my semi-padding solution: (4n+7)(n+1) vs (4n+8)(n+3); and they can be represented with 8 bits instead of 128. Execution time is increased by ~40% but I can live with that (and it's still a decrease of 20% compared to the first solution).\nI might be missing something here, but for now I'm pretty satisfied with this solution.\nEDIT\nWhen trimming the zeroes of the RHS matrices before effecting the product, the execution time is reduced by 30% compared to the previously most efficient solution; all's well that ends well.","Q_Score":0,"Tags":"python,scipy,linear-algebra","A_Id":64436772,"CreationDate":"2020-10-16T03:37:00.000","Title":"How to avoid inserting unnecessary zeroes in a scipy sparse matrix","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a square region of size [a, a] containing real number coordinates. I want to fill it with with N random points. The conditions is that the distance between any two points has to be greater than a minimum distance D.\nThe brute force way is to keep generating a random point until it meets the condition. But, to check the condition with all other points is kinda expensive. Is there a better algorithm to do this?","AnswerCount":2,"Available Count":1,"Score":0.2913126125,"is_accepted":false,"ViewCount":166,"Q_Id":64394133,"Users Score":3,"Answer":"If you had some grid overlay on top of the points, you could generate a circle whose radius is the minimum distance around each point, and flag each grid cell that's in those circles. Then, randomly pick a non-flagged grid cell to generate a point at, then repeat until there's no spaces left.","Q_Score":0,"Tags":"python,2d,coordinates","A_Id":64394236,"CreationDate":"2020-10-16T17:56:00.000","Title":"put random points in a square region while maintaining a minimum distance (Python)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Can we open a fdb file with pandas or numpy without invoking the database authentications? Or can we just use fdb to connect and then read the file?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":446,"Q_Id":64401270,"Users Score":0,"Answer":"Firebird is a full-fledged database management system, and requires authentication to access the database. On Windows (any Firebird version) and Linux (Firebird 3 or higher) this can be circumvented by using Firebird Embedded instead of Firebird Server. You will still need to specify a user name, but the password is then ignored.\nHowever, doing this may require additional configuration to ensure that the client library doesn't try to connect through a Firebird Server running on the same system. Unless you have a good reason, I would recommend just to accept that you have to authenticate.","Q_Score":0,"Tags":"python,pandas,firebird","A_Id":64401707,"CreationDate":"2020-10-17T10:07:00.000","Title":"Reading a FDB file without invoking database authentication with pandas","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I had some strings in my dataframe (female x male, region and so on) and I wanted to fit a decision tree. Therefore, I applied one hot encoder in all these categorical features - which returned a bunch of new columns with 0 and 1.\nHowever, the the default of features' threshold in decision tree are 0.5. That doesn't make sense for these categorical columns.\nDoes someone know how I can change the threshold for lots of columns at once (without having to input the name of each column) in python?\nI want something like: column female split in 0 and 1. I want to do all these before calculating statistics (AUC, ROC, ACC, etc).\nps: I also have some numerical data (income, for example), so I can't change the threshold for all the columns\nps2: The categorical 1 and 0 are in columns 6 to 30.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":184,"Q_Id":64404487,"Users Score":0,"Answer":"Well, a threshold of 0.5 for a binary feature does make sense.\nIt just means that when the feature takes a value > 0.5 (which is thus 1) then the split is made to (say) the right, and of the feature takes a value < 0.5 (i.e. 0) the decision tree takes the other path (left).\nThere is no sense in changing the threshold value: any value between 0 and 1 has the same effect as 0.5 and values lower than 0 or larger than 1 mean that no split is done and all observations go to the same child node.","Q_Score":0,"Tags":"python,python-3.x,data-science,decision-tree","A_Id":64452578,"CreationDate":"2020-10-17T16:05:00.000","Title":"How to change features threshold of decision trees after applying one hot encoder?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I recently had a problem with Tensorflow installing but I solved it by creating a virtual environment in anaconda navigator. I get a warning saying\n\n2020-10-17 13:44:04.120482: W tensorflow\/stream_executor\/platform\/default\/dso_loader.cc:55] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found\n2020-10-17 13:44:04.120745: I tensorflow\/stream_executor\/cuda\/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.\n\nThe thing is that I have a GPU on my laptop(T2000). How do I fix this?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":547,"Q_Id":64405547,"Users Score":0,"Answer":"did you install tensorflow with pip? If you did uninstall it and install tensorflow using conda. Conda automatically installs cudnn 7.6.5 and CUDA Toolkit 10.1.243 and tensorflow 2.1.0. If you want tensorflow 2.2 first install 2.1.0 as described. Then use pip to install 2.2 with pip install tensorflow ==2.2.0. 2.2 is compatible with the toolkit and cudnn versions installed with 2.1. Conda can only install tensorflow up to version 2.1.0. Install whatever other packages you need using either pip or conda.","Q_Score":0,"Tags":"python,tensorflow,pycharm","A_Id":64407212,"CreationDate":"2020-10-17T17:49:00.000","Title":"Warning for GPU in tensorflow pycharm","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I keep getting the below error when trying to import numpy in kivy on an android device.\nNo module named 'numpy.core._multiarray_umath'\nWhy am I getting this error if I already installed numpy where the main.py file is located and I also\nmade sure the file it is trying to import (_multiarray_umath) is located in the numpy library before building with buildozer, that is ->\n_multiarray_umath.cpython-36m-x86_64-linux-gnu.so located in numpy\/core?\nThanks in advance.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":236,"Q_Id":64408261,"Users Score":1,"Answer":"The file you talk about is a desktop linux binary, not compatible with your android device. That is why it didn't work on android and (per the comments) the fix was to put numpy in the requirements so that an android version was built and included by buildozer.\n\nListing numpy in the buildozer.spec file fixed the error, but I can't seem to get tensorflow to compile in kivy for android. Does tensorflow not work in kivy on android?\n\nTensorflow is not currently supported. Apparently tensorflow lite works, but you need to include it via gradle and write some java wrapper code to access it.","Q_Score":0,"Tags":"python,numpy,kivy","A_Id":64412950,"CreationDate":"2020-10-17T23:19:00.000","Title":"No module named 'numpy.core._multiarray_umath' in kivy","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":1,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"When trying to run a program on JupyterLab within an OpenVino environment on my Raspberry Pi 4, I get the following error when I try to import Tensorflow:\n\nImportError: cannot import name 'context' from 'tensorflow.python.eager' (unknown location)\n\nThis program was having no issue importing anything just the other day, so I don't know what went wrong, nor how to remedy this issue.\nOther pertinent information is that I'm running Python 3.7 and Tensorflow 2.3\nAny help with this is appreciated.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":342,"Q_Id":64408396,"Users Score":0,"Answer":"Well I ended up resolving this issue. Turns out it was due to an issue in the cloning process. Created a new backup and restored from this new backup and the error went away.\nThanks for the help everyone.","Q_Score":2,"Tags":"python,tensorflow,raspberry-pi,jupyter-lab,openvino","A_Id":64419292,"CreationDate":"2020-10-17T23:46:00.000","Title":"Tensorflow ImportError (Unknown Location)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a Numpy array for 3d points in the format (n, 3), where n is the number of points, and column 1 is the x coordinate, column 2, is the y coordinate, and column 3 is the z coordinate. How do I get all the point in the outer bounding box, but not in a inner bounding box?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":334,"Q_Id":64409900,"Users Score":0,"Answer":"How are the orientations of both boxes? Are the axis parallel to x, y, z?\nIn this case it is not so difficult.\n\nFind out if the point is in the x, y, z range of the outher box\nif yes: do the same test for the inner box\n\nJust let me know when you need the code","Q_Score":0,"Tags":"python,python-3.x,numpy,point-clouds,bounding-box","A_Id":64410315,"CreationDate":"2020-10-18T05:03:00.000","Title":"How do I get all 3d points in a numpy array that are not within a inner bounding box, but between the outer bounding box?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Given many patches that are taken from an image, the task is creating a single image that is composed of the patches.\nI have tried the naive solution:\n\nfor every 2 images, go over many patches and compare.\nIf they are similar above some confidence threshold, create a new image of the 2.\nAdd the new image to the pool and remove the other 2.\nrepeat until the pool is of size 1.\n\nThe problem is that this solution is very slow, and the main bottleneck is the patch comparing.\nIs there a better way of doing that which is faster?\nMaybe a better patch selection and comparison method?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":302,"Q_Id":64410913,"Users Score":1,"Answer":"I would try:\n\nmake ordered list of all feature points from all images once.\nso create a list where hash of feature or the feature alone is stored, and also info from which image it was taken and maybe even position. Then sort this list by the hash (or on the fly).\nas a feature select what ever you use for comparing images now. As you have no scaling or rotation you do not need scale and rotation invariant features however if you use those it would not hurt. I usually chose pixels which are local maximum or minimum of intensity. And then compute histogram of pixels up to some constant distance from it (which is invariant on rotation) Then hash the histogram...\n\ngo through the list\n\ncheck if one hash is in the list more than once but from different images\nin ordered list they would be grouped together\n\nif yes compare\/merge those images to which the features belong\nalso update feature list so just change image id in the list to the new merged one.\n\n\nIf I see it right You current approach is O(m*n^2) and this would be O((n*m)*log(n*m)) where n is number of images and m is avg number of features per image.","Q_Score":3,"Tags":"python,algorithm,opencv,image-processing,processing-efficiency","A_Id":64423059,"CreationDate":"2020-10-18T07:44:00.000","Title":"Merging overlapping images into a single image by correctly positioning the patches one on the other","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have extracted few rows from a dataframe to a new dataframe. In this new dataframe old indices remain. However, when i want to specify range from this new dataframe i used it like new indices, starting from zero. Why did it work? Whenever I try to use the old indices it gives an error.\ngermany_cases = virus_df_2[virus_df_2['location'] == 'Germany']\ngermany_cases = germany_cases.iloc[:190]\nThis is the code. The rows that I extracted from the dataframe virus_df_2 have indices between 16100 and 16590. I wanted to take the first 190 rows. in the second line of code i used iloc[:190] and it worked. However, when i tried to use iloc[16100:16290] it gave an error. What could be the reason?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":20,"Q_Id":64411400,"Users Score":0,"Answer":"In pandas there are two attributes, loc and iloc.\nThe iloc is, as you have noticed, an indexing based on the order of the rows in memory, so there you can reference the nth line using iloc[n].\nIn order to reference rows using the pandas indexing, which can be manually altered and can not only be integers but also strings or other objects that are hashable (have the __hash__ method defined), you should use loc attribute.\nIn your case, iloc raises an error because you are trying to access a range that is outside the region defined by your dataframe. You can try loc instead and it will be ok.\nAt first it will be hard to grasp the indexing notation, but it can be very helpful in some circumstances, like for example sorting or performing grouping operations.","Q_Score":0,"Tags":"python,matplotlib","A_Id":64411551,"CreationDate":"2020-10-18T08:48:00.000","Title":"Does iloc use the indices or the place of the row","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"The question is just like normal counting inversion question, but instead of a list of single numbers, now the input is a list of (x,y) pair.\nFor a list of pairs [(x1,y1),(x2,y2),(x3,y3),...,(xn,yn)], a pair (i,j) is a inversion iff i < j and xi>xj, yi>yj. Is it possible to write the algorithm in O(nlognlogn)? I tried several ways but during the merge step, each element from the right half of list has to compare with all elements in the left one, resulting in a time complexity of n square.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":65,"Q_Id":64414421,"Users Score":0,"Answer":"Split the list into two halves, left and right based on the x coordinate. Then, compare the lowest point of the two halves (based on their y coordinate). There are two cases:\n\nThe left point is lower than the right point, then the left point has xiyj condition hold true for any point to its left.\nAfter updating you answer according to these 2 cases, you can remove one of these two points and continue working on the remaining sorted lists (by recursively solving for left and right as well). This should work in O(nlog^2n)","Q_Score":0,"Tags":"python,inversion","A_Id":64421460,"CreationDate":"2020-10-18T14:24:00.000","Title":"Counting inversions of 2D pair (x,y) in a list","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a problem I'm not sure how to tackle.\nI currently am trying to run a program with JupyterLab on my Raspberry Pi 4, but when trying to load a Tensorflow Model, I get the following warning in the terminal:\n\nAllocation of 360087552 exceeds 10% of free system memory\n\nNow, this is confounding to me. The model it's trying to load is only about 900mb. The Raspberry Pi model I have has 8gb of RAM, same as my laptop. It's using a 64gb SD card with 42.8gb free space (more than my laptop). Yet, despite having the same amount of RAM and more free space than my laptop (which runs everything without issue), it is unable to load the model, and the kernel crashes.\nI've already done everything I could think of to free up memory, including Expanding the Filesystem and increasing the Memory Split to 256 in the raspi-config, and increasing the CONF_SWAPSIZE to 1024.\nSo, is there anything further I can do to try to resolve this issue, or is this merely a limitation of the Raspberry Pi 4, and should I look into alternative and more powerful single board computers?\nThanks for the help,\nSam","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":255,"Q_Id":64419381,"Users Score":0,"Answer":"My suspicion is that you're using the 32 bit os with pae, that only allows 3gb per process. The allocation given would exceed that. Did you try with the 64 bit os?","Q_Score":0,"Tags":"python,tensorflow,memory,jupyter-notebook,raspberry-pi","A_Id":65441844,"CreationDate":"2020-10-18T23:38:00.000","Title":"Raspberry Pi 4 - 8gb RAM, 64gb SD Card Running Out of Memory Trying to Load Tensorflow Model","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm just starting with Python - but have over 60 years experience in other programming languages, which may be part of the problem. Clearly there's something fundamental about Python that I don't seem to be getting.\nUsing Numpy and Pandas. I just read in a 2 x 4 CSV file. Now I want to iterate through the array modifying the first column of every row. I checked the size with size=np.shape(InputArray)\nwhen I try to access the 1st element of \"size\" with n=size(0) I get an error 'tuple\" object is not callable\nSimilarly if I try to access the input array by indexing into it ie x=InputArray(1,m)\n. Clearly I'm missing something very basic here.\nBy the way, the 2 x 4 array is just a test. The actual array I need to process is vastly bigger\nThanks much ie x=InputArray(0,1)","AnswerCount":2,"Available Count":2,"Score":0.0996679946,"is_accepted":false,"ViewCount":141,"Q_Id":64419958,"Users Score":1,"Answer":"[] bracket is used to access element of an array in python. But here you are using (), that's why you are getting error as 'tuple' object is not collable.\nTo access 1st element of array named size, you should use size[0].","Q_Score":0,"Tags":"python,pandas,numpy","A_Id":64420071,"CreationDate":"2020-10-19T01:21:00.000","Title":"How do I index through an array I've read from a .csv file","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm just starting with Python - but have over 60 years experience in other programming languages, which may be part of the problem. Clearly there's something fundamental about Python that I don't seem to be getting.\nUsing Numpy and Pandas. I just read in a 2 x 4 CSV file. Now I want to iterate through the array modifying the first column of every row. I checked the size with size=np.shape(InputArray)\nwhen I try to access the 1st element of \"size\" with n=size(0) I get an error 'tuple\" object is not callable\nSimilarly if I try to access the input array by indexing into it ie x=InputArray(1,m)\n. Clearly I'm missing something very basic here.\nBy the way, the 2 x 4 array is just a test. The actual array I need to process is vastly bigger\nThanks much ie x=InputArray(0,1)","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":141,"Q_Id":64419958,"Users Score":0,"Answer":"Thanks for the response. I think I finally found the solution to the problem I was having accessing the actual array (the suggested answer worked for \"Size\" but not to index the array proper.) I found that instead of trying to index (for example) ABC, the variable into which I read the file I have to access it as ABC.iloc(index1, index 2) which I think is how I pass the indices to what is effectively a function (iloc) that maps the indices to the physical structure of the actual object.\nMy experience was with ancient languages like Fortran and PL\/1 as well as machine language - not to mention plugboard wiring. It was a long time ago. Things have changed.","Q_Score":0,"Tags":"python,pandas,numpy","A_Id":64437641,"CreationDate":"2020-10-19T01:21:00.000","Title":"How do I index through an array I've read from a .csv file","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I used to use Tensorflow a lot before, but moved over to Pytorch because it was just a lot easier to debug. The nice thing I found with PyTorch is that I have to write my own training loop, so I can step through the code and find errors. I can fire up pdb and check the tensor shapes and transformations, etc., without difficulty.\nIn Tensorflow I was using the model.fit() function all the time, and so any error message I got was like 6 pages of C code where the error message did not give me any indication was in the python code. User's can't step through the model.fit() function since it is a static graph, so that really slowed down my development process. BUT, I was thinking about using Tensorflow again and I was wondering whether a user can step through a custom training loop and look at tensor shapes, etc., or whether even a custom training loop is compiled to a static graph and hence users cannot step through it?\nI did google this question, but all of the tutorials for custom training loops in Tensorflow focus on custom loops being for advanced users, such as if you want to apply some exotic callback while training or if you want to apply some conditional logic. So the simple question of whether it is easy to step through a custom training loop is not answered.\nAny help is appreciated. Thanks.","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":655,"Q_Id":64448607,"Users Score":0,"Answer":"Tensorflow uses eager execution, it means your graph is connected dynamically. Offcourse it\u2019s not as dynamic as PyTorch. But, google is trying its best and incorporated a lot of features in 2.0 and beyond.\nFor writing a custom loop in Tensorflow you need to use tf.GradientTape. I would say it involves the same steps as in pytorch. Compute gradients and then update using optimizer.","Q_Score":0,"Tags":"python,tensorflow,machine-learning,keras,deep-learning","A_Id":64451282,"CreationDate":"2020-10-20T15:39:00.000","Title":"Tensorflow 2.0: How can I fully customize a Tensorflow training loop like I can with PyTorch?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to find a way to bulk load a csv file into postgresql. However, the data has datetime column with the format of \"YYYY-MM-DD HH24:MI:SS\". I couldn't find any documentation on how to bulk load date column using psycopg2 package in python 3.x. Can I get some help on this? Thanks in advance.\nI am able to load the data using the below code:\ncur.copy_from(dataIterator,'cmodm.patient_visit',sep=chr(31),size=8192,null='') conn.commit()\nHowever, only the date part got loaded in the table. The time part was initialized:\n2017-04-13 00:00:00 2017-04-13 00:00:00 2017-04-12 00:00:00","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":485,"Q_Id":64461078,"Users Score":1,"Answer":"After discussing with @Belayer, it was concluded that copy_from takes the timestamp input value in the format 'YYYY-MM-DD HH:MI:SS'. If the source has some other format, then that needs to be converted to the desired format mentioned before in this response before feeding it into copy_from.","Q_Score":1,"Tags":"python-3.x,postgresql","A_Id":64595337,"CreationDate":"2020-10-21T09:56:00.000","Title":"How to load csv with datetime into postgresql using copy_from","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I tried to build a docker container with python and the tensorflow-gpu package for a ppc64le machine. I installed miniconda3 in the docker container and used the IBM repository to install all the necessary packages. To my surprise the resulting docker container was twice as big (7GB) as its amd64 counterpart (3.8GB).\nI think the reason is, that the packages from the IBM repository are bloating the installation. I did some research and found two files libtensorflow.so and libtensorflow_cc.so in the tensorflow_core directory. Both of theses files are about 900MB in size and they are not installed in the amd64 container.\nIt seems these two files are the API-files for programming with C and C++. So my question is: If I am planning on only using python in this container, can I just delete these two files or do they serve another purpose in the ppc64le installation of tensorflow?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":256,"Q_Id":64465852,"Users Score":2,"Answer":"Yes. Those are added as there were many requests for it and it's a pain to cobble together the libraries and headers yourself for an already built TF .whl.\nThey can be removed if you'd rather have the disk space.\nWhat is the content of your \"amd64 container\"? Just a pip install tensorflow?","Q_Score":1,"Tags":"python,docker,tensorflow,conda,powerpc","A_Id":64482752,"CreationDate":"2020-10-21T14:31:00.000","Title":"Tensorflow on IBM Power9 ppc64le - Can libtensorflow.so be deleted?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":1,"Web Development":0},{"Question":"Although my csv wasn't that large, it gave this error when i tried to read it:\nCParserError: Error tokenizing data. C error: Buffer overflow caught - possible malformed input file.\nIt gave this error when i used df = pd.read_csv(path).\nThen I changed the code into df = pd.read_csv(path,engine='python'), and it perfectly worked.\nWhat could be the reason for that?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":44,"Q_Id":64468818,"Users Score":0,"Answer":"As far as i know the cause was that there were some carriage returns in the data and pandas was using as a line terminator as if it was a newline. You can try with also lineterminator='\\n' keyword.","Q_Score":0,"Tags":"python,pandas,data-science","A_Id":64468878,"CreationDate":"2020-10-21T17:34:00.000","Title":"Errorin reading a CSV file","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to know if the order of features on array interferes on training model and validation scores.\nFor exemple if I had this list of features to train my model:\n[\"close\", \"close_returns\", \"log_returns\", \"open\", \"open_returns\", \"open_log_returns\"]\nIf I invert de order like:\n[\"close\", \"open\",\"log_returns\", \"close_returns\", \"open_log_returns\", \"open_returns\"]\nThis make any difference on predicted model? Or the sort order dosent interfere?\nIf the order interfere. How I can know what the beast order?\nAnd how I can know if determinate feature is relevant or not for my lstm model on Keras?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":352,"Q_Id":64469283,"Users Score":0,"Answer":"The order of the features does not make much of a difference as you will have a separate output node for each feature.\nWhat matters is the order of the events (the rows). This is the sequence you will be modelling and predicting with the model. To determine which features to use you must know what you are modelling. Putting all of them in will give you predictions for all the columns but will also probably make the model harder to train and optimize.\nSo you should think about which of the features you actually need to include in the model. For example, can you infer feature A from feature B? If so, feature A does not need to be included as its easy to calculate.\nWhat about features that do not add much information such as columns that do not change very often. Are they necessary?","Q_Score":0,"Tags":"python,tensorflow,keras,lstm,predict","A_Id":64557838,"CreationDate":"2020-10-21T18:05:00.000","Title":"Python Keras LSTM Features order relevance","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am new to dask,\nCan anyone help me how to embed Dask's dashboard plots,Dask Graph directly into JupyterLab panes. without\nDask JupyterLab Extension ??","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":50,"Q_Id":64475766,"Users Score":1,"Answer":"I strongly recommend using the Dask JupyterLab extension.\nIf you want to make it yourself then you will need to make new iframes in JLab panes, and use the \/individual-* pages hosted by the Dask scheduler dashboard.","Q_Score":1,"Tags":"python,python-3.x,dask,dask-distributed","A_Id":64669945,"CreationDate":"2020-10-22T05:21:00.000","Title":"How to embed Dask's dashboard plots directly into JupyterLab panes","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have deeplabv3 frozen graph. There are some tensors in this graph. for example\nImageTensor => (,)\nSqueeze => (,)\nI want to change the dtype from uit8 to float32 and save the modified graph. How I can do this?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":43,"Q_Id":64478142,"Users Score":0,"Answer":"I do not know exactly how your deeplabv3 graph works, but if you just want to convert a tensor to a different type, you can use tf.cast().","Q_Score":0,"Tags":"python,tensorflow,machine-learning,deep-learning","A_Id":64482324,"CreationDate":"2020-10-22T08:22:00.000","Title":"Change datatype of tensors from checkpoint or frozen graph","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have been trying to import a large scale data from csv to Postgres after every 10mins.\nWith the help of celery I have scheduled few jobs parallelly.\nNo. of rows in csv are not matching after import into postgres.\nI've been writing CSVs into db with df.to_sql() method and it is not throwing any error but still some rows are missing in DB.\nAccording to my observance the increasing size of table is leading to missing rows.\nIs it Postgres limit?\nor is it the overlapping schedule of jobs which is causing locks or anything?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":39,"Q_Id":64495324,"Users Score":0,"Answer":"In one of the columns of my CSV file I had data in this format:\n\n\"abc, xyz\"\n\nSo, using quotechar='\"' helped me to fix my issue.\nThank you all for your ideas and suggestions.","Q_Score":0,"Tags":"python-3.x,postgresql,import,django-celery","A_Id":65558585,"CreationDate":"2020-10-23T06:58:00.000","Title":"import from CSV to Postgres is missing some rows in python","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have trained a model for image segmentation task on 320x240x3 resolution images using tensorflow 2.x. I am wondering if there is a way to use the same model or tweak the model to make it work on different resolutions?\nI have to use a model trained on a 320x240 resolution for Full HD (1920x1080) and SD(1280x720) images but as the GPU Memory is not sufficient to train the model at the specified resolutions with my architecture, I have trained it on 320x240 images.\nI am looking for a scalable solution that works at all the resolutions. Any Suggestions?","AnswerCount":2,"Available Count":2,"Score":1.2,"is_accepted":true,"ViewCount":236,"Q_Id":64495805,"Users Score":2,"Answer":"The answer to your question is no: you cannot use a model trained at a particular resolution to be used at different resolution; in essence, this is why we train the models at different resolutions, to check the performance and possibly improve it.\nThe suggestion below omits one crucial aspect: that, depending on the task at hand, increasing the resolution can considerably improve the results in object detection and image segmentation, particularly if you have small objects.\nThe only solution for your problem, considering the GPU memory constraint, is to try to split the initial image into smaller parts (or maybe tiles) and train per part(say 320x240) and then reconstruct the initial image; otherwise, there is no other solution than to increase the GPU memory in order to train at higher resolutions.\nPS: I understood your question after reading it a couple of times; I suggest that you modify a little bit the details w.r.t the resolution.","Q_Score":0,"Tags":"python-3.x,tensorflow,deep-learning","A_Id":64497096,"CreationDate":"2020-10-23T07:34:00.000","Title":"How to use a trained deeplearning model at different resolutions?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have trained a model for image segmentation task on 320x240x3 resolution images using tensorflow 2.x. I am wondering if there is a way to use the same model or tweak the model to make it work on different resolutions?\nI have to use a model trained on a 320x240 resolution for Full HD (1920x1080) and SD(1280x720) images but as the GPU Memory is not sufficient to train the model at the specified resolutions with my architecture, I have trained it on 320x240 images.\nI am looking for a scalable solution that works at all the resolutions. Any Suggestions?","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":236,"Q_Id":64495805,"Users Score":0,"Answer":"YEAH, you can do it in high resolution image. But the small resolution is easy to train and it is easy for the model to find the features of the image. Training in small resolution models saves your time and makes your model faster since it has the less number of parameters. HD images contains large amount of pixels, so if you train your model in higher resolution images, it makes your training and model slower as it contains large number of parameters due to the presence of higher number of pixels and it makes difficult for your model to find features in the high resolution image. So, mostly your are advisable to use lower resolution instead of higher resolution.","Q_Score":0,"Tags":"python-3.x,tensorflow,deep-learning","A_Id":64496798,"CreationDate":"2020-10-23T07:34:00.000","Title":"How to use a trained deeplearning model at different resolutions?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I just installed Spyder (Python 3.8) and in the Anaconda Prompt, i installed OpenCV, however while running the following statements:\nimport cv2\nface_cascade = cv2.CascadeClassifier('haarcascade_frontalcatface.xml') \nI receive as error: module 'cv2' has no attribute 'CascadeClassifier'.\nLet me tell you that i've already downloaded 'haarcascade_frontalcatface.xml' file.\nPlease help me to fix this problem.\nThank you!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":510,"Q_Id":64513148,"Users Score":0,"Answer":"Strange. Did you install the latest version of OpenCV or the version which actually contains the implementation of this CascadeClassifier?\nMaybe, you could try running conda update opencv and see if it resolves the problem or not.","Q_Score":2,"Tags":"python,opencv,deep-learning,anaconda,spyder","A_Id":64513263,"CreationDate":"2020-10-24T12:06:00.000","Title":"How to fix 'cv2' has no attribute 'CascadeClassifier'?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm training a DL model in Tensorflow 2.1. I prepared a training set of several greyscale (1-channel) images.\nI have seen that it is recommended to normalize the training set by dividing it by 255.0, so that the values are inside the range [0-1]. So I have some questions regarding it:\n\nWhy is this normalization recomended?\nMy target masks contain values from 0-1 and are float 64. Is it valid to use this data type?\nFinally, Should I normalize the images that I use for future predictions as well, or can I just leave them as 8-bit images (0-255).","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":36,"Q_Id":64513779,"Users Score":1,"Answer":"The normalization is recommended as it was empirically observed that\nthe network converges faster and to better global optima when all\nthe pixel values lie between (0 and 1) rather than 0 and 255.0. You\ncan try to see how the network behaves when you train with the\nvalues between 0 and 1.0 and 0 and 255.0.\n\nThe mask value does not need to be converted, leave it as it is(presuming you are doing image segmentation), just ensure the labels are correct.\n\nYes, the same preprocessing that is applied during the training must be applied during the testing scenario\/future predictions, otherwise your model will not work.","Q_Score":0,"Tags":"python,tensorflow,deep-learning","A_Id":64513912,"CreationDate":"2020-10-24T13:25:00.000","Title":"Re-Scale Training Set","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to upload a txt file which contains data as below . I have around 1M records in the file .\nData consist of different fields (which is to be columns ) in which I have manually added a comma as a delimiter.\nThe challenge is all the records does not have the same set of fields.\nThe columns should be \"Time\" , \"ENTER\" , \"TRANSID\" , \"SUPERCODE\" ,\"ID\", \"MRP\",\"VOLUME\",\"VALUE\",\"PRODUCTtype\",\"BUILDING\",\"TAXNUM\", \"TAGFIELDS\"\n\n00:00:00.000:, ENTER, transId=1, Supercode=BD3G, id=1, MRP=0.12s9,\nvolume=110333, value=20942463.27, productype=se IA CF, building=11430,\ntaxnumber=110F1, tagFields={B=C C=NZd3\/1 D=\"20170514 07:41:53.616\"\nF=:00000017PouM H=LMT O=6521B841:00023662-A-15.1sd01.200.0.50dsd03.0.0\nR=\"Order not Added\" a=A c=FIRST3eNZA j=N}\n00:00:00.000:, ENTER,transId=2,Supercode=BYG, id=2, MRP=0.195,\nvolume=223000, value=43485,> productype=se IA CF, building=110,\ntaxnumber=110I1, tagFields={B=C> C=NZ3 D=\"20170514 07:41:25.161\"\nF=:00000017PouK H=LMT> O=6521B841:00023625-A-15.101.200.0.5003.0.0\nR=\"Ordernot Added\" a=A> c=FIRSTNZA j=N}\n\n\n#For this record, there is no taxnumber , so the TAXnumber column field should be blank\/Nan for this record\n00:00:00.000:, ENTER, transId=3, Supercode=TBC, id=3,MRP=2.71,\nvolume=3750, value=10162.5, productype=It CF UeCP,> building=110,\ntagFields={B=C C=4331K D=\"20170514 > 13:59:51.288\"\nH=LMT K=12345O=6521B841:0027d59B6-B-15.101.200.0.5009.0.0 R=\"Order\nnotAdded\" a=P c=4sd33E> j=N}\n\n#For this record, there is no building number , so the building number column field should be blank\/Nan for this record\n\n00:00:00.000:, ENTER, transId=4, Supercode=ABT, id=4, MRP=2.73,>\nvolume=357, value=974.61, productype=se IrA CtF,\ntaxnumber=110B1, tagFields={B=C C=ZBJF D=\"20170929 16:10:01.321\" H=LT\nO=6521B5841:003A98565-A-15.101.2050.0.5009.0.0 R=\"Order not Added\" a=A\nc=BNPLLCOLO j=Y}\n\nI have tried the below steps:\n\ndata = pd.read_csv(\"path.txt\",delimiter=\",\",header=None)\n\nI have got the output\n\nParserError: Error tokenizing data. C error: Expected 10 fields in\nline 66017, saw 11","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":139,"Q_Id":64520774,"Users Score":0,"Answer":"try using engine='python' and error_bad_lines=False in your pd.read_csv()","Q_Score":0,"Tags":"python,pandas,dataframe,text,python-import","A_Id":64521013,"CreationDate":"2020-10-25T05:54:00.000","Title":"How to upload a .txt file in python dataframe","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to merge two data frames using the merge function in pandas. When I want to do so on a common column, jupyter notebook gives me the following error \"The kernel appears to have died. It will restart automatically.\" each data frame is about 50k rows. But when I try the same thing with only 50 rows from each data frame it works fine. I was wondering if anyone has a suggestion.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":699,"Q_Id":64543392,"Users Score":1,"Answer":"This is most likely a ram\/memory issue with your machine. check the ram that you have and monitor it while you do the merge operation.","Q_Score":0,"Tags":"python,pandas,dataframe,merge,jupyter-notebook","A_Id":64544268,"CreationDate":"2020-10-26T18:59:00.000","Title":"Merge two data frames in pandas giving \"The kernel appears to have died. It will restart automatically.\" using Jupyter notebook","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am getting the following error message while trying to do a pip install pandas:\nERROR: Could not install packages due to an EnvironmentError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '\"C:'\nI've tried all the other solutions I've found but nothing is working for me. Any help would be appreciated.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":120,"Q_Id":64543424,"Users Score":0,"Answer":"ryan's computer is actually your user name? This is asking for trouble. Change it, and you'll be able to install any package w\/o any problems.","Q_Score":1,"Tags":"python,pandas","A_Id":64544505,"CreationDate":"2020-10-26T19:02:00.000","Title":"EnvironmentError: [WinError 123] during pandas installation","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"Gurobi and CPLEX are solvers that have been very popular in recent years. CPLEX is easier for academics in terms of the license. It is also said to be very high in performance. But Gurobi is claimed to be the fastest solver in recent years, with continuous improvements. However, it is said that its performance decreases when the number of constraints increases.\nIn terms of speed and performance, which solver is generally recommended specifically for large-scale problems with the quadratic objective function, which have not too many constraints?\nWill their use within Python affect their performance?","AnswerCount":2,"Available Count":2,"Score":0.2913126125,"is_accepted":false,"ViewCount":4002,"Q_Id":64543863,"Users Score":3,"Answer":"As mattmilten already said, if you compare the performance of the major commercial solvers on a range of problems you will find instances where one is clearly better than the others. However that will depend on many details that might seem irrelevant. We did a side-by-side comparison on our own collection of problem instances (saved as MPS files) that were all generated from the same C++ code on different sub-problems of a large optimisation problem. So they were essentially just different sets of data in the same model and we still found big variations across the solvers. It really does depend on the details of your specific problem.","Q_Score":3,"Tags":"python,cplex,gurobi","A_Id":64554706,"CreationDate":"2020-10-26T19:36:00.000","Title":"Comparison between CPLEX and Gurobi","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":1,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Gurobi and CPLEX are solvers that have been very popular in recent years. CPLEX is easier for academics in terms of the license. It is also said to be very high in performance. But Gurobi is claimed to be the fastest solver in recent years, with continuous improvements. However, it is said that its performance decreases when the number of constraints increases.\nIn terms of speed and performance, which solver is generally recommended specifically for large-scale problems with the quadratic objective function, which have not too many constraints?\nWill their use within Python affect their performance?","AnswerCount":2,"Available Count":2,"Score":1.0,"is_accepted":false,"ViewCount":4002,"Q_Id":64543863,"Users Score":9,"Answer":"Math programming is inherently hard and there will likely always be instances where one solver is faster than another. Often, problems are solved quickly just because some heuristic was \"lucky\".\nAlso, the size of a problem alone is not a reliable measure for its difficulty. There are tiny instances that are still unsolved while we can solve instances with millions of constraints in a very short amount of time.\nWhen you're looking for the best performance, you should analyze the solver's behavior by inspecting the log file and then try to adjust parameters accordingly. If you have the opportunity to test out different solvers you should just go for it to have even more options available. You should be careful about recommendations for either of the established, state-of-the-art solvers - especially without hands-on computational experiments.\nYou also need to consider the difficulty of the modeling environment\/language and how much time you might need to finish the modeling part.\nTo answer your question concerning Gurobi's Python interface: this is a very performant and popular tool for all kinds of applications and is most likely not going to impact the overall solving time. In the majority of cases, the actual solving time is still the dominant factor while the model construction time is negligible.","Q_Score":3,"Tags":"python,cplex,gurobi","A_Id":64551828,"CreationDate":"2020-10-26T19:36:00.000","Title":"Comparison between CPLEX and Gurobi","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":1,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"So I'm trying to do the following:\nself.cashflows[\"Balance\"] * self.assumptions[\"Default Rates\"][current_period - 1]\nwhere cashflows is a list with python floats and assumptions is a list with numpy floats.\nI used numpy to fill the assumption vector and I am getting the following error when I try to multiply the two:\ncan't multiply sequence by non-int of type 'numpy.float64\nI get the error but what would be my best course of action here?\nthx","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":505,"Q_Id":64543865,"Users Score":1,"Answer":"Depends on what you want to do. Do you want to multiply every item in the list self.cashflow[\"Balance\"] with self.assumptions[\"Default Rates\"][current_period - 1]? Then you can use some list comprehension:\nresult = [q * self.assumptions[\"Default Rates\"][current_period - 1] for q in self.cashflow[\"Balance\"]]\nor convert your second argument to np.float:\nresult = self.assumptions[\"Default Rates\"][current_period - 1]* np.asarray(self.cashflow[\"Balance\"])\nOtherwise, multiplying a whole list by N repeats that list N times. If thats what you want, cast your np.float64 to int.\nEDIT: Added missing multiplication sign","Q_Score":0,"Tags":"python,numpy","A_Id":64544038,"CreationDate":"2020-10-26T19:36:00.000","Title":"python multiplying python float with numpy float","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am new to Pandas. I try to find a way to iterate over two columns (output from value_counts method). For the last hour I copy the values separately from the output which is of course pretty time consuming. I thought maybe Stackoverflow has a hint for me. Thanks.\nBachelor\u2019s degree (B.A., B.S., B.Eng., etc.)--5786\nMaster\u2019s degree (M.A., M.S., M.Eng., MBA, etc.) --1980\nSome college\/university study without earning a degree -- 1219\nAssociate degree (A.A., A.S., etc.) -- 497\nOther doctoral degree (Ph.D., Ed.D., etc.) -- 389\nSecondary school (e.g. American high school, German Realschule or Gymnasium, etc.) -- 269\nProfessional degree (JD, MD, etc.) -- 54\nI never completed any formal education -- 49\nPrimary\/elementary school -- 41","AnswerCount":1,"Available Count":1,"Score":-0.1973753202,"is_accepted":false,"ViewCount":58,"Q_Id":64544058,"Users Score":-1,"Answer":"Try putting it back into a dataframe","Q_Score":0,"Tags":"python,pandas","A_Id":64544706,"CreationDate":"2020-10-26T19:50:00.000","Title":"How can I iterate over value_counts output that consist of two columns?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm teaching a discrete math course in which I've incorporated a programming component. We have been using Python Notebooks through Jupyter.\nWe're coming up on a section in probability theory, and I would like to provide them with a \"mystery random variable:\" I want students to be able to sample the random variable without knowing how it is defined.\nI don't know the best way to implement this, and was hoping someone could provide a suggestion. Here are the features that I want:\n\nI define one or several random variables (preferably in Python),\nThe students should be able to sample from the random variable in a Python notebook (so they can do experimentation with it), but\nthe students should not be able to see the code that defines the random variable.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":239,"Q_Id":64545044,"Users Score":0,"Answer":"If this system support modules, you could define a function returning several random values (for instance giving an index) or several functions returning each a random value and put these functions in one module that your students don't have access to. They could import the .pyc module and use it but not seen the codes inside it.","Q_Score":2,"Tags":"python,random,jupyter-notebook,source-code-protection","A_Id":64545507,"CreationDate":"2020-10-26T21:12:00.000","Title":"How to provide students with a mystery function in Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I try to get text features for stylometry task in identifying the author of the given text.\nI check for :\n\ntext length by word\ntext length by character\npunctuation count\nunique word count\netc...\nbut in classifying this feature give unreasonable results, so:\ni want to check more features...\nI have two questions:\n\n\nIs there any good feature that I forget to extract from text to help classifying result\nI have a data frame like this:\ntext , author , pos\ni go to school , x , [N,V,...]\n..\nwe are good , y , [N,V,ADj]\n\nmy question is that how can I get good feature from pos column? for example the ratio of \"N\" to other? or some thing like this...\nhow to improve this multi_input single_lable multi_class classification result? with which feature? is there any good source?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":62,"Q_Id":64554731,"Users Score":1,"Answer":"Many studies have shown that the frequency and distribution of FUNCTION WORDS is significant and indicative of individual style. FUNCTION WORDS are those with little or no LEXICAL MEANING: articles THE, AN, A, conjunctions, personal pronouns, auxiliary verbs. etc.","Q_Score":0,"Tags":"python,nlp,multiclass-classification","A_Id":64562422,"CreationDate":"2020-10-27T12:45:00.000","Title":"how to get stylometric feature from text( for task of author attribution)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have an imblearn (not sklearn) pipeline consisting of the following steps:\n\nColumn selector\nPreprocessing pipeline (ColumnTransformer with OneHotEncoders and CountVectorizers on different columns)\nimblearn's SMOTE\nXGBClassifier\n\nI have a tabular dataset and I'm trying to explain my predictions.\nI managed to work out feature importance plots with some work, but can't get either\neli5 or lime to work.\nLime requires that I transform the data to the state of before the last transformation (because the transformers in the Pipeline like custom vectorizers create new columns).\nIn principle, I can slice my Pipeline like this: pipeline[:-1].predict(instance). However, I get the following error: {AttributeError}'SMOTE' object has no attribute 'predict'.\nI also tried an eli5 explainer, since it supposedly works with Sklearn Pipelines.\nHowever, after running eli5.sklearn.explain_prediction.explain_prediction_sklearn_not_supported(pipeline, instance_to_explain) I get the message that the classifier is not supported.\nWill appreciate any ideas on how to proceed with this.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":397,"Q_Id":64558402,"Users Score":1,"Answer":"Imblearn's samplers are effectively no-op (ie. identity) transformers during prediction. Therefore, it should be safe to delete them after the pipeline has been fitted.\nTry the following workflow:\n\nConstruct an Imblearn pipeline, and fit it.\nExtract the steps of the fitted Imblearn pipeline to a new Scikit-Learn pipeline.\nDelete the SMOTE step.\nExplain your predictions using standard Scikit-Learn pipeline explanation tools.","Q_Score":0,"Tags":"python,machine-learning,imblearn,smote","A_Id":64559304,"CreationDate":"2020-10-27T16:06:00.000","Title":"How can I explain predictions of an imblearn pipeline?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using Keras from tensorflow 2.2.0. I have a model with several UpSampling2D layers with bilinear interpolations. When trying to convert the model using CoreML 4.0, I get the following error:\n\nValueError: \"ResizeBilinear\" op: the second input, which is the output size, must have elements of type int32\n\nWhen the UpSampling2D interpolation is nearest the export works. Still I want the interpolation to be 'bilinear'\nIs there a fix for this?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":63,"Q_Id":64569649,"Users Score":0,"Answer":"Looks like a bug in coremltools. In situations like these, I would (temporarily) change the model to use \"nearest\" just so that you can do the conversion, then patch up the mlmodel file afterwards to change the type of this layer to \"bilinear\". You can do this with coremltools and the protobuf API (see my book).","Q_Score":0,"Tags":"python,tensorflow,keras,coreml","A_Id":64571057,"CreationDate":"2020-10-28T09:10:00.000","Title":"ValueError: \"ResizeBilinear\" op: the second input, which is the output size, must have elements of type int32","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"!cat datasets\/Admission_Predict.csv\nERROR:\n'cat' is not recognized as an internal or external command,\noperable program or batch file.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":77,"Q_Id":64571305,"Users Score":0,"Answer":"Try !more datasets\/Admission_Predict.csv","Q_Score":0,"Tags":"python,pandas","A_Id":64571541,"CreationDate":"2020-10-28T10:51:00.000","Title":"How to resolve the error of this Shell Commands in JupyterNotebook","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"If I run several Google Colab Notebooks (runtimes) at the same time, is the perfomance shared?\nI have a big dataframe to operate on so I decided to split it and let the code run on each part on a different notebook. However it seems to take as long as it would take on the whole thing in one.\nIs there any information on that?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":960,"Q_Id":64573058,"Users Score":0,"Answer":"Each Colab notebook uses a distinct virtual machine backend in order to perform computations. From a performance perspective, each notebook will be isolated from the activity of distinct notebooks.\nIn order to offer more useful guidance, please share a self-contained example that shows, with code, what you are doing and the performance bottleneck you observe.","Q_Score":1,"Tags":"python,jupyter-notebook,google-colaboratory","A_Id":64575813,"CreationDate":"2020-10-28T12:39:00.000","Title":"Running several Google Colab Notebooks at the same time","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a dataset with a lot of fields, so I don't want to load all of it into a pd.DataFrame, but just the basic ones.\nSometimes, I would like to do some filtering upon loading and I would like to apply the filter via the query or eval methods, which means that I need a query string in the form of, i.e. \"PROBABILITY > 10 and DISTANCE <= 50\", but these columns need to be loaded in the dataframe.\nIs is possible to extract the column names from the query string in order to load them from the dataset?\nI know some magic using regex is possible, but I'm sure that it would break sooner or later, as the conditions get complicated.\nSo, I'm asking if there is a native pandas way to extract the column names from the query string.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":59,"Q_Id":64576913,"Users Score":0,"Answer":"I think you can use when you load your dataframe the term use cols I use it when I load a csv I dont know that is possible when you use a SQL or other format.\nColumns_to use=['Column1','Column3']\npd.read_csv(use_cols=Columns_to_use,...)\nThank you","Q_Score":0,"Tags":"python,pandas,string,extract","A_Id":64577103,"CreationDate":"2020-10-28T16:13:00.000","Title":"Extract pandas dataframe column names from query string","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working in a gradient notebook in Paperspace. I am using the PETS dataset in the fastai library to save and deploy the Classifying breeds. When I use the learn.export() command, I am getting the error OSError: [Errno 30] Read-only file system: \u2018\/storage\/data\/oxford-iiit-pet\/export.pkl\u2019.\nI read some of the problems of the same topics in the forum, but still, I have a problem.\nAny advice is appreciated.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":105,"Q_Id":64577088,"Users Score":0,"Answer":"I would guess the file system is read-only ?\nMaybe you opened the file as read and not write. Would be my only guess other than that it is read-only","Q_Score":0,"Tags":"python,deployment,deep-learning,dataset,fast-ai","A_Id":64577205,"CreationDate":"2020-10-28T16:23:00.000","Title":"OSError: [Errno 30] Read-only file system: \u2018\/storage\/data\/oxford-iiit-pet\/export.pkl\u2019 (using fastai library)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I would like to programmatically add a header to an already existing CSV file using Python. The problem is that I do not want to overwrite the first row of the file, I would like to push all data downwards by one row and add the header on the first row without overwriting anything. Can this be done? Thanks in advance.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":80,"Q_Id":64589190,"Users Score":1,"Answer":"Is not possible to add data at the beginning of a file, you can only replace content or add data at the end of a file.\nThe solution would be to write a new file with your header and all the content of your original file.","Q_Score":0,"Tags":"python,csv","A_Id":64589258,"CreationDate":"2020-10-29T10:24:00.000","Title":"Add Header to CSV file using Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have two meshes (call them A and B) which I am interacting within python using the open3d library (happy to use import trimesh or something else if it works better). Mesh A is a curved structure and mesh B approximates to a flatter surface.\nI need to rotate the meshes so that the surface I am interested in is facing the camera.\nTo identify the surfaces that I need I have written functions to turn the meshes into point clouds and create the best fit sphere for mesh A and a best-fit plane for mesh B. These work really well and match the objects nicely.\nI need to rotate the meshes and have gotten stuck with how to perform the rotation.\nThe input data that I have:\nfor mesh A:\ncentroid of mesh A coords and coords of its best fit sphere (+ its radius) - I want to rotate the mesh so that is perpendicular to the vector described by the above data?\nfor mesh B:\ncentroid of mesh B coords and vector of the normal of the best fit plane - I want to rotate the mesh so that is perpendicular to the vector described by the above data","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":1934,"Q_Id":64590271,"Users Score":0,"Answer":"I don't know that library, but maybe you could try to rotate your objects throughout Affine2D() class, of Matplotlib.\nSpecifically, try with this function:\nmtransforms.Affine2D().rotate()\nFirst, you will have to import it: matplotlib.transforms as mtransforms","Q_Score":0,"Tags":"python,open3d,trimesh","A_Id":64590392,"CreationDate":"2020-10-29T11:31:00.000","Title":"rotate a mesh in python to be parallel to a vector","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am currently working on my master thesis. My topic is the development of a duplicate checking system in ABAP for a customer in the SAP environment. Up to now, the whole thing works in such a way that if the checking system does not know exactly whether an incoming data record is a duplicate or not, a clerk intervenes and makes the final decision. The clerk is to be \"replaced by a machine learning model\", which is to be located on a Python server, so that the clerk intervenes less in the process and becomes more and more of an \"AI trainer\". The communication between the duplicate checking system and the ML model is done by a REST API. The ML-model should decide whether incoming data records are duplicates or not.\nMy first problem is that I don't have any training data to create an ML model. The second problem is that I still do not know exactly what my training data might look like from the structure. It is possible to get client data records from the client, but for various reasons this is quite unlikely. Is there a way to generate \"synthetic data\" to create an ML model? What could it look like for my application? Which tools could I use to make my work a little easier?\nMany greetings","AnswerCount":2,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":111,"Q_Id":64593429,"Users Score":2,"Answer":"You can't.\nWhen you don't have any real-world data and how humans classified it, then you can not train a ML system to classify real-world data.\nWhat you can do is train a system with data you generated and classified in a way you believe to be similar to what the program might encounter in the wild. This would allow you to try your methodology and see if it works at all. But if you want to create an ML model which is actually useful in the real world, you need to repeat the training process with real-world data.","Q_Score":0,"Tags":"python,machine-learning,duplicates,abap","A_Id":64595482,"CreationDate":"2020-10-29T14:45:00.000","Title":"How to train a ML Model for detecting duplicates without having data sets","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I need to create a matrix MxN where every element of the matrix is a list of integers. I need a list so that I can append new elements as I go, therefore a 3D matrix would not work here.\nI'm not sure if what I need here would actually be a list of lists.","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":257,"Q_Id":64598762,"Users Score":1,"Answer":"In numpy, you can create a matrix with dtype=object (instead of the usual int or float). This can be used to store empty lists, to which you can then append.","Q_Score":1,"Tags":"python,python-3.x","A_Id":64598957,"CreationDate":"2020-10-29T20:26:00.000","Title":"How to create a matrix of lists?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I currently am working on a bioinformatics project that currently involves a dictionary corresponding to about 10million unique keys, which each return a subset of categorical strings.\nI currently use unpickle a dictionary object, but my main issue is that unpickling takes a very long time. I also need to iterate through a file, generating a set of keys(~200) for each row, lookup the keys, appending the list to a list-of-lists, and then subsequently flattening the list to generate a counter object of value frequencies for each row, and I have heard that a SQL database like structure would end up trading load times for lookup times.\nThe file that has keys typically contain about 100k rows and so this was my best solution, however it seems like even on faster pcs with increased ram, num of cores, and NVME storage that the time spent on loading the database is extremely slow.\nI was wondering what direction (different database structure, alternatives to pickle such as shelves or mashall, parallelizing the code with multiprocess) would provide an overall speed up (either through faster loading times, faster lookup, or both) to my code?\nSpecifically: Need a create databases of the format key -> (DNA sub-sequence) : value ->[A,B,C,Y,Z] on the order of 1e6\/1e7 entries.\nWhen used, this database is loaded, and then given a query file (1e6 DNA sequences to query), perform a lookup of all the sub sequences in each sequence do the following.\nFor each query:\n\nslice the sequence into subsequences.\nLookup each subsequence and return the list of categoricals for each subsequence\nAggregate lists using collections.Counter\n\nI was wondering how to either:\n\nSpeed up the loading time of the database, either through a better data structure, or some optimization\nGenerally improve the speed of the run itself (querying subsequences)","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":77,"Q_Id":64598968,"Users Score":0,"Answer":"I'm not sure there is a right answer here since there are some tradeoff, BUT.\ntwo options come to mind:\n1st. consider using panads.DataFrame for the data-stucture.\nIt will allow serialization\/deserialization to many formats (I believe CSV should be the fastest but would give SQL a try). as for query time, it should be much faster than a dict for the complex queries.\n2nd.\nkey value store, such as MongoDB that has map-reduce and other fancy query capilites, in this case the data is always available without loading times.","Q_Score":1,"Tags":"python-3.x,database,optimization,data-structures","A_Id":64837712,"CreationDate":"2020-10-29T20:43:00.000","Title":"Speeding up python load times for read only dictionary?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"Hi am trying to calculate a vector of the major axis through a 3d mesh in python (using open3d library to interact with the mesh).\nI have turned the mesh into a pointcloud using a poisson distribution (1000 points in a numpy array) and have thought about using scikit learn and its PCA functionality to try and get the value of this vector.\nFrom googling around I think I'm on the right tract but have little idea about how to use the PCA function to get what I want.\nI think I need to extract the largest eigenvalue from the pointcloud and its accompanying eigenvector - which should hopefully be what I'm looking for.\nHave little idea how to do this as I am completely unfamiliar with scikit learn.\nAny help please?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":666,"Q_Id":64609820,"Users Score":0,"Answer":"Have found a solution using trimesh library:\nused the principal_inertia_vectors function to find the 3 largest eigenvalues and corresponding eigenvectors. The eigen vectors correspond to the 3 axes of the mesh.\nThis functions runs straight off the mesh therefore not requiring conversion to a point cloud.","Q_Score":0,"Tags":"python,scikit-learn,pca","A_Id":64622542,"CreationDate":"2020-10-30T14:00:00.000","Title":"using PCA to find the major axis of a 3d pointcloud of a mesh","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm currently running a script in Jupyter Notebook which loops over a Dataframe and manipulates the data of the current row. As my Dataframe has thousands of rows and each loop takes a while to run, I am wondering whether it's safe to interrupt the script without losing all of my progress?\nI am keeping track of rows that have already been processed so I could just start where I left off in the case that the manipulations on the Dataframe don't get lost. I don't want to take the risk of trying it out right now so advice would be appreciated.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":204,"Q_Id":64615785,"Users Score":0,"Answer":"Unless you are storing progress in external files, interrupting Jupyter will lose you data. I highly do not recommend on counting on the variables inside of Jupyter on being in some state if you are mid-way through a calculation, just save intermediate steps in files to track progress, chunking as you go.","Q_Score":0,"Tags":"python,jupyter-notebook","A_Id":64615840,"CreationDate":"2020-10-30T21:07:00.000","Title":"Will interrupting the script delete the progress in Jupyter Notebook?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"Let\u2019s say one saves a Tensorflow model created using large data and GPUs. If one wanted to then use the saved model to do a single prediction with one small piece of data, does one still need the huge computers that created the model?\nI\u2019m wondering more generally how the size and computing resources needed to generate a deep learning model relate to using the model to make predictions.\nThis is relevant because if one is using Google Cloud Compute it costs more money if one has to use the huge computers all the time. If one could just use the huge computers to train the model and then more modest ones to run their app that make predictions it would save a lot of money.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":175,"Q_Id":64626121,"Users Score":4,"Answer":"Resources needed for prediction depend on the model size - not on the training device.\nIf the model has 200 bln variables - you will not be able to run it on workstation (because you have not enough memory).\nBut you can use model with 10 mln variables with no problems even if it was trained on GPU or TPU.\nEvery variable takes 4 to 8 bytes. If you have 8 GB of memory - you will probably be able to run a model with hundreds million variables.\nPrediction is fast (assuming you have enough memory). Resources needed to train model quickly. It is efficient to train on GPU\/TPU even if your model is small.","Q_Score":1,"Tags":"python,tensorflow,machine-learning,deep-learning,gpu","A_Id":64626316,"CreationDate":"2020-10-31T20:31:00.000","Title":"Can a Tensorflow saved model created on a large GPU be used to make predictions on a small CPU?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"UnsatisfiableError: The following specifications were found\nto be incompatible with the existing python installation in your environment:\nSpecifications:\n\ntensorflow -> python[version='3.5.*|3.6.*|3.7.*']\n\nYour python: python=3.8\n\nIf python is on the left-most side of the chain, that's the version you've asked for.\nWhen python appears to the right, that indicates that the thing on the left is somehow not available for the python version you are constrained to. Note that conda will not change your python version to a different minor version unless you explicitly specify that.","AnswerCount":2,"Available Count":1,"Score":-0.0996679946,"is_accepted":false,"ViewCount":234,"Q_Id":64629624,"Users Score":-1,"Answer":"open cmd and write pip install tensorflow\nor in anaconda prompt write conda install tenorflow","Q_Score":0,"Tags":"python","A_Id":64630256,"CreationDate":"2020-11-01T07:32:00.000","Title":"My anaconda version is 1.9.12 and Python is 3.8.3 but when I want to install tensorflow I get a problem","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to do inner anti join in pyspark. For example i have a common key in both df, now what i need is to extract all the row which are not common in both df. That is id of one should not match with id of another.\ndf1=df1.join(df2,how='inner',df1.id !=df2.id) \nBut with this code,I am getting rows those ids are same in both df.\nThanks in advance for help.","AnswerCount":2,"Available Count":1,"Score":-0.0996679946,"is_accepted":false,"ViewCount":1620,"Q_Id":64632926,"Users Score":-1,"Answer":"Spark allows you to handle such use cases in multiple ways\n1. Use except : will return a new DataFrame containing rows in dataFrame1 but not in dataframe2.\ndf1.except(df2)\n2. Use subtract, Return a new DataFrame containing rows in this DataFrame but not in another DataFrame.\ndf1.subtract(df2)\n3. Use exceptAll() : Return a new DataFrame containing rows in this DataFrame but not in another DataFrame while preserving duplicates.\ndf1.exceptAll(df2)\n4. Use left_anti join : Key present which is part of DF1 and as well as DF2, should not be part of the resulted dataset\ndf = df1.join(df2, df1.key == df2.key, \"left_anti\")","Q_Score":1,"Tags":"python-3.x,join,pyspark","A_Id":64639618,"CreationDate":"2020-11-01T14:22:00.000","Title":"Inner anti join in pyspark","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I wonder if there's anyways to upload a dataframe and create a new table in Exasol? import_from_pandas assumes the table already exists. Do we need to run a SQL separately to create the table? for other databases, to_sql can just create the table if it doesn't exist.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":301,"Q_Id":64639010,"Users Score":0,"Answer":"Yes, As you mentioned import_from_pandas requires a table. So, you need to create a table before writing to it. You can run a SQL create table ... script by connection.execute before using import_from_pandas. Also to_sql needs a table since based on the documentation it will be translated to a SQL insert command.","Q_Score":0,"Tags":"python,pandas,dataframe,exasolution,exasol","A_Id":64639787,"CreationDate":"2020-11-02T02:16:00.000","Title":"Upload data to Exasol from python Dataframe","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a question regarding RMSE and RMSLE:\nto create my model, I first scaled all my feature and target data between 0 and 1 and then converted their distribution to normal distribution using gauss rank scaler.\nafter I fitted a XGBoost model and made prediction on my test sets I used RMSE and RMSLE to evaluate my model.\nmy question is this:\ndo I have to convert my data (both predicted and original target values) back to its original form and then calculate RMSE and RMSLE?\nor the data scaling and converting mentioned above do not affect the RMSE and RMSLE of the model?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":42,"Q_Id":64640258,"Users Score":0,"Answer":"First of all you might not even require to transform the target, depends on use case.\nHowever if you have transformed ( here scaled 0-1), you lose the unit of measurement and then using any evaluation metric for comparison e.g. rmse (or any other in case of regression), it (rmse) here is standard deviation of the residuals calculated on scaled target not on actual values. Thus we must not report this value, however it can be used to comparing across experiments when all experiments uses same underlying data.\nFor example, based on some features you are predicting age ( say, 0 to 125 yrs). If you scaled age and used as target. Resulting rmse would be over (0-1) scaled target not (0-125 yr).","Q_Score":2,"Tags":"python,machine-learning,statistics,regression,xgboost","A_Id":71615084,"CreationDate":"2020-11-02T05:31:00.000","Title":"do scaling data between 0 and 1, and converting their distribution to a normal distribution changes model's RMSLE","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I know my question is similar to others out there, but its also kind of not.\nI have python 3.5.2 which is installed under SQL 2017 CU16 Machine Learning Services ( MLS ).\nWhen trying to upgrade scikit-learn from its vendor-installed level of 0.18 up to 0.22 I get the message\n\" It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.\"\nI could just hunt for all instances of scikit-learn in the windows directories and delete them, but I think this is a bad idea, and I have no real concept of how python packages are installed in windows, so I suspect my package is registered somewhere deep inside windows somewhere but I'm not sure where.\nThe problem is our data scientists now want to go up in scikit-learn package values and of course they cant unless I can work out how to cleanly de-install scikit-learn and install a new package using pip.\nI even did a clean install and was running pip 9.x and tried to remove the package via pip and got this message :\n\"DEPRECATION: Uninstalling a distutils installed project (scikit-learn) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project.\nOne option is we have python 3.7.1 recently installed side by side with the existing python 3.5.2 due to applying SQL 2017 CU22, but could have the same issue later when I want to upgrade packages that are installed by the initial install process. This seems to be a significant shortcoming with SQL 2017 MLS in that youre locked down in terms of what python software you can run, which is not very flexible.\nI'm wondering if there is there a way to stop certain packages being installed as part of the initial SQL 2017 MLS install process, like scikit-learn, so they can be installed later.\nAny help is greatly appreciated...","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":121,"Q_Id":64643494,"Users Score":0,"Answer":"When SQL 2017 MLS does the initial installation, it functions as the package manager. So when Pip comes along and tries to update the distutil packages, the packages dont recognize Pip as having authority to update the packages.\nThis also effectively means that MLS has a hard limitation with any packages that are \"distutils locked\" and these specific packages are 100% non-updatable. This may affect your application if it needs to update these packages.\nPossibly this means a separate non-MS python stack that can be 100% updated would be the go if you need to update any package as required.","Q_Score":1,"Tags":"sql-server,python-3.x","A_Id":65407718,"CreationDate":"2020-11-02T10:11:00.000","Title":"SQL Server 2017 MLS and pip - cannot uninstall : \u201cIt is a distutils installed project\u201d","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm working on a research project where the data is stored in a remote Windows desktop. The desktop does not have Python, it only has Rstudio, but most of the research conducted in this topic was in Python. I want to benchmark already existing implementations, but I can't run the code on the data because there's no Python and this will not change. As far as I understand, tools like reticulate still need an underlying Python interpreter in the system to work and I am not allowed to do that.\nHas anyone come up with a smart solution that does not involve me manually translating the python code to R? Any R packages that can read python? Any other out-of-the-box ideas on how to get that code to run on the data?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":186,"Q_Id":64645563,"Users Score":0,"Answer":"Say you have (1) the remote Windows Desktop that does not have Python and (2) the local computer you work on.\nUse the remote Windows Desktop (1) as a git repository, clone that repository on your local machine, make changes to it and run locally using Python, then submit the code to the remote repository again.","Q_Score":0,"Tags":"python,r,rstudio,translate","A_Id":68750468,"CreationDate":"2020-11-02T12:23:00.000","Title":"How do I get Python code to run in RStudio? No Python installed in the system","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Imagine that you have 100+ columns, about 90% of features have about 20% missing values. The total dataset is about 10000+ rows. Will you impute missing values for categorical by most frequent values or just simply delete the missing values? As I found the PCA plot after imputation is two vertical lines, probably because of the imputation. After delete these features the plot seems normal (scatters around). Do you have any suggestions? Thanks.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":36,"Q_Id":64649933,"Users Score":0,"Answer":"It realy depends on the data, one good possible solution is to fill the missing values with the average of each feature (or the median). If your data is cleaned for obvious outliers and scaled it should not affect them much.\nAnother possible solution here with promising results would be to determine the k closest neighbors to each element and use their average or median value to fill the missing columns in the row. keep in mind the dimensionality curse will negatively affect this method","Q_Score":0,"Tags":"python,cluster-analysis,pca","A_Id":64650217,"CreationDate":"2020-11-02T16:59:00.000","Title":"Will you drop features or values for missing value handling in clustering project?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I installed pyarrow using this command \"conda install pyarrow\".\nI am running a sagemaker notebook and I am getting the error no module named pyarrow.\nI have python 3.8.3 installed on mac.\nI have numpy 1.18.5 , pandas 1.0.5 and pyarrow 0.15.1\nThanks","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":463,"Q_Id":64651724,"Users Score":0,"Answer":"I have not yet used AWS Sagemaker notebooks, but they may be similar to GCP 'AI Platform notebooks', which I have used quite extensively. Additionally, if you're experiencing additional problems, could you describe how you're launching the notebooks (whether from command line or from GUI)?\nIn GCP, I defaulted to using pip install for my packages, as the conda environments were a bit finicky and didn't provide much support when creating notebooks sourced from my own created conda environments.\nAssuming you're installing conda into your base directory, when you launch jupyter notebooks, this should be the default conda environment, else if you installed to a separate conda environment, you should be able to change this within jupyter notebooks using the CONDA tab and selecting which notebook uses which conda environment.\n-Spencer","Q_Score":0,"Tags":"python,anaconda,amazon-sagemaker,pyarrow","A_Id":64651933,"CreationDate":"2020-11-02T19:03:00.000","Title":"No Module named pyarrow","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have two categories of images segmented using MaskRCNN. First category contains dent images on car.\nSecond category contains images of reflection\/shadows fallen on car that the Mask RCNN detects as dent.\nIs there any methods in image processing that can distinguish between the same? I tried Canny, Gaussian, LBP, SIFT, watershed etc. Can anyone suggest a suitable approach for the same.\nThanks in advance!!","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":80,"Q_Id":64657814,"Users Score":1,"Answer":"If the image of shadows generally are darker than the dents, you can convert the images to HSV, and compare the average V values of the pixels. V value contains the brightness of the pixel.\nYou can use hsv_img = cv2.cvtColor(img, cv2.BGR2HSV).","Q_Score":0,"Tags":"python,image-processing,deep-learning,canny-operator","A_Id":64657890,"CreationDate":"2020-11-03T06:34:00.000","Title":"How to differentiate between two types of images using image processing?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"while working with CNNs I was wondering which of my Input Channels gives the most information to the neural network for the prediction.\nFor example: The is a image of a frog. The CNN is suppose to predict which kind of animal is in the image.\nSo because frogs are green most of the time, the CNN uses the channel G from RGB the most for prediction.\nIs there a way of finding out which channel is the most important for a specific neural network?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":61,"Q_Id":64663363,"Users Score":0,"Answer":"IF a color channel is the most important, you can check manually by getting the weights of the input convolution layer. They will be in (filtersizex x filtersizey x 3) X the number of filters. you then need to add the weights so you get (1 x 3) X the number of filters. So you have for each filter the most important channel, if you need this for the whole network add them all together and you end with an (1 x 3) array, the max of this is the most important channel.","Q_Score":0,"Tags":"python,tensorflow2.0,prediction,conv-neural-network","A_Id":64664028,"CreationDate":"2020-11-03T13:02:00.000","Title":"CNN: Which channel gives the most informations?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a data frame in which the target value is not in normal distribution. I want to choose only a sample of the data that represent a normal distribution of this target. How can I do this?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":94,"Q_Id":64663570,"Users Score":0,"Answer":"With the given information, this is a sampling question. I am not sure whether this is an acceptable practise to choose a targeted sample. Instead, choose samples randomly and make sure they follow normal distribution. If the sample is not normally distributed, try normalizing your target value using transformation procedures. For example, a square root transformation might make your target value normal. More information on the problem will help address this comprehensively.","Q_Score":0,"Tags":"python,pandas,dataframe,normal-distribution","A_Id":64663653,"CreationDate":"2020-11-03T13:15:00.000","Title":"How to choose a sample from the data points that represent normal distribution?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a physical model with one independent variable X and three parameters A, B and C. The dependent variable is Y=F(X,A,B,C) where F is the model's function which is smooth and continuous.\nI have many files with data points (X,Y) that I want to fit (each file) with the model to study how the parameters change. The model is non-linear with respect to the independent variable and all the parameters.\nTo fit the model, I use scipy.optimize curve_fit in Python inside a for loop throughout the files with the data points. For each file, I get the best fitting parameters (A,B,C) and the model fits great to all the files. However, when I check the parameter errors after the fittings, I notice that the errors in A are really large, even two orders of magnitude higher than the corresponding values.\nThe experience tells me that these large variances might be due to the fact that the parameter A could be correlated to any of the others. To check this assumption, I plotted the obtained values of A against the values of B and C. I see that, in fact, a power-law relation of the form A=a*B^b arises, which is physically acceptable.\nIs there a way to tell curve_fit to take care of this correlation without having to introduce new parameters (say a and b) in order to fit the model with the lowest variance possible?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":195,"Q_Id":64665533,"Users Score":0,"Answer":"Try to use method = 'trf' as a parameter for your fit. This avoids using least squares and works with pseudoinverse of the Jacobian. I believe a Jacobian with a zero eigenvalue then should not be a problem.","Q_Score":0,"Tags":"python,scipy,correlation,curve-fitting,model-fitting","A_Id":64689608,"CreationDate":"2020-11-03T15:12:00.000","Title":"Correlated variables and scipy curve_fit","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using odeint in scipy to integrate a function. The function is basically the velocities in x,y,z directions which I need to integrate to find the corresponding x,y,z position coordinates. Odeint in python asks for a list of timesteps and return values for those number of timesteps only. But, I require all values of x,y,z coordinate positions calculated at each internally defined timestep and not just at the timesteps I send as a parameter. So, is there a way to just send the min and max timestep and get all the values calculated at each internally defined timestep between the given min and max timestep?\nThe reason I need this is that when I plot the x,y,z coordinates returned, I am getting sharp turns and not smooth paths. So, in order to plot a smooth path, I will require all the coordinates calculated at each internally defined timestep.\nIf I am not wrong, the ODE45 function in Matlab returns all values calculated at every automatically defined internal timestep. Is there a way to get this to work in python?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":144,"Q_Id":64676414,"Users Score":0,"Answer":"You get this functionality with scipy.integrate.solve_ivp or by fashioning your own time loop using the stepper classes, the old ode class or the new RK45, Radau, LSODA etc.\nNote that in Matlab the option parameter 'Refine' is set to the default value 4, so that for every internal step there are 3 interpolated points added so that the output looks curved despite large time steps due to the step size control. This trick is not present in the python routines, you would have to enrich the output yourself.","Q_Score":0,"Tags":"python,integration,ode,odeint","A_Id":64711686,"CreationDate":"2020-11-04T08:24:00.000","Title":"How to return values for all internally defined time steps by odeint in python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm facing this error AttributeError: module 'cv2' has no attribute 'face' when testing on Android. I've got opencv and opencv_extras included in requirements. This error won't show up when running on desktop but it shows up when tested on Android.\nAny advice ?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":110,"Q_Id":64681167,"Users Score":0,"Answer":"Hey mate I also faced the same error today.....\nWell the solution is uninstalling your current version of python and installing new version, that is downgrading your current version of opencv\nopencv-contrib-python==3.4.6.27\nAlso this can be verified by typing\nhelp(cv2.face) in the IDE\nif it shows the path the version opencv would work...\nWell the above version of opencv I mentioned does have cv2.face\nSo to install it you type\npip install opencv-contrib-python==3.4.6.27 in the cmd or whatever depending upon your environment","Q_Score":0,"Tags":"opencv,kivy,buildozer,opencv-python","A_Id":64681308,"CreationDate":"2020-11-04T13:38:00.000","Title":"AttributeError: module 'cv2' has no attribute 'face' despite using \"opencv_extras\" recipe","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"My dataset contains 1000 sets which I'm using it for the classification problem. I used LR and SVM as a machine learning algorithm. I was wondering if I should use Bootstrapping from training set and then apply LR & SVM or use Bootstrapping from original dataset? When I look at the accuracy score, I shouldn't use bootstrapping from original dataset.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":298,"Q_Id":64687774,"Users Score":0,"Answer":"Bootstrapping from the original dataset defeats the purpose of having the two different datasets (train\/test). You always train the model on the training dataset and calculate the accuracy or another score on the test dataset.\nIf you bootstrap from the original dataset, you'll be training your model on (a subset of) the whole dataset, which will include a part of the test dataset, so your resulting metrics (that you'll calculate based on the test dataset) will be biased because you trained the model on part of the test dataset.","Q_Score":0,"Tags":"python,resampling","A_Id":64687830,"CreationDate":"2020-11-04T21:09:00.000","Title":"Bootstrapping after training_test split or original dataset?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I tried following the instructions on pytorch.org and ran the command provided by them for my configuration, but I get the following error\nERROR: Could not find a version that satisfies the requirement torch===1.7.0+cu110 (from versions: 0.1.2, 0.1.2.post1, 0.1.2.post2)\nERROR: No matching distribution found for torch===1.7.0+cu110\nA similar error is being thrown for any other installation methods that I try, e.g. earlier cuda versions, CPU only etc. My Python version is 3.9 and was installed using the .exe installer provided at python.org, if that's relevant.","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":1396,"Q_Id":64691517,"Users Score":0,"Answer":"Well, I installed a new Operating System and did a fresh install of Python and CUDA. After that the commands given on pytorch.org worked just fine. For immediate reference, the command is\npip install torch==1.7.0+cu110 torchvision==0.8.1+cu110 torchaudio===0.7.0 -f https:\/\/download.pytorch.org\/whl\/torch_stable.html\nI had to resort to this because I had messed up my python installation by tinkering around with pip, conda and anaconda all at once. The process of removing anaconda completely didn't quite work as intended and everything was just a wee bit broken.\nSo, I'm guessing that if anyone else is facing the same error and other documented solutions do not work, then a fresh installation of python might become necessary. In my case, it was in the form of a completely new operating system.","Q_Score":0,"Tags":"python,pip,pytorch","A_Id":64693626,"CreationDate":"2020-11-05T05:07:00.000","Title":"Unable to install PyTorch on Windows 10 (x86_64) with Cuda 11.0 using pip","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a matrix with the following shape (20, 17) with rows being the time and columns the number of variables.\nWhen i compute the correlation matrix using data.corr() naturally i get a (17 , 17) matrix.\nMy questions:\nIs there a way to normalise the variables directly within the .corr() function? (i know i can do that before hand and then apply the function)\nMy correlation matrix is large and I have trouble viewing everything in one go (i have to scroll down to do the necessary comparison). Is there a way to present the results in a concise way (like a heat map) where i can easily spot the highest from the lowest correlation?\nMany Thanks","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":183,"Q_Id":64693985,"Users Score":1,"Answer":"You could use matplotlib's imshow() to see a heatmap of any matrix.\nAlso, consider using pandas dataframes, this way you could sort by correlation strength and keep the labels of each row and col.","Q_Score":1,"Tags":"python-3.x,cross-correlation,pearson-correlation","A_Id":64694075,"CreationDate":"2020-11-05T08:57:00.000","Title":"Pearson correlation in python data.corr()","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Whenever we perform any operations with the images, we convert them into Arrays, what's the specific reason?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":179,"Q_Id":64694273,"Users Score":2,"Answer":"OpenCV images are stored as three-dimensional Numpy arrays. When you read in images using the library, they are represented as Numpy arrays.\nWith Numpy you can make blazing fast operations on numerical arrays, no matter which dimension, shape they are.","Q_Score":0,"Tags":"python,arrays,image,image-processing,multidimensional-array","A_Id":64694309,"CreationDate":"2020-11-05T09:18:00.000","Title":"Why do we convert image in arrays for image processing?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Im having an image as input, and need to resize it. I have earlier used pillow to do this but the library wasnt available where i needed it. np.resize(image, (50,50)) returns a different array then cv2.resize(image, (50,50)) and (pillow) Image.fromarray(image), image_from_array.resize((50, 50)).\nWondering whats the difference between these methods.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":56,"Q_Id":64703798,"Users Score":1,"Answer":"np.resize doesn't 'resize' images, instead it interprets the data that's already there in a different way. E.g. say you have four integers [1, 2, 3, 4], then .resize((2, 2)) will give you [[1, 2], [3, 4]].\nUse cv2.resize if you actually want to resize an image.","Q_Score":0,"Tags":"python,numpy,opencv,image-processing,python-imaging-library","A_Id":64704157,"CreationDate":"2020-11-05T19:06:00.000","Title":"Whats the diffrence between numpy.resize() and cv2.resize()?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"When i convert a pandas data frame to spark, spark automatically strips the String columns\/ deletes leading and trailing spaces. How can this be stopped?\nsparkframe = spark.createDataFrame(pandas_df)\nExample ' ' -> '' or 'ab ' -> 'ab'","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":15,"Q_Id":64704555,"Users Score":1,"Answer":".option(\"ignoreTrailingWhiteSpace\",False).option(\"ignoreLeadingWhiteSpace\",False)\nwhen saving is the the solution. Why its default True is a mystery","Q_Score":1,"Tags":"python,pandas,pyspark","A_Id":64704861,"CreationDate":"2020-11-05T20:04:00.000","Title":"stop spark createdataframe(pandas.df) from stripping \/ trimming strings","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have been able to successfully detect an object(face and eye) using haar cascade classifier in python using opencv. When the object is detected, a rectangle is shown around the object. I want to get coordinates of mid point of the two eyes. and want to store them in a array. Can any one help me? how can i do this. any guide","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":236,"Q_Id":64708800,"Users Score":0,"Answer":"So you already detected the eye? You also have a bounding box around the eye?\nSo your question comes down to calculatiing the distance between 2 bounding boxes and then dividing it by 2?\nOr do I misunderstand?\nIf you need exact the center between the two eyes a good way to go about that would be to take the center of the 2 boxes bounding the 2 eyes.\nCalculate the distance between those two points and divide it by 2.\nIf you're willing to post your code I'm willing to help more with writing code.","Q_Score":1,"Tags":"python,opencv,coordinates","A_Id":64710334,"CreationDate":"2020-11-06T04:17:00.000","Title":"How to Get coordinates of detected area in opencv using python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have been able to successfully detect an object(face and eye) using haar cascade classifier in python using opencv. When the object is detected, a rectangle is shown around the object. I want to get coordinates of mid point of the two eyes. and want to store them in a array. Can any one help me? how can i do this. any guide","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":236,"Q_Id":64708800,"Users Score":0,"Answer":"I suppose you have the coordinates for the bounding boxes of both eyes.\nSomething like X1:X2 Y1:Y2 for both boxes.\nYou just have to find the center of these boxes: (X2-X1)\/2+X1 and (Y2-Y1)\/2+Y1\nYou'll get two XY coordinates from this, basically just do the above again with these coordinates, and you'll get the center point","Q_Score":1,"Tags":"python,opencv,coordinates","A_Id":64711514,"CreationDate":"2020-11-06T04:17:00.000","Title":"How to Get coordinates of detected area in opencv using python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to introduce data quality testing (empty fields\/max-min values\/regex\/etc...) into my pipeline which will essentially consume kafta topics testing the data before it is logged into the DB.\nI am having a hard time choosing between the Deequ and Great Expectations frameworks. Deequ lacks clear documentation but has \"anomaly detection\" which can compare previous scans to current ones. Great expectations has very nice and clear documentation and thus less overhead. I think neither of these frameworks is made for data streaming specifically.\nCan anyone offer some advice\/other framework suggestions?","AnswerCount":2,"Available Count":1,"Score":1.0,"is_accepted":false,"ViewCount":2871,"Q_Id":64711388,"Users Score":6,"Answer":"As Philipp observed, in most cases batches of some sort are a good way to apply tests to streaming data (even Spark Streaming is effectively using a \"mini-batch\" system).\nThat said: if you need to use a streaming algorithm to compute a metric required for your validation (e.g. to maintain running counts over observed data), it is possible to decompose your target metric into a \"state\" and \"update\" portion, which can be properties of the \"last\" and \"current\" batches (even if those are only one record each). Improved support for that kind of cross-batch metric is actually the area we're most actively working on in Great Expectations now!\nIn that way, I think of the concept of the Batch as both baked deeply into the core concepts of what gets validated, but also sufficiently flexible to work in a streaming system.\nDisclaimer: I am one of the authors of Great Expectations. (Stack Overflow alerts! :))","Q_Score":3,"Tags":"python,great-expectations,amazon-deequ","A_Id":64715840,"CreationDate":"2020-11-06T08:45:00.000","Title":"Data testing framework for data streaming (deequ vs Great Expectations)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":1},{"Question":"I am trying to use curve fit to fit some temperature that looks like a sinusoid function added to a linear function. My initial predictions are way off and I believe it is because I need to adjust p0, however I was wondering if there was a good way to get an initial guess for p0 or if its just an endless game of guess and check. Alternatively, if there is a better way to get the regression line please let me know!\nThanks!","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":487,"Q_Id":64723823,"Users Score":1,"Answer":"This is not algorithmic. It all depends on the model and data. E.g., if there's a sinusoid, a rough guess for the period (e.g. from the distance between maxima) goes a long way etc","Q_Score":0,"Tags":"python,scipy,model,regression,curve-fitting","A_Id":64727388,"CreationDate":"2020-11-07T02:20:00.000","Title":"Is there a good way to optimize p0 in scipy.optimize.curve_fit?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I read through the documentation, but something wasn't clear for me: if I coded a custom layer and then used it in a model, can I just save the model as SavedModel and the custom layer automatically goes within it or do I have to save the custom layer too?\nI tried saving just the model in H5 format and not the custom layer. When I tried to load the model, I had an error on the custom layer not being recognized or something like this. Reading through the documentation, I saw that saving to custom objects to H5 format is a bit more involved. But how does it work with SavedModels?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":180,"Q_Id":64723898,"Users Score":0,"Answer":"If I understand your question, you should simply use tf.keras.models.save_model(,'file_name',save_format='tf').\nMy understanding is that the 'tf' format automatically saves the custom layers, so loading doesn't require all libraries be present. This doesn't extend to all custom objects, but I don't know where that distinction lies. If you want to load a model that uses non-layer custom objects you have to use the custom_objects parameter in tf.keras.models.load_model(). This is only necessary if you want to train immediately after loading. If you don't intend to train the model immediately, you should be able to forego custom_objects and just set compile=False in load_model.\nIf you want to use the 'h5' format, you supposedly have to have all libraries\/modules\/packages that the custom object utilizes present and loaded in order for the 'h5' load to work. I know I've done this with an intializer before. This might not matter for layers, but I assume that it does.\nYou also need to implement get_config() and save_config() functions in the custom object definition in order for 'h5' to save and load properly.","Q_Score":0,"Tags":"python,tensorflow,model,save","A_Id":68923767,"CreationDate":"2020-11-07T02:37:00.000","Title":"Saving Tensorflow models with custom layers","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":1},{"Question":"i'm building a CNN to identify facial keypoints. i want to make the net more robust, so i thought about applying some zoom-out transforms because most pictures have about the same location of keypoints, so the net doesn't learn much.\nmy approach:\ni want augmented images to keep the original image size so apply MaxPool2d and then random (not equal) padding until the original size is reached.\nfirst question\nis it going to work with simple average padding or zero padding? i'm sure it would be even better if i made the padding appear more like a background but is there a simple way to do that?\nsecond question\nthe keypoints are the target vector, they come as a row vector of 30. i'm getting confused with the logic needed to transform them to the smaller space.\ngenerally if an original point was at (x=5,y=7) it transforms to (x=2,y=3)- i'm not sure about it but so far manually checked and it's correct. but what to do if to keypoints are in the same new pixel? i can't feed the network with less target values.\nthat's it. would be happy to hear your thoughts","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":1511,"Q_Id":64727718,"Users Score":2,"Answer":"I suggest to use torchvision.transforms.RandomResizedCrop as a part of your Compose statement. which will give you random zooms AND resize the resulting the images to some standard size. This avoids issues in both your questions.","Q_Score":0,"Tags":"python,neural-network,pytorch,conv-neural-network,data-augmentation","A_Id":64728540,"CreationDate":"2020-11-07T12:38:00.000","Title":"clever image augmentation - random zoom out","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am preprocessing ImageNet data so all the data is the same shape, (256, 256, 3). My idea was to crop the data to (256, 256). However, I am running into issues because the images are of variable size and some are smaller than 256 in width\/height, or both. Some example dimensions include (194, 150, 3) and (200, 300, 3). Do I just resize all the images to (256, 256)? This would potentially throw off aspect ratio and cause distortions. How do I best approach this? Any examples of this in tensorflow would also be helpful.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":124,"Q_Id":64736281,"Users Score":0,"Answer":"Padding then cropping is probably the good solution.","Q_Score":1,"Tags":"python,tensorflow,reshape,image-preprocessing,imagenet","A_Id":64736402,"CreationDate":"2020-11-08T08:50:00.000","Title":"How to preprocess ImageNet data that is smaller than 256 x 256?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to index the 2nd axis of a BxNxM array (the N axis) with B indices and get a BxM array as the result.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":18,"Q_Id":64739112,"Users Score":1,"Answer":"Figured it out. Say the BxNxM array is called A, then the desired output is A[(np.arange(B), indices)].","Q_Score":0,"Tags":"python,numpy,scipy","A_Id":64739316,"CreationDate":"2020-11-08T14:17:00.000","Title":"In Numpy, how can I index an B x N x M array with a size B array of indices to yield a B x M array?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am slightly confused about the scaling concept in Machine learning models.\nIn Classification, if the variables are having a different scale, I usually perform scaling on independent variable and label encoding on Target variable and inverse transform the predicted results to get the actual labels\nIn Regression, if my variables are in different, I know we have to scale the independent variables, should I also scale my Target variable?\nCould someone please help me if my understanding is correct in the above scenario and should I scale my Target variable in Regression models?\nThanks in advance.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":57,"Q_Id":64739128,"Users Score":0,"Answer":"Scaling should only be applied on features since it has an effect on the training procedure, so when all the features (independent variables) are on the same(or similar) scales, generally training goes faster and it converges to a good solution especially if you're using a gradient-based training algorithm like SGD or Adam, but for the target (dependant) variable you don't need scaling since you would just add extra computation that won't affect the quality of the classifier (regressor) you'll get.","Q_Score":0,"Tags":"python,machine-learning,regression,classification","A_Id":64740996,"CreationDate":"2020-11-08T14:18:00.000","Title":"Scaling on Machine Learning Models","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to install OpenCV in a docker container (CentOS).\nI tried installing python first and then tried yum install opencv-contrib but it doesn't work.\nCan someone help me out as to how to install OpenCV in Docker (CentOS)?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":225,"Q_Id":64739928,"Users Score":0,"Answer":"To install OpenCV use the command: sudo yum install opencv opencv-devel opencv-python\nAnd when the installation is completed use the command to verify: pkg-config --modversion opencv","Q_Score":2,"Tags":"python,linux,docker,opencv,anaconda","A_Id":64748740,"CreationDate":"2020-11-08T15:39:00.000","Title":"How to install OpenCV in Docker (CentOs)?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":1,"Web Development":0},{"Question":"So, I've googled prior to asking this, obviously, however, there doesn't seem to be much mention on these modes directly. Tensorflow documentation mentions \"test\" mode in passing which, upon further reading, didn't make very much sense to me.\nFrom what I've gathered, my best shot at this is that to reduce ram, when your model is in prediction mode, you just use a pretrained model to make some predictions based on your input?\nIf someone could help with this and help me understand, I would be extremely grateful.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":26,"Q_Id":64755952,"Users Score":0,"Answer":"Training refers to the part where your neural network learns. By learning I mean how your model changes it's weights to improve it's performance on a task given a dataset. This is achieved using the backpropogation algorithm.\nPredicting, on the other hand, does not involve any learning. It is only to see how well your model performs after it has been trained. There are no changes made to the model when it is in prediction mode.","Q_Score":0,"Tags":"python,tensorflow,deep-learning,neural-network","A_Id":64756216,"CreationDate":"2020-11-09T17:00:00.000","Title":"Tensorflow - What does Training and Prediction mode mean when making a model?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I need to build a neural network accepting data from a particular .csv file where most columns' type is object, i.e. they are neither numerical nor string. My question is: can a neural network accept such an input? If not, how should I overcome such adversity?, and, if so, where could I learn more about it? I am working with Python.\nThanks in advance.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":99,"Q_Id":64758511,"Users Score":0,"Answer":"Simple answer is no.\nTwo key components in neural networks are matrix multiplications and activation functions, both are operate for numbers, integer (rarely) or floating point. In case of strings, you need to encode them into vectors of numbers first before you can use them in neural networks. Same for objects.\nTake pictures as example, the convolutional neural network will treat pictures as pixels in 2D and then present them as matrix of numbers. So same in your case, you need to present your \"object\" (for whatever it is) as tensors (i.e. n-dimensional arrays of floats) first.","Q_Score":0,"Tags":"python,keras,neural-network","A_Id":64758583,"CreationDate":"2020-11-09T20:03:00.000","Title":"Can a neural network accept an object (i.e. not numerical nor string) as an input?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working on an automated ML (Regression) algorithm where the flow of process is:\nUser uploads a data -- Data Cleaning -- Encoding(Target Encoder) -- Fitting model -- results.\nI am completely fine until this point, my confusion is when the user wants to test this in an unseen data without target variable, then I need to again perform Data cleaning -- Encoding and encoding technique I have used while fitting the model can work only if there is a target variable (unseen data will not have a target variable) and I cannot change the Encoding technique on unseen data as the testing data needs to go through the same procedure as the data used while fitting the model as per my knowledge.\nCould someone please help me in finding a way to overcome this issue or any suggestions would be of great help.\nThanks in advace.","AnswerCount":3,"Available Count":2,"Score":0.0665680765,"is_accepted":false,"ViewCount":880,"Q_Id":64759579,"Users Score":1,"Answer":"What you have outlined above is the training pipeline. In a test (inference) scenario, the pipeline would be slightly modified. Data upload and data cleaning should be performed identically as in the training scenario, but as you acknowledge there is no need (or even possibility) for performing target encoding since the target is what we are trying to predict using the model during testing. In this case encoding is not performed, and the model is used to predict the target based on the cleaned data.\nIn short, the model pipeline should be nearly identical for train\/test, with the exceptions that target encoding is not performed in the test scenario, and the final step will be a fit in the train scenario and a predict in the testing scenario.","Q_Score":4,"Tags":"python,machine-learning,encoding,prediction,test-data","A_Id":65062709,"CreationDate":"2020-11-09T21:34:00.000","Title":"Predicting unseen data on Target variable based Encoding Technique","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working on an automated ML (Regression) algorithm where the flow of process is:\nUser uploads a data -- Data Cleaning -- Encoding(Target Encoder) -- Fitting model -- results.\nI am completely fine until this point, my confusion is when the user wants to test this in an unseen data without target variable, then I need to again perform Data cleaning -- Encoding and encoding technique I have used while fitting the model can work only if there is a target variable (unseen data will not have a target variable) and I cannot change the Encoding technique on unseen data as the testing data needs to go through the same procedure as the data used while fitting the model as per my knowledge.\nCould someone please help me in finding a way to overcome this issue or any suggestions would be of great help.\nThanks in advace.","AnswerCount":3,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":880,"Q_Id":64759579,"Users Score":0,"Answer":"For predictions on unseen data, you should simply omit the target encoding from your pipeline. You can therefore implement two versions of the pipeline.\nThis would be your training\/testing\/cross-validation pipeline:\nUser uploads training data -- Data Cleaning -- Encoding(Target Encoder) -- Training the model -- result\nNote: use fit_transform on the encoding when running training data, and transform when running test or validation data to avoid data leakage\nAnd this would be your prediction pipeline:\nUser uploads testing data -- Data Cleaning -- predictions using trained models","Q_Score":4,"Tags":"python,machine-learning,encoding,prediction,test-data","A_Id":65062860,"CreationDate":"2020-11-09T21:34:00.000","Title":"Predicting unseen data on Target variable based Encoding Technique","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have many categorical variables which exist in my test set but don't in my train set. They are important so I can't drop them. Should I combine train and test set or what other solution should I make?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":527,"Q_Id":64768676,"Users Score":0,"Answer":"How did you end up in this situation? Normally you take a dataset and divide it into two subsets. The first subset is used to fit the model and is referred to as the training dataset. The second subset is not used to train the model; instead, the input element of the dataset is provided to the model, then predictions are made and compared to the expected values. This second dataset is referred to as the test dataset.\nBut it is clear that, because they originate from the same original dataset, that they both have the same categorical variables.","Q_Score":0,"Tags":"python,machine-learning,artificial-intelligence","A_Id":64768749,"CreationDate":"2020-11-10T12:09:00.000","Title":"How to solve mismatch in train and test set after categorical encoding?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm comparing in python the reading time of a row of a matrix, taken first in dense and then in sparse format.\nThe \"extraction\" of a row from a dense matrix costs around 3.6e-05 seconds\nFor the sparse format I tried both csr_mtrix and lil_matrix, but both for the row-reading spent around 1-e04 seconds\nI would expect the sparse format to give the best performance, can anyone help me understand this ?","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":413,"Q_Id":64784929,"Users Score":2,"Answer":"arr[i,:] for a dense array produces a view, so its execution time is independent of arr.shape. If you don't understand the distinction between view and copy, you need to do more reading about numpy basics.\ncsr and lil formats allow indexing that looks a lot like ndarray's, but there are key differences. For the most part the concept of a view does not apply. There is one exception. M.getrowview(i) takes advantage of the unique data structure of a lil to produce a view. (Read its doc and code)\nSome indexing of a csr format actually uses matrix multiplication, using a specially constructed 'extractor' matrix.\nIn all cases where sparse indexing produces sparse matrix, actually constructing the new matrix from the data takes time. Sparse does not use compiled code nearly as much as numpy. It's strong point, relative to numpy is matrix multiplication of matrices that are 10% sparse (or smaller).\nIn the simplest format (to understand), coo, each nonzero element is represented by 3 values - data, row, col. Those are stored in 3 1d arrays. So it has to have a sparsity of less than 30% to even break even with respect to memory use. coo does not implement indexing.","Q_Score":1,"Tags":"python,performance,matrix,sparse-matrix","A_Id":64790236,"CreationDate":"2020-11-11T10:45:00.000","Title":"dense matrix vs sparse matrix in python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":1,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"How can I read a csv file from s3 without few values.\nEg: list [a,b]\nExcept the values a and b. I need to read all the other values in the csv. I know how to read the whole csv from s3. sqlContext.read.csv(s3_path, header=True) but how do I exclude these 2 values from the file and read the rest of the file.","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":120,"Q_Id":64795124,"Users Score":1,"Answer":"You don't. A file is a sequential storage medium. A CSV file is a form of text file: it's character-indexed. Therefore, to exclude columns, you have to first read and process the characters to find the column boundaries.\nEven if you could magically find those boundaries, you would have to seek past those locations; this would likely cost you more time than simply reading and ignoring the characters, since you would be interrupting the usual, smooth block-transfer instructions that drive most file buffering.\nAs the comments tell you, simply read the file as is and discard the unwanted data as part of your data cleansing. If you need the file repeatedly, then cleanse it once, and use that version for your program.","Q_Score":0,"Tags":"python,amazon-web-services,amazon-s3","A_Id":64795271,"CreationDate":"2020-11-11T22:28:00.000","Title":"Read a csv file from s3 excluding some values","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Does the learning rate reset when I stop training in jupyter? I said during training to lower it by * 0.1 when my model starts to stagnate.\nIf I stop training and then restart it right after, does that reset the learning rate?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":81,"Q_Id":64805202,"Users Score":1,"Answer":"Yes, ideally it will restart again if you are not initializing with new value.\nThis of this as a function which is stopped and rerun again. If you don't write the custom logic to restart again from the old LR it will continue from its initialized value which is the begging again.","Q_Score":0,"Tags":"python,tensorflow,keras","A_Id":64807189,"CreationDate":"2020-11-12T13:51:00.000","Title":"Does the learning rate reset when I stop training in jupyter? Tensorflow.Keras","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have an organized point cloud file of an assembly generated using FreeCAD. I am using open3d python library to visualize this point cloud file. I just wonder whether there's a method to resize (cut down) this point cloud to a smaller size (shrink in size), but keeping this cloud organized in its original shape. That means I want to reduce the spacing between the points so that they become closer and the point cloud compresses while maintaining the shape of the point cloud.\nI think this shouldn't be the same as down sampling. What I want to do next is that I want to combine the 2 point clouds together so that the shrinker point cloud object appears to be within the bigger point cloud object\nI am working on python using the approach of storing these point clouds in lists etc. and visualizing using open3D python library.\nAny advice is welcome, thanks first!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":438,"Q_Id":64805510,"Users Score":0,"Answer":"Have you tried scaling it?\nFor example, converting the units from meters to millimeters - multiply\/divide each coordinate by the same constant (for example - 1000 for m<->mm conversion).\nThen, center each point cloud (subtract the mean from each point) and merge them. You can adjust their centroid and the scaling for better output.","Q_Score":0,"Tags":"python,point-clouds","A_Id":65287100,"CreationDate":"2020-11-12T14:10:00.000","Title":"Point Cloud Shrink in size","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I would like to know why Pandas can open in chunks a gzip-compressed file while Dask has to load to memory the whole file before processing it.\nConcretely, I have a gzip-compressed csv file of size ~10GB (and ~50GB when not compressed). My computer has 16GB of RAM.\nI thought gzip files cannot be operated in chunks because they need to be decompressed before they can be partitioned. However, I am able to use the chunk method of Pandas to process the gzip file with no issue.\nAdditionaly, since I want to use Dask in the future, can you recommend me any compressed format that can easily be read in chunks by Dask ?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":155,"Q_Id":64806692,"Users Score":1,"Answer":"Specifically, you cannot random access a gzipped file: to get to a particular point in the decompressed data, you need to read through the whole file to that point. Thus, you can load chunk-by-chunk sequentially, maintaining the file position.\nHowever, dask wants to be able to access some arbitrary offset in the file, so that each partition can be loaded independently and in parallel. For gzip, this would mean each task spooling through the file to the offset they need, which is a really bad idea.","Q_Score":0,"Tags":"python,pandas,parallel-processing,gzip,dask","A_Id":64807653,"CreationDate":"2020-11-12T15:18:00.000","Title":"Why Pandas can load a gzip file in chunks while Dask cannot?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm currently working on an AI to predict the winner of a 1v1 match on a video game. The thing is that I do not know in what form I need to have the data (inputs and labels).\nFor now I have the following data :\n\nthe day of the match (there is a day 0)\nname of player 1\ncountry of player 1\nname of player 2\ncountry of player 2\nwinner\n\nI can also get the score of the match but sometimes it is in best of 3 and sometimes in best of 5 so I do not know if it could be reliable or not.\nBased on the data I have, my two main questions are :\n\nIs is possible that the AI predict two different results if I just reverse the player columns ?\nIf yes, how can I avoid it ?\nHow am I saying to the AI that the prediction I want is only one of the two players I present to it and not other players ?\n\nThanks in advance, I really appreiciate","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":68,"Q_Id":64820841,"Users Score":2,"Answer":"It seems that your data is categorical even though I do not exactly understand what you mean by player1 and player2. Do you have the names of the players or some skill set?\nNeural networks or any AI algorithm work with numbers. They do not know anything about the real world such as day name(Monday, Tuesday etc.) or Country names. What you have to do is you have to create a mapping between these real-world issues and numbers.\nThey are something categorical(it can not take a continuous value) you can map the days from 0 to N. For the countries you can do the same, every country can have a unique ID. You have to be careful tough if, during inference the model receives a day or country that was not extant in the training, it will be unknown to the model. So either adds all the countries that are relevant or if you can not know this in prior, you can add a label -1 for the case of unknown country and day.\nFor each feature, you will have a column and each row represents a match. In the column, you will have to correspondings IDs for that particular feature and match and you can pass this data to AI. By the way, it is okay that you use the same IDs\/numbers for different features. (So you can you 1 for Tuesday and in the other Column 1 can be Switzerland)\nAnswers to your questions:\n\nYes, in theory, this can happen. If you have enough samples and a good model the model itself might learn it.\n\nIf you can do, you can input relative values to the model instead of absolute values. So for example, if you have some skill set attributes\/scores with respect to players, instead of feeding both scores to the system, you can create your data based on the difference of these score. E.g shooting for player1 is 80 and for player2 78. You have a column for shooting and there you put the value 80-78, then the modal knows the player1 is better by 2 or if vice versa you could put -2 and thne th emodel knows the player2 is better by 2 in that category. Another approach would be to have each match 2 times in the training data. The second one with player orders reversed. The model might also learn this from the data.\n\nThat is easy to do, your model will output not players IDs or anything related to the player. Your problem is a binary classification problem. Your model should output in any case either 0 or 1. 0 meaning player1 wins, 1 meaning player2 wins and then you can convert this output to the players by yourself.","Q_Score":1,"Tags":"python,machine-learning","A_Id":64821189,"CreationDate":"2020-11-13T12:22:00.000","Title":"In what form should I have my data for 1v1 match prediction?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Hello Everyone,\nI have an issue I have to immediately deal with it. I installed mlxtend and used the library for apriori(market research). In my first attempt it worked then next day I tried to update it with new data but it gives exactly this error ModuleNotFoundError: No module named 'mlxtend'. And I read everywhere to find where my mistake is? Sadly, I couldn't find it. I updated my mlxtend to current version however, again I faced with the exact, same problem. When I try to install mlxtend I got this as it is expected \"Requirement already satisfied\". I would appreciate and be glad if you have any suggestions? By the way, thanks to everyone who read this.","AnswerCount":1,"Available Count":1,"Score":0.537049567,"is_accepted":false,"ViewCount":1202,"Q_Id":64828540,"Users Score":3,"Answer":"Are you installing it in the Conda shell or somewhere else? To ensure it gets installed in the correct environment type\n%pip install mlxtend\nfrom within the Jupyter notebook (in a cell at the top) that you are working in and execute that cell.\nIf it installs successfully you can comment out that cell or remove it.","Q_Score":3,"Tags":"python,python-3.x,jupyter-notebook,mlxtend","A_Id":64828695,"CreationDate":"2020-11-13T21:57:00.000","Title":"ModuleNotFoundError: No module named 'mlxtend'","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I decided to build a large dataset with augmented images in order to save time during the training, which takes too long due to every image being augmented on the fly, thus reducing performance and GPU usage.\nI was wondering if it is possible for every epoch to train on a subset of the dataset in order to save time (train on 4000 images instead of 40000). This is somehow similar to cross validation, but my aim is simply to reduce the portion of dataset on which the model is being trained every epoch, and alternating these small portions randomly. In cross validation of course I would not reduce my training dataset size, just alternate the validation set.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":506,"Q_Id":64833692,"Users Score":1,"Answer":"By definition an epoch means that the entire dataset is passed trought the model for training. However you can use mini-batch training, divide the entire dataset into batches and train one batch at the time using .next_batch() function or by iterating over the dataset.\nWhen you define your dataset you can use .shuffle() if you want the data in your bacthes to be randomly selected at each epoch and .batch(batch_size) to define how many samples to use for each batch.","Q_Score":0,"Tags":"python,tensorflow,machine-learning,deep-learning,training-data","A_Id":64834322,"CreationDate":"2020-11-14T12:04:00.000","Title":"Tensorflow training on different subset of dataset each epoch","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am training several agents with PPO algorithms in a multi-agent environment using rllib\/ray. I am using the ray.tune() command to train the agents and then loading the training data from ~\/ray_results. This data contains the actions chosen by the agents in each training episode, but I also need the corresponding agent rewards. I've looked at the documentation, but there doesn't seem to be configuration argument that allows for saving episode rewards. Does anyone have a workaround for this?","AnswerCount":3,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":374,"Q_Id":64833781,"Users Score":0,"Answer":"Did you check progress.csv and result.json? The details of the reward for each agent in every episode can be found there.","Q_Score":2,"Tags":"python,reinforcement-learning,ray,rllib,ray-tune","A_Id":68217425,"CreationDate":"2020-11-14T12:15:00.000","Title":"Save episode rewards in ray.tune","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am training several agents with PPO algorithms in a multi-agent environment using rllib\/ray. I am using the ray.tune() command to train the agents and then loading the training data from ~\/ray_results. This data contains the actions chosen by the agents in each training episode, but I also need the corresponding agent rewards. I've looked at the documentation, but there doesn't seem to be configuration argument that allows for saving episode rewards. Does anyone have a workaround for this?","AnswerCount":3,"Available Count":2,"Score":0.0665680765,"is_accepted":false,"ViewCount":374,"Q_Id":64833781,"Users Score":1,"Answer":"You need to add these values into the info dict, then it will get collected by ray tune.","Q_Score":2,"Tags":"python,reinforcement-learning,ray,rllib,ray-tune","A_Id":68344747,"CreationDate":"2020-11-14T12:15:00.000","Title":"Save episode rewards in ray.tune","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Introduction\nI have written code to give me a set of numbers in '36 by q' format ( 1<= q <= 36), subject to following conditions:\n\nEach row must use numbers from 1 to 36.\nNo number must repeat itself in a column.\n\nMethod\nThe first row is generated randomly. Each number in the coming row is checked for the above conditions. If a number fails to satisfy one of the given conditions, it doesn't get picked again fot that specific place in that specific row. If it runs out of acceptable values, it starts over again.\nProblem\nUnlike for low q values (say 15 which takes less than a second to compute), the main objective is q=36. It has been more than 24hrs since it started to run for q=36 on my PC.\nQuestions\n\nCan I predict the time required by it using the data I have from lower q values? How?\n\nIs there any better algorithm to perform this in less time?\n\nHow can I calculate the average number of cycles it requires? (using combinatorics or otherwise).","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":48,"Q_Id":64841034,"Users Score":1,"Answer":"Graph q vs time\nFit a curve,\nExtrapolate to q = 36.\n\nYou might want to also graph q vs log(time) as that may give an easier fitted curve.","Q_Score":0,"Tags":"python-3.x,algorithm,time,computation","A_Id":64853811,"CreationDate":"2020-11-15T03:48:00.000","Title":"Question(s) regarding computational intensity, prediction of time required to produce a result","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have got a dataframe looks like this:\n\n12000 pa\n13000 per annum\n25000 pa\n34000 per annum\n\nI need to update all four cells into int only, so:\n\n12000\n13000\n25000\n34000\n\nWhat is the quickest method for doing this?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":17,"Q_Id":64843082,"Users Score":0,"Answer":"One of the possible solutions:\ndf[\"price_int\"] = df[\"price\"].apply(lambda value: int(value.split(\" \")[0]))\nOr you can use Regex (more robust):\ndf[\"price_int\"] = df[\"price\"].str.extract(r'(^[0-9]+)').astype(int)","Q_Score":0,"Tags":"python","A_Id":64843127,"CreationDate":"2020-11-15T09:56:00.000","Title":"Update column under dataframe by regex","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"When splitting the data into the test and training data what split size should I choose?\nI was told that set by default is 80 % for training data,and 20 % for test data, can somebody ensure me?\nThanks","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":391,"Q_Id":64847418,"Users Score":0,"Answer":"The default split size in sklearn.model_selection.train_test_split are 75% training and 25% testing data split. Data splits should depend on the task at hand.\nThe rule of thumb is that you have enough represent data that represent your problem to train a model and a enough representative data to validate your trained model.","Q_Score":0,"Tags":"python,tensorflow,keras","A_Id":64847609,"CreationDate":"2020-11-15T17:15:00.000","Title":"What is a default split_size in model training?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm facing a problem with ANFIS model if the number of columns used in X range exceeds two I will receive an error as below. Is there any way to increase the number of Inputs ? Thanks In advance\nimport anfis\nimport membershipfunction\nimport mfDerivs\nimport pandas as pd\nimport numpy as np\nts = pd.read_csv(\"ANFIS training sets.csv\")\nX = ts.iloc[:,0:3].values\nY = ts.iloc[:,-1].values\nError:\nNumber of variables does not match number of rule sets\nTraceback (most recent call last):\nFile \"D:\/UTAR\/ANFIS monthly Inflow.py\", line 16, in \nanf.trainHybridJangOffLine(epochs=5)\nFile \"D:\\UTAR\\anfis.py\", line 66, in trainHybridJangOffLine\n[layerFour, wSum, w,] = forwardHalfPass(self, self.X)\nFile \"D:\\UTAR\\anfis.py\", line 178, in forwardHalfPass\nlayerOne = ANFISObj.memClass.evaluateMF(Xs[pattern,:])\nFile \"D:\\UTAR\\membershipfunction.py\", line 22, in evaluateMF\nreturn [[self.funcDictself.MFList[i][k][0] for k in range(len(self.MFList[i]))] for i in range(len(rowInput))]\nFile \"D:\\UTAR\\membershipfunction.py\", line 22, in \nreturn [[self.funcDictself.MFList[i][k][0] for k in range(len(self.MFList[i]))] for i in range(len(rowInput))]\nIndexError: list index out of range","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":185,"Q_Id":64852604,"Users Score":0,"Answer":"Anyway after reading through python libraries it just accept 2 inputs so my advice is do use MATLAB as it is a lot more easier as ANFIS is already built in it","Q_Score":0,"Tags":"python,pycharm,artificial-intelligence,indexoutofrangeexception","A_Id":64869476,"CreationDate":"2020-11-16T04:08:00.000","Title":"Is there any way to have more than 2 inputs in ANFIS?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I know how to use scikit-learn and pandas to encode my categorical data. I've been using the category codes in pandas for now which I later will transform into an OneHot encoded format for ML.\nMy issues is that I need to create a pre-processing pipeline for multiple files with the same data format. I've discovered that using the pandas category codes encoding is not consistent, even if the categories (strings) in the data are identical across multiple files.\nIs there a way to do this encoding lexicographically so that it's done the same way across all files or is there any specific method that can be used which would result in the same encoding when applied on multiple files?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":58,"Q_Id":64875297,"Users Score":0,"Answer":"The LabelEncoder like all other Sklearn-Transformers has three certain methods:\n\nfit(): Creates the labels given some input data\ntransform(): Transforms data to the labels of the encoder instance. It must have called fit() before or will throw an error\nfit_transform(): That's a convenience-method that will create the labels and transform the data directly.\n\nI'm guessing you are calling fit_transform everywhere. To fix this, just call the fit-method once (on a superset of all your data because it will throw an error if it encounters a label that was not present in the data you called fit on) and than use the transform method.","Q_Score":0,"Tags":"python,pandas,scikit-learn","A_Id":64875397,"CreationDate":"2020-11-17T12:28:00.000","Title":"Maintaining label encoding across different files in pandas","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Since today tensorflow seems to output the entire model per epoch for some reason. I am breaking my head over this problem and have no idea what to do.\nEpoch 1\/12\niterator: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\niterator_1: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential_conv2d_conv2d_readvariableop_resource: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential_conv2d_biasadd_readvariableop_resource: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential_conv2d_1_conv2d_readvariableop_resource: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential_conv2d_1_biasadd_readvariableop_resource: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential_conv2d_2_conv2d_readvariableop_resource: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential_conv2d_2_biasadd_readvariableop_resource: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential_dense_matmul_readvariableop_resource: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential_dense_biasadd_readvariableop_resource: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential_dense_1_matmul_readvariableop_resource: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential_dense_1_biasadd_readvariableop_resource: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential_dense_2_matmul_readvariableop_resource: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential_dense_2_biasadd_readvariableop_resource: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nassignaddvariableop_resource: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nassignaddvariableop_1_resource: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nadam_cast_readvariableop_resource: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nadam_readvariableop_resource: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nadam_cast_2_readvariableop_resource: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nadam_cast_3_readvariableop_resource: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nadam_adam_update_resourceapplyadam_m: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nadam_adam_update_resourceapplyadam_v: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nadam_adam_update_1_resourceapplyadam_m: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nadam_adam_update_1_resourceapplyadam_v: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nadam_adam_update_2_resourceapplyadam_m: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nadam_adam_update_2_resourceapplyadam_v: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nadam_adam_update_3_resourceapplyadam_m: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nadam_adam_update_3_resourceapplyadam_v: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nadam_adam_update_4_resourceapplyadam_m: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nadam_adam_update_4_resourceapplyadam_v: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nadam_adam_update_5_resourceapplyadam_m: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nadam_adam_update_5_resourceapplyadam_v: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nadam_adam_update_6_resourceapplyadam_m: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nadam_adam_update_6_resourceapplyadam_v: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nadam_adam_update_7_resourceapplyadam_m: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nadam_adam_update_7_resourceapplyadam_v: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nadam_adam_update_8_resourceapplyadam_m: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nadam_adam_update_8_resourceapplyadam_v: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nadam_adam_update_9_resourceapplyadam_m: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nadam_adam_update_9_resourceapplyadam_v: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nadam_adam_update_10_resourceapplyadam_m: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nadam_adam_update_10_resourceapplyadam_v: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nadam_adam_update_11_resourceapplyadam_m: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nadam_adam_update_11_resourceapplyadam_v: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nassignaddvariableop_2_resource: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nassignaddvariableop_3_resource: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nassignaddvariableop_4_resource: (_Arg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nIteratorGetNext: (IteratorGetNext): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nExpandDims: (ExpandDims): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/conv2d\/Conv2D\/ReadVariableOp: (ReadVariableOp): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/conv2d\/Conv2D: (Conv2D): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/conv2d\/BiasAdd\/ReadVariableOp: (ReadVariableOp): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/conv2d\/BiasAdd: (BiasAdd): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/conv2d\/Relu: (Relu): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/max_pooling2d\/MaxPool: (MaxPool): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/conv2d_1\/Conv2D\/ReadVariableOp: (ReadVariableOp): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/conv2d_1\/Conv2D: (Conv2D): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/conv2d_1\/BiasAdd\/ReadVariableOp: (ReadVariableOp): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/conv2d_1\/BiasAdd: (BiasAdd): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/conv2d_1\/Relu: (Relu): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/max_pooling2d_1\/MaxPool: (MaxPool): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/conv2d_2\/Conv2D\/ReadVariableOp: (ReadVariableOp): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/conv2d_2\/Conv2D: (Conv2D): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/conv2d_2\/BiasAdd\/ReadVariableOp: (ReadVariableOp): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/conv2d_2\/BiasAdd: (BiasAdd): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/conv2d_2\/Relu: (Relu): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/max_pooling2d_2\/MaxPool: (MaxPool): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/flatten\/Reshape: (Reshape): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/dense\/MatMul\/ReadVariableOp: (ReadVariableOp): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/dense\/MatMul: (MatMul): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/dense\/BiasAdd\/ReadVariableOp: (ReadVariableOp): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/dense\/BiasAdd: (BiasAdd): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/dense\/Sigmoid: (Sigmoid): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/dense_1\/MatMul\/ReadVariableOp: (ReadVariableOp): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/dense_1\/MatMul: (MatMul): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/dense_1\/BiasAdd\/ReadVariableOp: (ReadVariableOp): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/dense_1\/BiasAdd: (BiasAdd): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/dense_1\/Tanh: (Tanh): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/dense_2\/MatMul\/ReadVariableOp: (ReadVariableOp): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/dense_2\/MatMul: (MatMul): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/dense_2\/BiasAdd\/ReadVariableOp: (ReadVariableOp): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/dense_2\/BiasAdd: (BiasAdd): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/Cast: (Cast): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/sub: (Sub): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/clip_by_value\/Minimum: (Minimum): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/clip_by_value: (Maximum): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/add: (AddV2): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/Log: (Log): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/mul: (Mul): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/sub_1: (Sub): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/sub_2: (Sub): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/add_1: (AddV2): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/Log_1: (Log): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/mul_1: (Mul): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/add_2: (AddV2): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/Neg: (Neg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/Mean: (Mean): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/weighted_loss\/Mul: (Mul): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/weighted_loss\/Sum: (Sum): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/weighted_loss\/num_elements: (Size): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/weighted_loss\/num_elements\/Cast: (Cast): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/weighted_loss\/Sum_1: (Sum): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/weighted_loss\/value: (DivNoNan): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nShape: (Shape): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nstrided_slice: (StridedSlice): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nCast: (Cast): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nMul: (Mul): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nSum: (Sum): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAssignAddVariableOp: (AssignAddVariableOp): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nSum_1: (Sum): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAssignAddVariableOp_1: (AssignAddVariableOp): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/weighted_loss\/value\/BroadcastGradientArgs: (BroadcastGradientArgs): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/weighted_loss\/value\/div_no_nan: (DivNoNan): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/weighted_loss\/value\/Sum: (Sum): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/weighted_loss\/value\/Reshape: (Reshape): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/weighted_loss\/value\/Neg: (Neg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/weighted_loss\/value\/div_no_nan_1: (DivNoNan): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/weighted_loss\/value\/div_no_nan_2: (DivNoNan): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/weighted_loss\/value\/mul: (Mul): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/weighted_loss\/value\/Sum_1: (Sum): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/weighted_loss\/value\/Reshape_1: (Reshape): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/weighted_loss\/Reshape: (Reshape): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/weighted_loss\/Tile: (Tile): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/weighted_loss\/Reshape_1: (Reshape): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/weighted_loss\/Shape: (Shape): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/weighted_loss\/Tile_1: (Tile): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/weighted_loss\/Mul: (Mul): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/Shape: (Shape): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/add: (AddV2): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/mod: (FloorMod): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/range: (Range): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/Fill: (Fill): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/DynamicStitch: (DynamicStitch): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/Reshape: (Reshape): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/BroadcastTo: (BroadcastTo): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/Shape_2: (Shape): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/Shape_3: (Shape): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/Prod: (Prod): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/Prod_1: (Prod): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/Maximum: (Maximum): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/floordiv: (FloorDiv): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/Cast: (Cast): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/truediv: (RealDiv): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/Neg: (Neg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/add_2\/Shape: (Shape): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/add_2\/Shape_1: (Shape): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/add_2\/BroadcastGradientArgs: (BroadcastGradientArgs): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/add_2\/Sum: (Sum): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/add_2\/Reshape: (Reshape): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/add_2\/Sum_1: (Sum): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/add_2\/Reshape_1: (Reshape): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/mul\/Shape: (Shape): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/mul\/Shape_1: (Shape): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/mul\/BroadcastGradientArgs: (BroadcastGradientArgs): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/mul\/Mul: (Mul): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/mul\/Sum: (Sum): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/mul\/Reshape: (Reshape): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/mul_1\/Shape: (Shape): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/mul_1\/Shape_1: (Shape): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/mul_1\/BroadcastGradientArgs: (BroadcastGradientArgs): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/mul_1\/Mul: (Mul): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/mul_1\/Sum: (Sum): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/mul_1\/Reshape: (Reshape): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/Reciprocal: (Reciprocal): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/mul: (Mul): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/Reciprocal_1: (Reciprocal): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/mul_1: (Mul): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/sub_2\/Shape: (Shape): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/sub_2\/Shape_1: (Shape): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/sub_2\/BroadcastGradientArgs: (BroadcastGradientArgs): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/sub_2\/Neg: (Neg): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/sub_2\/Sum: (Sum): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/sub_2\/Reshape: (Reshape): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAddN: (AddN): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/clip_by_value\/zeros_like: (ZerosLike): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/clip_by_value\/GreaterEqual: (GreaterEqual): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/clip_by_value\/SelectV2: (SelectV2): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/clip_by_value\/zeros_like_1: (ZerosLike): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/clip_by_value\/LessEqual: (LessEqual): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/clip_by_value\/SelectV2_1: (SelectV2): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/sequential\/dense_2\/BiasAdd\/BiasAddGrad: (BiasAddGrad): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/sequential\/dense_2\/MatMul: (MatMul): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/sequential\/dense_2\/MatMul_1: (MatMul): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/sequential\/dense_1\/TanhGrad: (TanhGrad): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/sequential\/dense_1\/BiasAdd\/BiasAddGrad: (BiasAddGrad): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/sequential\/dense_1\/MatMul: (MatMul): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/sequential\/dense_1\/MatMul_1: (MatMul): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/sequential\/dense\/Sigmoid\/SigmoidGrad: (SigmoidGrad): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/sequential\/dense\/BiasAdd\/BiasAddGrad: (BiasAddGrad): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/sequential\/dense\/MatMul: (MatMul): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/sequential\/dense\/MatMul_1: (MatMul): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/sequential\/flatten\/Shape: (Shape): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/sequential\/flatten\/Reshape: (Reshape): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/sequential\/max_pooling2d_2\/MaxPool\/MaxPoolGrad: (MaxPoolGrad): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/sequential\/conv2d_2\/ReluGrad: (ReluGrad): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/sequential\/conv2d_2\/BiasAdd\/BiasAddGrad: (BiasAddGrad): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/sequential\/conv2d_2\/Conv2D\/ShapeN: (ShapeN): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/sequential\/conv2d_2\/Conv2D\/Conv2DBackpropInput: (Conv2DBackpropInput): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/sequential\/conv2d_2\/Conv2D\/Conv2DBackpropFilter: (Conv2DBackpropFilter): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/sequential\/max_pooling2d_1\/MaxPool\/MaxPoolGrad: (MaxPoolGrad): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/sequential\/conv2d_1\/ReluGrad: (ReluGrad): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/sequential\/conv2d_1\/BiasAdd\/BiasAddGrad: (BiasAddGrad): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/sequential\/conv2d_1\/Conv2D\/ShapeN: (ShapeN): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/sequential\/conv2d_1\/Conv2D\/Conv2DBackpropInput: (Conv2DBackpropInput): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/sequential\/conv2d_1\/Conv2D\/Conv2DBackpropFilter: (Conv2DBackpropFilter): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/sequential\/max_pooling2d\/MaxPool\/MaxPoolGrad: (MaxPoolGrad): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/sequential\/conv2d\/ReluGrad: (ReluGrad): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/sequential\/conv2d\/BiasAdd\/BiasAddGrad: (BiasAddGrad): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/sequential\/conv2d\/Conv2D\/ShapeN: (ShapeN): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/sequential\/conv2d\/Conv2D\/Conv2DBackpropInput: (Conv2DBackpropInput): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/sequential\/conv2d\/Conv2D\/Conv2DBackpropFilter: (Conv2DBackpropFilter): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/Cast\/ReadVariableOp: (ReadVariableOp): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/Identity: (Identity): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/ReadVariableOp: (ReadVariableOp): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/add: (AddV2): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/Cast_1: (Cast): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/Cast_2\/ReadVariableOp: (ReadVariableOp): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/Identity_1: (Identity): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/Cast_3\/ReadVariableOp: (ReadVariableOp): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/Identity_2: (Identity): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/Pow: (Pow): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/Pow_1: (Pow): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/sub: (Sub): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/Sqrt: (Sqrt): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/sub_1: (Sub): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/truediv: (RealDiv): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/mul: (Mul): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/sub_2: (Sub): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/sub_3: (Sub): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/Adam\/update\/ResourceApplyAdam: (ResourceApplyAdam): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/Adam\/update_1\/ResourceApplyAdam: (ResourceApplyAdam): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/Adam\/update_2\/ResourceApplyAdam: (ResourceApplyAdam): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/Adam\/update_3\/ResourceApplyAdam: (ResourceApplyAdam): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/Adam\/update_4\/ResourceApplyAdam: (ResourceApplyAdam): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/Adam\/update_5\/ResourceApplyAdam: (ResourceApplyAdam): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/Adam\/update_6\/ResourceApplyAdam: (ResourceApplyAdam): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/Adam\/update_7\/ResourceApplyAdam: (ResourceApplyAdam): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/Adam\/update_8\/ResourceApplyAdam: (ResourceApplyAdam): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/Adam\/update_9\/ResourceApplyAdam: (ResourceApplyAdam): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/Adam\/update_10\/ResourceApplyAdam: (ResourceApplyAdam): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/Adam\/update_11\/ResourceApplyAdam: (ResourceApplyAdam): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/Adam\/AssignAddVariableOp: (AssignAddVariableOp): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nCast_1: (Cast): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nGreater: (Greater): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nCast_3: (Cast): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nEqual: (Equal): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nCast_4: (Cast): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nMean: (Mean): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nSum_2: (Sum): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAssignAddVariableOp_2: (AssignAddVariableOp): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nSize: (Size): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nCast_5: (Cast): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAssignAddVariableOp_3: (AssignAddVariableOp): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ndiv_no_nan\/ReadVariableOp: (ReadVariableOp): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ndiv_no_nan\/ReadVariableOp_1: (ReadVariableOp): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ndiv_no_nan: (DivNoNan): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nIdentity: (Identity): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ndiv_no_nan_1\/ReadVariableOp: (ReadVariableOp): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ndiv_no_nan_1\/ReadVariableOp_1: (ReadVariableOp): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ndiv_no_nan_1: (DivNoNan): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nIdentity_1: (Identity): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAssignAddVariableOp_4: (AssignAddVariableOp): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nNoOp: (NoOp): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nNoOp_1: (NoOp): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nIdentity_2: (Identity): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nIdentity_3: (Identity): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nidentity_2_RetVal: (_Retval): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nidentity_3_RetVal: (_Retval): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nConst: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nExpandDims\/dim: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nsequential\/flatten\/Const: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/Const: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/Const_1: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/sub\/x: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/add\/y: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/sub_1\/x: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/sub_2\/x: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/add_1\/y: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/Mean\/reduction_indices: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/weighted_loss\/Const: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/weighted_loss\/Const_1: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nbinary_crossentropy\/weighted_loss\/Const_2: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nstrided_slice\/stack: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nstrided_slice\/stack_1: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nstrided_slice\/stack_2: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nConst_1: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nConst_2: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nones: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/weighted_loss\/value\/Shape: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/weighted_loss\/value\/Shape_1: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/weighted_loss\/Reshape\/shape: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/weighted_loss\/Const: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/weighted_loss\/Reshape_1\/shape: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/Size: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/Shape_1: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/range\/start: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/range\/delta: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/Fill\/value: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/Const: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/Const_1: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\ngradient_tape\/binary_crossentropy\/Maximum\/y: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/add\/y: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/sub\/x: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/sub_1\/x: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/Const: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/sub_2\/x: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/sub_3\/x: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nAdam\/Adam\/Const: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nCast_2\/x: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nMean\/reduction_indices: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nConst_3: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\nConst_4: (Const): \/job:localhost\/replica:0\/task:0\/device:CPU:0\n7\/15 [=============>................] - ETA: 1:12 - loss: 0.0874 - accuracy: 0.9498","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":73,"Q_Id":64883800,"Users Score":1,"Answer":"Figured out why I get this output all of a sudden...\nI have a piece of code at the start of training to prepare my environment, also where I can force use GPU or CPU usage. For over two years now I had been using:\ntf.debugging.set_log_device_placement(True)\nwith no logging happening at all.\nNow all of a sudden tensorflow decided it was a nice idea to start logging all of it. Set it to False and all is good now!","Q_Score":0,"Tags":"python,tensorflow","A_Id":64891750,"CreationDate":"2020-11-17T21:45:00.000","Title":"Tensorflow gives different console output, and is slower for some reason","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have simultaneous equations(with many equations), which are no solution, and I need to find a best solutions. Each element of solution must>0 (no 0 or negative).\nnp.linalg.lstsq could get the best solution, but may also appear negative elements.\nscipy.optimize.nnls could get best solution without negative elements, but may also appear 0.\nHow can I restrict to get the best solution with each element>0 or is there any other function can use to solve the problem?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":59,"Q_Id":64890254,"Users Score":0,"Answer":"For each parameter p, define p_ = p - eps for very small eps.\nSolve for {p_}, then assign p = p_ + eps and you get all parameters above zero.\nIn practice, just add epsilon to the solution.\nIf that doesn't suffice, please explain why.","Q_Score":0,"Tags":"python,numpy,scipy,linear-algebra","A_Id":64890515,"CreationDate":"2020-11-18T09:24:00.000","Title":"python solve the simultaneous equations with solutions > 0","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"My requirement is to pass the list of all column names as a parameter in dataframe.select(columns)\n\nFirst of all I am using dataframe.columns to get me the list of\nall the columns. Which I am storing as list1=(dataframe.columns)\n\nSecondly I am using .join to convert my\nlist of columns in strings like - (strList1 = \"','\".join(list1)) which gives me the following output\n\ncol1','col2','col3','col4\n\nAs you see there is some missing single quotes at the start & end of the string\n\nTo rectify strList1 i use f-string formatting as follows -\nstrList2 = f\"{strList1}'\"which gives me the following output\n\n'col1','col2','col3','col4'\n\n\n\nThe main problem:\nWhen you pass strList2 as a parameter in dataframe.select(strList2) gives me the following error\n\nPy4JJavaError: An error occurred while calling o5813.select. :\norg.apache.spark.sql.AnalysisException: cannot resolve\n'backquotecol1','col2','col3','col4'backquote'\ngiven input columns: [\ncol1, col2, db.table.col4,\ndb.table.col3];; 'Project\n['col1','col2','col3','col4']\n\nNote - There is a backquote before col1 and after col4\nI don't understand why the select function isn't taking a proper string value \/ variable (strList2)","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":275,"Q_Id":64894644,"Users Score":1,"Answer":"You are passing a string \"'col1','col2','col3','col4'\" to df.select. There is no such column called \"'col1','col2','col3','col4'\", therefore df.select(\"'col1','col2','col3','col4'\") will result in an error.\nInstead of passing that string, what you need to do is to pass in a list of strings of column names to df.select. df.columns is already that list (e.g. ['col1', 'col2']), so you can simply do df.select(df.columns).\nIn fact, if you simply want to show all columns, you can do df.select('*').","Q_Score":1,"Tags":"python,list,apache-spark,pyspark","A_Id":64894990,"CreationDate":"2020-11-18T14:04:00.000","Title":"How to convert all the contents of a list to individual strings to pass as a parameter in dataframe.select()?","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have an array of y-values which are evenly spaced along the x-axis and I need to programmatically find the \"troughs\". I think either Octave or Python3 are good language choices for this problem as I know both have strong math capabilities.\nI thought to interpolate the function and look for where the derivatives are 0, but that would require my human eyes to first analyze the resulting graph to know where the maxima and minima already were, but I need this entire thing to be automatic; as to work with an arbitrary dataset.\nIt dawned on me that this problem likely had an existing solution in a Python3 or Octave function or library, but I could not find one. Does there exist a library to automatically report local maximas and minimas within a dataset?\nMore Info\nMy current planned approach is to implement a sort of \"n-day moving average\" with a threshold. After initializing the first day moving average, I'll watch for the next moving average to move above or below it by a threshold. If it moves higher then I'll consider myself in a \"rising\" period. If it moves lower then I'm in a \"falling\" period. While I'm in a rising period, I'll update the maximum observed moving average until the current moving average is sufficiently below the previous maximum.\nAt this point, I'll consider myself in a \"falling\" period. I'll lock in the point where the moving average was previously highest, and then repeat except using inverse logic for the \"falling\" period.\nIt seemed to me that this is probably a pretty common problem though, so I'm sure there's an existing solution.","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":53,"Q_Id":64899840,"Users Score":1,"Answer":"Octave answer:\nI believe immaximas and imregionalmax do exactly what you are looking for (depending on which of the two it is exactly that you are looking for - have a look at their documentation to see the difference).\nThese are part of the image package, but will obviously work on 1D signals too.\nFor more 'functional' zero-finding functions, there is also fzero etc.","Q_Score":1,"Tags":"python,python-3.x,math,octave,analytics","A_Id":64910826,"CreationDate":"2020-11-18T19:14:00.000","Title":"How to programatically report reasonable local maximas and minimas in a data set?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to create a Word2Vec model using gensim but I don't understand what Workers mean.\nThis is an examples from radimrehurek.com with workers = 4 but there is no explanation for that.\nWord2Vec(sentences=common_texts, vector_size=100, window=5, min_count=1, workers=4)\nI would be very thankful of anyone can help me.Thxx","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":314,"Q_Id":64901436,"Users Score":1,"Answer":"It's the number of Python worker threads that will be used during the training phase.\nIf you're using the traditional iterable-of-texts (like your sentences parameter) to supply your corpus, and you're on a machine with at least 4 CPU cores, you'll usually get the best throughput with a workers value of at least 3, and perhaps as high as 8-12 (but never higher than the number of CPU cores minus one).\nIf your input is a plain text file, with tokens already whitespace-delimited, and individual newline-delimited texts of no more than 10000-tokens each, you can use the more-recently introduced corpus_file option to specify the corpus. In that case, you are likely to achieve maximum training throughput with workers equal to the number of available CPU cores.\n(You can get the number of cores with import multiprocessing then multiprocessing.cpu_count().)","Q_Score":0,"Tags":"python,nlp,gensim,word2vec","A_Id":64901759,"CreationDate":"2020-11-18T21:10:00.000","Title":"what does workers means in gensim Word2Vec?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"The size of my jupyter notebook at this moment is 417 MB. I am analyzing 7 huge csv files at the same time and plotting figures using plotly. I am fairly new to coding. Is it normal to create such huge notebooks?\nThank you.","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":595,"Q_Id":64925423,"Users Score":2,"Answer":"Select the Cell -> then select All Outputs -> There you will find Clear option select that. And then save the file. This will reduce the size of your file (From MBs to kbs). It will also reduce the time to load the notebook next time you open it in your browser.","Q_Score":3,"Tags":"python,optimization,jupyter-notebook,plotly","A_Id":64925487,"CreationDate":"2020-11-20T07:30:00.000","Title":"How can i reduce the size of my Jupyter Notebook where i am analyzing a huge dataset and plotting using plotly?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"Tensorflow 2.3 introduced new preprocessing layers, such as tf.keras.layers.experimental.preprocessing.Resizing.\nHowever, the typical flow to train on images with Keras uses tf.keras.preprocessing.image.ImageDataGenerator, which can only take a fixed target_size parameter. As far as I understand, the root cause is that keras is handling images as a numpy array in the background, where all images have to be the same size (is that true?).\nWhile I could then use a model with a resizing layer that was trained on a fixed size to then predict images of arbitrary size, this seems to be risky since the training data and inference data would have systematic differences. One workaround could be to use ImageDataGenerator with a target_size and interpolation method that match the ones of the resizing layer, so that during training the resizing layer basically does nothing, but then it seems that the resizing layer is not really of any benefit.\nSo the question is, is there a way to train directly on mixed size images to fully take advantage of the resizing layer?","AnswerCount":1,"Available Count":1,"Score":-0.1973753202,"is_accepted":false,"ViewCount":489,"Q_Id":64925719,"Users Score":-1,"Answer":"models needs to operate on images of a FIXED size. If you train a model with a fixed size for example (224 X 224) then if you want to use the trained model to make predictions on images you need to resize those images to 224 X 224. Specifically whatever pre-processing you did on the training images you should also do on the images that you wish to predict. For example if your model was trained on RGB images but the images you want to predict are say BGR images (like reading in images with CV2) the results will be incorrect. You would need to convert them to RGB . Similarly if you rescaled you training images by dividing by 255 you should also rescale the images you want to predict.","Q_Score":0,"Tags":"python,tensorflow,keras","A_Id":64932709,"CreationDate":"2020-11-20T07:55:00.000","Title":"Correct way to take advantage of Resizing layer in Tensorflow 2.3?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a camera in a fixed position looking at a target and I want to detect whether someone walks in front of the target. The lighting in the scene can change so subtracting the new changed frame from the previous frame would therefore detect motion even though none has actually occurred. I have thought to compare the number of contours (obtained by using findContours() on a binary edge image obtained with canny and then getting size() of this) between the two frames as a big change here could denote movement while also being less sensitive to lighting changes, I am quite new to OpenCV and my implementations have not been successful so far. Is there a way I could make this work or will I have to just subtract the frames. I don't need to track the person, just detect whether they are in the scene.","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":490,"Q_Id":64943957,"Users Score":0,"Answer":"There are a handful of ways you could do this.\nThe first that comes to mind is doing a 2D FFT on the incoming images. Color shouldn't affect the FFT too much, but an object moving, entering\/exiting a frame will.\nThe second is to use SIFT or SURF to generate a list of features in an image, you can insert these points into a map, sorted however you like, then do a set_difference between the last image you took, and the current image that you have. You could also use the FLANN functionality to compare the generated features.","Q_Score":1,"Tags":"python,c++,opencv,image-processing","A_Id":64944021,"CreationDate":"2020-11-21T14:08:00.000","Title":"How do you detect if there is motion between frames using opencv without simply subtracting the frames?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a camera in a fixed position looking at a target and I want to detect whether someone walks in front of the target. The lighting in the scene can change so subtracting the new changed frame from the previous frame would therefore detect motion even though none has actually occurred. I have thought to compare the number of contours (obtained by using findContours() on a binary edge image obtained with canny and then getting size() of this) between the two frames as a big change here could denote movement while also being less sensitive to lighting changes, I am quite new to OpenCV and my implementations have not been successful so far. Is there a way I could make this work or will I have to just subtract the frames. I don't need to track the person, just detect whether they are in the scene.","AnswerCount":2,"Available Count":2,"Score":0.1973753202,"is_accepted":false,"ViewCount":490,"Q_Id":64943957,"Users Score":2,"Answer":"I am a bit rusty but there are various ways to do this.\nSIFT and SURF are very expensive operations, so I don't think you would want to use them.\nThere are a couple of 'background removal' methods.\n\nAverage removal: in this one you get the average of N frames, and consider it as BG. This is vulnerable to many things, light changes, shadow, moving object staying at a location for long time etc.\n\nGaussian Mixture Model: a bit more advanced than 1. Still vulnerable to a lot of things.\n\nIncPCP (incremental principal component pursuit): I can't remember the algorithm totally but basic idea was they convert each frame to a sparse form, then extract the moving objects from sparse matrix.\n\nOptical flow: you find the change across the temporal domain of a video. For example, you compare frame2 with frame1 block by block and tell the direction of change.\n\nCNN based methods: I know there are a bunch of them, but I didn't really follow them. You might have to do some research. As far as I know, they often are better than the methods above.\n\n\nNotice that, for a @30Fps, your code should complete in 33ms per frame, so it could be real time. You can find a lot of code available for this task.","Q_Score":1,"Tags":"python,c++,opencv,image-processing","A_Id":64944752,"CreationDate":"2020-11-21T14:08:00.000","Title":"How do you detect if there is motion between frames using opencv without simply subtracting the frames?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Been searching for a while in order to understand how to do this basic task without any success which is very strange.\nI have a dataset where some of the rows contain '-', I have no clue under which columns these values lie.\nHow do I search in the whole dataset (including all columns) for '-' and drop the rows containing this value?\nthank you!","AnswerCount":3,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":142,"Q_Id":64949099,"Users Score":0,"Answer":"This is a bit more robust than wwnde's answer, as it will work if some of the columns aren't originally strings:\ndf.loc[~df.apply(lambda x: any('-' in str(col) for col in x), axis = 1)]\nIf you have data that's stored as datetime, it will display as having -, but will return an error if you check for inclusion without converting to str first. Negative numbers will also return True once converted to str. If you want different behavior, you'll have to do something more complicated, such as\ndf.loc[~df.apply(lambda x: any('-' in col if isinstance(col, str) else False for col in x), axis = 1)]","Q_Score":2,"Tags":"python,pandas","A_Id":64949307,"CreationDate":"2020-11-21T23:14:00.000","Title":"Pandas, find and delete rows","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm new to the MacOS and I have recently downloaded PyCharm on it. I was able to successfully install some packages like numpy, matplotlib, sympy, etc. However, Pytorch won't get installed; not through PyCharm nor through the Terminal. These are the commands I tried in the Terminal (other than attempting to install them directly from PyCharm):\n\npip install torch\npip install torch torchvision torchaudio\n\nI could post the error messages but some are quite lengthy :(\nI'm using Python 3.9 interpreter with pip on the latest version (20.2.4) (everything else is also up to date). Running this on the new Mac Mini (running the M1 chip).\nAny ideas on what I should do? Thanks!!!","AnswerCount":2,"Available Count":2,"Score":1.2,"is_accepted":true,"ViewCount":1930,"Q_Id":64949501,"Users Score":3,"Answer":"Try building from the source code, run these commands\n\ngit clone https:\/\/github.com\/pytorch\/pytorch.git\ncd pytorch\ngit submodule update --init --recursive\npython3 setup.py build\npython3 setup.py install","Q_Score":1,"Tags":"python,python-3.x,macos,pip,pycharm","A_Id":65528845,"CreationDate":"2020-11-22T00:18:00.000","Title":"Pytorch won't install in PyCharm on MacOS","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm new to the MacOS and I have recently downloaded PyCharm on it. I was able to successfully install some packages like numpy, matplotlib, sympy, etc. However, Pytorch won't get installed; not through PyCharm nor through the Terminal. These are the commands I tried in the Terminal (other than attempting to install them directly from PyCharm):\n\npip install torch\npip install torch torchvision torchaudio\n\nI could post the error messages but some are quite lengthy :(\nI'm using Python 3.9 interpreter with pip on the latest version (20.2.4) (everything else is also up to date). Running this on the new Mac Mini (running the M1 chip).\nAny ideas on what I should do? Thanks!!!","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":1930,"Q_Id":64949501,"Users Score":0,"Answer":"Are you using a venv? If so you could try checking the box \"install to user's site packages directory\" in the Project Interpreter settings when you add a package.","Q_Score":1,"Tags":"python,python-3.x,macos,pip,pycharm","A_Id":64950507,"CreationDate":"2020-11-22T00:18:00.000","Title":"Pytorch won't install in PyCharm on MacOS","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a depth map image which was obtained using a kinect camera.\nIn that image I have selected a region of size [400,400] and stored it as another image.\nNow, I would like to know how to resize this image into a size of [x,y] in python.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":1044,"Q_Id":64952495,"Users Score":0,"Answer":"I don't recommend to reduce resolution of depth map the same way like it is done for images. Imagine a scene with a small object 5 m before the wall:\n\nUsing bicubic\/bilinear algorithms you will get depth of something between the object and the wall. In reality there is just a free space in between.\nUsing nearest-neighbor interpolation is better but you are ignoring a lot of information and in some cases it may happed that the object just disappears.\n\nThe best approach is to use the Mode function. Divide the original depth map into windows. Each window will represent one pixel in the downsized map. For each of them calculate the most frequent depth value. You can use Python's statistics.mode() function.","Q_Score":2,"Tags":"python,image-processing,computer-vision,kinect,opencv-python","A_Id":71402433,"CreationDate":"2020-11-22T09:23:00.000","Title":"How to resize a depth map from size [400,400] into size [60,60]?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have an n-element array. All elements except 4\u221an of them are sorted. We do not know the positions of these misplaced elements. What is the most efficient way of sorting this list?\nIs there an O(n) way to do this?\nUpdate 1:\ntime complexity of an\u200b insertion sort is O(n) for almost sorted data (is it true in worst case?)?","AnswerCount":2,"Available Count":1,"Score":1.0,"is_accepted":false,"ViewCount":1084,"Q_Id":64956096,"Users Score":6,"Answer":"There is a fast general method for sorting almost sorted arrays:\n\nScan through the original array from start to end. If you find two items that are not ordered correctly, move them to a second array and remove them from the first array. Be careful; for example if you remove x2 and x3, then you need to check again that x1 \u2264 x2. This is done in O(n) time. In your case, the new array is at most 8sqrt(n) in size.\n\nSort the second array, then merge both arrays. With the small number of items in the second array, any reasonable sorting algorithm will sort the small second array in O(n), and the merge takes O(n) again, so the total time is O(n).\n\n\nIf you use a O(n log n) algorithm to sort the second array, then sorting is O(n) as long as the number of items in the wrong position is at most O (n \/ log n).","Q_Score":5,"Tags":"python,arrays,algorithm,sorting,data-structures","A_Id":64956474,"CreationDate":"2020-11-22T15:41:00.000","Title":"insertion sort worst time complexity for near sorted array?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":1,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've created a Matlab program which resolve some linear program and i've translate the code in python.\nThe two solvers return a different results.\nI've used:\nPYTHON:\nres=linprog(f,A,b,A_eq=None,b_eq=None,bounds=(None,None),options={\"maxiter\":200, \"tol\":1e-6})\nMATLAB\noptions = optimoptions('linprog','Algorithm','interior-point');\n[res,fval]=linprog(f,A,b,[],[],[],[],options);\nDoes anyone know why i get different results?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":96,"Q_Id":64958268,"Users Score":0,"Answer":"Please, note that you compare different implementations of the same idea, but not the same method in different environments, so results may be different.\nIn general, the optimal solution is not stable, even for simple linear problems. If methods are slightly different or data are slightly different, solutions may vary a lot.\nIf I understand correctly modern Matlab interior-point uses a crossover process (after interior-point it locates the closest basis solution), so it is much different from the classical interior-point which scipy implementation is closer to. But even if you try interior-point-legacy in Matlab it probably still will be different from the opensource interior-point used in scipy.\nBut the optimal objective value is stable. So, look at the objective value. If it is closer than your tolerance (1e-6) then you just got numerically different solutions.\nIf the objective value diverges then it may be the result of slightly different data. If you generate data in Matlab write down to file and then read it in Python you may lose accuracy.\nIf data absolutely the same then it means that one of the solvers fails to find a solution. Again, it is different solvers.","Q_Score":0,"Tags":"python,matlab","A_Id":64959071,"CreationDate":"2020-11-22T19:01:00.000","Title":"LINPROG DIFFERENCES MATLAB AND PYTHON","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"My question is simple and divided in two sub-questions :\n\nI have two LabelEncoders with the exact same parameter .classes_ . But when I compare then with ==, they seems different. How can I check they are equal ?\n\nI also want to check two sklearn model (RandomForest already fitted) are equals ? The == check does not seems to work.","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":385,"Q_Id":64964765,"Users Score":1,"Answer":"If you compare two objects with ==, it will return False because they have different id.\nYou'd better override __eq__ function of class.","Q_Score":1,"Tags":"python,scikit-learn","A_Id":64965082,"CreationDate":"2020-11-23T08:22:00.000","Title":"Assert two sklearn object are equal","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Let there be an pattern that is known at certain points, but has an unknown functional form. Let there also be a data set. Both, as far as the computer can be concerned, are just a set of (x,y) values.\nHowever, I still want to fit my pattern to the data with a simple relation, a*P+b, and I want to find the best values for the parameters a,b with an actual fitting routine. How can I do this with something akin to optimize.curve_fit(), or do I have to invent my own method?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":202,"Q_Id":64971409,"Users Score":0,"Answer":"What you are trying to achieve has a name. It is a regression problem. You want to find a relation between data points and how they are linked.\nHaving said that, you can look into LinearRegression() from sci-kit learn. It would be useful for your case.\nNote: It might be possible that maybe linear regression can't capture whatever relation your data holds then try other models like SVM with a non linear kernel or maybe NN. (duh).","Q_Score":0,"Tags":"python,data-analysis,curve-fitting","A_Id":64971528,"CreationDate":"2020-11-23T15:32:00.000","Title":"Fitting one data pattern to another in Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I recently working on a non-convex optimization problem, and I have used Bayesian Optimization as a method to solve this problem. And it didn't show good convergence. (Is Bayesian Optimization is an effective way to solve this problem?)\nAnyone can help me to see if there're other efficient ways to solve the non-convex optimization problem?\nI'm using python, so, could anyone show me some package in python that can do it?\nThank you!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":116,"Q_Id":64977532,"Users Score":0,"Answer":"There\u2019s way too little information about your problem to suggest a solution. How many parameters do you have in your objective function? Do you have analytical gradients available? Is your objective function expensive to evaluate or very fast? Do you have bound constraints? Linear and\/or nonlinear constraints? Do you care about trying to find a global optimum or are you happy with a good enough local minimum\/maximum? Any reason why you chose Bayesian optimization to start with?","Q_Score":0,"Tags":"python,optimization,non-convex","A_Id":64999506,"CreationDate":"2020-11-23T22:32:00.000","Title":"Non-convex function optimization","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":1,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Let's say I have a CNN model to classify the handwritten numbers 1 to 10. I am using a dataset with 20,000 samples and I make a train test split of 50:50.\nThat leaves me with 10,000 for training and testing. Will, it automatically pick 1000 images from each class for testing\/training, or will it approximate it?\nI am trying a similar problem, (with different numbers of samples and classes) but I noticed that the testing data is not evenly split. For example, it has 1010 number ones being tested but only 990 number twos.\nIs this normal? I couldn't find any documentation verifying this. My dataset is large enough that the small discrepancy is irrelevant, but I still would like to confirm.\nThanks!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":106,"Q_Id":64978918,"Users Score":0,"Answer":"The test train loader will approximate the split, since it uses sampling with replacement each epoch to generate a test batch.","Q_Score":0,"Tags":"python,tensorflow,machine-learning,testing,training-data","A_Id":64978937,"CreationDate":"2020-11-24T01:18:00.000","Title":"When picking a train test split for model training, does it choose an even number of samples from all class?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a dataframe created from an excel sheet (the source).\nThe excel sheet will not have a header row.\nI have a table in mysql that is already created (the target). It will always be the exact same layout as the excel sheet.\nsource_data = pd.read_excel(full_path, sheet_name=sheet_name, skiprows=ignore_rows, header=None)\ndb_engine = [function the returns my mysql engine]\nsource_data.to_sql(name=table_name, con=db_engine, schema=schema_name, if_exists='append', index=False)\nThis fails with an error due to pandas using numbers as column names in the insert statement..\n[SQL: INSERT INTO [tablename] (0, 1) VALUES (%(0)s, %(1)s)]\nerror=(pymysql.err.OperationalError) (1054, \"Unknown column '0' in 'field list'\nhow can i get around this? Is there a different insert method i can use? do i really have to load up the dataframe with the proper column names from the table?","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":440,"Q_Id":64980947,"Users Score":0,"Answer":"Maybe after importing the data into Pandas, you can rename the columns to something that is not a number, e.g. \"First\", \"Second\", etc. or [str(i) for i in range(len(source_data))]\nThis would resolve the issue of SQL being confused by the numerical labels.","Q_Score":0,"Tags":"python,mysql,pandas,dataframe,sqlalchemy","A_Id":64981061,"CreationDate":"2020-11-24T05:55:00.000","Title":"using a pandas dataframe without headers to write to mysql with to_sql","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a dataframe created from an excel sheet (the source).\nThe excel sheet will not have a header row.\nI have a table in mysql that is already created (the target). It will always be the exact same layout as the excel sheet.\nsource_data = pd.read_excel(full_path, sheet_name=sheet_name, skiprows=ignore_rows, header=None)\ndb_engine = [function the returns my mysql engine]\nsource_data.to_sql(name=table_name, con=db_engine, schema=schema_name, if_exists='append', index=False)\nThis fails with an error due to pandas using numbers as column names in the insert statement..\n[SQL: INSERT INTO [tablename] (0, 1) VALUES (%(0)s, %(1)s)]\nerror=(pymysql.err.OperationalError) (1054, \"Unknown column '0' in 'field list'\nhow can i get around this? Is there a different insert method i can use? do i really have to load up the dataframe with the proper column names from the table?","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":440,"Q_Id":64980947,"Users Score":0,"Answer":"Found no alternatives.. went with adding the column names to the data frame during the read..\nSo first i constructed the list of column names\nsql = (\"select [column_name] from [table i get my metadata from];\")\ndb_connection = [my connection for sqlalchemy]\nresult = db_connection.execute(sql)\ncolumn_names = []\nfor column in result:\n column_names.append(column[0])\nAnd then i use that column listing in the read command:\nsource_data = pd.read_excel(full_path, sheet_name=sheet_name, skiprows=ignore_rows,header=None, names=column_names) \nthe to_sql statement then runs without error.","Q_Score":0,"Tags":"python,mysql,pandas,dataframe,sqlalchemy","A_Id":64993227,"CreationDate":"2020-11-24T05:55:00.000","Title":"using a pandas dataframe without headers to write to mysql with to_sql","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a data set that consists of two columns as coordinates. I would like to import them to python under one header list called \"coordinates\". Does anyone have any solution?. Thanks!","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":46,"Q_Id":64997349,"Users Score":1,"Answer":"You can use: df.values.tolist().\nFirst select the columns from the name of your dataframe:\ndf = pd.DataFrame(name_of_dataframe, columns= ['col1', 'col2'])\nNext change it to a list: list = df.values.tolist().\nThen flatten the list with a loop appending each smaller list into one bigger list.","Q_Score":0,"Tags":"python,numpy","A_Id":64997439,"CreationDate":"2020-11-25T01:36:00.000","Title":"Import two columns from csv into python under one header numpy list","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Please, may anyone have solved this problem.\nI have two classes in my masks but do not work.\nInvalidArgumentError: labels out of bound\nCondition x < y did not hold.\nFirst 3 elements of x:\n[0 0 0]\nFirst 1 elements of y:\n[2]","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":56,"Q_Id":65008064,"Users Score":0,"Answer":"Thank you,\nI solved it by\ny_true = y_true\/255","Q_Score":0,"Tags":"python,tensorflow","A_Id":65058659,"CreationDate":"2020-11-25T15:46:00.000","Title":"Testing the model tensorflow","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"The csv created using dataframe.to_csv() contains 1.6135E+14 instead of 161349731180627. In the dataframe, it was confirmed that 161349731180627 is displayed correctly. How do I get 161349734480627 in csv properly? (in python)","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":38,"Q_Id":65015632,"Users Score":0,"Answer":"While using df.to_csv(), add the argument float_format='{:f}'.format","Q_Score":0,"Tags":"python,pandas,dataframe,csv,export-to-csv","A_Id":65015661,"CreationDate":"2020-11-26T03:15:00.000","Title":"How to make csv appear as numbers instead of E(python)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I find many examples of passing a list of images, and returning a stitched image, but not much information about how these images have beeen stitched together.\nIn a project, we have a camera fixed still, pointing down, and coveyers pass underneath. The program detects objects and start recording images. However some objects do not enter completely in the image, so we need to capture multiple images and stich then together, but we need to know the position of the stitched image because there are other sensors synchronized with the captured image, and we need to also synchronize their readings within the stitched image (i.e. we know where the reading is within each single capture, but not if captures are stitched together).\nIn short, given a list of images, how can we find the coordinates of each images relative to each other?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":201,"Q_Id":65023161,"Users Score":0,"Answer":"Basically while stiching correspondence between two (or more) images are setup. This is done with some constant key points. After finding those key points the images are warped or transformed & put together, i.e. stitched.\nNow those key points could be set\/ noted as per a global coordinate system (containing all images). Then one can get the position after stitching too.","Q_Score":0,"Tags":"python,opencv","A_Id":65025179,"CreationDate":"2020-11-26T13:38:00.000","Title":"How to find the stitch (seam) position between two images with OpenCV?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"First, I want to explain my task. I have a dataset of 300k documents with an average of 560 words (no stop word removal yet) 75% in German, 15% in English and the rest in different languages. The goal is to recommend similar documents based on an existing one. At the beginning I want to focus on the German and English documents. \u00a0\nTo achieve this goal I looked into several methods on feature extraction for document similarity, especially the word embedding methods have impressed me because they are context aware in contrast to simple TF-IDF feature extraction and the calculation of cosine similarity.\u00a0\nI'm overwhelmed by the amount of methods I could use and I haven't found a proper evaluation of those methods yet. I know for sure that the size of my documents are too big for BERT, but there is FastText, Sent2Vec, Doc2Vec and the Universal Sentence Encoder from Google. My favorite method based on my research is Doc2Vec even though there aren't any or old pre-trained models which means I have to do the training on my own.\nNow that you know my task and goal, I have the following questions:\n\nWhich method should I use for feature extraction based on the rough overview of my data?\nMy dataset is too small to train Doc2Vec on it. Do I achieve good results if I train the model on English \/ German Wikipedia?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":241,"Q_Id":65027694,"Users Score":1,"Answer":"You really have to try the different methods on your data, with your specific user tasks, with your time\/resources budget to know which makes sense.\nYou 225K German documents and 45k English documents are each plausibly large enough to use Doc2Vec - as they match or exceed some published results. So you wouldn't necessarily need to add training on something else (like Wikipedia) instead, and whether adding that to your data would help or hurt is another thing you'd need to determine experimentally.\n(There might be special challenges in German given compound words using common-enough roots but being individually rare, I'm not sure. FastText-based approaches that use word-fragments might be helpful, but I don't know a Doc2Vec-like algorithm that necessarily uses that same char-ngrams trick. The closest that might be possible is to use Facebook FastText's supervised mode, with a rich set of meaningful known-labels to bootstrap better text vectors - but that's highly speculative and that mode isn't supported in Gensim.)","Q_Score":0,"Tags":"python,gensim,word-embedding,doc2vec,fasttext","A_Id":65028926,"CreationDate":"2020-11-26T18:45:00.000","Title":"Which document embedding model for document similarity","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a dataset with non-ordinal categorical features. What is the best way to transform them (encoding + scaling) before training the machine learning model (Linear SVC)?\nThings I tried:\n\nLabel Encoding - This works. But scaling doesn't make sense as different categories in a feature don't have any specific order.\n\nOne-Hot encoding - There are thousand's of unique categories in a features, which is making the ML model complex by creating thousands of columns.\n\nCount encoding - My train-test split didn't have all unique categories of a feature in the training set, which introduces NaN's in test set when I count-encode those features.\n\n\nAppreciate your help!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":132,"Q_Id":65028379,"Users Score":0,"Answer":"To tackle your problem of having some unique values in the test set that are not in the training set, you can try to do the following :\n\nMerge the training dataset using df = train.append(test)\nApply the encodings that you have used earlier\nSplit the datasets back into train and test using :\n\n\ntrain = df.head(len(train))\n\ntest = df.tail(len(test))\n\n\nBased on my experience I can say that LabelEncoding and OneHotEncoding are some of the best techniques to encode non-ordinal features.\nHope this was helpful :)","Q_Score":0,"Tags":"python,encoding,scikit-learn","A_Id":65028768,"CreationDate":"2020-11-26T19:45:00.000","Title":"Dataset features Encoding and Scaling","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I import an Excel file with pandas and when I try to convert all columns to float64 for further manipulation. I have several columns that have a type like:\n0\ncolumn_name_1 float64\ncolumn_name_1 float64\ndtype: object\nand it is unable to do any calculations. May I ask how I could change this column type to float64?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":27,"Q_Id":65031692,"Users Score":0,"Answer":"I just solved it yesterday and it is because I have two same columns in the Data frame and it causes that when I try to access pd['something'] it automatically combine two columns together and then it becomes an object instead of float64","Q_Score":1,"Tags":"python,excel,pandas","A_Id":65046305,"CreationDate":"2020-11-27T03:21:00.000","Title":"Unable to change data types of certain columns read from xslx and by Pandas","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a tensor with shape [1, 2, 96, 96] and would like two tensors with the shape [1, 1, 96, 96], is there a quick way of doing this? Thanks in advance","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":914,"Q_Id":65033693,"Users Score":1,"Answer":"a, b = tensor.split(1, dim=1) should do the job. By specifying 1 you specify how many elements should be in each split e.g. [1,2,3,4,5,6].split(2) -> [1,2] [3,4] [5,6]. Then dim just specifies which dimension to split over which in your case would be one.\nEDIT:\nif you wanted to cut it in half more generally use tensor.split(n) where n is half the size of the tensor. So in your specific case if you had shape [1,10,96,96] you would use tensor.split(5,dim=1)","Q_Score":1,"Tags":"python,pytorch","A_Id":65052602,"CreationDate":"2020-11-27T07:49:00.000","Title":"How to \"cut\" a tensor into half in Pytorch?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I would like to pass a matrix as initial condition for scipy.integrate.solve_ivp.\nWith odeInt this was possible by flattening the matrix as:\nResult = odeint(myfunction, myMatrix.ravel(),myTimeVector )\nInside the function myFunction, the matrix is reshaped into a 3x3 matrix for some calculations.\nIf I try to use solve_ivp(myfunction, myTimeVector,myMatrix.ravel() ), I get the following error:\nValueError: cannot reshape array of size 1 into shape (3,3)\nbecause it only passes the first element of the array, instead of the whole array. Is it possible pass the matrix as initial condition as was withodeint?\nBest Regards","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":249,"Q_Id":65049163,"Users Score":1,"Answer":"Well... Solved it in the following manner:\nChanged the entries in myFunction(y,t) to myFunction(t,y)\nResult=solve_ivp(myfunction, (myTimeVector[0], myTimeVector[-1]), myMatrix.ravel(), t_eval=myTimeVector)","Q_Score":0,"Tags":"python,scipy,ode","A_Id":65049793,"CreationDate":"2020-11-28T11:39:00.000","Title":"Using a matrix as initial condition in scipy.integrate.solve_ivp","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm working with several ongoing datasets of assets with one or more user applied tag(s) (str) which need to be mapped to one catalog-class (str), each, before importing into a database. Naively I call this 'mapping'.\nLookup Table? Mapping?\nThe term 'lookup table' has offered more accurate search results, if not a solution. Other terms like mapping, classification, matching are easily confused with other popular problems. My knowledge of LUTs extends to simple Python dictionaries and as the concept in general. Lookup table is what I've used to try to make this a more concrete programming question, but taxonomy mapping is the goal.\nIf you accept my use of the term mapping in taxonomy mapping, What idioms of mapping, or some other domain solutions can I use for:\n\nmany-to-one mapping\ndecision trees, or weights, or something else to resolve conflicts\nvalidation\/audit for mapping rules after updates\n\nI've implemented simpler mapping problems using CSV for storage and management of one-to-one relationships, and simple dict\/Pandas DataFrame idioms to get the results I need. I thought for a minute I might do a graphy-like thing, because who doesn't like graphs...","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":78,"Q_Id":65064860,"Users Score":0,"Answer":"I was focused on the effectiveness of my simple solution using CSV files, I didn't consider the obvious-- SQLLite with SQLAlchemy.","Q_Score":0,"Tags":"python,mapping","A_Id":65874331,"CreationDate":"2020-11-29T20:31:00.000","Title":"Many-to-One Lookup Table for taxonomy mapping","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I installed fasttext manually and also installing it using pip install. But\nwhen I use this code\nmodel = fastText.train_supervised(input=training_data_path, **hyper_params)\noutput: No module named 'fastText'\nAlso this code:\nmodel = fasttext.train_supervised(input=training_data_path, **hyper_params)\noutput: fasttext' has no attribute 'train_supervised'\nI already installed and follow the documentation still no fix","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":464,"Q_Id":65076865,"Users Score":1,"Answer":"Copied the folder named fasttext in anaconda site-packages dir and paste it in site-packages of Python dir and renaming it by:\norig name: \"fasttext\"\nchanges: \"fastText\"","Q_Score":0,"Tags":"python,fasttext","A_Id":65089579,"CreationDate":"2020-11-30T15:56:00.000","Title":"fasttext' has no attribute 'train_supervised' on Windows 10","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have different excel files in the same folder, in each of them there are the same sheets. I need to select the last sheet of each file and join them all by the columns (that is, form a single table). The columns of all files are named the same. I think it is to identify the dataframe of each file and then paste them. But I do not know how","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":34,"Q_Id":65084238,"Users Score":0,"Answer":"Just do what Recessive said and use a for loop to read the excel file one by one and do the following:\n\nexcel_files = os.listdir(filepath)\n\n\nfor file in excel_files:\n\nread excel file sheet\n\n\n\n\nsave specific column to variable\n\n\n\n\nend of loop\n\n\n\nconcatenate each column from different variables to one dataframe","Q_Score":0,"Tags":"python,dataframe,file","A_Id":65084562,"CreationDate":"2020-12-01T03:18:00.000","Title":"I have different excel files in the same folder","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have few large pandas data frames in python and would like to improve the speed of join operations by adding index. In the similar lines of adding index to a database table.\nWhat i see when searched is only multi-index options. which it looks like a composite index\/multi column index in databases.\nWhat i need is independent indexes on few columns,(Independent because the columns are not related) so that the joins would hopefully work faster.\nIs it possible to define few columns as independent index in pandas?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":44,"Q_Id":65094838,"Users Score":0,"Answer":"Well, As you looked, You can use multilevel index in df but if you want independent indexes on specific column, you can apply a trick by setting and resetting index as before joining operation.","Q_Score":1,"Tags":"python,pandas","A_Id":65094935,"CreationDate":"2020-12-01T16:49:00.000","Title":"pandas multiple independent indexes(not multi index)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"My goal is to feed an object that supports the buffer protocol into hashlib's sha2 generator such that sha2 hashes generated from the same underlying data in different execution environments are consistent, and so can be used for equality tests.\nI would like this to work for arbitrary data types without having to write a bunch of boilerplate wrappers around bytes() or bytearray(), ie, one function I can pass strings (with encoding), numerics, and bools. Extra points if I can get the memory layout for a complex type like a dict or list.\nI am looking at struct, as well as doing something like loading the data into a pandas DataFrame and then using Apache Arrow to access the memory layout directly.\nLooking for guidance as to the most \"pythonic\" way to accomplish this.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":74,"Q_Id":65096561,"Users Score":0,"Answer":"hashlib.sha256(bytes(struct.pack('!f', 12.3))).hexdigest())\nRepeat for all native types.","Q_Score":2,"Tags":"python,pandas,memory,hash,apache-arrow","A_Id":65114471,"CreationDate":"2020-12-01T18:40:00.000","Title":"Converting Arbitrary Objects into Bytes in Python3","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to make a new column by calculating existing columns.\nFor example df\ndf\nno data1 data2\n1 10 15\n2 51 46\n3 36 20\n......\ni want to make this\nnew_df\nno data1 data2 data1\/-2 data1\/2 data2\/-2 data2\/2\n1 10 15 -5 5 -7.5 7.5\n2 51 46 -25.5 25.5 -23 23\n3 36 20 -18 18 -9 9\nbut i don't know how to make this as efficient as possible","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":19,"Q_Id":65101780,"Users Score":0,"Answer":"To create a new df column based on the calculations of two or more other columns, you would have to define a new column and set it equal to your equation. For example:\ndf['new_col'] = df['col_1'] * df['col_2']","Q_Score":0,"Tags":"python,dataframe","A_Id":65101842,"CreationDate":"2020-12-02T03:27:00.000","Title":"python : Compute columns of data frames and add them to new columns","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"When I plot a circle like for example:\nmyPlot.circle(0, 0, line_width=0.5, size=6, line_color=\"green\", fill_color=None)\nthe size of 6 is not fixed. When I zoom out or in it stays the same. How can I bind the size to the x and y axis? So if my x and y axis is Meter my circle has a radius of 6 meter.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":141,"Q_Id":65109855,"Users Score":1,"Answer":"size is always in screen (pixel) units. You need to set a radius which is in \"data-space\" units. Note you will probably also want to set match_aspect=True and use default auto-ranges on the figure, to make sure the radius has the same length in data-space on both axes.","Q_Score":0,"Tags":"python,bokeh","A_Id":65131711,"CreationDate":"2020-12-02T14:16:00.000","Title":"How to make the size of a glyph \"fixed\" in Bokeh?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm creating a Python application with dash\/plotly which works with dataframe with unknown number of columns, and I need to make some visualization which depends on this number. For example, I need to make a table which contains the same number of columns as my dataframe, and also I need the same number of graphs. I tried to do it with creating elements in cycles, but it didn't work. What shall I do?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":15,"Q_Id":65113370,"Users Score":0,"Answer":"Start with an empty table, and an empty container. Run your callback to create the table as you need it, and update its data and columns properties, and just output all the graphs as children of the container.","Q_Score":0,"Tags":"python,plotly-dash","A_Id":65117887,"CreationDate":"2020-12-02T17:42:00.000","Title":"Problem with creation elements in Dash by cycles","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I used the TextRank algorithm for ranking sentences of some articles. The total number of sentences in the articles range from 10 to 71. I wanted to know if there is any way of determining the value of k for selecting the top k ranked sentences as the summary. Or is that fixed to be some number?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":30,"Q_Id":65114269,"Users Score":0,"Answer":"That's probably mostly determined by how large of a summarization you need. In other words, if the summary must fit into some constraint (e.g., 400 characters or less; at least 50 words) then what's an appropriate setting of k to satisfy the constraints? Relatively speaking, it's similar to hyperparmeter optimization in ML.\nAlso, the quality will tend to be affected. Too small of k yields results that probably aren't effective. FWIW, I try to use k >= 3 generally. Too large of k and the results become less readable.","Q_Score":1,"Tags":"python-3.x,summarization,textrank","A_Id":65118298,"CreationDate":"2020-12-02T18:47:00.000","Title":"Is there any way of determining the value of k for selecting top k sentences in text summarization","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to cluster some GPS points with DBSCAN algorithm and I select eps:20 m and min_samples:4.\nThe algorithm works fine on my data, however I need to also consider time of point in the clustering process.\nSuppose there are 10 points in a cluster, however 4 of them are between 8 am and 8:30 am and others in duration of 11 am and 11:15 am. What I want is that the algorithm detects 2 clusters here, one with time of 8 points and one with time of 11 points.\nI mean I need to have another criteria for my DBSCAN algorithm rather than eps and min_samples.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":172,"Q_Id":65121781,"Users Score":0,"Answer":"Use Generalized DBSCAN.\nThen define neighbors as being both\n\nwithin distance maxNeighborDistance km\nwithin maxNeighborTime minutes","Q_Score":0,"Tags":"python,dbscan","A_Id":65634893,"CreationDate":"2020-12-03T07:48:00.000","Title":"Considering time in DBSCAN","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"%%time\ntrain_data = dt.fread('..\/input\/prediction\/train.csv').to_pandas()\nThe output results as an error and says UsageError: Line magic function %%time not found. Suggest some approach.","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":19737,"Q_Id":65124633,"Users Score":1,"Answer":"%%time was the first thing in the cell and after going through the documentation i found %%time is now updated with %time","Q_Score":16,"Tags":"python,dataframe,magic-function,magicline","A_Id":69712765,"CreationDate":"2020-12-03T10:58:00.000","Title":"Line magic function `%%time` not found","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am training a computer vision model.\nI divide the images in 3 datasets: training, validation and testing.\nSo that I get always the same images in training, vaidation and testing, I use the random_state parameter of train_test_split function.\nHowever, I have a problem:\nI am training and testing on two different computers (linux and windows).\nI thought that the results for a given random state would be same but they aren't.\nIs there a way that I get the same results on both computers ?\nI can't divide the images in 3 folders (training, validation and testing) since I want to change the test size and validation size during different experiments.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":59,"Q_Id":65126722,"Users Score":0,"Answer":"On a practical note, training of the models may require\nthe usage of a distant computer or server (e.g. Microsoft\nAzur, Google collaboratory etc.) and it is important to be\naware that random seeds vary between different python versions and operating systems.\nThus, when dividing the original dataset into training, validation and testing datasets,\nthe usage of spliting functions with random seeds is prohibited as it could lead to overlapping testing and training\ndatasets. A way to avoid this is by keeping separate .csv\nfiles with the images to be used for training, validation, or\ntesting.","Q_Score":0,"Tags":"python,random,scikit-learn","A_Id":71892581,"CreationDate":"2020-12-03T13:15:00.000","Title":"sklearn.model_selection.train_test_split random state","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am currently translating a pytorch code into tensorflow.\nThere is a point that i am aggregating 3 losses in a tensorflow custom loop and i get an error that i am passing a two dimensional array vs a 1 dimensional into CategoricalCrossEntropy of tensorflow which is very legit and i understand why this happens... but in the pytorch code i am passing the same shapes and it's perfectly working with CrossEntropyLoss. Does anybody know what i have to do to transfer this into TF?\nthe shapes that are passing in are (17000,100) vs (17000)","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":117,"Q_Id":65143404,"Users Score":0,"Answer":"Try using the loss loss=tf.keras.losses.sparse_categorical_crossentropy","Q_Score":0,"Tags":"python,numpy,tensorflow,pytorch","A_Id":65144531,"CreationDate":"2020-12-04T12:17:00.000","Title":"Pytorch CrossEntropyLoss Tensorflow Equivalent","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"i have a 3d point clouds of my object by using Open3d reconstruction system ( makes point clouds by a sequence of RGBD frames) also I created a 3d bounding box on the object in point clouds\nmy question is how can I have 2d bounding box on all of the RGB frames at the same coordinates of 3d bounding box?\nmy idea Is to project 3d bb to 2d bb but as it is clear, the position of the object is different in each frame, so I do not know how can i use this approach?\ni appreciate any help or solution, thanks","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":472,"Q_Id":65160942,"Users Score":0,"Answer":"calculate points for the eight corners of your box\ntransform those points from the world frame into your chosen camera frame\nproject the points, apply lens distortion if needed.\n\nOpenCV has functions for some of these operations and supports you with matrix math for the rest.\nI would guess that Open3d gives you pose matrices for all the cameras. you use those to transform from the world coordinate frame to any camera's frame.","Q_Score":0,"Tags":"python,opencv,point-clouds,bounding-box,open3d","A_Id":65161287,"CreationDate":"2020-12-05T19:15:00.000","Title":"How can i have 2D bounding box on a sequence of RGBD frames from a 3D bounding box in point clouds?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":1,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am just trying to calculate the percentage of one column against another's total, but I am unsure how to do this in Pandas so the calculation gets added into a new column.\nLet's say, for argument's sake, my data frame has two attributes:\n\nNumber of Green Marbles\nTotal Number of Marbles\n\nNow, how would I calculate the percentage of the Number of Green Marbles out of the Total Number of Marbles in Pandas?\nObviously, I know that the calculation will be something like this:\n\n(Number of Green Marbles \/ Total Number of Marbles) * 100\n\nThanks - any help is much appreciated!","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":1029,"Q_Id":65167120,"Users Score":0,"Answer":"df['percentage columns'] = (df['Number of Green Marbles']) \/ (df['Total Number of Marbles'] ) * 100","Q_Score":1,"Tags":"python,pandas,math,percentage","A_Id":65167227,"CreationDate":"2020-12-06T10:45:00.000","Title":"Pandas: How to calculate the percentage of one column against another?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to implement a dive-and-fix algorithm in Gurobi. What I want to build is a function into which you put an optimized model last_model, make a deepcopy of this model called new_model and add certain constraints to new_model accoording to certain optimized values of last_model.\nI found the function .copy() that would make a deepcopy for me. But I\u2019m still having an awful time adding constraints to my copied new_model as I can\u2019t in any way alter my constraints. (And yes, i am using last_model.update() before copying)\nIf I don\u2019t do anything to my variables after new_model = last_model.copy() and tried to add a constant on z, it would tell me that Variable not in model.\nI\u2019ve tried .getVarByName(\u2018z\u2019), which would tell me that z was a NoneType. (I found this on stackexchange)\nI\u2019ve tried new_model._data = last_model._data, which just returns that the function _data does not exist. (I found this on the gurobi support site)\nI\u2019ve tried .getVars which would just create a list and does not allow me to add any constraints on the actual variables.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":152,"Q_Id":65169092,"Users Score":0,"Answer":"You are on the right track with getVars() - you really do need to get the variables of the copied model again to be able to add new constraints. The variables of the original model are only going to refer to the original model, even if they may have the same name. Think of the variables as handles for the actual variables in the model - they can only refer to one model.","Q_Score":0,"Tags":"python,optimization,deep-copy,gurobi","A_Id":65201353,"CreationDate":"2020-12-06T14:21:00.000","Title":"How to make a copy of a Gurobi model and add constraints to the copy in Python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Is there any python library for computing EMD between two signatures? There are multiple options to compute EMD between two distributions (e.g. pyemd). But I didn't find any implementation for the exact EMD value. For example, consider Signature_1 = {(1,1), (4,1)} and Signature_2 = {(1,1), (2,1), (3,1), (4,1)}, where first coordinate is the position and second coordinate is the weight. True EMD(Signature_1, Signature_2) = 0 whereas if we consider these as distributions then the distance is 0.5 (the emd_samples in pyemd gives this answer). But I would be interested in the implementation of True EMD. Any help in this regard would be appreciated.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":146,"Q_Id":65175926,"Users Score":0,"Answer":"No worries. I got the answer. You can just use \"normalized\" = False, \"extra_mass_penalty\" = 0 in the arguments of \"emd_samples\" function of pyemd.","Q_Score":0,"Tags":"python,earth-movers-distance","A_Id":65272218,"CreationDate":"2020-12-07T03:52:00.000","Title":"Exact Earth Mover's Distance (NOT Mallows Distance) Python Code","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I installed termux on my Android tablet, and was able to successfully install Python 3.9 and Numpy, but not matplotlib. Apparently the .whl was downloaded and cached, and now when I try to install, whether using pip or pkg it attempts to use the cached .whl file. I tried clearing memory and reinstalling everything from scratch, but it still downloads the same .whl, with the same result. (The termux wiki provided no clues that I could find)\nAnybody have a work around or fix?","AnswerCount":5,"Available Count":1,"Score":0.0399786803,"is_accepted":false,"ViewCount":4632,"Q_Id":65184413,"Users Score":1,"Answer":"As I did not want to install Ubuntu on the tablet, what I wound up doing was installing Pydroid 3. I was then able to install Numpy and Matplotlib using pip. Thanks for the effort!","Q_Score":1,"Tags":"python,android,matplotlib,termux","A_Id":65860935,"CreationDate":"2020-12-07T15:20:00.000","Title":"pip install matplotlib does not work under termux (Android)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Why does Pandas not round DataFrames when the dypes are np.float16?\npd.DataFrame(np.random.rand(10) for x in range(0, 10)).astype(np.float16).round(2)\nOr\nnp.round(pd.DataFrame(np.random.rand(10) for x in range(0, 10)).astype(np.float16), 2)\nOr\npd.DataFrame(np.random.rand(10) for x in range(0, 10)).astype(np.float16).round({0:2, 1:2})\nThis must have come up before but I can't find it anywhere?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":198,"Q_Id":65187037,"Users Score":0,"Answer":"It is rounding. Up to the limits of float16 precision, the results are exactly what you asked for. However, the limits of float16 precision are significantly lower than the 6 significant figures Pandas attempts to print by default, so you see some of the representation imprecision that is usually hidden when printing floating-point numbers.","Q_Score":0,"Tags":"python,pandas","A_Id":65187103,"CreationDate":"2020-12-07T18:06:00.000","Title":"Why doesn't Pandas round when dtype is float16?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am dealing with a semantic segmentation problem where the two classes in which I am interested (in addition to background) are quiet unbalanced in the image pixels. I am actually using sparse categorical cross entropy as a loss, due to the way in which training masks are encoded. Is there any version of it which takes into account class weights? I have not been able to find it, and not even the original source code of sparse_categorical_cross_entropy. I never explored the tf source code before, but the link to source code from API page doesn't seem to link to a real implementation of the loss function.","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":1153,"Q_Id":65188739,"Users Score":1,"Answer":"As far as I know you can use class weights in model.fit for any loss function. I have used it with categorical_cross_entropy and it works. It just weights the loss with the class weight so I see no reason it should not work with sparse_categorical_cross_entropy.","Q_Score":4,"Tags":"python,tensorflow,keras,image-segmentation,cross-entropy","A_Id":65191246,"CreationDate":"2020-12-07T20:16:00.000","Title":"Weighted sparse categorical cross entropy","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"In machine learning, you split the data into training data and test data.\nIn cross validation, you split the training data into training sets and validation set.\n\"And if scaling is required, at each iteration of the CV, the means and standard deviations of the training sets (not the entire training data) excluding the validation set are computed and used to scale the validation set, so that the scaling part never include information from the validation set. \"\nMy question is when I include scaling in the pipeline, at each CV iteration, is scaling computed from the smaller training sets (excluding validation set) or the entire training data (including validation set)? Because if it computes means and std from entire training data , then this will lead to estimation bias in the validation set.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":50,"Q_Id":65193318,"Users Score":1,"Answer":"I thought about this, too, and although I think that scaling with the full data leaks some information from training data into validation data, I don't think it's that severe.\nOne one side, you shuffle the data anyway, and you assume that the distributions in all sets are the same, and so you expect means and standard deviations to be the same. (Of course, this is only theoretic (law of large numbers).)\nOn the other side, even if the means and stds are different, this difference will not be siginificant.\nIn my optinion, yes, you might have some bias, but it should be negligible.","Q_Score":0,"Tags":"python,machine-learning,scikit-learn,pipeline,scaling","A_Id":65193455,"CreationDate":"2020-12-08T04:57:00.000","Title":"Sklearn Pipeline: is there leakage \/bias when including scaling in the pipeline?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a numpy ndarray train_data of length 200, where every row is another ndarray of length 10304.\nHowever when I print np.shape(train_data), I get (200, 1), and when I print np.shape(train_data[0]) I get (1, ), and when I print np.shape(train_data[0][0]) I get (10304, ).\nI am quite confused with this behavior as I supposed the first np.shape(train_data) should return (200, 10304).\nCan someone explains to me why this is happening, and how could I get the array to be in shape of (200, 10304)?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":61,"Q_Id":65200418,"Users Score":0,"Answer":"I'm not sure why that's happening, try reshaping the array:\nB = np.reshape(A, (-1, 2))","Q_Score":0,"Tags":"python,numpy","A_Id":65200891,"CreationDate":"2020-12-08T14:02:00.000","Title":"2D numpy array showing as 1D","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to generate good sentence embeddings for some specific type od texts, using sentence transformer models while testing the the similarity and clustering using kmeans doesnt give good results.\nAny ideas to improve? I was thinking of training any of the sentence transformer model on my dataset(which are just sentences but do not have any labels).\nHow can i retrain the existing models specifically on ny data to generate better embeddings.\nThanks.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":262,"Q_Id":65200530,"Users Score":0,"Answer":"The sentence embeddings produced by pre-trained BERT model are generic and need not be appropriate for all the tasks.\nTo solve this problem:\n\nFine-tune the model with the task specific corpus on the given task (If the end goal is classification, fine-tune the model for classification task, later you can use the embeddings from the BERT model) (This is the method suggested for the USE embeddings, especially when the model remains a black-box)\n\nFine-tune the model in unsupervised manner using masked language model. This doesn't require you to know the task before hand, but you can just use the actual BERT training strategy to adapt to your corpus.","Q_Score":0,"Tags":"python,embedding,bert-language-model,sentence-transformers","A_Id":65201274,"CreationDate":"2020-12-08T14:09:00.000","Title":"How can I train a bert model for representational learning task that is domain specific?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Can you make mpld3-matplotlib interactive ?\nwhat I mean is display a graph on a web page and be able to update the time series i.e. not simply static graph, but dynamic one page graph-app ?\nWhat can be leveraged from mpld3 ?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":52,"Q_Id":65204165,"Users Score":0,"Answer":"if you don't have to support matplotlib then an option is Bokeh or Dash library instead.","Q_Score":0,"Tags":"python,matplotlib,mpld3","A_Id":65226053,"CreationDate":"2020-12-08T17:50:00.000","Title":"Can you make mpld-matplotlib interactive graph web app?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":1},{"Question":"When loading in an excel file, Pandas is ingesting a value (1735582) into a float value of (1735582.0). Subsequently, when importing the file to SQL, the value is ingested as a truncated scientific notation value (1.73558e+06), thereby rendering the value useless.\nMy first thought was to trim any trailing '.0' from all values, and then see if the import goes smoothly to retain the native values.\nI have attempted to use the dataframe.replace to identify values across the entire dataframe that have a trailing '.0', but have no come up with the right solution:\ndf_update = df.replace(to_replace ='\\.\\[0]$', value = '', regex = True)\nI need a way to 1) ingest the values without the trailing '.0', 2) remove the trailing '.0', or 3) prevent to_sql from outputting the values as truncated scientific notation.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":67,"Q_Id":65206980,"Users Score":0,"Answer":"Just use df.apply and then use lambda with \"{:.2f}\".format(x) to limit it to 2 digits after the 0","Q_Score":0,"Tags":"python,sql,regex,pandas","A_Id":65207199,"CreationDate":"2020-12-08T21:12:00.000","Title":"Remove trailing .0 from values in Python","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"If I want to determine the type of model i.e. from which framework was it made programmatically, is there a way to do that?\nI have a model in some serialized manner(Eg. a .h5 file). For simplicity purposes, assume that my model can be either tensorflow's or scikit learn's. How can I determine programmatically which one of these 2 is the one?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":66,"Q_Id":65210822,"Users Score":0,"Answer":"you can either use type(model) to see its type\nyou can also use help(model) to get the doc string from model.\nyou can also use dir(model) to see its member function or parameters.\nyou can also use import inspect inspect.getsource(model) to get source code of a object.","Q_Score":0,"Tags":"python,tensorflow,machine-learning,keras,scikit-learn","A_Id":65216668,"CreationDate":"2020-12-09T04:49:00.000","Title":"How to detect the given model is a keras or scikit model using python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am new to Deep Learning. I finished training a model that took 8 hours to run, but I forgot to plot the accuracy graph before closing the jupyter notebook.\nI need to plot the graph, and I did save the model to my hard-disk. But how do I plot the accuracy graph of a pre-trained model? I searched online for solutions and came up empty.\nAny help would be appreciated! Thanks!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":318,"Q_Id":65212386,"Users Score":0,"Answer":"What kind of framework did you use and which version? In the future problem, you may face, this information can play a key role in the way we can help you.\nUnfortunately, for Pytorch\/Tensorflow the model you saved is likely to be saved with only the weights of the neurons, not with its history. Once Jupyter Notebook is closed, the memory is cleaned (and with it, the data of your training history).\nThe only thing you can extract is the final loss\/accuracy you had.\nHowever, if you regularly saved a version of the model, you can load them and compute manually the accuracy\/loss that you need. Next, you can use matplotlib to reconstruct the graph.\nI understand this is probably not the answer you were looking for. However, if the hardware is yours, I would recommend you to restart training. 8h is not that much to train a model in deep learning.","Q_Score":0,"Tags":"python,tensorflow,matplotlib,deep-learning,jupyter-notebook","A_Id":65212598,"CreationDate":"2020-12-09T07:30:00.000","Title":"Can you plot the accuracy graph of a pre-trained model? Deep Learning","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"How can I make python loop faster through DataFrame columns with 1 million rows and search for a pattern of strings? Should return True or False\npattern_example = \"home|property|house|apartment\"\nThis is what I have right now\ndf[field].str.contains(pattern_example.lower(), case = False, regex=False)\nThis is what I am trying to implement\ndf[field].apply(lambda x: True if pattern_example.lower() in x else False)\nHowever, it cannot recognize the OR(|) operator and searchers for full \"home|property|house|apartment\"\nAny suggestions?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":180,"Q_Id":65218798,"Users Score":0,"Answer":"@furas thanks for the contribution.\nIt worked.\nThis is what I used\ndf[field].apply(lambda x: True if any (word in x for word in pattern.lower().split('|')) else False)","Q_Score":2,"Tags":"python,pandas,search,lambda","A_Id":65251649,"CreationDate":"2020-12-09T14:31:00.000","Title":"How to make pandas str.contains faster","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"If I have a single GPU with 8GB RAM and I have a TensorFlow model (excluding training\/validation data) that is 10GB, can TensorFlow train the model?\nIf yes, how does TensorFlow do this?\nNotes:\n\nI'm not looking for distributed GPU training. I want to know about single GPU case.\nI'm not concerned about the training\/validation data sizes.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":304,"Q_Id":65222907,"Users Score":0,"Answer":"No you can not train a model larger than your GPU's memory. (there may be some ways with dropout that I am not aware of but in general it is not advised). Further you would need more memory than even all the parameters you are keeping because your GPU needs to retain the parameters along with the derivatives for each step to do back-prop.\nNot to mention the smaller batch size this would require as there is less space left for the dataset.","Q_Score":1,"Tags":"python,tensorflow,memory,gpu,ram","A_Id":71564955,"CreationDate":"2020-12-09T18:38:00.000","Title":"On single gpu, can TensorFlow train a model which larger than GPU memory?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I work on a python script executing standard image recognition processing using tensorflow. Using Python 3.8, Tensorflow 2, Idle lauched from a virtual env.\nSince I am following a tutorial, I would like to augment and execute my script chunk by chunk : e.g.\n\nwrite the code for the data load\nexecute\nwrite the code for training\nexecute only training (without reloading the data)\n\nIs there a way to run a python script chunk by chunk, without restarting the idle shell, and keeping results from the previous steps?","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":89,"Q_Id":65234016,"Users Score":0,"Answer":"In an IDLE editor, one can right click on multiple lines to add breakpoints. Start IDLE's debugger in Shell, using Shell menu. Run file. Click go and execution will start and stop at first breakpoint. Click go again to run to next breakpoint.","Q_Score":0,"Tags":"python,tensorflow,execution,python-idle","A_Id":65244896,"CreationDate":"2020-12-10T11:53:00.000","Title":"Run edited python script step by step \/ without reloading dataset","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I work on a python script executing standard image recognition processing using tensorflow. Using Python 3.8, Tensorflow 2, Idle lauched from a virtual env.\nSince I am following a tutorial, I would like to augment and execute my script chunk by chunk : e.g.\n\nwrite the code for the data load\nexecute\nwrite the code for training\nexecute only training (without reloading the data)\n\nIs there a way to run a python script chunk by chunk, without restarting the idle shell, and keeping results from the previous steps?","AnswerCount":2,"Available Count":2,"Score":1.2,"is_accepted":true,"ViewCount":89,"Q_Id":65234016,"Users Score":1,"Answer":"Read\u2013eval\u2013print loop (REPL)\nYes , this is what exactly you are looking for.\nThis is an interactive environment that takes single user inputs, executes them, and returns the result to the user; a program written in a REPL environment is executed piecewise\nThere are lot of Platforms which offer this.\nJupyter Notebook (Local)\nGoogle Colab (Online)\nI prefer Google colab .\nIts free & we don't have to waste our Local system Resources","Q_Score":0,"Tags":"python,tensorflow,execution,python-idle","A_Id":65234730,"CreationDate":"2020-12-10T11:53:00.000","Title":"Run edited python script step by step \/ without reloading dataset","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I would like to run an ordinal regression model in stats model and someone posted this (from statsmodels.miscmodels.ordinal_model import OrderedModel) however it doesnt seem to work.\nI also checked on stats models website and ordered models dont appear on there.\nHas anyone done an oridinal logistic regression in Python?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":812,"Q_Id":65237256,"Users Score":0,"Answer":"Due to the ease of analyzing model results (more R like) I would like to use statsmodels to run an ordinal logistic regression as well, but in Python, unless you use rpy2, the only other option I know of is using mord.\nfrom mord import LogisticAT","Q_Score":1,"Tags":"python,statsmodels,ordinal","A_Id":65462824,"CreationDate":"2020-12-10T15:17:00.000","Title":"How do i run a ordinal regression using stats model?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Is it possible in python with the latest CV2 to use CV2 to directly bind mjpeg output from the camera to a stream without having to do source -> cv2.read() -> numpy array -> cv2.imencode(\".jpg\") -> mjpeg? I am looking to do source -> mjpeg in a pythonic way.\nLatency is a major issue so any advice including options beyond CV2 would be appreciated.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":98,"Q_Id":65243321,"Users Score":0,"Answer":"No. OpenCV is not a media library. Its video I\/O is not intended or made for this.\nI would advise to use PyAV, which is the only proper python wrapper around ffmpeg's libraries that I know of. PyAV comes with a few examples to give you a feel for how it works.\nthe basic problem then is how to use ffmpeg's libraries to enumerate available video devices, query their modes, select the mode you want, and move packets around.","Q_Score":1,"Tags":"python,python-3.x,opencv","A_Id":65244382,"CreationDate":"2020-12-10T22:40:00.000","Title":"Python Open CV image streaming without decoding and reencoding?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have my twitter archive downloaded and wanted to run word2vec to experiment most similar words, analogies etc on it.\nBut I am stuck at first step - how to convert a given dataset \/ csv \/ document so that it can be input to word2vec? i.e. what is the process to convert data to glove\/word2vec format?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":78,"Q_Id":65255029,"Users Score":1,"Answer":"Typically implementations of the word2vec & GLoVe algorithms do one or both of:\n\naccept a plain text file, where tokens are delimited by (one or more) spaces, and text is considered each newline-delimited line at a time (with lines that aren't \"too long\" - usually, short-article or paragraph or sentence per line)\n\nhave some language\/library-specific interface for feeding texts (lists-of-tokens) to the algorithm as a stream\/iterable\n\n\nThe Python Gensim library offers both options for its Word2Vec class.\nYou should generally try working through one or more tutorials to get a working overview of the steps involved, from raw data to interesting results, before applying such libraries to your own data. And, by examining the formats used by those tutorials \u2013 and the extra steps they perform to massage the data into the formats needed by exactly the libraries you're using \u2013 you'll also see ideas for how your data needs to be prepared.","Q_Score":0,"Tags":"python,nlp,stanford-nlp,word2vec","A_Id":65256256,"CreationDate":"2020-12-11T16:24:00.000","Title":"How can I Convert a dataset to glove or word2vec format?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to visualize such 4D data in the 2D plane. Is there any way to do that?","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":449,"Q_Id":65273122,"Users Score":0,"Answer":"Depending on the data type, you can plot them on a 2d field with the following dimensions:\nDim 1-2: X and Y axes\nDim 3: plotted point size\nDim 4: plotted point color gradient\nOr if you do it with a 3D software, you can plot in 3D, with all the point plotted with color gradient. While rotating the field, you can have vision on all dimensions.","Q_Score":2,"Tags":"python,data-analysis","A_Id":69504433,"CreationDate":"2020-12-13T06:54:00.000","Title":"How to visualize 4D data in 2D plane?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have some long machine learning modules I am doing on Python\nusing Anaconda Python and sklearn, and numpy libraries\nThese processes take days to finish.\nand I am doing these processes on my laptop.\nThe problem is that I cannot keep my laptop on for days without turning it off\nIs there a way I can preserve the Machine Learning processes before restarting then resume where stopped after restarting?\nHow to do that?","AnswerCount":2,"Available Count":2,"Score":1.2,"is_accepted":true,"ViewCount":98,"Q_Id":65282639,"Users Score":0,"Answer":"As @Mr. For Example stated this can easily be overcome with checkpoints, save checkpoints of your model, and later load the last checkpoint (or just any checkpoint you like) and continue your training process.","Q_Score":2,"Tags":"python,machine-learning,scikit-learn","A_Id":65286117,"CreationDate":"2020-12-14T01:48:00.000","Title":"How to resume python machine learning after restart machine?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have some long machine learning modules I am doing on Python\nusing Anaconda Python and sklearn, and numpy libraries\nThese processes take days to finish.\nand I am doing these processes on my laptop.\nThe problem is that I cannot keep my laptop on for days without turning it off\nIs there a way I can preserve the Machine Learning processes before restarting then resume where stopped after restarting?\nHow to do that?","AnswerCount":2,"Available Count":2,"Score":-0.0996679946,"is_accepted":false,"ViewCount":98,"Q_Id":65282639,"Users Score":-1,"Answer":"I don't know any way of stopping the process and then start it again in a few days.\nAnyway, there is a free tool called Google Colab where you can execute your code there for up to 12 hours and you won't use your own resources but google servers. The downside to that is that they will keep your code (you will loose the intellectual property) but it executes faster and if you are not using it for business purposes it is perhaps a good alternative.","Q_Score":2,"Tags":"python,machine-learning,scikit-learn","A_Id":65285986,"CreationDate":"2020-12-14T01:48:00.000","Title":"How to resume python machine learning after restart machine?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've a dataset, where the output is logarithmic, I mean, it varies from values of 0.02 order to 15000 order, I should just train the model normally, or I should preprocess the output someway?\nThanks","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":81,"Q_Id":65295507,"Users Score":2,"Answer":"You'll likely get better results if you preprocess to ensure that the output is mostly within [0, 1]. Since your output is \"logarithmic\", it may also help to make the output more linear; that is, take the log of your original outputs and rescale such that the logs are in [0, 1].","Q_Score":0,"Tags":"python,tensorflow,keras,deep-learning","A_Id":65295549,"CreationDate":"2020-12-14T19:48:00.000","Title":"How to train a tensorflow model that the output covers a huge range","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Error occurred when I am trying to run face_rec using CUDA, there's no file missing, but the system states that it cannot find the related file.\nCould not load library libcudnn_cnn_train.so.8. Error: libcudnn_ops_train.so.8: cannot open shared object file: No such file or directory\nPlease make sure libcudnn_cnn_train.so.8 is in your library path!\nAborted (core dumped)","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":617,"Q_Id":65299281,"Users Score":0,"Answer":"I am solving this question. In the NEXT.\nsudo ln -sf \/usr\/local\/cuda-11.5\/targets\/x86_64-linux\/lib\/libcudnn_adv_train.so.8.3.0 \/usr\/local\/cuda-11.5\/targets\/x86_64-linux\/lib\/libcudnn_adv_train.so.8\nsudo ln -sf \/usr\/local\/cuda-11.5\/targets\/x86_64-linux\/lib\/libcudnn_ops_infer.so.8.3.0 \/usr\/local\/cuda-11.5\/targets\/x86_64-linux\/lib\/libcudnn_ops_infer.so.8\nsudo ln -sf \/usr\/local\/cuda-11.5\/targets\/x86_64-linux\/lib\/libcudnn_cnn_train.so.8.3.0 \/usr\/local\/cuda-11.5\/targets\/x86_64-linux\/lib\/libcudnn_cnn_train.so.8\nsudo ln -sf \/usr\/local\/cuda-11.5\/targets\/x86_64-linux\/lib\/libcudnn_adv_infer.so.8.3.0 \/usr\/local\/cuda-11.5\/targets\/x86_64-linux\/lib\/libcudnn_adv_infer.so.8\nsudo ln -sf \/usr\/local\/cuda-11.5\/targets\/x86_64-linux\/lib\/libcudnn_ops_train.so.8.3.0 \/usr\/local\/cuda-11.5\/targets\/x86_64-linux\/lib\/libcudnn_ops_train.so.8\nsudo ln -sf \/usr\/local\/cuda-11.5\/targets\/x86_64-linux\/lib\/libcudnn_cnn_infer.so.8.3.0 \/usr\/local\/cuda-11.5\/targets\/x86_64-linux\/lib\/libcudnn_cnn_infer.so.8\nif your cuda not like me, you should change the cuda-11.5 into your cuda","Q_Score":4,"Tags":"python,face-recognition,dlib","A_Id":71674426,"CreationDate":"2020-12-15T02:41:00.000","Title":"Could not load library libcudnn_cnn_train.so.8","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working with an imbalanced dataset where I have a class variable of 2 different values: 0 and 1.\nThe number of '0' values is 1000 and the number of '1' values is 3000.\nFor XGBClassifier, LGBMClassifier and CatBoostClassifier I found that there is a parameter called \"scale_pos_weight\" which enables to modify the weights of the class values:\nscale_pos_weight = number_of_negative_values \/ number_of_positive_values\nMy question is: how can we know which value of class variable is positive and which negative?","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":565,"Q_Id":65304302,"Users Score":0,"Answer":"For binary classification imbalanced dataset, always consider positive value to the minority class (class 1) and negative values to the majority class (class 0).\nBut you have assumed class 0 as minority class & class 1 as majority class.\nBy default value of scale_pos_weight=1 or > 1","Q_Score":0,"Tags":"python,classification,xgboost,catboost,imbalanced-data","A_Id":65304680,"CreationDate":"2020-12-15T10:43:00.000","Title":"How can I know which is the positive class value and negative class value for XGBoost?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I got an image stack of 4 gray scale images which i want to pass to a neural network with tensorflow.\nAfter reading in my 4 gray scale images and convert them to a tensor their shape is (4,120,160)\nWhen i pass it to the neural network i get an error message. After some googling i found that i need the input shape of (4,120,160,1) in which the 1 stands for the color channel.\nI have not found anyway to change the shape of my tensor in this way.\nIt seems to work with the expand dims function but it is a little bit cryptic for me to understand what it does.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":235,"Q_Id":65305528,"Users Score":1,"Answer":"You can use tf.expand_dims(image, -1).\n\nGiven a tensor input, this operation inserts a dimension of length 1 at the dimension index axis of input's shape.","Q_Score":0,"Tags":"python,tensorflow","A_Id":65305663,"CreationDate":"2020-12-15T12:07:00.000","Title":"Add a dimension to a tensorflow tensor","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm training a Neural Network over a TFRecordDataset. However, at the end of every epoch, i.e. with ETA: 0s, the training gets stuck for tens of seconds. For reference, one epoch takes around a minute to be completed over a dataset of around 25GB (before parsing a subset of the features).\nI'm running TensorFlow 2.3.1 with a Nvidia Titan RTX GPU. Is this the intended behavior? Maybe due to the preprocessing in the input pipeline? Is that preprocessing performed by the CPU only or offloaded to the GPU? Thanks!","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":150,"Q_Id":65309983,"Users Score":2,"Answer":"If you have a validation set and you're using model.fit(), it's probably the time it takes to calculate the loss and the metrics. In most cases, it should take an extra 25% to compute the metrics of a 80\/20 split.","Q_Score":0,"Tags":"python,tensorflow,keras,dataset,nvidia","A_Id":65310128,"CreationDate":"2020-12-15T16:37:00.000","Title":"Tensorflow stuck for seconds at the end of every epoch","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Configuration:\nTensorFlow 2.3 Python 3.6\nHow to load the TensorFlow model stored on Google Drive or on any other remote server\/location in the Python program?\nI am looking for a solution which do not require the downloading of the model and giving the filepath. ie. a solution in which I can directly give the url of my TensorFlow model to load the TensorFlow model. This url is irrespective of Google Drive, i.e. it can be the url of any remote storage\/server.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":69,"Q_Id":65321863,"Users Score":0,"Answer":"You should download the model to the local device and the load it.","Q_Score":0,"Tags":"python,remote-server,tensorflow2.x","A_Id":65321893,"CreationDate":"2020-12-16T10:53:00.000","Title":"Loading TensorFlow model from remote location","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm fully aware of the previous post regarding this error. That issue was with scikit-learn < 0.20. But I'm having scikit-learn 0.23.2 and I've tried uninstall and reinstall 0.22 and 0.23 and I still have this error.\nFollowup: Although pip list told me the scikit-learn version is 0.23.2, but when I ran sklearn.__version__, the real version is 0.18.1. Why and how to resolve this inconsistency? (Uninstall 0.23.2 didn't work)","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":294,"Q_Id":65327149,"Users Score":0,"Answer":"[RESOLVED]\nIt turned out that my Conda environment has different sys.path as my jupyter environment. The jupyter environment used the system env, which is due to the fact that I installed the ipykernel like this: python -m ipykernel install without use --user flag. The correct way should be to do so within the Conda env and run pip install jupyter","Q_Score":0,"Tags":"python,scikit-learn","A_Id":65330188,"CreationDate":"2020-12-16T16:21:00.000","Title":"ImportError: No module named 'sklearn.compose' with scikit-learn==0.23.2","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a connection object in Scala cell, which I would like reuse it in Python cell.\nIs there alternate to temp table to access this connection.\nDatabricks","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":19,"Q_Id":65329670,"Users Score":0,"Answer":"Not really - Python code is executed in the different context, so you can have some data exchange either via SparkSession itself (.set\/.get on the SparkConf, but it works only for primitive data), or by registering the temp view","Q_Score":0,"Tags":"python,scala,jdbc,databricks","A_Id":65338265,"CreationDate":"2020-12-16T19:10:00.000","Title":"How can access Scala JDBC connection in Python Notebook ---Databricks","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to use machine learning in Python. Right now I am using sklearn and TensorFlow. I was wondering what to do if I have a model that needs updating when new data comes. For example, I have financial data. I built an LSTM model with TensorFlow and trained it. But new data comes in every day, and I don't want to retrain the model every day. Is there a way just to update the model and not retrain it from scratch?\nIn sklearn, the documentation for .fit() method (using DecisionTreeClassifier as an example) says that it\n\nBuild a decision tree classifier from the training set (X, y).\n\nSo it seems like it will retrain the entire model from scratch.\nIn tensorflow, .fit() method (using Sequential as an example) say\n\nTrains the model for a fixed number of epochs (iterations on a\ndataset).\n\nSo it seems like it does update the model instead of retraining. But I am not sure if my understanding is correct. I would be grateful for some clarification. And if sklearn indeed retrains the entire model using .fit(), is there a function that would just update the model instead of retraining from scratch?","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":820,"Q_Id":65334672,"Users Score":0,"Answer":"In sklearn, the .fit() method retrains on the dataset i.e as you use .fit() on any dataset, any info pertaining to previous training will all be discarded. So assuming you have new data coming in every day you will have to retrain each time in the case of most sklearn algorithms.\nAlthough, If you like to retrain the sklearn models instead of training from scratch, some algorithms of sklearn (like SGDClassifier) provide a method called partial_fit(). These can be used to retrain and update the weights of an existing model.\nAs per Tensorflow, the .fit() method actually trains the model without discarding any info pertaining to previous trainings. Hence each time .fit() is used via TF it will actually retrain the model.\nTip: you can use SaveModel from TF to save the best model and reload and re-train the model as and when more data keeps flowing in.","Q_Score":1,"Tags":"python,tensorflow,scikit-learn","A_Id":65335235,"CreationDate":"2020-12-17T04:18:00.000","Title":"Does model get retrained entirely using .fit() in sklearn and tensorflow","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a list which has 8 elements and all of those elements are arrays whose shape are (3,480,364).Now I want to transform this list to array as (8,3,480,364).When I use the array=nd.array(list) this command,it will takes me a lot of time and sometimes it will send 'out of memory' error.When I try to use this command array=np.stack(list.aixs=0),when I debug the code,it will stay at this step and can't run out the result.So I wonder how can I transform a list to array quickly when I use the Mxnet framework?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":60,"Q_Id":65337206,"Users Score":0,"Answer":"Your method of transforming a list of lists into an array is correct, but an 'out of memory' error means you are running out of memory, which would also explain the slowdown.\nHow to check how much RAM you have left:\non Linux, you can run free -mh in the terminal.\nHow to check how much memory a variable takes:\nThe function sys.getsizeof tells you memory size in bytes.\nYou haven't said what data type your arrays have, but, say, if they're float64, that's 8 bytes per element, so your array of 8 * 3 * 480 * 364 = 4193280 elements should only take up 4193280 * 8 bytes = about 30 Mb. So, unless you have very little RAM left, you probably shouldn't be running out of memory.\nSo, I'd first check your assumptions: does your list really only have 8 elements, do all the elements have the same shape of (3, 480, 364), what is the data type, do you create this array once or a thousand times? You can also check the size of a list element: sys.getsizeof(list[0]).\nMost likely this will clear it up, but what if your array is really just too big for your RAM?\nWhat to do if an array doesn't fit in memory\nOne solution is to use smaller data type (dtype=np.float32 for floating point, np.int32 or even np.uint8 for small integer numbers). This will sacrifice some precision for floating point calculations.\nIf almost all elements in the array are zero, consider using a sparse matrix.\nFor training a neural net, you can use a batch training algorithm and only load data into memory in small batches.","Q_Score":0,"Tags":"python,mxnet","A_Id":65338624,"CreationDate":"2020-12-17T08:39:00.000","Title":"How can I transform a list to array quickly in the framework of Mxnet?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"How can I get the median of ConvertedComp column for all Gender = 'Woman' from this Pandas dataframe (It only shows 'Man' because I'm only showing df.head(10)):\n\n\n\n\n\nConvertedComp\nGender\n\n\n\n\n0\n61000.0\nMan\n\n\n1\n95179.0\nMan\n\n\n2\n90000.0\nMan\n\n\n3\n455452.0\nMan\n\n\n4\n65277.0\nMan\n\n\n5\n31140.0\nMan\n\n\n6\n41244.0\nMan\n\n\n7\n103000.0\nMan\n\n\n8\n69000.0\nMan\n\n\n9\n26388.0\nMan","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":886,"Q_Id":65348297,"Users Score":0,"Answer":"Try this:\ndf[df['Gender']=='Woman']['ConvertedComp'].median()","Q_Score":1,"Tags":"python,pandas,dataframe","A_Id":70317860,"CreationDate":"2020-12-17T21:01:00.000","Title":"How to get the median of a column based on another column value using Pandas?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a Dataframe with millions of rows, to create a model, I have taken a random sample from this dataset using dataset.sample(int(len(dataset)\/5)) which returns a random sample of items from an axis of the object. Now I want to verify if the sample does not lose statistical significance from the population, that is, ensure the probability distribution of each of the features (columns) of the sample has the same probability distribution for the whole dataset (population). I have numerical as well as categorical features. How can I check that the features have the same probability distribution in Python?","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":1562,"Q_Id":65353833,"Users Score":1,"Answer":"This does not require a test. If you have taken a simple random sample from the entire data frame, the probability distribution of whatever features the data set has is, in fact, the whole data set. That's a property of a simple random sample.\nUnfortunately, unless the data set was ALSO sampled properly (something I assume you cannot control at this point) you cannot guarantee that the data set and sample have the same distribution. The probability distribution was determined at the point of sampling the data.\nBut if you're happy to assume that, then you need no additional checking step to ensure that your random sample does its job - this is provably guaranteed.","Q_Score":3,"Tags":"python,machine-learning,probability","A_Id":65354120,"CreationDate":"2020-12-18T08:29:00.000","Title":"How to check if sample has same probability distribution as population in Python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've been searching and reading quite a bit but I can't seem to find an answer to the question of how to pauze a Vpyton object in a simulation (for a second preferably). I considered briefly time.sleep() but this pauzes the entire simulation, my goal however is to pauze just one object.\nIf there are any question or I need to elaborate further, please ask.\nKind regards,\nZo\u00eb","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":25,"Q_Id":65354377,"Users Score":1,"Answer":"Use sleep(1), not time.sleep(1). However, I don't understand the meaning of \"pause just one object\". If by that you mean that you have several objects moving and you want to pause one of them while keeping the others moving, you would set a global variable t = clock() and in your animation loop keep checking whether clock()-t is still less than 1 (second) and, if so, avoid changing the \"paused\" object's position.","Q_Score":0,"Tags":"vpython","A_Id":65543361,"CreationDate":"2020-12-18T09:17:00.000","Title":"How to let a Vpyton object pauze within a simulation","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I need to calculate EMA for a set of data from csv file where dates are in descending order.\nWhen I apply pandas.DataFrame.ewm I get EMA for the latest (by date) equal to the value. This is because ewm starts observation from top to bottom in DataFrame.\nSo far, I could not find option to make it reverse for ewm. So I guess, I will have to reverse all my dataset.\nMaybe somebody knows how to make ewm start from bottom values?\nOr is it recommended to always use datetimeindex sorted chronologically? From oldest values on top to newest on the bottom?","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":91,"Q_Id":65362721,"Users Score":0,"Answer":"From pandas' documentation:\n\nTimes corresponding to the observations. Must be monotonically increasing and datetime64[ns] dtype.\n\nI guess, datetimeindex must be chronological..","Q_Score":0,"Tags":"python,pandas,dataframe,datetimeindex","A_Id":65362758,"CreationDate":"2020-12-18T19:17:00.000","Title":"Do I have to sort dates chronologically to use pandas.DataFrame.ewm?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm training a word embedding using GENSIM (word2vec) and use the trained model in a neural network in KERAS. A problem arises when I have an unknown (out-of-vocabulary) word so the neural network doesn't work anymore because it can't find weights for that specific word. I think one way to fix this problem is adding a new word () to the pre-trained word embedding with zero weights (or maybe random weights? which one is better?) Is this approach fine? Also, for this word embedding, the weights are not trainable in this neural network.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":652,"Q_Id":65370297,"Users Score":1,"Answer":"Most typical is to ignore unknown words. (Replacing them with either a plug-word, or the origin-vector, is more distorting.)\nYou could also consider training a FastText mode instead, which will always synthesize some guess-vector for an out-of-vocabulary word, from the character-n-gram vectors created during training. (These synthetic vectors are often better than nothing, especially when a word has overlapping word roots with related words \u2013 but getting more training data with examples of all relevant word usages is better, and simply ignoring rare unknown words isn't that bad.)","Q_Score":1,"Tags":"python,keras,gensim,word2vec,word-embedding","A_Id":65376881,"CreationDate":"2020-12-19T13:23:00.000","Title":"Unknown words in a trained word embedding (Gensim) for using in Keras","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I trained a model using Tensorflow object detection API using Faster-RCNN with Resnet architecture. I am using tensorflow 1.13.1, cudnn 7.6.5, protobuf 3.11.4, python 3.7.7, numpy 1.18.1 and I cannot upgrade the versions at the moment. I need to evaluate the accuracy (AP\/mAP) of the trained model with the validation set for the IOU=0.3. I am using legacy\/eval.py script on purpose since it calculates AP\/mAP for IOU=0.5 only (instead of mAP:0.5:0.95)\npython legacy\/eval.py --logtostderr --pipeline_config_path=training\/faster_rcnn_resnet152_coco.config --checkpoint_dir=training\/ --eval_dir=eval\/\nI tried several things including updating pipeline config file to have min_score_threshold=0.3:\neval_config: {\nnum_examples: 60\nmin_score_threshold: 0.3\n..\nUpdated the default value in the protos\/eval.proto file and recompiled the proto file to generate new version of eval_pb2.py\n\/\/ Minimum score threshold for a detected object box to be visualized\noptional float min_score_threshold = 13 [default = 0.3];\nHowever, eval.py still calculates\/shows AP\/mAP with IOU=0.5\nThe above configuration helped only to detect objects on the images with confidence level < 0.5 in the eval.py output images but this is not what i need.\nDoes anybody know how to evaluate the model with IOU=0.3?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":116,"Q_Id":65375340,"Users Score":0,"Answer":"I finally could solve it by modifing hardcoded matching_iou_threshold=0.5 argument value in multiple method arguments (especially def __init) in the ..\/object_detection\/utils\/object_detection_evaluation.py","Q_Score":1,"Tags":"python,tensorflow,object,detection,evaluation","A_Id":65417109,"CreationDate":"2020-12-19T23:06:00.000","Title":"How to evaluate trained model Average Precison and Mean AP with IOU=0.3","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have been trying to stack two images.\nThe end result will be used as the input to my convolutional neural network.\nNow I tried to use dstack, I also tried to use PIL by importing Image.blend but I cannot seem to be arriving to my desired result.\nI am asking if anyone has any other ideas which I can use would be greatly appreciated.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":225,"Q_Id":65375662,"Users Score":0,"Answer":"Resize them so that they are the same size, and then use np.stack with axis=3 (if you are using multi-channel images. Else, use axis=2.\nOr are you trying to combine them into one image? If so, how? Masking, adding subtracting?","Q_Score":1,"Tags":"python,image-processing,stack","A_Id":65377715,"CreationDate":"2020-12-19T23:57:00.000","Title":"Stack two images to obtain a single image on Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I just learned how to use the machine learning model Random Forest; however, although I read about the random_state parameter, I couldn't understand what it does. For example, what is the difference between random_state = 0 and random_state = 300\nCan someone please explain?","AnswerCount":3,"Available Count":3,"Score":0.0,"is_accepted":false,"ViewCount":544,"Q_Id":65380064,"Users Score":0,"Answer":"Random forests introduce stochasticity by randomly sampling data and features. Running RF on the exact same data may produce different outcomes for each run due to these random samplings. Fixing the seed to a constant i.e. 1 will eliminate that stochasticity and will produce the same results for each run.","Q_Score":0,"Tags":"python,data-science,random-forest,random-seed","A_Id":65411284,"CreationDate":"2020-12-20T12:53:00.000","Title":"random_state in random forest","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I just learned how to use the machine learning model Random Forest; however, although I read about the random_state parameter, I couldn't understand what it does. For example, what is the difference between random_state = 0 and random_state = 300\nCan someone please explain?","AnswerCount":3,"Available Count":3,"Score":0.0,"is_accepted":false,"ViewCount":544,"Q_Id":65380064,"Users Score":0,"Answer":"train_test_split splits arrays or matrices into random train and test subsets. That means that everytime you run it without specifying random_state, you will get a different result, this is expected behavior.\nWhen you use random_state=any_value then your code will show exactly same behaviour when you run your code.","Q_Score":0,"Tags":"python,data-science,random-forest,random-seed","A_Id":65381558,"CreationDate":"2020-12-20T12:53:00.000","Title":"random_state in random forest","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I just learned how to use the machine learning model Random Forest; however, although I read about the random_state parameter, I couldn't understand what it does. For example, what is the difference between random_state = 0 and random_state = 300\nCan someone please explain?","AnswerCount":3,"Available Count":3,"Score":0.0,"is_accepted":false,"ViewCount":544,"Q_Id":65380064,"Users Score":0,"Answer":"In addition, most people use the number 42 when we use random_state.\nFor example, random_state = 42 and there's a reason for that.\nBelow is the answer.\nThe number 42 is, in The Hitchhiker's Guide to the Galaxy by Douglas Adams, the \"Answer to the Ultimate Question of Life, the Universe, and Everything\", calculated by an enormous supercomputer named Deep Thought over a period of 7.5 million years. Unfortunately, no one knows what the question is","Q_Score":0,"Tags":"python,data-science,random-forest,random-seed","A_Id":65385737,"CreationDate":"2020-12-20T12:53:00.000","Title":"random_state in random forest","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"When we have discrete variable such as age, number of sick leaves, number of kids in the family and number of absences within a dataframe which i wanted to make a prediction model with binary result, is it okay to include these variables along with other numeric continuous variables into a standardization or normalization process?\nor should i categorize these discrete variables into a categoric variable and turned them into dummy variables?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":980,"Q_Id":65382855,"Users Score":0,"Answer":"If they are not one of the target variables, It is okay to include these variables along with other numeric continuous variables into a standardization or normalization process.","Q_Score":0,"Tags":"python,normalization,methodology,discrete,standardization","A_Id":65388263,"CreationDate":"2020-12-20T17:39:00.000","Title":"Standardizing or Normalizing discrete variable?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a large CSV file(>100 GB) that I want to read into memory and process the data in chunks. There are two constraints I have:\n\nObviously I cannot read the whole entire file into memory. I only have about 8GB of ram on my machine.\nThe data is tabular and unordered. I need to read the data in groups.\n\n\n\n\n\nTicker\nDate\nField1\nField2\nField3\n\n\n\n\nAAPL\n20201201\n0\n0\n0\n\n\nAAPL\n20201202\n0\n0\n0\n\n\nAAPL\n20201203\n0\n0\n0\n\n\nAAPL\n20201204\n0\n0\n0\n\n\nNFLX\n20201201\n0\n0\n0\n\n\nNFLX\n20201202\n0\n0\n0\n\n\nNFLX\n20201203\n0\n0\n0\n\n\nNFLX\n20201204\n0\n0\n0\n\n\n\n\nThe concern here is that the data has to be read in groups. Grouped by Ticker and date. If I say I want to read 10,000 records in each batch. The boundary of that batch should not split groups. i.e. All the AAPL data for 2020 December should end up in the same batch. That data should not appear in two batches.\nMost of my co-workers when they face a situation like this, they usually create a bash script where they use awk, cut, sort, uniq to divide data into groups and write out multiple intermediate files to the disk. Then they use Python to process these files. I was wondering if there is a homogenous Python\/Pandas\/Numpy solution to this.","AnswerCount":3,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":134,"Q_Id":65384208,"Users Score":0,"Answer":"I would look into two options\nVaex and Dask.\nVaex seems to be focused exactly on what you need. Lazy processing and very large datasets. Check their github. However it seems, that you need to convert files to hdf5, which may be little bit time consuming.\nAs far as Dask is concerned, I wouldnt count on success. Dask is primarily focused on distributed computation and I am not really sure if it can process large files lazily. But you can try and see.","Q_Score":3,"Tags":"python,pandas,numpy","A_Id":65384605,"CreationDate":"2020-12-20T19:56:00.000","Title":"How do you read a large file with unsorted tabular data in chunks in Python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":1,"Web Development":0},{"Question":"I have a large CSV file(>100 GB) that I want to read into memory and process the data in chunks. There are two constraints I have:\n\nObviously I cannot read the whole entire file into memory. I only have about 8GB of ram on my machine.\nThe data is tabular and unordered. I need to read the data in groups.\n\n\n\n\n\nTicker\nDate\nField1\nField2\nField3\n\n\n\n\nAAPL\n20201201\n0\n0\n0\n\n\nAAPL\n20201202\n0\n0\n0\n\n\nAAPL\n20201203\n0\n0\n0\n\n\nAAPL\n20201204\n0\n0\n0\n\n\nNFLX\n20201201\n0\n0\n0\n\n\nNFLX\n20201202\n0\n0\n0\n\n\nNFLX\n20201203\n0\n0\n0\n\n\nNFLX\n20201204\n0\n0\n0\n\n\n\n\nThe concern here is that the data has to be read in groups. Grouped by Ticker and date. If I say I want to read 10,000 records in each batch. The boundary of that batch should not split groups. i.e. All the AAPL data for 2020 December should end up in the same batch. That data should not appear in two batches.\nMost of my co-workers when they face a situation like this, they usually create a bash script where they use awk, cut, sort, uniq to divide data into groups and write out multiple intermediate files to the disk. Then they use Python to process these files. I was wondering if there is a homogenous Python\/Pandas\/Numpy solution to this.","AnswerCount":3,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":134,"Q_Id":65384208,"Users Score":0,"Answer":"How about this:\n\nopen the file\nloop over reading lines: For each line read:\n\n\nparse the ticker\nif not done already:\n\ncreate+open a file for that ticker (\"ticker file\")\nappend to some dict where key=ticker and value=file handle\n\n\nwrite the line to the ticker file\n\n\nclose the ticker files and the original file\nprocess each single ticker file","Q_Score":3,"Tags":"python,pandas,numpy","A_Id":65384348,"CreationDate":"2020-12-20T19:56:00.000","Title":"How do you read a large file with unsorted tabular data in chunks in Python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":1,"Web Development":0},{"Question":"I have data set that has both NaN and inf values and I am looking for linear regression library that can take both NaN and inf values. I have used sklearn in the past but also have seen linregress used a lot, but both libraries require NaN and inf values to be dropped beforehand.\nThanks for the suggestions","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":87,"Q_Id":65385645,"Users Score":1,"Answer":"As @Moosefeather mentioned you have to deal with this yourself. Easiest option is to drop those samples or replace them with an average.\nA more sophisticated approach would be something like estimating the expected missing value conditioned on the other values of the observation. This is more work and if you have enough clean data dropping the bad values might be better.","Q_Score":0,"Tags":"python,scikit-learn","A_Id":65386130,"CreationDate":"2020-12-20T22:55:00.000","Title":"Linear Regression Library that can take NaN and inf values suggestion","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I keep on reading that Naive Bayes needs fewer features than many other ML algorithms. But what's the minimum number of features you actually need to get good results (90% accuracy) with a Naive Bayes model? I know there is no objective answer to this -- it depends on your exact features and what in particular you are trying to learn -- but I'm looking for a numerical ballpark answer to this.\nI'm asking because I have a dataset with around 280 features and want to understand if this is way too few features to use with Naive Bayes. (I tried running Naive Bayes on my dataset and although I got 86% accuracy, I cannot trust this number as my data is imbalanced and I believe this may be responsible for the high accuracy. I am currently trying to fix this problem.)\nIn case it's relevant: the exact problem I'm working on is generating time tags for Wikipedia articles. Many times the infobox of a Wikipedia article contains a date. However, many times this date appears in the text of the article but is missing from the infobox. I want to use Naive Bayes to identify which date from all the dates we find in the article's text we should place in the infobox. Every time I find a sentence with a date in it I turn it into a feature vector -- listing what number paragraph I found this in, how many times this particular date appears in the article, etc. I've limited myself to a small subset of Wikipedia articles -- just apple articles -- and as a result, I only have 280 or so features. Any idea if this is enough data?\nThanks!","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":92,"Q_Id":65386211,"Users Score":1,"Answer":"I know there is no objective answer to this -- it depends on your exact features and what in particular you are trying to learn -- but I'm looking for a numerical ballpark answer to this.\n\nWell, you kind of answered this question yourself but you're still hoping there is an objective answer ;)\nThere can't be any kind of objective answer (whether precise or not) because it depends on the data, i.e. relationships between features and class. It's easy to find examples of simple problems where only a couple features is enough to achieve perfect performance, and it's also easy to create a dataset of millions of random features which can't even reach mediocre performance.\n\ngood results (90% accuracy)\n\nSimilar point about performance: there are tasks where 90% accuracy is mediocre and there are tasks where 60% is excellent, it depends how hard the problem is (i.e. how easy it is to find the patterns in the data which help predict the answer).\n\nI'm asking because I have a dataset with around 280 features and want to understand if this is way too few features to use with Naive Bayes.\n\nDefinitely not too few, as per my previous observations. But it also depends on how many instances there are, in particular the ratio features\/instances. If there are too few instances, the model is going to overfit badly with NB.\n\nmy data is imbalanced and I believe this may be responsible for the high accurac\n\nGood observation: accuracy is not an appropriate evaluation measure for imbalanced data. The reason is simple: if the majority class represents say 86% of the instances, the classifier can just label all the instances with this class and obtain 86% accuracy, even though it does nothing useful. You should use precision, recall and F-score instead (based on the minority class).","Q_Score":2,"Tags":"python,nlp,dataset,wikipedia,naivebayes","A_Id":65396742,"CreationDate":"2020-12-21T00:34:00.000","Title":"What's the minimum number of features you need to get good results with a Naive Bayes model?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"In a classification problem involving the identification of fraudulent transactions, I reduced the dimensionality of the data(28 columns)[A complete quasi-separation was detected by Logit in statsmodels] using a stacked auto encoder(28->15->5) and fed the compressed data(5 columns) into a neural network with two hidden layers, each having 10 nodes and 'relu' activation function. I trained the model over a 100 epochs(The AUC metric didn't go beyond 0.500 and the train loss became constant after a few epochs).The model predicted all the records of the test set as non-fraudulent(0 class) and yielded a confusion matrix like this:\nConfusion matrix:\n[[70999 0]\n[ 115 0]]\nAccuracy Score : 0.9983828781955733\nCan someone please explain the problem behind this result and suggest a feasible solution?..","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":31,"Q_Id":65396944,"Users Score":0,"Answer":"Since your accuracy is over 99% on all zero class prediction, the percent of fraud cases in your train set is less than 1%\nTypically if the fraud cases are rare, the model will not place enough importance on the fraud cases to predict well.\nto fix this you can add costs to penalize the majority class, or add weights to penalize the majority class or use class balancing methods such as SMOTE","Q_Score":0,"Tags":"python,neural-network,classification","A_Id":65397808,"CreationDate":"2020-12-21T17:02:00.000","Title":"\"All zero class\" prediction by Neural Network","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to classify images as \"good\" or \"bad\". In a given region of interest, if the region of interest painted well then it is a good image else bad. I segmented the painted parts using K means clustering then I counted pixels of painted parts. How can I set a threshold value to classify images as good or bad by using the counted pixel numbers? Or is there a better approach that I can try? I tried training simple CNN but the dataset has a big class imbalance (as I observed) and I don't have labels for images.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":47,"Q_Id":65404798,"Users Score":1,"Answer":"There is no \"right\" answer to your question, you are the only who could know what constitutes an acceptable paint-job. My suggestion would be to create a script which processes a big number of images you consider to be \"good\", append all your pixel counts to a list and then extract some statistics from that list. See what the min, max, mean values of that list are and decide accordingly what your thershold value would be. Then make the same thing for images you consider to be \"bad\" and see if the threshold value is always biggest than your max \"bad\" value. Of course the more data you have, the more reliable your result will be.","Q_Score":0,"Tags":"python,computer-vision","A_Id":65404934,"CreationDate":"2020-12-22T07:36:00.000","Title":"Setting a threshold value for color segmented images to classify them","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Is it okay to use python pandas to manipulate tabular data within a flask\/django web application?\nMy web app receives blocks of data which we visualise in chart form on the web. We then provide the user some data manipulation operations like, sorting the the data, deleting a given column. We have our own custom code to perform these data operations which it would be much easier to do it using pandas however I'm not sure if that is a good idea or not?","AnswerCount":2,"Available Count":2,"Score":0.1973753202,"is_accepted":false,"ViewCount":259,"Q_Id":65412596,"Users Score":2,"Answer":"Actually yes, but don't forget to move your computation into a separate process if it takes too long.","Q_Score":0,"Tags":"python,pandas,flask","A_Id":65412933,"CreationDate":"2020-12-22T16:47:00.000","Title":"Using pandas within web applications - good or bad?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":1},{"Question":"Is it okay to use python pandas to manipulate tabular data within a flask\/django web application?\nMy web app receives blocks of data which we visualise in chart form on the web. We then provide the user some data manipulation operations like, sorting the the data, deleting a given column. We have our own custom code to perform these data operations which it would be much easier to do it using pandas however I'm not sure if that is a good idea or not?","AnswerCount":2,"Available Count":2,"Score":0.1973753202,"is_accepted":false,"ViewCount":259,"Q_Id":65412596,"Users Score":2,"Answer":"It\u2019s a good question, pandas could be use in development environment if dataset isn\u2019t too big , if dataset is really big I think you could use spark dataframes or rdd, if data increase in function of time you can think on streaming data with pyspark.","Q_Score":0,"Tags":"python,pandas,flask","A_Id":65412799,"CreationDate":"2020-12-22T16:47:00.000","Title":"Using pandas within web applications - good or bad?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":1},{"Question":"I am building a face-recognition for a large number of people and I when to detect more and more when I add more data to train the model.\nMy current pipeline is:\n\nDetecting faces with Yolov4-tiny\nRecognize faces with KNN classifier (I train it with around 80 classes with each class contains around 5 pictures)\n\nCurrently, it can run in real-time with around 10fps on CPU. My concern is that through some research, I found that KNN will have problems if I increase the dataset (the curse of dimensionality). So i would like to know if it is ok for using KNN for this problem ? If not is there a way around this or another way to sort this problem ?","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":219,"Q_Id":65420484,"Users Score":2,"Answer":"Increasing the dataset does not cause the curse of dimensionality. The curse of dimensionality occurs in high dimensional spaces for example when using a large number of features. Increasing the dataset has instead a positive effect.\nI do see a problem in only using 5 pictures per class.\nAlso if you are interested in real-time performance (usually people mean 30fps+ when talking about real-time), I would look into running yolov4-tiny on a GPU instead of a CPU if that is possible.","Q_Score":0,"Tags":"python,tensorflow,machine-learning,deep-learning,computer-vision","A_Id":65420642,"CreationDate":"2020-12-23T07:29:00.000","Title":"Face recognition for large number of people","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to upload training job artifacts to S3 in a non-compressed manner.\nI am familiar with the output_dir one can provide to a sagemaker Estimator, then everything saved under \/opt\/ml\/output is uploaded compressed to the S3 output dir.\nI want to have the option to access a specific artifact without having to decompress the output every time. Is there a clean way to go about it? if not any workaround in mind?\nThe artifacts of my interest are small meta-data files .txt or .csv, while in my case the rest of the artifacts can be ~1GB so downloading and decompressing is quite excessive.\nany help would be appreciated","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":253,"Q_Id":65421005,"Users Score":1,"Answer":"I ended up using the checkpoint path that is by default being synced with the specified S3 path in an uncompressed manner.","Q_Score":1,"Tags":"python,boto3,amazon-sagemaker","A_Id":65977591,"CreationDate":"2020-12-23T08:15:00.000","Title":"how to save uncompressed outputs from a training job in using aws Sagemaker python SDK?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am currently looking for a possibly fast way to create (or use an already existing) classifier for images. The main goal is to classify the images whether they are (mainly) a logo or not. This means that I am not interested in recognizing the brand\/name of the company. But instead the model would have to tell how possible it is that the image is a logo.\nDoes such a categorizer already exist? And if not, is there any possible solution to avoid neural networks for this task?\nThanks in advance.","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":60,"Q_Id":65422821,"Users Score":1,"Answer":"I am not sure about the existence of this project, but I have a couple of ideas that can work for this without neural networks. I think as a convention neural networks would be much easier but I think it might be done K-means algorithm or by a clustering algorithm. I have imagined like if logo data are in the same area and image data are in another same area, they can be clustered.However, I haven't done it sth like that before but theoretically, it seems logical","Q_Score":0,"Tags":"python,image-processing,image-classification","A_Id":65423238,"CreationDate":"2020-12-23T10:32:00.000","Title":"Binary image classifier for logos","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am currently constructing a model in Pytorch that requires multiple custom layers. I have only been defining the forward method and thus do not define a backward method. The model seems to run well, and the optimizer is able to update using the gradients from the layers. However, I see many people defining backward methods, and I wonder if I am missing something.\nWhy might you need to define a backwards pass?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":481,"Q_Id":65425429,"Users Score":3,"Answer":"In very few cases should you be implementing your own backward function in PyTorch. This is because PyTorch's autograd functionality takes care of computing gradients for the vast majority of operations.\nThe most obvious exceptions are\n\nYou have a function that cannot be expressed as a finite combination of other differentiable functions (for example, if you needed the incomplete gamma function, you might want to write your own forward and backward which used numpy and\/or lookup tables).\n\nYou're looking to speed up the computation of a particularly complicated expression for which the gradient could be drastically simplified after applying the chain rule.","Q_Score":1,"Tags":"python,optimization,pytorch,layer","A_Id":65425809,"CreationDate":"2020-12-23T13:54:00.000","Title":"Why define a backward method for a custom layer in Pytorch?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I had read a file from excel and read as pandas dataframe.\nI have to make few transformation in floating data type values.\nI want to add trailing zeroes or change decimal places of the values.\nFor example:\n25 to 25.0000\n23.3 to 23.3000\n24.55 to 24.5500\nI have tried changing the values to str and then add zeroes.\nBut on exporting it back to excel ,I am getting string(text),which I want as numbers.\nI have also tried Decimal library, but facing same issue while exporting.\nkindly help guys.\nI want to export file to excel so need to make changes accordingly.\nThank you","AnswerCount":4,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":452,"Q_Id":65425954,"Users Score":0,"Answer":"You could try df['column']=df['column'].astype(float). This would change for a float number.\nIf you back to string, Excel read as text.","Q_Score":0,"Tags":"python,excel,pandas,dataframe,numpy","A_Id":65426368,"CreationDate":"2020-12-23T14:30:00.000","Title":"How to add trailing zeroes to floating point value and export to excel as float(number)?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"SOLVED!\nI am using keras with functional API and I have a tensor that is X = (None, 2) tensor and I need to concatenate it with a Y = (None,7) tensor to get a (None,9) tensor. The problem is X and Y's first dimension are unknown so I will have to repeat X a variable number of times, z, to make it equal Y.I have figured out how to repeat X with an unknown z using RepeatedVector but that adds an extra dimension (None, None, 2). So Now I need a way to flatten (None, None, 2) into (None, 2) so I can concatenate them leaving me with an object (None, 9) that I can put into a dense layer.\nso what i have tried...\n1 - tf.squeeze(X) but this removes all dimensions (None, None)\n2 - tf.keras.layers.Reshape but this doesn't accept None arguments for output_shape which i need since y is variable\n3 - K.flatten but this makes it 1 dimension.\n4- tried adding a dimension to Y = (1,None,7) created odd error.\nSOLUTION:\ntf.reshape(X, shape=[tf.shape(X)[0]*tf.shape(x)[1],2])\ni am calling the None dimensions using tf.shape() and multiplying them by each other.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":378,"Q_Id":65432925,"Users Score":0,"Answer":"Solution\ntf.reshape(X, shape=[tf.shape(X)[0]*tf.shape(x)[1],2])\ni am calling the None dimensions using tf.shape() and multiplying them by each other.","Q_Score":2,"Tags":"python,tensorflow,keras","A_Id":65434005,"CreationDate":"2020-12-24T01:29:00.000","Title":"Reduce (None, None, 2) to (None,2) using Keras","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"How do you flatten an image?\nI know that we make use conv2d and pooling to detect the edges and minimize the size of the picture, so do we then flatten it after that?\nWill the flattened, pooled image will be a vector in one row and features or one column and the features?\nDo we make the equation x_data=x_date\/255 after flattening or before convolution and pooling?\nI hope to know the answer.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":313,"Q_Id":65445537,"Users Score":0,"Answer":"Here's the pipeline:\nInput image (could be in batches - let's say your network processes 10 images simultaneously) so 10 images of size (28, 28) -- 28 pixels height \/ weight and let's say the image has 1 filter only (grayscale).\nYou are supposed to provide to your network an input of size (10, 28, 28, 1), which will be accepted by a convolutional layer. You are free to use max pooling and maybe an activation function. Your convolutional layer will apply a number of filters of your choice -- let's assume you want to apply 40 filters. These are 40 different kernels applied with different weights. If you want to let's say classify these images you will (most likely) have a number of Dense layers after your convolutional layers. Before passing the output of the convolutional layers (which will be a representation of your input image after a feature extraction process) to your dense layers you have to flatten it in a way (You may use the simplest form of flattening, just passing the numbers one after the other). So your dense layer accepts the output of these 40 filters, which will be 'images' -- their size depends on many things (kernel size, stride, original image size) which will later be flattened into a vector, which supposedly propagates forward the information extracted by your conv layer.\nYour second question regarding MinMaxScaling (div by 255) - That is supposed to take place before everything else. There are other ways of normalizing your data (Standar scaling -- converting to 0 mean and unit variance) but keep in mind, when using transformations like that, you are supposed to fit the transformation on your train data and transform your test data accordingly. You are not supposed to fit and transform on your test data. Here, dividing by 255 everything is accepted but keep that in mind for the future.","Q_Score":0,"Tags":"python,image-processing,deep-learning,conv-neural-network","A_Id":65447758,"CreationDate":"2020-12-25T05:28:00.000","Title":"How to flatten an image?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I was looking at the scikit-learn logistic regression documentation, and saw that the penalty can be L1 and L2. I know that lasso and ridge regression are also known as L1 and L2 regularization respectively, so I was wondering if the L1 and L2 penalties refer to the same thing?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":292,"Q_Id":65460759,"Users Score":1,"Answer":"Yes that's correct. For L1 and L2 regularization (Lasso and Ridge Regression), the regularization term is often called L1 penalty or L2 penalty.","Q_Score":1,"Tags":"python,scikit-learn,logistic-regression,lasso-regression","A_Id":65461219,"CreationDate":"2020-12-26T21:11:00.000","Title":"L1 and L2 Penalties on Sklearn Logistic Classifier","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"pickle[\"CSE_TS_SAMPLING\"].head(2)\noutput:\n0 02-DEC-2020 20:16:09\n1 03-DEC-2020 03:43:33\nName: CSE_TS_SAMPLING, dtype: object\nfrom datetime import datetime\ndef convert_date(x):\nreturn datetime.strptime(x, \"%d-%m-%Y %H:%M:%S\")\npickle[\"sample_date\"]=pickle[\"CSE_TS_SAMPLING\"].apply(lambda x:convert_date(x))\nerror:\ntime data '02-DEC-2020 20:16:09' does not match format '%d-%m-%Y %H:%M:%S'","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":27,"Q_Id":65463995,"Users Score":1,"Answer":"%m is the month 01 through 12. %b would match your date of \"DEC\" (note, %b depends on locale).","Q_Score":0,"Tags":"python-3.x,datetime","A_Id":65464094,"CreationDate":"2020-12-27T08:24:00.000","Title":"Error while converting string to date time using datetime.strptime()","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I was wondering if it is possible to concatenate two different pytorch tensors with different shapes.\none tensor is of shape torch.Size([247, 247]) and the other is of shape torch.Size([10, 183]). Is it possible to concatenate these using torch.cat() on dim=1?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":158,"Q_Id":65466208,"Users Score":1,"Answer":"I think you should use broadcasting. That is, to broadcast torch.Size([10, 183]) along dimension 0 (to reach 247) or do it for the other dimensions. For torch.cat to work, you need to have matching dimensions along which you are trying to concatenate.","Q_Score":0,"Tags":"python,python-3.x,concatenation,tensor","A_Id":65817111,"CreationDate":"2020-12-27T13:20:00.000","Title":"How to concatenate 2d tensors with 2 different dimensions","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Desired Output -\n\n\n\n\nid\ngender\nrandom_genre\n\n\n\n\n1\nF\nfiction\n\n\n1\nF\nhistory\n\n\n2\nM\nmystery\n\n\n3\nF\nfiction\n\n\n4\nM\nhistory\n\n\n\n\nI have a dataframe where a user can have multiple preferences and I have to join these with some other kind of preferences which makes the table exponentially large. Like x, y etc. preferences are up to 80+ of one kind and almost 40 are of another kind.\nUntil now I was pivoting the table (pivot_table) and performing merge but I want to use the output for charts (count of a preference etc.).\nCurrent output after pivot_table -\n\n\n\n\nid\ngender\nfiction\nhistory\nmystery\n\n\n\n\n1\nF\n1\nNaN\nNaN\n\n\n1\nF\nNaN\n2\nNaN\n\n\n2\nM\nNaN\nNaN\n3\n\n\n3\nF\n1\nNaN\nNaN\n\n\n4\nM\nNaN\n2\nNaN\n\n\n\n\nHaving almost 80+ preferences of just one type and more after joining.\nHow can I convert all these back after joins to the first table, where I just have a single column for all the preferences and if an id has multiple preferences a new row is created for the same?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":176,"Q_Id":65490297,"Users Score":0,"Answer":"Have a look at pandas.melt function. It might do the trick for you","Q_Score":1,"Tags":"python-3.x,pandas","A_Id":65490557,"CreationDate":"2020-12-29T09:52:00.000","Title":"Wide to long format pandas","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to preprocess an RGB image before sending it into my model. The shape of the image is (2560, 1440,3). For that I need to calculate the mean of every channel and substract them from corresponding channel pixels. I know that I can do it by:\nnp.mean(image_array, axis=(0, 1)).\nHowever, I cannot understand the process how it is being done.\nI am aware of how axes work individually (axis=0 for columns and axis = 1 for rows). How does the axis = (0,1) work in this situation?\nAnd also how can I do the same thing for multiple images, say, train_data_shape = (1000, 256, 256, 3)?\nI appreciate every feedback!","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":78,"Q_Id":65501984,"Users Score":1,"Answer":"Consider what happens when you have an array X of shape (5, 3) and you execute np.mean(X, axis=0). You\u2019ll get back an array of shape (1, 3) where the (0, i) element is the average of the 5 values in column i. You\u2019re essentially \u2018averaging out\u2019 that first dimension. If you instead set axis=1, you\u2019d get back an array of shape (5, 1) where the (i, 0) element is the average of the 3 values in row i - now, you\u2019re averaging out that second dimension.\nIt works similarly when multiple axes are provided. Say X is of shape (5, 4, 2). Then, executing np.mean(X, axis=(0,1)) will return an array of shape (1, 2) where the (0, i) element is the average of the sub-array X[:, :, i] (of shape (5, 4)). We\u2019re averaging out the first two dimensions.\nTo answer your second question: If you want to compute means on an image-by-image and channel-by-channel basis, use axis=(1,2). If you want to compute means over all of your images per channel, use axis=(0,1,2).","Q_Score":0,"Tags":"python,mean,preprocessor","A_Id":65502295,"CreationDate":"2020-12-30T04:22:00.000","Title":"I am trying to understand how the process of calculating the mean for every channel of RGB image","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a doubt about classification algorithm comparation.\nI am doing a project regarding hyperparameter tuning and classification model comparation for a dataset.\nThe Goal is to find out the best fitted model with the best hyperparameters for my dataset.\nFor example: I have 2 classification models (SVM and Random Forest), my dataset has 1000 rows and 10 columns (9 columns are features) and 1 last column is lable.\nFirst of all, I splitted dataset into 2 portions (80-10) for training (800 rows) and tesing (200rows) correspondingly. After that, I use Grid Search with CV = 10 to tune hyperparameter on training set with these 2 models (SVM and Random Forest). When hyperparameters are identified for each model, I use these hyperparameters of these 2 models to test Accuracy_score on training and testing set again in order to find out which model is the best one for my data (conditions: Accuracy_score on training set < Accuracy_score on testing set (not overfiting) and which Accuracy_score on testing set of model is higher, that model is the best model).\nHowever, SVM shows the accuracy_score of training set is 100 and the accuracy_score of testing set is 83.56, this means SVM with tuning hyperparameters is overfitting. On the other hand, Random Forest shows the accuracy_score of training set is 72.36 and the accuracy_score of testing set is 81.23. It is clear that the accuracy_score of testing set of SVM is higher than the accuracy_score of testing set of Random Forest, but SVM is overfitting.\nI have some question as below:\n_ Is my method correst when I implement comparation of accuracy_score for training and testing set as above instead of using Cross-Validation? (if use Cross-Validation, how to do it?\n_ It is clear that SVM above is overfitting but its accuracy_score of testing set is higher than accuracy_score of testing set of Random Forest, could I conclude that SVM is a best model in this case?\nThank you!","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":168,"Q_Id":65516888,"Users Score":0,"Answer":"I would suggest splitting your data into three sets, rather than two:\n\nTraining\nValidation\nTesting\n\nTraining is used to train the model, as you have been doing. The validation set is used to evaluate the performance of a model trained with a given set of hyperparameters. The optimal set of hyperparameters is then used to generate predictions on the test set, which wasn't part of either training or hyper parameter selection. You can then compare performance on the test set between your classifiers.\nThe large decrease in performance on your SVM model on your validation dataset does suggest overfitting, though it is common for a classifier to perform better on the training dataset than an evaluation or test dataset.","Q_Score":0,"Tags":"python,machine-learning,model,comparison,hyperparameters","A_Id":65516996,"CreationDate":"2020-12-31T05:11:00.000","Title":"Hyper-prparameter tuning and classification algorithm comparation","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"i'm kind of new to the Keras\/Tensorflow field and am currently trying to learn by using existing tutorial models for keras and trying to modify them afterwards. I chose an image classification task as this is what i will need it for if i ever get far enough to be able to handle the whole stuff ;)\nSituation: I gathered 20k indoor and outdoor pictures of apartements and houses to sort them into indoor\/outdoor pictures. The model I use and modified step by step has an accuracy of 95.2% right now but i would like to try reaching an even higher accuracy.\nProblem: On my PC, is takes about 24h to run 50 epochs with training and testing and a batch size of 128 with pictures of 256x256. This means, it takes endless to check if a modification to the model does result in an reasonable improvement of the result.\nFor example, lower batch size, smaller pictures or less epochs result in lower accuracy of the model. Reducing epochs has a smaller impact on the divergence between the test run and an full run, but in the end, it does not make a difference if the model needs 12 or 24 hours for training, if i would like to check, if a modification does have a positive effect.\nMy question: How do you check if changes to a model tend to result in a higher accuracy? Test runs with only a few pics? Reducing the epochs to a very low number? I tested some ways but every time a reduce the complexity in terms of pictures number, picture resolution, epochs etc., a \"test run\" does most of the time not indicate the final accuracy with a full run. E.g. test run performs worse while full run does better or vice versa.\nAny hints? Would be much appreciated!","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":47,"Q_Id":65521826,"Users Score":0,"Answer":"You are the only one how could answer this question. Let me see if I can explain my answer. You have 2 factors to take in consideration. The complexity of your model and the diversity of your pictures and those go hand in hand. It is usually not required to train your model on all data because there is a certain degree of \"repetition\". That is basically the reason why Stochastic Gradient Descendent works.\nYou could try to find an optimal dataset size by doing the following.\n\nSelect a random number of images ( let's say, 500).\nPick a configuration for our model, epochs, etc\nTrain your model and record the accuracy\nIncrease the number of images by 10% and repeat step 1-4 a few times.\nPlot the accuracy of your model.\n\nIf you notice that the accuracy does not increase, it could be because you either reached the \"optimal dataset size\" for your model or your model is not capable of learn anymore.\nAt this point, you could start reducing the complexity of your model, number of epochs, etc and again plot the accuracy. If that does not decreased , your model was capable of learning but there was nothing more to learn from your images.\nJust an idea.","Q_Score":0,"Tags":"python,tensorflow,machine-learning,keras","A_Id":65535869,"CreationDate":"2020-12-31T13:57:00.000","Title":"Keras Tensoflow model optimization based on test runs possible?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to do TIN Interpolation on a layer but when I fill all the fields with the right data (vector layer, interpolation attribute, extent etc) the algorithm does not run and shows me this message:\nTraceback (most recent call last):\nFile \"C:\/PROGRA~1\/QGIS 3.14\/apps\/qgis\/.\/python\/plugins\\processing\\algs\\qgis\\TinInterpolation.py\", line 188, in processAlgorithm\nwriter.writeFile(feedback)\nException: unknown\nExecution failed after 0.08 seconds\nDoes anybody have an idea about it?? Thank you","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":641,"Q_Id":65524297,"Users Score":0,"Answer":"I had the same issue. I converted a dxf file into a shape file and then I tried to use Tin interpolation but it didn't work. Then I realized that, in my dxf file, there were some very very small lines and polyline and, after removing them, the interpolation went just fine. I don't really have an explanation but maybe this could help you.","Q_Score":0,"Tags":"python,algorithm,vector,interpolation,qgis","A_Id":65921946,"CreationDate":"2020-12-31T18:09:00.000","Title":"Why I cannot do TIN Interpolation in QGIS?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to do TIN Interpolation on a layer but when I fill all the fields with the right data (vector layer, interpolation attribute, extent etc) the algorithm does not run and shows me this message:\nTraceback (most recent call last):\nFile \"C:\/PROGRA~1\/QGIS 3.14\/apps\/qgis\/.\/python\/plugins\\processing\\algs\\qgis\\TinInterpolation.py\", line 188, in processAlgorithm\nwriter.writeFile(feedback)\nException: unknown\nExecution failed after 0.08 seconds\nDoes anybody have an idea about it?? Thank you","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":641,"Q_Id":65524297,"Users Score":0,"Answer":"It is because of some small lines that are in your file that cannot be handled by Interpolation. You can use Generalizer3 in QGIS plugins to remove those lines.","Q_Score":0,"Tags":"python,algorithm,vector,interpolation,qgis","A_Id":71080481,"CreationDate":"2020-12-31T18:09:00.000","Title":"Why I cannot do TIN Interpolation in QGIS?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to develop a program in Python to predict the outcome of a Pseudo Random Number Generator.\nI already have a program that gets the seed of the previously generated number using seed = random.getstate(). My question is whether there is any way to calculate the next seed that will be used, so I can predict the next number.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":145,"Q_Id":65532406,"Users Score":1,"Answer":"The reason that pseudorandom number generators are so named is that they're deterministic; they generate a sequence of numbers that appear to be random, but which aren't really. If you start a PRNG with the same seed, you'll get the same sequence every time.\n\nI already have a programm that gets the seed of the previous generated number using seed = random.getstate()\n\nYou're not really getting a seed here, but rather the internal state of the PRNG. You could save that state and set it again later. That could be useful for testing, or just to continue with the same sequence.\n\nNow, my question is if there is anyway to calculate the next seed that will be used, so I can predict the number.\n\nAgain, not really a seed, which is the initial value that you supply to start a PRNG sequence. What you're getting is the internal state of the PRNG. But yes, if you have that state, then it's trivial to predict the next number: just call random.setstate(...) with the state that you got, generate the next number, and then call random.setstate(...) again to put the PRNG back in the same state so that it'll again generate that same number.","Q_Score":1,"Tags":"python,random,random-seed","A_Id":65532559,"CreationDate":"2021-01-01T18:18:00.000","Title":"Is there anyway to calculate the next seed knowing the previous seed?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"What will happen if I use the same training data and validation data for my machine learning classifier?","AnswerCount":5,"Available Count":4,"Score":0.0399786803,"is_accepted":false,"ViewCount":192,"Q_Id":65534207,"Users Score":1,"Answer":"We create multiple models and then use the validation to see which model performed the best. We also use the validation data to reduce the complexity of our model to the correct level. If you use train data as your validation data, you will achieve incredibly high levels of success (your misclassification rate or average square error will be tiny), but when you apply the model to real data that isn't from your train data, your model will do very poorly. This is called OVERFITTING to the train data.","Q_Score":2,"Tags":"python,validation,machine-learning","A_Id":65534230,"CreationDate":"2021-01-01T22:21:00.000","Title":"Train and validation data structure","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"What will happen if I use the same training data and validation data for my machine learning classifier?","AnswerCount":5,"Available Count":4,"Score":0.0,"is_accepted":false,"ViewCount":192,"Q_Id":65534207,"Users Score":0,"Answer":"Basically nothing happens. You are just trying to validate your model's performance on the same data it was trained on, which practically doesn't yield anything different or useful. It is like teaching someone to recognize an apple and asking them to recognize just the same apple and see how they performed.\nWhy a validation set is used then? To answer this in short, the train and validation sets are assumed to be generated from the same distribution and thus the model trained on training set should perform almost equally well on the examples from validation set that it has not seen before.","Q_Score":2,"Tags":"python,validation,machine-learning","A_Id":65534468,"CreationDate":"2021-01-01T22:21:00.000","Title":"Train and validation data structure","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"What will happen if I use the same training data and validation data for my machine learning classifier?","AnswerCount":5,"Available Count":4,"Score":0.0,"is_accepted":false,"ViewCount":192,"Q_Id":65534207,"Users Score":0,"Answer":"Generally, we divide the data to validation and training to prevent overfitting. To explain it, we can think a model that classifies that it is human or not and you have dataset contains 1000 human images. If you train your model with all your images in that dataset , and again validate it with again same data set your accuracy will be 99%. However, when you put another image from different dataset to be classified by the your model ,your accuracy will be much more lower than the first. Therefore, generalization of the model for this example is a training a model looking for a stickman to define basically it is human or not instead of looking for specific handsome blonde man. Therefore, we divide dataset into validation and training to generalize the model and prevent overfitting.","Q_Score":2,"Tags":"python,validation,machine-learning","A_Id":65534699,"CreationDate":"2021-01-01T22:21:00.000","Title":"Train and validation data structure","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"What will happen if I use the same training data and validation data for my machine learning classifier?","AnswerCount":5,"Available Count":4,"Score":0.0798297691,"is_accepted":false,"ViewCount":192,"Q_Id":65534207,"Users Score":2,"Answer":"If the train data and the validation data are the same, the trained classifier will have a high accuracy, because it has already seen the data. That is why we use train-test splits. We take 60-70% of the training data to train the classifier, and then run the classifier against 30-40% of the data, the validation data which the classifier has not seen yet. This helps measure the accuracy of the classifier and its behavior, such as over fitting or under fitting, against a real test set with no labels.","Q_Score":2,"Tags":"python,validation,machine-learning","A_Id":65534254,"CreationDate":"2021-01-01T22:21:00.000","Title":"Train and validation data structure","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"So the current methods for capturing a downscaled image is to capture the full thing then downscale it, but I'm trying to go fast and thus don't want to capture the full image only every 10th pixel giving me an image 144 along and 108 down. which would result in a 10X speed increase because I don't have to get all the pixels from a full resolution just the few I want.\nThanks in advance","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":19,"Q_Id":65545844,"Users Score":0,"Answer":"I don't think this is possible due to driver\/library limitations, I'm thinking they'd be sending you the entire frame, try looking into the library you're using","Q_Score":1,"Tags":"python,image,video,resize","A_Id":65545880,"CreationDate":"2021-01-03T01:29:00.000","Title":"Python if I'm capturing at 1080 by 1440 is there a way to only read the pixel value from every 10th pixel","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to train a Word2Vec model using \"gensim\". I want to determine the initial rating rate. However, it is written that both \"alpha\" and \"start_alpha\" parameters can be used to do so. What is the difference between them? Are they the same?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":101,"Q_Id":65549685,"Users Score":0,"Answer":"They're essentially the same. If you specify non-default values in the constructor:\n\nthey're cached inside the model as alpha & min_alpha\n\nif you also took the option of specifying a training corpus in the constructor (sentences\/corpus_iterable\/corpus_file), the alpha & min_alpha will become the start_alpha, end_alpha for the automatic .train()\n\n\nIf you instead call .train() explicitly:\n\nyou can specify a start_alpha & end_alpha, just for that call, that will be used instead of the values set during the constructor (but won't be cached in the model for future calls)\n\nIf you're calling .train() multiple times on the same model some reason \u2013 which is usually an unnecessary bad idea, except in some non-standard expert-usage situations \u2013 it's likely you'd want to properly choose the right progression of alpha ranges across each call (so that it's not bouncing up-and-down nonsensically).\nThat expert use is the real reason the separate, non-cached start_alpha & end_alpha parameters exist. Most users should stick with the defaults (so not use any of these), and if they ever do get to the point of tinkering, just try different alpha values in the constructor, carefully monitoring if it helps or not.","Q_Score":0,"Tags":"python,gensim,word2vec","A_Id":65553620,"CreationDate":"2021-01-03T12:10:00.000","Title":"Difference between \"alpha\" and \"start_alpha\"","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am having problems with installing a python package (pandas) on Ubuntu 18.04 to a specific Python (3.6.5) distribution in Salome_meca located in:\n\/home\/username\/salome_meca\/V2019.0.3_universal\/prerequisites\/Python-365\/lib\/python3.6\/os.py\nif I run:\nsudo python3.6 -m pip install --install-option=\"--prefix=\/home\/username\/salome_meca\/V2019.0.3_universal\/prerequisites\/Pandas-120\" pandas\nIt raises an error:\nRequirement already satisfied: pandas in \/usr\/lib\/python3\/dist-packages\nAnd I cannot import this module as the python (3.6.5) distribution in Salome_meca cannot find it, when I run the code in the Salome_meca invornment.","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":215,"Q_Id":65554051,"Users Score":0,"Answer":"The problem was solved by firstly input in terminal .\/salome shell and then pip3 install pandas and this installed pandas under the python distribution within salome_meca. The only problem is that it was not installed in the correct folder (but works anyway). Probably one should set also the target dir, and then the command should be: pip3 install pandas --target=\/home\/lskrinjar\/salome_meca\/V2019.0.3_universal\/prerequisites\/Pandas-115","Q_Score":0,"Tags":"python,pandas,ubuntu,pip","A_Id":65619170,"CreationDate":"2021-01-03T19:31:00.000","Title":"Install python package to python distribution of salome_meca on Ubuntu 18.04","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using time series data from surgery to label a patient (binary) as having a certain medical condition or not as the patient is discharged from surgery. I am hoping to use LSTM or RNN. However, there are certain features that are missing in the sequence when the patient goes on bypass (for example, there is no pulse because the heart is stopped). Thus, all my patients have 'missing data' at some point. Should I still use imputation or is there a way that I can still use these features with their known gaps?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":53,"Q_Id":65555469,"Users Score":0,"Answer":"Depends on your application.\nOne way to deal with it is to remove any samples with missing features from the train set.\nOf course, at test-time, the predictions will not be reliable, as it's an unseen situation. So it's your task to detect those conditions at test-time and tell the user the predictions are not reliable.\nAnother option:\nIf the features that might be missing are categorical, an \"unknown\" category might be just fine to train on. For numeric features that doesn't work.","Q_Score":0,"Tags":"python,deep-learning","A_Id":65555562,"CreationDate":"2021-01-03T22:13:00.000","Title":"Known periods of missing data for deep learning applications","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am a bit confused about the definition of the r-squared score in the linear regression model.\nAs far as I know, the R-squared score represents how much of the dependent variable can be determined by the independent variables. However, in the scikit learn library, we have an r2-score function that calculates the r-squared score like r2_score(y_true, y_pred). But both of the parameters here are the output values, and it doesn't seem that it involves any of the indepent variables. Could you help me to understand how this is calculated?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":398,"Q_Id":65556670,"Users Score":1,"Answer":"You asked about the python code x = r2_score(y_true, y_pred)\nNote that:\n\n\n\n\ny_pred\ny_true\n\n\n\n\ny_pred stands for \"prediction of the y-variable\"\ny_true stands for \"true value of the y-variable\"\n\n\nThe predicted value is never the raw data. Often times, the predicted value is a line of best fit.\ny_true are the raw numbers you collect during either an experiment, survey, or scientific study.\n\n\n\n\nSuppose that you have a model of a teenagers height as a function of age.\n\n\n\n\nAGE (years since birth)\n10 years\n12 years\n14 years\n16 years\n\n\n\n\nHIEGHT (inches)\n55\n60\n65\n68\n\n\n\n\nAGE is defined as years since birth (not years since conception, like in China).\nAlso, we round age down to the nearest whole year.\nA child 10.81773 years old is listed as 10 years old.\nAn example of a predicted value might be that you think, on average, a child 10 years of age is 55 inches tall.\nIf you conduct a study where you measure the height of 1,038 children who are each 10 years old, you will find that the children are not all exactly 55 inches tall.\nThe raw data (measured heights of children) is known as the set of true y-values.\nStatisticians often measure error by comparing the distance from the measured height of a child from the predicted height.\nFor example, 10-year-old Joanna's height is 52 inches (rounded to the nearest whole inch).\nWe predicted Joanna's height to be 55 inches.\nThere are 3 inches of difference between the true, and the predicted, values.\nOften times, statisticians want one number for a data set, instead of 1,038 different numbers.\nOne thing you can do is convert the difference between the predicted height, and the actual heights of the children, into a positive number. For example, -5 becomes +5\nAfter that, compute the average positive-difference (in inches) between actual height and predicted height.\nTaking the absolute difference is important. Some children are shorter than predicted (-2 inches), and some children are taller (+7 inches).\nIf you allow negative numbers the average difference between the average height and actual height will always be zero.\n\nTake 1,038 actual heights.\nsubtract 55 inches from the actual height.\nsum up the height discrepancies without converting to positive numbers\nthe result will always be zero.\n\nIn fact, one way to define mean is that the mean of a sequence of numbers is a number x such that when you calculate the difference between each data-point and x, then sum the results, the answer is zero.\nGenerally, statisticians square the differences.\nSince Joanna was short (-2 inches) the squared error for Joanna is +4 inches.\nA negative number times a negative number is always a positive number.\nSquaring gets rid of the negative signs.\nTaking the absolute value gets rid of the negative signs.\nActually... there are about a million ways to get rid of the negative signs.\nSome statistician's are like the parrots in the 1998 movie \"Paulie.\"\nI say \"taco\" and they say \"TACO! TACO! TACO!\"\nThey copy what other statisticians do, and it never occurs to them that there is more than one way to do statistical analysis.\nI have a degree in math, I have seen proofs that the curve which minimizes the mean-squared-error is ideal in some ways.\nHowever, the mean-squared-error is more of a heuristic, or proxy, than a measure of what really, truly, matters.\nNobody actually has a formula which perfectly computes for data-set A, and data-set B, which data-set is more \"spread-out\" than the other.\nIt is difficult to tell what humans care about.\nAnyways, mean-square-error is better than nothing. IT measures how spread-out a data-set is. A\nre the data-points WAY WAY far away from the average, or all pretty close to the average?\nWhat-if 55 inches was the true average height of a 10-year-old child?\nAlso imagine \"what-if\" the true standard deviation was 4 inches.\nIn that imaginary world, suppose you randomly sampled 1,038 children, each 10 years of age.\nYour sample-variance (computed from experimental data) is 7.1091 inches.\nWhat is the likelihood that a sample of 1,038 children would have a variance of 7.1091 inches or more?\nIf your model is correct, what is the likelihood that the data would as far, or further, from the model's prediction as that you observed?\nIf the data you see is way WAY WAY far away from the predicted value, then your model is probably bad.\nAnyway the R-squared measure is:\n\n0% if the data does not match the model at all\n100% if the differences between the data and the prediction are adequately explained by random chance.\n\nFor example, if you toss a fair-coin 1,000 times, it is reasonably that 491 results would be heads instead of exactly 500 results of \"heads\".\nThe question is, is the observed value (491 heads out of 1,000 tosses) likely, or extremely weird, given the model which says that it should be about 500 out of 1,000.","Q_Score":0,"Tags":"python,machine-learning,data-science,modeling","A_Id":65557112,"CreationDate":"2021-01-04T01:31:00.000","Title":"what is r-squared in linear regression models?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Is there any polynomial or linear regression function in python, which error function is the Mean Absolute Error? Sklearn use MSE, but since the noise in the data has normal distribution, i would like to use MAE to minimise.\nAfter that i need a mathematical function(coefficients) also.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":319,"Q_Id":65562744,"Users Score":0,"Answer":"light gbm regression can work with MAE","Q_Score":0,"Tags":"python,function,regression,gradient,loss","A_Id":65566268,"CreationDate":"2021-01-04T12:28:00.000","Title":"Polinomial regression with Mean Absolute Error cost function Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Is there any way to save the navigable window showing the graph with plt.show()?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":32,"Q_Id":65576303,"Users Score":0,"Answer":"Yes. You can use plt.savefig(\"graph.jpg\") to save your figures.","Q_Score":0,"Tags":"python,matplotlib","A_Id":65576417,"CreationDate":"2021-01-05T09:33:00.000","Title":"Is it possible to save the window obtained with plt.show() in a navigable format and not as a simple image?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Why does NumPy allow array[row_index, ] but array[, col_index] is not valid and gives Syntax Error. e.g. if I want to traverse the array row wise NumPy.array[row_index, :] and NumPy.array[row_index, ] both give the same answer where as only NumPy.array[:, col_index] produces the result in the latter case. Is there any reason behind this that I'm missing?","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":81,"Q_Id":65585701,"Users Score":2,"Answer":"arr[idx,] is actually short for arr[(idx,)], passing a tuple to the __getitem__ method. In python a comma creates a tuple (in most circumstances). (1) is just 1, (1,) is a one element tuple, as is 1,.\narr[,idx] is gives a syntax error. That's the interpreter complaining, not numpy.\narr[3], arr[3,] and arr[3,:] are all the same for a 2d array. Trailing : are added as needed. Leading : have to be explicit.","Q_Score":1,"Tags":"python,arrays,numpy","A_Id":65585869,"CreationDate":"2021-01-05T19:57:00.000","Title":"NumPy array row wise and column wise slicing syntax","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a collection of text documents. I've been asked to show each document in tf-idf vector space and in ntc form and then, train a svm model based on documents' vectors in python. What does ntc exactly mean here?\nI Found that it's the same as tf-idf weights with one step of normalization which is called \"cosine normalization\". But i can't find information about such thing. I found \"cosine similarity\" which is in my idea different from \"cosine normalization\". Are they the same? And how can i create this vector in python?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":119,"Q_Id":65613869,"Users Score":0,"Answer":"I suggest the sklearn.feature_extraction.text.TfidfVectorizer,\nscikit learn is a bib in python used for training machine learning model,\nit is easy and very useful,","Q_Score":0,"Tags":"python,nlp,tf-idf","A_Id":65667335,"CreationDate":"2021-01-07T14:07:00.000","Title":"What's exactly ntc form in tf-idf vector space?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I follow the Gilbert Tunner tutorial to Object Detection using Tensorflow 2, but I have this error during the training with model_main_ft2.py:\nTraceback (most recent call last):\n\nFile \"model_main_tf2.py\", line 113, in \ntf.compat.v1.app.run() File \"C:\\Users\\anaconda3\\envs\\tensorflow2\\lib\\site-packages\\tensorflow\\python\\platform\\app.py\",\nline 40, in run\n_run(main=main, argv=argv, flags_parser=_parse_flags_tolerate_undef) File\n\"C:\\Users\\anaconda3\\envs\\tensorflow2\\lib\\site-packages\\absl\\app.py\",\nline 300, in run\n_run_main(main, args) File \"C:\\Users\\anaconda3\\envs\\tensorflow2\\lib\\site-packages\\absl\\app.py\",\nline 251, in _run_main\nsys.exit(main(argv)) File \"model_main_tf2.py\", line 110, in main\nrecord_summaries=FLAGS.record_summaries) File \"C:\\Users\\anaconda3\\envs\\tensorflow2\\lib\\site-packages\\object_detection\\model_lib_v2.py\",\nline 566, in train_loop\nunpad_groundtruth_tensors) File \"C:\\Users\\anaconda3\\envs\\tensorflow2\\lib\\site-packages\\object_detection\\model_lib_v2.py\",\nline 339, in load_fine_tune_checkpoint\nif not is_object_based_checkpoint(checkpoint_path): File \"C:\\Users\\anaconda3\\envs\\tensorflow2\\lib\\site-packages\\object_detection\\model_lib_v2.py\",\nline 302, in is_object_based_checkpoint\nvar_names = [var[0] for var in tf.train.list_variables(checkpoint_path)] File\n\"C:\\Users\\anaconda3\\envs\\tensorflow2\\lib\\site-packages\\tensorflow\\python\\training\\checkpoint_utils.py\",\nline 112, in list_variables\nreader = load_checkpoint(ckpt_dir_or_file) File \"C:\\Users\\anaconda3\\envs\\tensorflow2\\lib\\site-packages\\tensorflow\\python\\training\\checkpoint_utils.py\",\nline 67, in load_checkpoint\nreturn py_checkpoint_reader.NewCheckpointReader(filename) File \"C:\\Users\\anaconda3\\envs\\tensorflow2\\lib\\site-packages\\tensorflow\\python\\training\\py_checkpoint_reader.py\",\nline 99, in NewCheckpointReader\nerror_translator(e) File \"C:\\Users\\anaconda3\\envs\\tensorflow2\\lib\\site-packages\\tensorflow\\python\\training\\py_checkpoint_reader.py\",\nline 35, in error_translator\nraise errors_impl.NotFoundError(None, None, error_message) tensorflow.python.framework.errors_impl.NotFoundError: Unsuccessful\nTensorSliceReader constructor: Failed to find any matching files for\nC:\/Users\/Desktop\/Tutorial\/models\/research\/object_detection\/efficientdet_d0_coco17_tpu-32\/chechpoint\/ckpt-0\n\nI've create efficientdet_d0_coco17_tpu-32 folder inside object detection folder, downloading and unzipping my model. I've already modify the model inside training folder adding a checkpoint PATH.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":235,"Q_Id":65618919,"Users Score":0,"Answer":"From comments\n\nThe error was an image with size over the efficentdetd0 size request (paraphrased from dons21)","Q_Score":0,"Tags":"python,tensorflow,object-detection,tensorflow2","A_Id":66354328,"CreationDate":"2021-01-07T19:41:00.000","Title":"Tensorflow2.4, model_main_tf2.py, chechpoint problem during training","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a pdf file with tables in it and would like to read it as a dataframe using tabula. But only the first PDF page has column header. The headers of dataframes after page 1 becomes the first row on information. Is there any way that I can add the header from page 1 dataframe to the rest of the dataframes? Thanks in advance. Much appreciated!","AnswerCount":1,"Available Count":1,"Score":0.537049567,"is_accepted":false,"ViewCount":4066,"Q_Id":65626278,"Users Score":3,"Answer":"One can solve this by following steps:\n\nRead the PDF:\ntables = tabula.read_pdf(filename, pages='all', pandas_options={'header': None})\n\n\nThis will create a list of dataframes, having pages as dataframe in the list.\n\npandas_options={'header': None} is used not to take first row as header in the dataframe.\n\nSo, the header of the first page will be first row of dataframe in tables list.\n\nSaving header in a variable:\ncols = tables[0].values.tolist()[0]\n\n\nThis will create a list named cols, having first row of first df in tables list which is our header.\n\nRemoving first row of first page:\ntables[0] = tables[0].iloc[1:]\n\n\nThis line will remove first row of first df(page) in tables list, as we have already stored in a variable we do not need it anymore.\n\nGiving header to all the pages:\nfor df in tables:\ndf.columns = cols\n\n\nThis loop will iterate through every dfs(pages) and give them the header we stored in cols variable.\nSo the header from page 1 dataframe will be given to the rest of the dataframes(pages).\nYou can also concat it in one dataframe with\n\nimport pandas as pd\n\nand:\n\ndf_Final = pd.concat(tables)\n\nHope this helps you, thanks for this oppurtunity.","Q_Score":1,"Tags":"python,dataframe,pdf","A_Id":65697278,"CreationDate":"2021-01-08T09:17:00.000","Title":"Using tabula.py to read table without header from PDF format","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am getting vehicle detections from YOLO with a video input. And I got some missing bounding box outputs for some frames. How can I get bounding box estimations for those missing frames using other known bounding boxes and centers of that sequence just by using coordinate geometry without using any advance tracking method?\nThanks!","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":150,"Q_Id":65627675,"Users Score":2,"Answer":"One way would be to just interpolate between adjacent frames. When a bounding box is missing in a frame but is present in adjacent frames, you can take the coordinates of the bounding boxes and calculate the average. If you want to make it more eleborate you can even include more frames and add a weight to weigh closer frames heavier.","Q_Score":1,"Tags":"python,object-detection,yolo,bounding-box","A_Id":65627783,"CreationDate":"2021-01-08T10:53:00.000","Title":"How can I estimate missing bounding box outputs using known bounding box data of a sequence?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have used sklearn.tree.DecisionTreeRegressor to predict a regression problem with two independables aka the features \"X\", \"Y\" and the predicted dependable variable \"Z\".\nWhen I plot the tree, the leafs do not seem to differ much from a Classification tree. The result is not a function at each leaf, but it is a single value at each leaf, just like in a classification.\nCan someone explain, why this is called a regression and why it is different to a classification tree?\nBecause I seem to have misunderstood the sklearn class, is there a tree package for python, that does a \"real\" regression and has a function as an output at each leaf? With X,Y and Z, this would probably be some kind of surface at each leaf.","AnswerCount":2,"Available Count":2,"Score":0.0996679946,"is_accepted":false,"ViewCount":120,"Q_Id":65631318,"Users Score":1,"Answer":"This is to be expected. The output at each leaf is not a function, it is a single value, representing the predicted numeric (hence regression) output for all instances in that leaf. The output is a \"function\" in the sense that you get different values depending on which leaf you would land in. Classification tree words exactly the same, but the output value represents a class probability, not the predicted value of Z.\nIn other words, regressions output functions that map to arbitrary values, but there is no rule that this function must be continuous. With trees, the function is more of a \"stair step\".","Q_Score":0,"Tags":"python,scikit-learn,regression,decision-tree","A_Id":65631380,"CreationDate":"2021-01-08T14:57:00.000","Title":"How is the result from a Decision Tree Regressor continuous?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have used sklearn.tree.DecisionTreeRegressor to predict a regression problem with two independables aka the features \"X\", \"Y\" and the predicted dependable variable \"Z\".\nWhen I plot the tree, the leafs do not seem to differ much from a Classification tree. The result is not a function at each leaf, but it is a single value at each leaf, just like in a classification.\nCan someone explain, why this is called a regression and why it is different to a classification tree?\nBecause I seem to have misunderstood the sklearn class, is there a tree package for python, that does a \"real\" regression and has a function as an output at each leaf? With X,Y and Z, this would probably be some kind of surface at each leaf.","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":120,"Q_Id":65631318,"Users Score":0,"Answer":"For anyone searching for what I was searching for:\nThere are combination of Linear\/Log\/... Regression Models with Decision Trees, called \"Model Tree\". Unfortunately not included in any free python package, but there are some implementations on github, if you google it.It is also supposed to be available soon with scikit-learn.\nThe Model Tree is simular to the M5 algorithm.","Q_Score":0,"Tags":"python,scikit-learn,regression,decision-tree","A_Id":65668497,"CreationDate":"2021-01-08T14:57:00.000","Title":"How is the result from a Decision Tree Regressor continuous?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have trained a custom object detection model using 750 images using ImageAI on Google Colab Pro about a month ago using TensorFlowGPU 1.13 and have roughly 30min\/epoch training time. Now, when I train using the same dataset but with TensorFlowGPU 2.4.3 (ImageAI doesnt support old TF anymore), I am getting very little GPU usage (0.1GB) and 6 hour per epoch training times. I have tried training the same model on my local machine and I am getting very slow training times as well.\nI am using the following imports (based on ImageAI documentation):\n!pip install tensorflow-gpu==2.4.0 keras==2.4.3 numpy==1.19.3 pillow==7.0.0 scipy==1.4.1 h5py==2.10.0 matplotlib==3.3.2 opencv-python keras-resnet==0.2.0\n!pip install imageai --upgrade\nI am pulling my training data from Google Drive.\nIs there anything I could be missing that could speed up my object detection training times on either Google Colab or my local machine? The slow training times is slowing my research down.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":372,"Q_Id":65632510,"Users Score":0,"Answer":"If you want full GPU usage, from my experience, you must revert back to previous versions of ImageAI and it's compatible packages. Here is a list of compatible packages that I have installed that work as of now (January 2021) on my local machine and Google Colab:\n\nTF-GPU==1.13.1\nKeras==2.2.4\nImageai==2.1.0\n\nThis fixed any issue caused by the most recent patch of ImageAI. I now am back to full GPU usage. Until the issue is patched, I suggest using the old version.","Q_Score":1,"Tags":"python,tensorflow,computer-vision,object-detection,imageai","A_Id":65654555,"CreationDate":"2021-01-08T16:10:00.000","Title":"Little to No GPU Usage during Custom Object Detection Training After Recent ImageAI Update","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've tried to import a model on Kaggle:\nfrom statsmodels.tsa.arima.model import ARIMA\nbut it returned this error:\nAttributeError: module 'numpy.linalg.lapack_lite' has no attribute '_ilp64'\nThere's numpy version 1.18.5. Could you please tell how to fix this error?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":920,"Q_Id":65632754,"Users Score":1,"Answer":"I've just back up statmodels library to the version 0.11.0:\npip uninstall statsmodels -y\npip install statsmodels==0.11.0\nIt seems like default version 0.11.1 has a bug","Q_Score":1,"Tags":"python,statsmodels,kaggle","A_Id":65636386,"CreationDate":"2021-01-08T16:26:00.000","Title":"Numpy doesn't provide an attribute","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"In the tensorflow documentation I see the call() method defined when subclassing activations and models. However, in case of subclassing regularizers, initializers and constraints, they define the __class__() method instead.\nWhen playing around with both, I could not find any differences myself.\nCould someone tell me what the difference is?","AnswerCount":2,"Available Count":2,"Score":1.2,"is_accepted":true,"ViewCount":95,"Q_Id":65635870,"Users Score":2,"Answer":"call() is just a regular method that you can call on an instance of a class, e.g. foo.call(...).\n__call__() is a special method that makes the instance itself callable. So instead of doing foo.call(...) you can just do foo(...). (You can also do foo.__call__() still.)","Q_Score":0,"Tags":"python,class,tensorflow,methods","A_Id":65636427,"CreationDate":"2021-01-08T20:19:00.000","Title":"What is the difference between call() and __call__() method in python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"In the tensorflow documentation I see the call() method defined when subclassing activations and models. However, in case of subclassing regularizers, initializers and constraints, they define the __class__() method instead.\nWhen playing around with both, I could not find any differences myself.\nCould someone tell me what the difference is?","AnswerCount":2,"Available Count":2,"Score":0.0996679946,"is_accepted":false,"ViewCount":95,"Q_Id":65635870,"Users Score":1,"Answer":"_call_ is python magic method (or dunder method) which make class objects callable. but on the other hand call is user defined method in Keras which at the background use mentioned _call_ method but before using it this user defined call do some extra things like building weight and bias tensors based on the input tensor shape.","Q_Score":0,"Tags":"python,class,tensorflow,methods","A_Id":65636398,"CreationDate":"2021-01-08T20:19:00.000","Title":"What is the difference between call() and __call__() method in python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have an image to threshold. But I dont want to classical methods. I have my own min and max threshold value. How can i apply this threshold values to my image and get a binary mask. For example min is 300 and max is 500 if my pixel value is between these I get 255 if not I get 0. Thanks for helping.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":243,"Q_Id":65636983,"Users Score":0,"Answer":"Assuming you're using opencv, there's the cv2.inRange(img, min, max) function that does exactly that. If you want a library agnostic solution then you could iterate through your image and build the mask yourself by checking each individual pixel value against your bounds.","Q_Score":0,"Tags":"python,image-processing,binary,minmax,image-thresholding","A_Id":65646466,"CreationDate":"2021-01-08T22:01:00.000","Title":"Image thresholding with my own min-max value with python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"for time in df[col]:\ndatetime.datetime.fromtimestamp(int(time))\nWhy is not updating directly the dataframe df[col]? My aim is to update one column of a data frame with new date format.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":19,"Q_Id":65641493,"Users Score":0,"Answer":"I solved; I creat a list and update the related column of the dataframe with the list.\na_list=datetime.datetime.fromtimestamp(int(time))\ndf[col]=a_list","Q_Score":0,"Tags":"python,dataframe,date,updates,epoch","A_Id":65641702,"CreationDate":"2021-01-09T10:18:00.000","Title":"Changing date format of a dataframe \/column","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"long ago i did the Deep Learning specialization on Coursera and i rewrite the NST notebook's code so it will run on Spyder. The code did run well and i haven't touch it for a year. Now i tried to run it again and i get \"NaN\" in the cost function and the generated picture is black. I tried to see the values of the variables from the Variables Explorer and it seems fine. Someone has an idea why it happens? i didn't change the code at all and the only thing i did since last year is installing packages.\nThanks!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":61,"Q_Id":65652302,"Users Score":0,"Answer":"either your model's weight too large or the learning rate is too large so it diverges, now, make sure to tune the learning rate (make it smaller than it's now) or use grad\/weights clipping","Q_Score":0,"Tags":"python,tensorflow,deep-learning,computer-vision,conv-neural-network","A_Id":65652451,"CreationDate":"2021-01-10T10:37:00.000","Title":"Getting \"NaN\" in Neural Style Transfer code","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have macbook air m1 and I can't install python modules like numpy, matplotlib.\nI install python3.8 with homebrew then install virtaulenv. In venv, when I run 'pip install numpy' the error shows up:\n'... ERROR: Failed building wheel for numpy\nFailed to build numpy\nERROR: Could not build wheels for numpy which use PEP 517 and cannot be installed directly'\nI tried 'pip install --upgrade pip setuptools wheel' doesn't work. Please help.","AnswerCount":1,"Available Count":1,"Score":0.6640367703,"is_accepted":false,"ViewCount":3810,"Q_Id":65653536,"Users Score":4,"Answer":"Install python 3.9.1 from python.org (ARM version)\nThen, for Numpy:\npython3 -m pip install cython\npython3 -m pip install --no-binary :all: --no-use-pep517 numpy==1.20rc1\nThen, for matplotlib:\nbrew install libjpeg\npython3 -m pip install matplotlib\nThis works for me on a Mac min with Apple Silicon.\nNo luck for SciPy yet, though.","Q_Score":3,"Tags":"python-3.x,virtualenv,homebrew,macos-big-sur,apple-silicon","A_Id":65745638,"CreationDate":"2021-01-10T12:59:00.000","Title":"I can't install python modules on Apple Silicon","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have an excel spreadsheet with raw data in:\ndemo-data:\n\n\n\n\n\n\n\n\n\n\n\n1\n2\n3\n\n\n4\n5\n6\n\n\n7\n8\n9\n\n\n\n\nHow do I combine all the numbers to one series, so I can start doing math on it. They are all just numbers of the same \"kind\"","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":40,"Q_Id":65657590,"Users Score":0,"Answer":"Given your dataframe as df, this function may help df.values.flatten().","Q_Score":0,"Tags":"python,pandas,dataframe,series","A_Id":65657647,"CreationDate":"2021-01-10T19:30:00.000","Title":"Python pandas - multiple columns to one series","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have few notions of machine learning and data science and I need to make a dimensional reduction of a data set, corresponding to the TV consumption of users. I have approximately 20 columns (features) and hundreds of thousands of samples.\nThe problem is that the features are of different kinds. For example, the region, the date, the type of device, the duration of consumption, etc.\nWhat algorithms could I implement in this particular case to reduce the number of features?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":27,"Q_Id":65664628,"Users Score":0,"Answer":"Look into feature selection algorithms, there are a ton of articles and public libraries that have implementations of these. Support Vector Machine's (SVM) is one that is commonly used. Take a look at sklearn\/tensorflow\/etc. docs to see implementation details and pick which one is best for your problem.","Q_Score":0,"Tags":"python,machine-learning,data-science,dimensionality-reduction","A_Id":65665322,"CreationDate":"2021-01-11T09:56:00.000","Title":"Dimensionality Reduction (Heterogenous Data)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a huge dataframe and I need to display it into an excel sheet such that every other 2 columns are colored except the 1st column.\nFor example:\nIf there are columns 1 to 100,\ncolumn 2,3 must be red\nthen 4,5 non colored\nthen 6,7 again red\nthen 8,9 non colored\nand it goes on and on till last column of the dataframe.","AnswerCount":4,"Available Count":1,"Score":0.049958375,"is_accepted":false,"ViewCount":240,"Q_Id":65667142,"Users Score":1,"Answer":"In Excel, Selected the columns containing you data or the entire spreadsheet. Click Conditional formatting on the Home Ribbon. Click New Rule. Click Use a formula to determine which cells to format. In the formula box enter =OR(MOD(COLUMN(A1),4)=2,MOD(COLUMN(A1),4)=3). Click the Format button. Select the fill tab. Set the fill color to what you want. Hit OK a few times and you should be done.\nThis will fill in the cells that or equal to 2 or 3 mod 4.","Q_Score":1,"Tags":"python,excel,dataframe,xlsxwriter","A_Id":65668488,"CreationDate":"2021-01-11T12:45:00.000","Title":"Color every other 2 columns of a dataframe into an excel?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"So I'm new at ML and I have a task where I need to be able to identify a specific object with my phone's camera and trigger an action at that moment. I got to the point where I'm able to train the model, hook it up with a sample Android app Google provides and run it. All of this works perfectly with a few datasets I've downloaded from different sites, things like dogs, or flowers work fine. Now, I'm trying to train the model with a set of images that contain a simple object, for this example I'm using a Sony Bluetooth speaker XB12B. I took a bunch of photos of it in different surroundings but when I train the model I always get an accuracy of 1 and when I use that model in my phone using image labeling, anything it sees is 100% that object.\nI'm training the model with only one class.\nAs I mentioned I'm new to this and I'm not sure what I'm doing wrong, if it's the shape of the object, the lack of more elements in the dataset or some other parameter I'm missing.\nAny insights you guys may have or clues are greatly appreciated\nCheers","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":38,"Q_Id":65667515,"Users Score":0,"Answer":"You would have to train the model with an existing dataset + your new set of images labeled as \"speaker\" (for the sake of this example). If you train a model with only 1 class, it will learn to predict \"how close is this object to a speaker?\" for every object it finds instead of \"is this a speaker?\".\nYou need to at least use 2 classes - mark speaker images as 'speaker' and the remaining images as 'other' OR you need to use more than 2 classes - mark speaker images as 'speaker' and the remaining images as per their assigned class of 'dog', 'cat', etc.","Q_Score":0,"Tags":"python,tensorflow,machine-learning,tensorflow-lite,image-classification","A_Id":65675031,"CreationDate":"2021-01-11T13:13:00.000","Title":"Issue with training an Image Classification Model with Tensorflow Lite Model Maker","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"am doing training for detecting the objects using yolov3 but i face some problem when i set batch_size > 1 it causes me cuda out of memory so i searched in google to see another solution found it depends on my GPU (GTX 1070 8G) .\nmay be the number of epoch is high and it require to be optimized .\nmaybe the epoch number should be decreased? and for training 1k images and 200 pic for validations .\nwhat is best epoch should i set to avoid overfitting?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":51,"Q_Id":65672181,"Users Score":0,"Answer":"your model's overfitting wont depend on the no. of epochs you set.....\nsince you hav made a val split in your data, make sure that your train loss - val loss OR train acc - val acc is nearly the same.This will assure that your model is not overfitting","Q_Score":0,"Tags":"python,machine-learning,deep-learning,pytorch","A_Id":65761464,"CreationDate":"2021-01-11T17:59:00.000","Title":"how many epoch for training 1k images","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Are there any solutions to distinguish person names from organization names?\nI was thinking NER, however the data are stored in a structured table (and are not unstructured sentences). Specifically, the NAME column lists person and organization names (which I'm trying to distinguish). In the below example, I would like to produce the values listed within the PERSON column, based on the values listed within the NAME column.\n\n\n\n\nNAME\nPERSON\n\n\n\n\nTom Hanks\nTRUE\n\n\nNissan Motors\nFALSE\n\n\nRyan Reynolds\nTRUE\n\n\nTesla\nFALSE\n\n\nJeff's Cafe\nFALSE","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":30,"Q_Id":65676915,"Users Score":0,"Answer":"If you have reason to believe that all entries are sufficiently known (i.e., common brands and celebrities), you could utilize distant learning approaches with Wikipedia as a source.\nEssentially, you search for each entry on Wikipedia, and utilize results from unique search results (i.e., searching for \"Tesla\" would lead to at least two uniquely different pages, namely the auto company, and the inventor). Most importantly, each page has assigned category tags at the bottom, which make it trivial to classify a certain article by using string matches with a few synonyms (e.g., Apple has the category tag \"Companies liste on NASDAQ\", so you could just say all categories that have \"company\"\/\"companies\" in the name are referring to articles that are companies.\nWith the results from the unique search terms, you should be able to construct a large enough training corpus with relatively high certainty of having accurate ground truth data, which you can in turn use to train a \"conventional\" ML model on the task.\nCaveat:\nI should note that it gets significantly harder if you are doing this with names that are relatively unknown and likely won't have a Wikipedia article. In that case, I could only think of utilizing dictionaries of frequently used first\/last names in your respective country. It is certainly more prone to false positive\/negatives (e.g., \"Toyota\" is also a very common last name in Japan, although Westerners likely refer to the car maker). Similarly, names that are less common (or have a different spelling) will also not be picked up and left out.","Q_Score":2,"Tags":"python,text,nlp","A_Id":65700031,"CreationDate":"2021-01-12T01:40:00.000","Title":"Distinguish Person's names from Organization names in structured table column","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am a newbie to Python and working on a small opencv application.\nI need local_threshold from scikit-image but getting below error :\n\nTraceback (most recent call last): File\n\"D:\/Projects\/Python\/Document_Scanner\/main.py\", line 6, in \nfrom skimage.filters import threshold_local File \"C:\\Users\\nash2\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\skimage\\filters_init_.py\",\nline 4, in \nfrom .edges import (sobel, sobel_h, sobel_v, File \"C:\\Users\\nash2\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\skimage\\filters\\edges.py\",\nline 18, in \nfrom ..restoration.uft import laplacian File \"C:\\Users\\nash2\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\skimage\\restoration_init_.py\",\nline 13, in \nfrom .rolling_ball import rolling_ball, ball_kernel, ellipsoid_kernel File\n\"C:\\Users\\nash2\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\skimage\\restoration\\rolling_ball.py\",\nline 3, in \nfrom ._rolling_ball_cy import apply_kernel, apply_kernel_nan ImportError: DLL load failed while importing _rolling_ball_cy: The\nspecified module could not be found.\n\nI tried reverting to older version of scikit-image , but still getting error.\nMy current version of scikit-image is 0.18.0","AnswerCount":4,"Available Count":4,"Score":0.0,"is_accepted":false,"ViewCount":3097,"Q_Id":65687480,"Users Score":0,"Answer":"I was able to get it work by reinstalling python on my machine. Hope it helps somebody.","Q_Score":2,"Tags":"python,python-3.x,opencv,scikit-learn,scikit-image","A_Id":65713830,"CreationDate":"2021-01-12T15:59:00.000","Title":"ImportError: DLL load failed while importing _rolling_ball_cy:","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am a newbie to Python and working on a small opencv application.\nI need local_threshold from scikit-image but getting below error :\n\nTraceback (most recent call last): File\n\"D:\/Projects\/Python\/Document_Scanner\/main.py\", line 6, in \nfrom skimage.filters import threshold_local File \"C:\\Users\\nash2\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\skimage\\filters_init_.py\",\nline 4, in \nfrom .edges import (sobel, sobel_h, sobel_v, File \"C:\\Users\\nash2\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\skimage\\filters\\edges.py\",\nline 18, in \nfrom ..restoration.uft import laplacian File \"C:\\Users\\nash2\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\skimage\\restoration_init_.py\",\nline 13, in \nfrom .rolling_ball import rolling_ball, ball_kernel, ellipsoid_kernel File\n\"C:\\Users\\nash2\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\skimage\\restoration\\rolling_ball.py\",\nline 3, in \nfrom ._rolling_ball_cy import apply_kernel, apply_kernel_nan ImportError: DLL load failed while importing _rolling_ball_cy: The\nspecified module could not be found.\n\nI tried reverting to older version of scikit-image , but still getting error.\nMy current version of scikit-image is 0.18.0","AnswerCount":4,"Available Count":4,"Score":0.1973753202,"is_accepted":false,"ViewCount":3097,"Q_Id":65687480,"Users Score":4,"Answer":"Installing the old version (0.18.0rc0 version) of scikit-image I solved this problem","Q_Score":2,"Tags":"python,python-3.x,opencv,scikit-learn,scikit-image","A_Id":65863625,"CreationDate":"2021-01-12T15:59:00.000","Title":"ImportError: DLL load failed while importing _rolling_ball_cy:","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am a newbie to Python and working on a small opencv application.\nI need local_threshold from scikit-image but getting below error :\n\nTraceback (most recent call last): File\n\"D:\/Projects\/Python\/Document_Scanner\/main.py\", line 6, in \nfrom skimage.filters import threshold_local File \"C:\\Users\\nash2\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\skimage\\filters_init_.py\",\nline 4, in \nfrom .edges import (sobel, sobel_h, sobel_v, File \"C:\\Users\\nash2\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\skimage\\filters\\edges.py\",\nline 18, in \nfrom ..restoration.uft import laplacian File \"C:\\Users\\nash2\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\skimage\\restoration_init_.py\",\nline 13, in \nfrom .rolling_ball import rolling_ball, ball_kernel, ellipsoid_kernel File\n\"C:\\Users\\nash2\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\skimage\\restoration\\rolling_ball.py\",\nline 3, in \nfrom ._rolling_ball_cy import apply_kernel, apply_kernel_nan ImportError: DLL load failed while importing _rolling_ball_cy: The\nspecified module could not be found.\n\nI tried reverting to older version of scikit-image , but still getting error.\nMy current version of scikit-image is 0.18.0","AnswerCount":4,"Available Count":4,"Score":0.0996679946,"is_accepted":false,"ViewCount":3097,"Q_Id":65687480,"Users Score":2,"Answer":"You need to install and distribute the contents of Microsoft's vcredist_x64.exe. In particular you need VCOMP140.DLL.","Q_Score":2,"Tags":"python,python-3.x,opencv,scikit-learn,scikit-image","A_Id":68213823,"CreationDate":"2021-01-12T15:59:00.000","Title":"ImportError: DLL load failed while importing _rolling_ball_cy:","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am a newbie to Python and working on a small opencv application.\nI need local_threshold from scikit-image but getting below error :\n\nTraceback (most recent call last): File\n\"D:\/Projects\/Python\/Document_Scanner\/main.py\", line 6, in \nfrom skimage.filters import threshold_local File \"C:\\Users\\nash2\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\skimage\\filters_init_.py\",\nline 4, in \nfrom .edges import (sobel, sobel_h, sobel_v, File \"C:\\Users\\nash2\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\skimage\\filters\\edges.py\",\nline 18, in \nfrom ..restoration.uft import laplacian File \"C:\\Users\\nash2\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\skimage\\restoration_init_.py\",\nline 13, in \nfrom .rolling_ball import rolling_ball, ball_kernel, ellipsoid_kernel File\n\"C:\\Users\\nash2\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\skimage\\restoration\\rolling_ball.py\",\nline 3, in \nfrom ._rolling_ball_cy import apply_kernel, apply_kernel_nan ImportError: DLL load failed while importing _rolling_ball_cy: The\nspecified module could not be found.\n\nI tried reverting to older version of scikit-image , but still getting error.\nMy current version of scikit-image is 0.18.0","AnswerCount":4,"Available Count":4,"Score":0.049958375,"is_accepted":false,"ViewCount":3097,"Q_Id":65687480,"Users Score":1,"Answer":"You need to install the scikit-image 0.18.0rc0 package. To install this package run the command below.\n\npip install scikit-image==0.18.0rc0\n\nNote - This also takes care of any previously installed versions of it by removing it and installing the specified version. If there is any problem with the installation, try running the command in an administrator terminal window.","Q_Score":2,"Tags":"python,python-3.x,opencv,scikit-learn,scikit-image","A_Id":69097068,"CreationDate":"2021-01-12T15:59:00.000","Title":"ImportError: DLL load failed while importing _rolling_ball_cy:","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have X lists of elements, each list containing a different number of elements (without repetitions inside a single list). I want to generate (if possible, 500) sequences of 3 elements, where each element belongs to a different list, and sequences do not repeat. So something like:\nX (in this case 4) lists of elements: [A1,A2], [B1,B2,B3,B4], [C1], [D1,D2,D3,D4,D5]\npossible results: [A1,B2,D2], [B3,C1,D2], [A1,B2,C1]... (here 500 sequences are impossible, so would be less)\nI think I know how to do it with a nasty loop: join all the lists, random.sample(len(l),3) from the joint list, if 2 indices belong to the same list repeat, if not, check if the sequence was not found before. But that would be very slow. I am looking for a more pythonic or more mathematically clever way.\nPerhaps a better way would be to use random.sample([A,B,C,D], 3, p=[len(A), len(B), len(C), len(D)]), then for each sequence from it randomly select an element from each group in the sequence, then check if a new sequence generated in this way hasn't been generated before. But again, a lot of looping.\nAny better ideas?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":30,"Q_Id":65706729,"Users Score":0,"Answer":"Check itertools module (combination and permutation in particular).\nYou can get a random.choice() from the permutations of 3 elements from the X lists (thus selecting 3 lists), and for each of them get a random.choice() (random module).","Q_Score":0,"Tags":"python,combinations,probability","A_Id":65706871,"CreationDate":"2021-01-13T17:19:00.000","Title":"Selecting mutiple random sequences of N elements from M different-length lists in Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've been handed a file with over 30 different neural network architectures, which I should examinate regarding certain metrics. Basically, without calling every single network explicitly, i.e. \"MapNet1()\", I want to iterate over the networks and just track the metrics I'm interested in.\nHow do I do that, especially regarding even bigger sizes of networks to investigate? Or better formulated: how can I loop over the networks defined in my file \"classification_models.py\" and the networks defined in there without calling each of the networks manually?\nAll the best.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":32,"Q_Id":65717092,"Users Score":1,"Answer":"Make a python list, which entries are yours neural networks (for example, append the trained models one by one). Then iterate over the list as usual.","Q_Score":0,"Tags":"python,automation,neural-network","A_Id":65717521,"CreationDate":"2021-01-14T10:17:00.000","Title":"How to iterate over neural network architectures?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have to generate a matrix (propagator in physics) by ordered multiplication of many other matrices. Each matrix is about the size of (30,30), all real entries (floats), but not symmetric. The number of matrices to multiply varies between 1e3 to 1e5. Each matrix is only slightly different from previous, however they are not commutative (and at the end I need the product of all these non-commutative multiplication). Each matrix is for certain time slice, so I know how to generate each of them independently, wherever they are in the multiplication sequence. At the end, I have to produce many such matrix propagators, so any performance enhancement is welcomed.\nWhat is the algorithm for fastest implementation of such matrix multiplication in python?\nIn particular -\n\nHow to structure it? Are there fast axes and so on? preferable dimensions for rows \/ columns of the matrix?\nAssuming memory is not a problem, to allocate and build all matrices before multiplication, or to generate each per time step? To store each matrix in dedicated variable before multiplication, or to generate when needed and directly multiply?\nCumulative effects of function call overheads effects when generating matrices?\nAs I know how to build each, should it be parallelized? For example maybe to create batch sequences from start of the sequence and from the end, multiply them in parallel and at the end multiply the results in proper order?\nIs it preferable to use other module than numpy? Numba can be useful? or some other efficient way to compile in place to C, or use of optimized external libraries? (please give reference if so, I don't have experience in that)\n\nThanks in advance.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":57,"Q_Id":65722938,"Users Score":1,"Answer":"I don't think that the matrix multiplication would take much time. So, I would do it in a single loop. The assembling is probably the costly part here.\nIf you have bigger matrices, a map-reduce approach could be helpful. (split the set of matrices, apply matrix multiplication to each set and do the same for the resulting matrices)\nNumpy is perfectly fine for problems like this as it is pretty optimized. (and is partly in C)\nJust test how much time the matrix multiplication takes and how much the assembling. The result should indicate where you need to optimize.","Q_Score":0,"Tags":"python,performance,matrix,matrix-multiplication","A_Id":65723725,"CreationDate":"2021-01-14T16:31:00.000","Title":"Fast subsequent multiplication of many matrices in python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to deploy a Python ML app (made using Streamlit) to a server. This app essentially loads a NN model that I previously trained and makes classification predictions using this model.\nThe problem I am running into is that because TensorFlow is such a large package (at least 150MB for the latest tensorflow-cpu version) the hosting service I am trying to use (Heroku) keeps telling me that I exceed the storage limit of 300MB.\nI was wondering if anyone else had similar problems or an idea of how to fix\/get around this issue?\nWhat I've tried so far\n\nI've already tried replacing the tensorflow requirement with tensorflow-cpu which did significantly reduce the size, but it was still too big so -\nI also tried downgrading the tensorflow-cpu version to tensorflow-cpu==2.1.0 which finally worked but then I ran into issues on model.load() (which I think might be related to the fact that I downgraded the tf version since it works fine locally)","AnswerCount":2,"Available Count":2,"Score":0.0996679946,"is_accepted":false,"ViewCount":144,"Q_Id":65728247,"Users Score":1,"Answer":"I've faced the same problem last year. I know this does not answer your Heroku specific question, but my solution was to use Docker with AWS Beanstalk. It worked out cheaper than Heroku and I had less issues with deployment. I can guide on how to do this if you are interested","Q_Score":0,"Tags":"python,tensorflow,heroku,keras,streamlit","A_Id":65780677,"CreationDate":"2021-01-14T23:11:00.000","Title":"Deploy TensorFlow model to server?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to deploy a Python ML app (made using Streamlit) to a server. This app essentially loads a NN model that I previously trained and makes classification predictions using this model.\nThe problem I am running into is that because TensorFlow is such a large package (at least 150MB for the latest tensorflow-cpu version) the hosting service I am trying to use (Heroku) keeps telling me that I exceed the storage limit of 300MB.\nI was wondering if anyone else had similar problems or an idea of how to fix\/get around this issue?\nWhat I've tried so far\n\nI've already tried replacing the tensorflow requirement with tensorflow-cpu which did significantly reduce the size, but it was still too big so -\nI also tried downgrading the tensorflow-cpu version to tensorflow-cpu==2.1.0 which finally worked but then I ran into issues on model.load() (which I think might be related to the fact that I downgraded the tf version since it works fine locally)","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":144,"Q_Id":65728247,"Users Score":0,"Answer":"You might have multiple modules downloaded. I would recommend you to open file explorer and see the actual directory of the downloaded modules.","Q_Score":0,"Tags":"python,tensorflow,heroku,keras,streamlit","A_Id":65728358,"CreationDate":"2021-01-14T23:11:00.000","Title":"Deploy TensorFlow model to server?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"get error when use this\ndf = pd.read_csv('filename.csv', usecols=[1,5,7])\nreturn Response(df.to_json(),status=status.HTTP_200_OK)","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":65,"Q_Id":65730183,"Users Score":0,"Answer":"df.to_json (r'Path where the new JSON file will be stored\\New File Name.json')\nto need to first save the than send it to a response","Q_Score":0,"Tags":"python,django,django-views","A_Id":65730219,"CreationDate":"2021-01-15T03:38:00.000","Title":"How to create response json from pandas csv in django?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":1},{"Question":"Ok, I am relatively new to Python (more of a MATLAB \/ R \/Stata user). I previously installed Python on my computer from the Python website. Everything was running smoothly until I had to install Pytorch too. I tried installing it via pip to no avail, so I had to make a new installation of Python but this time with Anaconda.\nHowever, now I have a mess and I can not load Scypi on Anaconda and I can not load Pytorch in the regular Python I have. Having to run them separately is driving me insane. Is there a way that I can merge the two versions together or should I uninstall and stick to only one?","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":111,"Q_Id":65755978,"Users Score":0,"Answer":"Have you tried pip3 install pytorch?\nSometimes Python2 is the main version. To use python 3 pip instead you have to use pip3 install","Q_Score":1,"Tags":"python,anaconda,pytorch","A_Id":65756225,"CreationDate":"2021-01-16T23:58:00.000","Title":"Managing several versions of Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"so I get this message right below the input cell when trying to fit the model:\nINFO:numexpr.utils:NumExpr defaulting to 8 threads.\nINFO:fbprophet:Disabling daily seasonality. Run prophet with daily_seasonality=True to override this.\nAfter setting daily_seasonality=True and running the cell again, Value error shows up that parameter daily_seasonality is not recognized.\nThanks","AnswerCount":1,"Available Count":1,"Score":0.6640367703,"is_accepted":false,"ViewCount":1103,"Q_Id":65759977,"Users Score":4,"Answer":"I've had the same problem.Access Anaconda Prompt for the environment that you are working with as admin. But it works after I follow some steps:\n1- conda install -c conda-forge fbprophet\n2- conda remove --force fbprophet\n3- In your jupyter notebook use pip : install fbprophet","Q_Score":0,"Tags":"python,valueerror,model-fitting,facebook-prophet","A_Id":65817878,"CreationDate":"2021-01-17T11:21:00.000","Title":"Value error when fitting Prophet() model - parameter not recognized","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a pandas DataFrame database of location and postal code addresses. But postal codes have been interpreted from Excel reading. For example, in France postal addresses are a department code followed by city code, e.g. 75600 (75 = 'Paris region', 600 = 'inner city').\nBut in some first postal codes, e.g. 01200 it have interpreted like 1200. How can I search integer values below 10000 and modify them? Or how to preserve the first zero. How to search and replace in a dataframe and use the content (to modify it)?","AnswerCount":4,"Available Count":1,"Score":0.049958375,"is_accepted":false,"ViewCount":651,"Q_Id":65779595,"Users Score":1,"Answer":"Solution of df = df[0].apply(lambda x: '0' + str(x) if x < 10000 else str(x)) is perfect. It convert the code to full string and then I can find GPS coordinates correspondant to national postal infos.\nMany thanks.","Q_Score":0,"Tags":"python,pandas,dataframe,leading-zero","A_Id":65781467,"CreationDate":"2021-01-18T17:47:00.000","Title":"Pandas dataframe search and modify leading zero on postal codes","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am creating and training a TensorFlow model in Google Cloud in their JupyterLab AI Notebooks but for some reason I cannot find a way to save my model after it's been created.\nTypically, I'd use created_model.save(str('\/saved_model_file')) in Colab to save to the local directory.\nBut JuptyerLab in Google Cloud responds with a \"Permission Denied\" error, I've tried giving all possible maximum permissions in AIM, I'm the only person on the count. But the error persists.\nBut I do seem capable of saving blobs to Buckets by using blob.upload_from_filename(source_file_name) or blob.upload_from_string(source_file_name) which saving to buckets seems like a more appropriate strategy.\nBut neither one of these will take the trained model created by TensorFlow since it's more of a function and not a file type they seem to be looking for. The tutorials seem to casually mention that you should save your model to a bucket but completely neglect to provide any simple code examples, apparently I'm the only guy on earth who wasn't born knowing how to do this.\nWould be a great if someone could provide some code examples on how to save a TensorFlow model to a bucket. I also need for this function to be done automatically by the python code. Thanks!","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":182,"Q_Id":65786211,"Users Score":0,"Answer":"It seems you just need to create the path with the OS module first then the TF function will work. This seems kind of odd, other platforms I've used let the TF function create the path by its self. Apparently Google Cloud doesn't like that, perhaps there's some user permission buried in a hierarchy somewhere that is causing this problem.\n\nMODEL_NAME = 'model_directory'\nmodel_version = int(time.time())\nmodel_path = os.path.join(MODEL_NAME, str(model_version))\nos.makedirs(model_path)\ntf.saved_model.save(model, model_path)","Q_Score":0,"Tags":"python,tensorflow,google-cloud-platform,jupyter-notebook","A_Id":65803372,"CreationDate":"2021-01-19T06:00:00.000","Title":"Google Cloud can't save Tensorflow model from Jupyter Notebook","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I know that detach() is used for detaching a variable from the computational graph. In that context, are the following expressions x = x - torch.mean(x, dim=0).detach() and x = x - torch.mean(x, dim=0) equivalent? I just want to subtract the mean out, don't want to pass gradients through the average calculation.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":98,"Q_Id":65791620,"Users Score":2,"Answer":"If you do not detach the mean, then you have lateral dependencies between all elements in the batch (dim=0) when estimating the gradient.","Q_Score":0,"Tags":"python,deep-learning,pytorch","A_Id":65792135,"CreationDate":"2021-01-19T12:34:00.000","Title":"Functionality of `detach()` in PyTorch for this specific case","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a training data with 3961 different rows and 32 columns I want to fit to a Random Forest and a Gradient Boosting model. While training, I need to fine-tune the hyper-parameters of the models to get the best AUC possible. To do so, I minimize the quantity 1-AUC(Y_real,Y_pred) using the Basin-Hopping algorithm described in Scipy; so my training and internal validation subsamples are the same.\nWhen the optimization is finished, I get for Random Forest an AUC=0.994, while for the Gradient Boosting I get AUC=1. Am I overfitting these models? How could I know when an overfitting is taking place during training?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":201,"Q_Id":65797412,"Users Score":0,"Answer":"To know if your are overfitting you have to compute:\n\nTraining set accuracy (or 1-AUC in your case)\nTest set accuracy (or 1-AUC in your case)(You can use validation data set if you have it)\n\nOnce you have calculated this scores, compare it. If training set score is much better than your test set score, then you are overfitting. This means that your model is \"memorizing\" your data, instead of learning from it to make future predictions.\nTo know if you are overfitting, you always need to do this process. However, if your training accuracy or score is too perfect (e.g. accuracy of 100%), you can sense that you are overfitting too.\nSo, if you don't have training and test data, you have to create it using sklearn.model_selection.train_test_split. Then you will be able to compare both accuracy. Otherwise, you won't be able to know, with confidence, if you are overfitting or not.","Q_Score":0,"Tags":"python,scikit-learn,overfitting-underfitting","A_Id":65799392,"CreationDate":"2021-01-19T18:31:00.000","Title":"How to know when an overfitting is taking place?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a cypher projection that used algo.unionFind in Neo4j. However, that algorithim has been deprecated. My query was:\nCALL algo.unionFind('MATCH (n) WHERE n.dtype=\\\"VALUE\\\" RETURN id(n) AS id','MATCH p=(n)-[]-(m) WHERE n.dtype=\\\"VALUE\\\" AND m.dtype=\\\"VALUE\\\" RETURN id(n) AS source, id(m) AS target', {write:true, partitionProperty:\\\"partition\\\", graph:'cypher'}) YIELD nodes, setCount, loadMillis, computeMillis, writeMillis\nI was hoping to find an equivalent approach with the Graph Data Science Library that runs the query and writes a new property partition in my nodes.\nAny help would be greatly appreciated!","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":130,"Q_Id":65799737,"Users Score":0,"Answer":"The algorithm has been renamed to gds.wcc.write in the new GDS library.","Q_Score":0,"Tags":"python,neo4j,cypher,py2neo,graph-data-science","A_Id":65807968,"CreationDate":"2021-01-19T21:24:00.000","Title":"Neo4j algo.unionFind equivalent with new Graph Data Science Library","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":1,"Web Development":0},{"Question":"How to print the data frame after \"pycaret setup\".That is after applying the one-hot encoder and other changes","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":109,"Q_Id":65804163,"Users Score":0,"Answer":"get_config() can help in general.\nFor example, in clustering module after setup() is run, you can get the transformed data by get_config('X').","Q_Score":0,"Tags":"python,pycaret","A_Id":67589240,"CreationDate":"2021-01-20T06:29:00.000","Title":"Want to print out DataFrame after applying the pycaret setup changes","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have an interactive notebook with a few widgets, that displays a plot (+other data) based on the information given by the widgets. The plot is only displayed if a Checkbox is checked.\nEverything works well except one thing: the Checkbox has a True value by default. When loading the notebook for the first time, it appears as clicked but the plot is not displayed -- if I interact with the widgets in any other way (either by re-clicking this checkbox twice, or by modifying some of the other widgets), then the plot is displayed.\nIs there a way to have the plot displayed at the beginning without waiting for the user to interact?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":274,"Q_Id":65810840,"Users Score":0,"Answer":"Start by creating your checkbox with the False value\ncb = widgets.Checkbox(value=False)\nThen, once you have set up your observse, in the code, change the value of the checkbox to True, and this should trigger your code.\ncb.value = True","Q_Score":1,"Tags":"jupyter-notebook,ipython,ipywidgets","A_Id":65825990,"CreationDate":"2021-01-20T13:49:00.000","Title":"Plot in a Jupyter notebook depending on a true\/false checkbox","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to write a program for a homework using recursion to search for a word in a matrix (2x2 or more), it can be going from left to right or from up to down (no other directions), for example if I am searching for ab , in the matrix [['a','b'],['c','d']], the program should return in what direction the word is written (across), the starting index(0), ending index(2), and the index of the row or column(0). \nMy problem is that I have the idea of the recursion but, I can't implement it. I tried to break the problem down into more little proplems, like searching for the word in a given row, I started by thinking of the smallest case which is 2x2 matrix, at the first row and column, I need to search one to the right and one to the bottom of the first char, and check if they are equal to my given string, then give my recursion function a smaller problem with the index+1. However I can't think of what to make my function return at the base case of the recursion, been trying to solve it and think of ways to do it for two days, and I can't code what I think about or draw.\nNote that I can't use any loops, I would really appreciate it if somone could push me in the right direction, any help would be pretty much appreciated, thanks in advance.\nEdit: more examples: for input of matrix : [['a','b','c'],['d','e','f'],['g','h','i']] the outputs are:\nwith the string ab : across,0,0,2\nwith the string be : down,1,0,2 \nwith the string ghi: across,2,0,3","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":193,"Q_Id":65812219,"Users Score":1,"Answer":"I assume that the word we are looking for could be found starting from any place but we can move up to down or left to right only.\nIn that case, you should have a function that takes the start index and a direction and then the function keeps moving in the given direction starting from the given index and keeps moving until it doesn't find a mismatch, and it just returns true or false based on the match of the given string.\nNow you need to call this function for each and every index of the matrix along with two directions up to down and left to right, and at any index, if you get the output of the function as true then you have found your answer.\nThis is a very basic idea to work, next it depends on you how you want to optimize the things in this method only.\n\nUpdate:\nTo avoid using the loops.\nThe other way I can think of is that the function which we have defined now takes the row, column, and the string to find. So at each call, you will first check if the character at the given row and column matches the first character of the given string if so then it calls the two more functions, one in the right direction and the other in the down direction, along with the string with the first character removed.\nNow to check all the columns of the matrix, you will anyway call the function in down and right direction with the exact same string.\nThe base case will be that if you reach the end of the string then you have found the answer and you will return True, otherwise False.\nOne more thing to notice here is that if any of the 4 function calls gives you a True response then the current row\/column will also return True.\nCheers!","Q_Score":0,"Tags":"python,recursion","A_Id":65812462,"CreationDate":"2021-01-20T15:09:00.000","Title":"Recursively search word in a matrix of characters","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I read that blender comes with its own python version. However I have troubles actually locating it in ubuntu. I had hoped for adding packages there. What is the current way of adding packages, like pandas to blender's python version?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":445,"Q_Id":65818610,"Users Score":0,"Answer":"Just copy the respective packages to\n\/usr\/share\/blender\/scripts\/modules\nand restart blender.","Q_Score":0,"Tags":"python,pandas,pip,blender","A_Id":65827045,"CreationDate":"2021-01-20T22:27:00.000","Title":"How to install pandas in blender 2.80 python on ubuntu?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":1,"Web Development":0},{"Question":"I have a large memory bank of information (in a class that has a large dictionary) that needs to be loaded into memory and updated as information is received once the data has been compiled into this super large structure (up to 20GB) I need to then save this updated memory bank to disk for later loading. However with pickle I haven't been able to find a way I can pickle a file by streaming the data as it serializes it(I can't exceed 25.5 GB). If you notice between having both a 20GB structure and needing to have the serialized pickle it well exceeds my memory resources.\nIs there a way to have pickle stream the information as it is serialized, or will I have to make my own function to write the memory to file(s) myself?\nIs there a way to keep memory costs low (offloading the memory from from to disk as the process is completed)?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":37,"Q_Id":65819466,"Users Score":0,"Answer":"If anyone must know, I solved this problem by converting my large memory structure into three smaller memory structures (order dependent) which I could then pickle. When I load the memory structure I have to also re concatenate the memories into a larger structure. The memory saving isn't much however it is a workaround I was able to do for now. This solution is of course structure dependent.","Q_Score":0,"Tags":"python-3.x,machine-learning,memory,pickle","A_Id":65820560,"CreationDate":"2021-01-21T00:11:00.000","Title":"Writing large memory structures to disk with limited Memory resources (Python)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am asked to normalize a probability distribution P=A(x^2)(e^-x) within 0 to infinity by finding the value for A. I know the algorithms to calculate the Numerical value of Integration, but how do I deal with one of the limits being Infinity.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":233,"Q_Id":65840009,"Users Score":0,"Answer":"The only way I have been able to solve this problem with some accuracy (I got full accuracy, indeed) is by doing some math first, in order to obtain the taylor series that represents the integral of the first.\nI have been looking here for my sample code, but I don't find it. I'll edit my post if I get a working solution.\nThe basic idea is to calculate all the derivatives of the function exp(-(x*x)) and use the coeficients to derive the integral form (by dividing those coeficients by one more than the exponent of x of the above function) to get the taylor series of the integral (I recommend you to use the unnormalized version described above to get the simple number coeficients, then adjust the result by multiplying by the proper constants) you'll get a taylor series with good convergence, giving you precise values for full precision (The integral requires a lot of subdivision, and you cannot divide an unbounded interval into a finite number of intervals, all finite)\nI'll edit this question if I get on the code I wrote (so stay online, and dont' change the channel :) )","Q_Score":0,"Tags":"c,python-3.x,gfortran,numerical-methods,numerical-integration","A_Id":65862048,"CreationDate":"2021-01-22T05:58:00.000","Title":"Numerical Integration in fortran with infinity as one of the limits","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"While accessing live-streaming IP camera.\nVideoCapture can open a video but then after some second or minute can't read it. cap.read\u200b() keeps returning false and frame is none after some time.\nFPS rate of that camera is 180000. This is so high.\nPython-> 3.8.5 (default, Jul 28 2020, 12:59:40)\n[GCC 9.3.0] on linux\nOS- Ubuntu (18.04 or 20.04)\nOpenCV - 4.4.0\nopencv-contrib-python==4.4.0.46","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":401,"Q_Id":65843787,"Users Score":1,"Answer":"This has kinda just been an issue that everyone seems to occasionally run into while using opencv with IP cameras. You can sidestep the problem by checking if cap.read() returns false and closing and re-opening the stream if it happens (If you keep having problems after closing and re-opening then there's actually a connection issue and it's not just opencv).","Q_Score":1,"Tags":"python-3.x,opencv,video-streaming,live-streaming,ip-camera","A_Id":65848192,"CreationDate":"2021-01-22T10:54:00.000","Title":"VideoCapture can open a video but then after some second or minute cap.read\u200b() keeps returning false","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"When computing ordinary least squares regression either using sklearn.linear_model.LinearRegression or statsmodels.regression.linear_model.OLS, they don't seem to throw any errors when covariance matrix is exactly singular. Looks like under the hood they use Moore-Penrose pseudoinverse rather than the usual inverse which would be impossible under singular covariance matrix.\nThe question is then twofold:\n\nWhat is the point of this design? Under what circumstances it is deemed useful to compute OLS regardless of whether the covariance matrix is singular?\n\nWhat does it output as coefficients then? To my understanding since the covariance matrix is singular, there would be an infinite (in a sense of a scaling constant) number of solutions via pseudoinverse.","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":524,"Q_Id":65844656,"Users Score":0,"Answer":"I noticed the same thing, seems sklearn and statsmodel are pretty robust, a little too robust making you wondering how to interprete the results after all. Guess it is still up to the modeler to do due diligence to identify any collinearity between variables and eliminate unnecessary variables. Funny sklearn won't even give you pvalue, which is the most important measure out of these regression. When play with the variables, the coefficient will change, that is why I pay much more attention on pvalues.","Q_Score":2,"Tags":"python,scikit-learn,linear-regression,statsmodels","A_Id":65855743,"CreationDate":"2021-01-22T11:53:00.000","Title":"Results of sklearn\/statsmodels ordinary least squares under singular covariance matrix","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to integrate a control problem, i.e. an ODE of the form dx\/dt = A.f(t), where\nx(t) is a function in R^3, f(t) is a function in R^4 and A is a matrix 3x4. In my special case, f(t) = F'(t), i.e. a time derivative of a function F. Furthermore, F is 1-periodic. Hence, integrating the ODE over the interval [0, 1] should yield the starting position again. However, methods like solve_ivp from scipy.integrate do not respect this periodicity at all (I have tried all the possible methods like RK45, Radau, DOP853, LSODA).\nIs there a special ODE solver that respects such periodicity to a high degree of precision?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":72,"Q_Id":65848198,"Users Score":2,"Answer":"All algorithms will suffer from precision loss anyway, so you will most likely never achieve exact periodicity. Nonetheless, you can also try to increase the precision of the integration by using the parameters \"atol\" and \"rtol\", which, roughly, will keep the error of the integration below (atol + rtol*y) at each time step. You can typically go as low as atol=rtol=1e-14.","Q_Score":0,"Tags":"python,scipy,integration,ode","A_Id":65851352,"CreationDate":"2021-01-22T15:40:00.000","Title":"ODE solver for python respecting periodicity","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a 2D numpy array [1,2], [3,4], [5,6]. How can I modify the values in the second column (eg. add 1 to each value, so the result would be ([1,3], [3,5], [5,7])?","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":29,"Q_Id":65865233,"Users Score":2,"Answer":"Psidom's comment above worked thanks.\narr[:,1] += 1","Q_Score":0,"Tags":"python,numpy","A_Id":65874097,"CreationDate":"2021-01-23T22:42:00.000","Title":"Modifying a multidimensional Numpy array","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Let's say I have a dataframe with two columns, a naive date, and it's corresponding timezone. I'd like to convert the naive date to a timezone aware date using the second column.\n\n\n\n\nnaive_date\ntimezone\n\n\n\n\n24-01-2021 05:00:00\n'Europe\/London'\n\n\n24-01-2021 06:00:00\n'Europe\/Amsterdam'\n\n\n24-01-2021 00:00:00\n'US\/Eastern'\n\n\n\n\nIf I just wanted to convert to a known timezone, I would do:\ndf['naive_date'].dt.tz_localize(tz='Europe\/London')\nBut what if the value passed to tz should be taken from the timezone column for that particular row? Is that possible? I tried, which unsurprisingly didn't work:\ndf['naive_date'].dt.tz_localize(tz=df['timezone'])\nFor context I'll be comparing the date against another timezone aware date column, and the comparison returns false when comparing naive to timezone aware datetime.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":27,"Q_Id":65866411,"Users Score":0,"Answer":"Pablo's answer was spot on, this is what I ended up using:\ndf['local_date'] = df.apply(lambda x: x['naive_date'].tz_localize(tz=x['timezone']), axis=1)","Q_Score":0,"Tags":"python,pandas","A_Id":65927361,"CreationDate":"2021-01-24T01:46:00.000","Title":"Passing a paremeter taken from a dataframe column to a pandas method","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I created a simple neural network with tensorflow and I am studying how the amount of epochs is affecting results. I use Google Colab for this purpose.\nScenario:\n\nI download the dataset from tensorflow (built-in)\nI create a model in tensorflow\nI set the variable with how many epochs I want to train the model\nCompile and train the model\n\nI noticed that when I re-run the script, the dataset is already downloaded and I am worried the model may be also kept in session memory..\nMy question is: if I re-run the script in google colab using option \"Run after\" with different epochs number, will this create new instance of the model and start training from 0, or will it start re-training already trained model?\nFor example:\nI run the script and trained network for 10 epochs. I change the variable to 50 and re-run the script.\nWill it start training model from 0 to 50, or will it take already trained model and train for 50 more epochs, so 60 in total?\nIs there any way to check for how many epochs the model was trained?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":63,"Q_Id":65866488,"Users Score":0,"Answer":"I created new script with network from tensorflow tutorial, added evaluation function after model compilation and before training and then after training.\nAnswer: when re-running the script model is always trained from 0 epoch.","Q_Score":0,"Tags":"python,tensorflow,keras,google-colaboratory,tensorflow2.0","A_Id":65867180,"CreationDate":"2021-01-24T02:01:00.000","Title":"Tensorflow networks in google colab, what happens when I re-run the script","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"How to change an element in np array by index without any loops and if statements.\nE.g we have array [1,2,3,4], and every second element, starting from 0, I want to change to 10. So as to get [10,2,10,4].","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":59,"Q_Id":65899550,"Users Score":0,"Answer":"Simply, you can use: a[::2]=10","Q_Score":0,"Tags":"python,numpy","A_Id":65899709,"CreationDate":"2021-01-26T10:23:00.000","Title":"How to change element in np.array by index","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"As far as I understand it, in Bert's operating logic, he changes 50% of his sentences that he takes as input. It doesn't touch the rest.\n1-) Is the changed part the transaction made with tokenizer.encoder? And is this equal to input_ids?\nThen padding is done. Creating a matrix according to the specified Max_len. the empty part is filled with 0.\nAfter these, cls tokens are placed per sentence. Sep token is placed at the end of the sentence.\n2-) Is input_mask happening in this process?\n3 -) In addition, where do we use input_segment?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":691,"Q_Id":65901473,"Users Score":1,"Answer":"The input_mask obtained by encoding the sentences does not show the presence of [MASK] tokens. Instead, when the batch of sentences are tokenized, prepended with [CLS], and appended with [SEP] tokens, it obtains an arbitrary length.\n\nTo make all the sentences in the batch has fixed number of tokens, zero padding is performed. The input_ids variable shows whether a given token position contians actual token or if it a zero padded position.\n\nUsing [MASK] token is using only if you want to train on Masked Language Model(MLM) objective.\n\nBERT is trained on two objectives, MLM and Next Sentence Prediction(NSP). In NSP, you pass two sentences and try to predict if the second sentence is the following sentence of first sentence or not. segment_id holds the information if of which sentence a particular token belongs to.","Q_Score":0,"Tags":"python,word,embedding,bert-language-model","A_Id":65921539,"CreationDate":"2021-01-26T12:34:00.000","Title":"About Bert embedding (input_ids, input_mask)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Situation: A csv lands into AWS S3 every month. The vendor adds\/removes\/modifies columns from the file as they please. So the schema is not known ahead of time. The requirement is to create a table on-the-fly in Snowflake and load the data into said table. Matillion is our ELT tool.\nThis is what I have done so far.\n\nSetup a Lambda to detect the arrival of the file, convert it to JSON, upload to another S3 dir and adds filename to SQS.\nMatillion detects SQS message and loads the file with the JSON Data into Variant column in a SF table.\nSF Stored proc takes the variant column and generates a table based on the number of fields in the JSON data. The VARIANT column in SF only works in this way if its JSON data. CSV is sadly not supported.\n\nThis works with 10,000 rows. The problem arises when I run this with a full file which is over 1GB, which is over 10M rows. It crashes the lambda job with an out of disk space error at runtime.\nThese are the alternatives I have thought of so far:\n\nAttach an EFS volume to the lambda and use it to store the JSON file prior to the upload to S3. JSON data files are so much larger than their CSV counterparts, I expect the json file to be around 10-20GB since the file has over 10M rows.\nMatillion has an Excel Query component where it can take the headers and create a table on the fly and load the file. I was thinking I can convert the header row from the CSV into a XLX file within the Lambda, pass it to over to Matillion, have it create the structures and then load the csv file once the structure is created.\n\nWhat are my other options here? Considerations include a nice repeatable design pattern to be used for future large CSVs or similar requirements, costs of the EFS, am I making the best use of the tools that I are avaialable to me? Thanks!!!","AnswerCount":4,"Available Count":3,"Score":0.0,"is_accepted":false,"ViewCount":859,"Q_Id":65909077,"Users Score":0,"Answer":"Why are you converting CSV into JSON; CSV is directly being loaded into table without doing any data transformation specifically required in case of JSON, the lateral flatten to convert json into relational data rows; and why not use Snowflake Snowpipe feature to load data directly into Snowflake without use of Matallion. You can split large csv files into smaller chunks before loading into Snowflake ; this will help in distributing the data processing loads across SF Warehouses.","Q_Score":1,"Tags":"python,amazon-web-services,lambda,snowflake-cloud-data-platform,matillion","A_Id":65913376,"CreationDate":"2021-01-26T20:49:00.000","Title":"Data Ingestion: Load Dynamic Files from S3 to Snowflake","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Situation: A csv lands into AWS S3 every month. The vendor adds\/removes\/modifies columns from the file as they please. So the schema is not known ahead of time. The requirement is to create a table on-the-fly in Snowflake and load the data into said table. Matillion is our ELT tool.\nThis is what I have done so far.\n\nSetup a Lambda to detect the arrival of the file, convert it to JSON, upload to another S3 dir and adds filename to SQS.\nMatillion detects SQS message and loads the file with the JSON Data into Variant column in a SF table.\nSF Stored proc takes the variant column and generates a table based on the number of fields in the JSON data. The VARIANT column in SF only works in this way if its JSON data. CSV is sadly not supported.\n\nThis works with 10,000 rows. The problem arises when I run this with a full file which is over 1GB, which is over 10M rows. It crashes the lambda job with an out of disk space error at runtime.\nThese are the alternatives I have thought of so far:\n\nAttach an EFS volume to the lambda and use it to store the JSON file prior to the upload to S3. JSON data files are so much larger than their CSV counterparts, I expect the json file to be around 10-20GB since the file has over 10M rows.\nMatillion has an Excel Query component where it can take the headers and create a table on the fly and load the file. I was thinking I can convert the header row from the CSV into a XLX file within the Lambda, pass it to over to Matillion, have it create the structures and then load the csv file once the structure is created.\n\nWhat are my other options here? Considerations include a nice repeatable design pattern to be used for future large CSVs or similar requirements, costs of the EFS, am I making the best use of the tools that I are avaialable to me? Thanks!!!","AnswerCount":4,"Available Count":3,"Score":0.0,"is_accepted":false,"ViewCount":859,"Q_Id":65909077,"Users Score":0,"Answer":"I also load CSV files from SFTP into Snowflake, using Matillion, with no idea of the schema.\nIn my process, I create a \"temp\" table in Snowflake, with 50 VARCHAR columns (Our files should never exceed 50 columns). Our data always contains text, dates or numbers, so VARCHAR isn't a problem. I can then load the .csv file into the temp table. I believe this should work for files coming from S3 as well.\nThat will at least get the data into Snowflake. How to create the \"final\" table however, given your scenario, I'm not sure.\nI can imagine being able to use the header row, and\/or doing some analysis on the 'type' of data contained in each column, to determine the column type needed.\nBut if you can get the 'final' table created, you could move the data over from temp. Or alter the temp table itself.","Q_Score":1,"Tags":"python,amazon-web-services,lambda,snowflake-cloud-data-platform,matillion","A_Id":66094723,"CreationDate":"2021-01-26T20:49:00.000","Title":"Data Ingestion: Load Dynamic Files from S3 to Snowflake","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Situation: A csv lands into AWS S3 every month. The vendor adds\/removes\/modifies columns from the file as they please. So the schema is not known ahead of time. The requirement is to create a table on-the-fly in Snowflake and load the data into said table. Matillion is our ELT tool.\nThis is what I have done so far.\n\nSetup a Lambda to detect the arrival of the file, convert it to JSON, upload to another S3 dir and adds filename to SQS.\nMatillion detects SQS message and loads the file with the JSON Data into Variant column in a SF table.\nSF Stored proc takes the variant column and generates a table based on the number of fields in the JSON data. The VARIANT column in SF only works in this way if its JSON data. CSV is sadly not supported.\n\nThis works with 10,000 rows. The problem arises when I run this with a full file which is over 1GB, which is over 10M rows. It crashes the lambda job with an out of disk space error at runtime.\nThese are the alternatives I have thought of so far:\n\nAttach an EFS volume to the lambda and use it to store the JSON file prior to the upload to S3. JSON data files are so much larger than their CSV counterparts, I expect the json file to be around 10-20GB since the file has over 10M rows.\nMatillion has an Excel Query component where it can take the headers and create a table on the fly and load the file. I was thinking I can convert the header row from the CSV into a XLX file within the Lambda, pass it to over to Matillion, have it create the structures and then load the csv file once the structure is created.\n\nWhat are my other options here? Considerations include a nice repeatable design pattern to be used for future large CSVs or similar requirements, costs of the EFS, am I making the best use of the tools that I are avaialable to me? Thanks!!!","AnswerCount":4,"Available Count":3,"Score":0.0,"is_accepted":false,"ViewCount":859,"Q_Id":65909077,"Users Score":0,"Answer":"Why not split the initial csv file into multiple files and then process each file in the same way you currently are?","Q_Score":1,"Tags":"python,amazon-web-services,lambda,snowflake-cloud-data-platform,matillion","A_Id":65910045,"CreationDate":"2021-01-26T20:49:00.000","Title":"Data Ingestion: Load Dynamic Files from S3 to Snowflake","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm creating a python script, that create csv files as result from sybase queries.\nWhen pandas creates the file, all numeric values inside csv file ends with \".0\" (for example, 2.0 instead of 2 )\nI can cast to integer in query, but it affects query performance.\nIn order to solve that, I setted coerce_float parameter to false inside read_sql function.\nHowever all columns are converted to string, and some columns must be floats, and the decimal separator is \".\" and I need \",\" as decimal separator.\nMy question is:\nIs there some way to change default decimal separator as a comma and keep coerce_float to False?\nObs: a simple string replace doesnt solve my problem, because the script will read several query files.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":210,"Q_Id":65910188,"Users Score":0,"Answer":"First of all, python uses \".\" to write floats so you cant have floats written with \",\". If you want floats written with \",\" they must be strings. However, you can save floats with the decimal \",\" as you save the .csv, by passing the argument decimal=',' to df.to_csv().","Q_Score":0,"Tags":"python,pandas,dataframe,sybase","A_Id":65910643,"CreationDate":"2021-01-26T22:27:00.000","Title":"Change default decimal separator in pandas read_sql","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've seen some paper providing Information Criterion for SVM (e.g. Demyanov, Bailey, Ramamohanarao & Leckie (2012)). But it doesn't seem that it exist any implementation of such method in python. For instance Sklearn only provide methods for linear model and random forest\/gradien boosting algorithms.\nMy question is then, is their any implementation of a potential Information Criterion for SVM in python ?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":27,"Q_Id":65917525,"Users Score":1,"Answer":"you can use SVM with changing the kernel for non-linear model.\nfor exemple kernel='poly'","Q_Score":0,"Tags":"python,machine-learning,svm,criterion","A_Id":65920315,"CreationDate":"2021-01-27T10:45:00.000","Title":"Information Criterion SVM","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Is there a way to have fractions (in python) with roots? When I write Fraction(np.sqrt(2), 2), it gives me 1\/2, because Fraction takes ints as arguments. I want to have square root of 2 divided by 2, and keep the 2 under the root as to not lose precision while calculating.\nEdit: I am using the package \"fraction\". I couldn't find \"fractions\" anywhere when I searched for the package to install.","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":402,"Q_Id":65923059,"Users Score":0,"Answer":"As a comment suggested, I found sqrt in the sympy package. For example sympy.sqrt(8) produces 2*sqrt(2), so it doesn't just keep the number under the root as not to lose precision, it also lets me make operations with it and simplifies it.","Q_Score":2,"Tags":"python","A_Id":66076912,"CreationDate":"2021-01-27T16:15:00.000","Title":"Is there a way to have fractions with roots?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am doing binary classification for a time series with keras LSTM. How could I extract the final output from the model? By this I mean, how can I get a list containing zero and one values from the final model?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":242,"Q_Id":65939879,"Users Score":0,"Answer":"You should attach right after a LSTM layer a Dense layer with as much neurons as you consider (that depends upon the LSTM output itself), and on top of that one add a final Dense classification layer with a single neuron, that'd be the binary output.","Q_Score":0,"Tags":"python,tensorflow,keras,deep-learning,lstm","A_Id":65944376,"CreationDate":"2021-01-28T15:09:00.000","Title":"Keras LSTM Binary Classification Output","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a set of points(x,y), could be setup as an Array or a List.\nI wish to calculate the distance between subsequent points.\nI then need to do some calculations on the between distances to set a threshold value T.\nI then wish to process the Array\/List of points such that when a between distance exceeds the threshold T, I call a function_A passing all the preceding points and then function_B passing the current and preceding point, before continuing test points against the threshold value.\ni.e. If I have between distance list [1, 1.5, 2, 1.7, 7, 2, 3, 8, 4 ]\nThreshold calculated as 7.\nI wish to call function_A with the points that correspond to [1, 1.5, 2, 1.7] function_B with the points that correspond to 1.7 and 7, then next time Threshold is exceeded i.e 8 call function_A with points corresponding to [2,3] etc.\nNeed to process several hundred points as above, so should I use numpty?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":19,"Q_Id":65942780,"Users Score":0,"Answer":"NumPy is optimized for numerical calculation, so you should use it. But in this case I would use Pandas instead, since it \"preserve the index\" when you do calculations and it's built on top of NumPy, so you can take advantage of NumPy's optimization.\nTo apply the functions you could use the conditional selection on your DataFrame, and then assign the results to a new column, and here is where you take the advantage of the index preservation in Pandas, since you don't want to lose the information about in which distance you're applying the functions.","Q_Score":0,"Tags":"python-3.x,numpy","A_Id":65944314,"CreationDate":"2021-01-28T18:02:00.000","Title":"Python : Processing sub List based on a condition","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am new on Medical Imaging. I am dealing with MRI images, namely T2 and DWI.\nI uploaded both images with nib.load, yet each sequence image has a different number of slices (volume, depth?). If I select one slice (z coordinate), how can get the corresponding slice on the other sequence image? ITK does it correctly, so maybe something in the NIFTI header could help?\nThank you so much for reading! I also tried interpolation, but it did not work.","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":76,"Q_Id":65946097,"Users Score":1,"Answer":"Reading the NIFTI, namely affine, and extracting the translation Transformation Matrix to create a mapping from the T2 to the DWI voxels.\nHint: nibabel.","Q_Score":1,"Tags":"python,registration,coordinate-systems,itk,medical-imaging","A_Id":65971759,"CreationDate":"2021-01-28T22:25:00.000","Title":"How to correlate different MRI sequences images in NIFTI format?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using PyEMD (Empirical Mode Decomposition) on a signal (train & test ) data. All seems be working fine for all signals (datasets), but in my one of the dataset number of IMFs it is decomposing is different for train & test dataset.\nI have tried (max_imf: ) argument, but by limiting the number to minimum value so that both (train & test ) have same number of IMF, the decomposition is not correct ( it is not decomposing till final trend).\nAny suggest will be appreciated.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":103,"Q_Id":65976652,"Users Score":0,"Answer":"You can decompose the data first, and then divide the training set and the test set for each component","Q_Score":1,"Tags":"python,decomposition","A_Id":68176650,"CreationDate":"2021-01-31T07:16:00.000","Title":"PyEMD returning different number of IMFs for train, test data","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm using Gensim for building W2V models and, I didn't find a way for adding a vector for Unkown words or padding parts in Gensim and, I have to do it manually.\nI also check the index of 0 in the created embedding and, it is also used for a specific word. This matter could cause a problem for padding words because they have the same index.\nAm I missing something in here? Is Gensim handle this problem?\nP.S: For handling this issue, I always append two vectors in the model weights after I train the model.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":556,"Q_Id":65978214,"Users Score":1,"Answer":"A Gensim Word2Vec model only learns, and reports, vectors for words that it learned during training.\nIf you want it to learn some vector for any synthetic 'unknown' or 'padding' symbols, you need to include them in the training data. (They may not be very interesting\/useful vector-values, though, and having such synthetic token vectors may not outperform simply ignoring unknown-tokens or avoiding artificial padding entirely.)","Q_Score":0,"Tags":"python,gensim,word2vec","A_Id":65983452,"CreationDate":"2021-01-31T10:49:00.000","Title":"Does Gensim handling pad index and UNK index in W2V models?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have imported an Excel file as a dataframe using pandas.\nI now need to delete all rows from row 41,504 (index 41,505) and below.\nI have tried df.drop(df.index[41504]), although that only catches the one row. How do I tell Pandas to delete onwards from that row?\nI did not want to delete by an index range as the dataset has tens of thousands of rows, and I would prefer not to scroll through the whole thing.\nThank you for your help.\nKind regards","AnswerCount":4,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":45,"Q_Id":65983380,"Users Score":0,"Answer":"You can reassign the range you do want back into the variable instead of removing the range you do not want.","Q_Score":0,"Tags":"python,python-3.x,pandas","A_Id":65983446,"CreationDate":"2021-01-31T19:34:00.000","Title":"Ask Pandas to delete all rows beneath a certain row","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have an incident number column that I'm trying to make consistent in terms of the format that it's in. Some are printed as '15-0019651' and others are '18490531'. All I'm trying to do is remove the hyphen for the Inci_no's that have them.\nWhen I run df.Inci_no.dtype it returns it as object.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":26,"Q_Id":65988666,"Users Score":1,"Answer":"df['incident_no'] = df['incident_no'].str.replace('-','')","Q_Score":0,"Tags":"python","A_Id":65988793,"CreationDate":"2021-02-01T07:27:00.000","Title":"Convert column into same format","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I would like to merge two lists:\nlon: [14.21055347, 14.21055347, 16.39356558, 16.39356558, 14.21055347]\nlat: [48.22824817, 48.22824817, 48.18617251, 48.18617251, 47.65823679]\nto get:\ncoordinates: [[14.21055347, 48.22824817], [14.21055347, 48.22824817], [16.39356558, 48.18617251], [16.39356558, 48.18617251], [14.21055347, 47.65823679]]\nHow is this done efficiently for very long lists of lon\/lat?\nThanks for your help!","AnswerCount":5,"Available Count":1,"Score":-0.0399786803,"is_accepted":false,"ViewCount":61,"Q_Id":66007041,"Users Score":-1,"Answer":"I'm not quite sure if I'm understanding your question correctly, but if you want to match the two arrays, just do:\nname = [array1, array2]","Q_Score":0,"Tags":"python,list,merge,coordinates","A_Id":66007125,"CreationDate":"2021-02-02T09:39:00.000","Title":"Merge two lists to create a list which contains items of the two lists as lists","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am wondering how best to feed back the changes my DQN agent makes on its environment, back to itself.\nI have a battery model whereby an agent can observe a time-series forecast of 17 steps, and 5 features. It then makes a decision on whether to charge or discharge.\nI want to includes its current state of charge (empty, half full, full etc) in its observation space (i.e. somewhere within the (17,5) dataframes I am feeding it).\nI have several options, I can either set a whole column to the state of charge value, a whole row, or I can flatten the whole dataframe and set one value to the state of charge value.\nIs any of these unwise? It seem a little rudimentary to me to set a whole columns to a single value, but should it actually impact performance? I am wary of flattening the whole thing as I plan to use either conv or lstm layers (although the current model is just dense layers).","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":40,"Q_Id":66008062,"Users Score":1,"Answer":"You would not want to add in unnecessary features which are repetitive in the state representation as it might hamper your RL agent convergence later when you would want to scale your model to larger input sizes(if that is in your plan).\nAlso, the decision of how much of information you would want to give in the state representation is mostly experimental. The best way to start would be to just give in a single value as the battery state. But if the model does not converge, then maybe you could try out the other options you have mentioned in your question.","Q_Score":0,"Tags":"python,deep-learning,reinforcement-learning,dqn","A_Id":66030093,"CreationDate":"2021-02-02T10:41:00.000","Title":"Reinforcement learning DQN environment structure","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I was reading a paper about disparity, and came across the following phrase:\n\"We use the deep unary features to compute the stereo\nmatching cost by forming a cost volume.\"\nI looked in the literature for definitions of 'unary features' and 'cost volume', yet struggled to find anything. Could someone clarify what these terms mean in the context of computer vision?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":348,"Q_Id":66014793,"Users Score":0,"Answer":"For a single 2D patch (wxwx1), if you're looking for its most similar sibling in another image, each pixel is a candidate, so if you write their similarity in another image, it'll be a 2D images with similarities. You can call it a similarity surface, or cost surface if you put, say, distances in them.\nIn the paper, that I can't seem to access properly (I did see the archived HTML version of it), for WxH images, they store the cost, or distance, between a feature in one image, with all the pixels in a window around it. Since we have WxH pixels, and the window is DXxDY, then the full array is WxHxDXxDY of costs. So it's 4D but they call it a \"cost volume\" by analogy.\nYou also find cost volumes in stereo, for WxH images, and D possible depths or disparities, we can build a WxHxD cost volume. If you were to find the smallest cost for each pixel, you wouldn't need a full volume, but if you also consider the pixels together (two neighbours probably have the same depth) then you look at the full cost volume instead of just small slices of it.","Q_Score":0,"Tags":"python,machine-learning,computer-vision,feature-extraction,vision","A_Id":66521350,"CreationDate":"2021-02-02T17:36:00.000","Title":"Unary Features and Cost Volume (Computer Vision)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Does ,_,_ have any specific meaning in this?\nfaces,_,_ = detector.run(image = imgR, upsample_num_times = 0, adjust_threshold = 0.0)\nIs it possible to code it like this?\nfaces = detector.run(image = imgR, upsample_num_times = 0, adjust_threshold = 0.0)","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":25,"Q_Id":66020807,"Users Score":1,"Answer":"detector.run might be returning three values. So you need three placeholders to read them. Since code might not be using the other two return values, them have been read into _ which is a style followed by people.","Q_Score":1,"Tags":"python,python-3.x","A_Id":66020816,"CreationDate":"2021-02-03T03:25:00.000","Title":"What does the ,_,_ mean in faces,_,_ = detector.run(image = imgR, upsample_num_times = 0, adjust_threshold = 0.0)?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am looking for ideas\/thoughts on the following problem:\nI am working with food ingredient data such as: milk, sugar, eggs, flour, may contain nuts\nFrom such piece of text I want to be able to identify and extract phrases like may contain nuts, to preprocess them separately\nThese kinds of phrases can change quite a lot in terms of length and content. I thought of using NER taggers, but I don't know if they will do the job correctly as they are mainly used for identifying single-word entities...\nAny ideas on what to use as a phrase-entity-recognition system? Also which package would you use? Cheers","AnswerCount":3,"Available Count":1,"Score":0.1325487884,"is_accepted":false,"ViewCount":389,"Q_Id":66024941,"Users Score":2,"Answer":"It looks like your ingredient list is easy to split into a list. In that case you don't really need a sequence tagger; I wouldn't treat this problem as phrase extraction or NER. What I would do is train a classifier on different items in the list to label them as \"food\" or \"non-food\". You should be able to start with rules and train a basic classifier using anything really.\nBefore training a model, an even simpler step would be to run each list item through a PoS tagger (say spaCy), and if there's a verb you can guess that it's not a food item.","Q_Score":2,"Tags":"python,nlp,text-processing,named-entity-recognition,information-extraction","A_Id":66060338,"CreationDate":"2021-02-03T09:47:00.000","Title":"Alternatives to NER taggers for long, heterogeneous phrases?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a question regarding cvxpy capability to systematically choose one of the solutions which result in the same value of an objective function.\nLet us consider a typical supply chain optimization problem as an example:\n\nThere is a product which is ordered by customers A, B, C.\n\nThe demand for this product is 100, 200, and 100 pcs, respectively (total demand is 400 pcs).\n\nThe available supply is 250 pcs (hence, there is 150 pcs shortage).\n\nEach customer pays the same price for the product ($10\/item).\n\nThe objective is to allocate this product among the customers in such a way that the revenue is maximized.\n\nSince unit prices are identical, there are multiple possible solutions \/ allocation alternatives resulting in the optimal value of the objective function of $2500 (i.e. the total allocation multiplied by the unit price).\n\n\nIs there a way to pass as a parameter to the solver (e.g. to CBC or cvxpy) which of the allocation alternatives should be chosen? By default, the solver does the allocation on the first come, first served basis, whereas the intended allocation is the one proportional to the demand.\nYour help and assistance would be much appreciated.","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":137,"Q_Id":66027371,"Users Score":2,"Answer":"I think this can be formulated as a multiple objective problem:\n\nMinimize Cost\nTry to be as close as possible to a single fraction of demand is met.\n\nThis can be solved in two steps:\n\nSolve for objective 1.\nAdd objective 1 as a constraint to the problem and solve for objective 2.\n\nWe need to allow deviations from the fraction of demand being met to allow objective 1 stay optimal, so I would do that by adding slacks and minimizing those.\nThis is similar to what @sascha suggested in the comments.","Q_Score":0,"Tags":"python,optimization,data-science,cvxpy,coin-or-cbc","A_Id":66028480,"CreationDate":"2021-02-03T12:15:00.000","Title":"Supply Chain Optimization Problem with CVXPY and CBC","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"My input csv file is already 1-hot encoded (its exported from another system):\n\n\n\n\nid\nvehicle_1(car)\nvehicle_1(truck)\nvehicle_1(other)\n\n\n\n\n1\n0\n1\n0\n\n\n2\n1\n0\n0\n\n\n\n\nIs there a way to tell pandas to treat the 'vehicle_' columns a 1-hot encoded? Perhaps during the construction of the dataframe? I'm assuming libraries like seaborn, which can plot data based on categories would need to know to treat the set of columns as 1-hot encoded values.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":40,"Q_Id":66035776,"Users Score":1,"Answer":"I don't think there's a way to tell pandas that the columns imported are already encoded (whichever it was used already before importing).\nThe advantage is you don't have to encode again.\nThe disadvantage is the imported DF treats your encoded columns as new columns rather than encoded values of the same column.","Q_Score":0,"Tags":"python,pandas","A_Id":66041052,"CreationDate":"2021-02-03T21:15:00.000","Title":"Creating a pandas dataframe from a csv file with 1-hot encoded set of columns","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to ask if there is any way to make the regression really generalized for my dataset.\nMy problem is that after I trained the data with Random forest or SVM regressor, it works kinda well in the training dataset but it shows very bad result when I try with test dataset.. even if they have the same underlying equations.\nI really don't have idea how to improve this. Does it mean that I should keep training my regression with more dataset?\nCould anybody help me? :(","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":51,"Q_Id":66038420,"Users Score":1,"Answer":"We are not able to answer your question. You dont even try to provide data or your code. How could one tell why your problem appears.\nJust my two cents:\n\nIs the train and test data unbalanced?\n-> This is the main reason for bad test results\n\nIs the sample reasonable large?","Q_Score":1,"Tags":"python,matlab,regression,svm,random-forest","A_Id":66044215,"CreationDate":"2021-02-04T02:11:00.000","Title":"How can I improve regression?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm new to Machine Learning and I'm a bit confused about how data is being read for the training\/testing process. Assuming my data works with date and I want the model to read the later dates first before getting to the newer dates, the data is saved in the form of earliest date on line 1 and line n has the oldest date. I'm assuming that naturally data is being read from line 1 down to line n, but I just need to be sure about it. And is there any way to make the model(E.g Logistic Regression) read data whichever direction I want it to?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":39,"Q_Id":66038977,"Users Score":2,"Answer":"A machine learning model in supervised learning method learns from all samples in no order, it is encouraged to shuffle the samples during training.\nMost of the times, the model won't get fed with all samples at once; the training set is split into batches, batches of random samples or just in whatever order it is in the training set.","Q_Score":0,"Tags":"python,machine-learning,scikit-learn,logistic-regression,random-forest","A_Id":66039014,"CreationDate":"2021-02-04T03:29:00.000","Title":"Do Machine Learning Algorithms read data top-down or bottom up?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working on a project where i have to detect moving object from moving camera for example: detecting hanging apples on trees using drone, detecting animals in farm using drone and detecting flowers on field like this. the main thing is i am using moving camera and i don't have fixed lighting condition as the video is captured in outdoor so i lighting may vary. I have to use open CV and python please suggest me reliable method that can be used for example as mentioned above.I know some basic method like background subtraction and motion detection but as my lighting conditions are not stationary i am not getting proper output","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":414,"Q_Id":66041548,"Users Score":0,"Answer":"You can try optical flow. Since your platform is moving it's difficult to differentiate stationary vs dynamic objects with typical background subtraction techniques. With optical flow objects at the same distance from the camera should be moving with the same direction and magnitude. You can detect moving objects because they have different velocities relative to the area around them. This isn't trivial though; be ready to do a lot of tweaking to get the detection to work well.","Q_Score":0,"Tags":"python,opencv","A_Id":66049951,"CreationDate":"2021-02-04T08:03:00.000","Title":"Extract moving object from video taken by moving camera(drone) using opencv python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Normal syntax for calling a function is func() but I have noticed that loc[] in pandas is without parentheses and still treated as a function. Is loc [] really a function in pandas?","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":311,"Q_Id":66043313,"Users Score":0,"Answer":"LOC[] is a property that allows Pandas to query data within a dataframe in a standard format. Basically you're providing the index of the data you want.","Q_Score":1,"Tags":"python,pandas","A_Id":66043424,"CreationDate":"2021-02-04T09:58:00.000","Title":"Is loc[ ] a function in Pandas","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I had developed a standalone application on Windows for Deep Learning \/ Computer vision in Python 3.X using various standard python libraries such as pandas, numpy, TensorFlow, Keras, Yolo, PyQt ...etc. I want to deliver this application to my client but without source code.\nCan you please help me how to do this?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":102,"Q_Id":66056606,"Users Score":0,"Answer":"\"I want to deliver this application to my client but without source code.\"\nCan you clarify this process?\nIf you just want to deliver this service to your client you can just use HTTP\/POST to let users upload their data to you, then you run these data on your network on the server, and finally, just return the prediction result to them.","Q_Score":0,"Tags":"python,python-3.x,windows,deep-learning","A_Id":66056643,"CreationDate":"2021-02-05T02:07:00.000","Title":"How to hide \/ encrypt source code written in Python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Hell everyone,\nCan Healpy compute a bispectrum of the CMB map?\nIt looks like there is no such built-in function in Healpy library.\nThanks!\nAll the best,","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":51,"Q_Id":66057826,"Users Score":2,"Answer":"No, there is no support for computing a bispectrum, if anyone implements it, it would be nice to have a pull request contribution towards healpy.","Q_Score":2,"Tags":"python,healpy","A_Id":66067928,"CreationDate":"2021-02-05T05:04:00.000","Title":"Can Healpy compute a bispectrum to study non-gaussianity of the CMB map?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using TF2.4 and when I start training the model I get this in my terminal:\n2021-02-05 07:44:03.982579: I tensorflow\/compiler\/mlir\/mlir_graph_optimization_pass.cc:116] None of the MLIR optimization passes are enabled (registered 2)\nI know this is not an error and it is benign and is saying MLIR was not being used, but my training deosnt start while stays at this without stopping. Therefore after couple of hours I just quit the program.\nHow can I proceed with training?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":856,"Q_Id":66059582,"Users Score":0,"Answer":"I found the error: This happens only when there is an issue on tf.record file. So i have re-done the tf.record and I realized there was a missing xml while there was no error in creating tf.record file. I have corrected that file and re created tf.record and problem solved.","Q_Score":1,"Tags":"python-3.x,tensorflow","A_Id":67303523,"CreationDate":"2021-02-05T07:59:00.000","Title":"TF2 object detection training doesnt start with no error","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using Tensorflow to train my model. I am routinely saving my model every 10 epochs. I have a limited number of samples to train, so I am augmenting my dataset to make a larger training dataset.\nIf I need to use my saved model to resume training after a power outage would it be best to resume training using the same dataset or to make a new dataset?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":51,"Q_Id":66070990,"Users Score":1,"Answer":"Your question very much depends on how you're augmenting your dataset. If your augmentation skews the statistical distribution of the underlying dataset then you should resume training with the pre-power outage dataset. Otherwise, you're assuming that your augmentation has not changed the distribution of the dataset.\nIt is a fairly safe assumption to make (assuming your augmentations do not change the data in an extremely significant way) that you are safe to resume training on a new dataset or the old dataset without significant change in accuracy.","Q_Score":0,"Tags":"python,tensorflow","A_Id":66071586,"CreationDate":"2021-02-05T21:41:00.000","Title":"Tensorflow stop and resume training","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a single camera that I can move around. I have the intrinsic parameter matrix and the extrinsic parameter matrix for each camera orientation. For object detection, I use YOLO and I get 2D bounding boxes in the image plane. My plan is to use a temporal pair of images, with the detected object in it, to triangulate the midpoint of the resulting 2D bounding box around the object.\nRight now, I use two images that are 5 frames apart. That means, the first frame has the object in it and the second frame has the same object in it after a few milliseconds. I use cv2.triangulatePoints to get the corresponding 3D point for the 2D midpoint of the bounding box.\nMy main problem is that when the camera is more or less steady, the resulting distance value is accurate (within a few centimeters). However, when I move the camera around, the resulting distance value for the object starts varying quite a bit (the object is static and never moves, only the camera looking at it moves). I can't seem to understand why this is the case.\nFor cv2.triangulatePoints, I get the relative rotation matrix between the two temporal camera orientations (R = R2R1) and then get the relative translation (t = t2 - Rt1). P1 and P2 are the final projection matrices (P1 for the camera at an earlier position and P2 for the camera at a later position). P1 = K[I|0] and P2 = K[R|t], where K is the 3x3 intrinsic parameter matrix, I is a 3x3 identity matrix, and 0 is 3x1 vector of zeros.\nShould I use a temporal gap of 10 frames or is using this method to localize objects using a single camera never accurate?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":164,"Q_Id":66071507,"Users Score":0,"Answer":"The centers of the bounding boxes are not guaranteed to be the projections of a single scene (3d) point, even with a perfect track, unless additional constraints are added. For example, that the tracked object is planar, or that the vertexes of the bounding boxes track points that are on a plane. Things get more complicated when tracking errors are present.\nIf you really need to triangulate the box centers (do you? are you sure you can't achieve your goals using only well-matched projections?), you could use a small area around the center in one box as a pattern, and track it using a point tracker (e.g. one based on the Lucas-Kanade algorithm, or one based on normalized cross-correlation) in the second image, using the second box to constrain the tracker search window.\nThen you may need to address the accuracy of your camera motion estimation - if errors are significant your triangulations will go nowhere. Bundle adjustment may need to become your friend.","Q_Score":0,"Tags":"python,deep-learning,computer-vision,opencv-python,3d-reconstruction","A_Id":66096269,"CreationDate":"2021-02-05T22:34:00.000","Title":"How to use cv2.triangulatePoints with a single moving camera","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a simple question:\nI have a 2D Array, with each 'x' and 'y' coordinate having a height 'z'. Can OpenCV be used on NumPy arrays to extract contours in Python? I've seen numerous examples with JPG, PNG etc but can't find examples with an input array.\nI just want to compare the quality\/suitability of the contour on DICOM arrays in my research.\nThanks in advance!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":61,"Q_Id":66084636,"Users Score":0,"Answer":"Image is simply an array. So, if you can do the same with images then obviously it's possible with the array as well. So, the answer to your question is yes. You can use the OpenCV to extract the contours from the NumPy array.","Q_Score":0,"Tags":"python,arrays,opencv","A_Id":66085297,"CreationDate":"2021-02-07T04:43:00.000","Title":"Contouring 2D Array with OpenCV (Python)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have VRP problem. I have vehicles starting positions and I have distance matrix. I want solution to be terminated\/finished when certain locations are visited.\nSo I don't want it to actually visit each index of location_matrix but if visiting different index beside \"MUST VISITS\" make for better solution then I have no problem. Because you know sometimes going from directly 1 to 3 is slower than 1-2-3. (visiting 2 which is not necessary but make it for shortcut)\nI defined a dummy depot which cost 0 , I used this for end because if you use starts you have to define ends. And I put ends 000 which are basically ending position. You might ask why you didnt put your \"JOB\" locations. But this means they have to end there. So it doesn't seem optimal because example one vehicle could be really near to both of \"JOB\" locations but if it terminates \/ ends because it has END defined vehicle would stop.\nI have no idea how to make this work. Basically what I want that if certain locations are visited once just terminate - that's the solution. So if jobs are (1,3,5) and Vehicle 1 visited 1,3 and Vehicle 2 just visited 2 it should be finished.\nIf I use solver in ortools It will be like TSP problem which will try to visit each location in distance_matrix. I don't exactly want this. It could visit if results better solution(does it make sense?) but it should be focusing on \"JOB\" locations and how to go them faster","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":112,"Q_Id":66087248,"Users Score":1,"Answer":"Potential approach: Compute a new distance matrix with only the \"MUST VISIT\" locations, and run a VRP with this matrix.\n\nCompute a distance matrix with only the \"MUST VISIT\" locations.\nEach cell contains the shortest path between two \"MUST VISIT\" locations.\nStore all the pairwise shortest paths found.\nRun a regular VRP on this distance matrix.\nReconstruct the full path using the shortest paths found earlier.","Q_Score":2,"Tags":"python,python-3.x,algorithm,or-tools,vehicle-routing","A_Id":66105127,"CreationDate":"2021-02-07T11:16:00.000","Title":"Vehicle Routing Problem - How to finish\/determine when certain locations are visited?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"How can I select the rows with null values in respect of columns name?\nWhat I have:\n\n\n\n\nID\nA\nB\n\n\n\n\n1\na\nb\n\n\n2\n\nv\n\n\n3\ny\n\n\n\n4\nw\nj\n\n\n5\nw\n\n\n\n\nWhat I want:\nSelect rows with null in respect with e.g. column B:\n\n\n\n\nID\nB\n\n\n\n\n3\ny\n\n\n5\nw","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":818,"Q_Id":66089946,"Users Score":1,"Answer":"I guess you can use isna() or isnull() functions.\ndf[df['column name'].isna()]\n(or)\ndf[df['column name'].isnull()]","Q_Score":1,"Tags":"python,pandas,dataframe","A_Id":66090038,"CreationDate":"2021-02-07T16:00:00.000","Title":"select rows with null value python-pandas","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm taking a MOOC on Tensorflow 2 and in the class the assignments insist that we need to use tf datasets; however, it seems like all the hoops you have to jump through to do anything with datasets means that everything is way more difficult than using a Pandas dataframe, or a NumPy array... So why use it?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":38,"Q_Id":66093323,"Users Score":0,"Answer":"The things you mention are generally meant for small data, when a dataset can all fit in RAM (which is usually a few GB).\nIn practice, datasets are often much bigger than that. One way of dealing with this is to store the dataset on a hard drive. There are other more complicated storage solutions. TF DataSets allow you to interface with these storage solutions easily. You create the DataSet object, which represents the storage, in your script, and then as far as you're concerned you can train a model on it as usual. But behind the scenes, TF is repeatedly reading the data into RAM, using it, and then discarding it.\nTF Datasets provide many helpful methods for handling big data, such as prefetching (doing the storage reading and data preprocessing at the same time as other stuff), multithreading (doing calculations like preprocessing on several examples at the same time), shuffling (which is harder to do when you can't just reorder a dataset each time in RAM), and batching (preparing sets of several examples for feeding to a model as a batch). All of this stuff would be a pain to do yourself in an optimised way with Pandas or NumPy.","Q_Score":0,"Tags":"python,tensorflow,conceptual","A_Id":66093460,"CreationDate":"2021-02-07T21:32:00.000","Title":"(Conceptual question) Tensorflow dataset... why use it?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm dealing with a highly imbalanced dataset for my project rn, for the simplicity, I will give a simple example here: a dataset has a number of 20 '0's and 80 '1's so the total is 100.\nSuppose I have already used X_train, X_test,y_train,y_test = train_test_split(X, y,stratify=y,random_state=42) to make a stratified split (X_train.shape is 80 and X_test.shape is 20), so my question is how to achieve under-sampling with K-fold validation in the train dataset at the same time.\nMy initial thought is use from imblearn.under_sampling import RandomUnderSampler to get 16 '0's and 16 '1's (total is 32) to make equal distributed dataset, and do the K-fold cross-validation on that 32 dataset and discard the rest of 48 in the X_train. Use the model to predict the X_test. So I was wondering if this is correct procedure to deal with.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":99,"Q_Id":66093809,"Users Score":0,"Answer":"You can use RandomUnderSampler method to achieve it. Put random states and ratio value in the arguments and try to see if this works.","Q_Score":0,"Tags":"python,machine-learning","A_Id":66102683,"CreationDate":"2021-02-07T22:32:00.000","Title":"How to do under-sampling with K-fold validation in machine learning","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"This is really throwing me for a loop. In a pandas dataframe (df) I have the following:\n\n\n\n\ndate\nNews\n\n\n\n\n2021-02-03\nSome random event occurred today.\n\n\n2021-02-03\nWe asked a question on Stack Overflow.\n\n\n2021-02-02\nThe weather is nice.\n\n\n2021-02-02\nHello. World.\n\n\n\n\nThe date column is the index which is of the date format, and the News column is a string. What I want to do is to combine the duplicate dates and join or concatenate the News column, for example:\n\n\n\n\ndate\nNews\n\n\n\n\n2021-02-03\nSome random event occurred today. We asked a question on Stack Overflow.\n\n\n2021-02-02\nThe weather is nice. Hello. World.\n\n\n\n\nSo far, I have:\ndf = df.groupby(['date']).agg({'News': list})\nHowever, while this does combine the duplicated dates, it puts the string values in a list, or rather according to the errors I've been getting while trying to join them, into a series. At this point, I am completely lost and any hint\/tip to lead me to the right pythonic way of doing this would be greatly appreciated!\nPS: I would like to avoid using a loop if at all possible since this will need to parse through roughly 200k records multiple times (as a function). If it makes any difference, I'll be using TextBlob on the News column to perform sentiment analysis on.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":39,"Q_Id":66104180,"Users Score":0,"Answer":"Quang Hoang answered the question perfectly! Although I'm not able to mark it as the answer sadly =(\n\ndf.groupby('date')['News'].agg(' '.join). \u2013 Quang Hoang Feb 8 at 15:08","Q_Score":1,"Tags":"python,pandas,string,dataframe,concatenation","A_Id":66169392,"CreationDate":"2021-02-08T15:07:00.000","Title":"Concatenating a series of strings into a single string within a Pandas Dataframe column (for each row)?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have an assignment to build an ANN for regression problems using Python from scratch without using any ML library. You might have guessed I am a true beginner at this and the process is a little confusing so I would really appreciate some help in answering the few questions that I have.\nThis is the basic training algorithm that I understand for training an ANN:\n\nForward prop for prediction\nBackward prop to calculate errors\nCalculate deltas for each weight using the errors\nAccumulate deltas over a dataset iteration and calculate the partial gradient for each weight\nOptimize weights using gradient descent\n\nI hope the steps make sense and are okay. Here are a few questions that I have:\n\nWhat activation function should I use? Sigmoid is probably not the answer.\nShould an activation function be used on the single output node?\nThe formula to calculate errors for hidden layers in back-prop is \u03b4(l) = Transpose[\u03f4(l)] x \u03b4(l+1) .* g`[z(l)] where l is the layer number and g`[z(l)] I believe is the derivative of the activation function usually taken as a(l) .* (1 - a(l)). Will this change as we use an activation function other than sigmoid?\nAny errors I made or any important tip?\n\nApologies if the questions are very basic. I am a raw beginner at this.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":49,"Q_Id":66118673,"Users Score":0,"Answer":"If anyone stumbles upon this with any of the same queries, here are the answers:\n1 - Sigmoid should work but it restricts the output between 0 and 1 and since this was a regression problem, you could design your problem to get a normalized output and scale it to the right number. Or just use ReLU.\n2 - Yes. The type of activation on the output node changes the type of output you get.\n3 - Of course it will. The derivative of the activation gradient is multiplied with the backpropagating global gradient to give the local gradient. Changing the activation function will change the derivative too.\n4 - Maybe try to understand the Math behind backpropagation. It's basic chain rule and once you get it, you won't get confused like this.","Q_Score":0,"Tags":"python,neural-network,linear-regression","A_Id":67556437,"CreationDate":"2021-02-09T12:06:00.000","Title":"Making an ANN for Polynomial Regression","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to know more about this as this is new for me..\nI am trying to query InfluxDB with python to fetch data in 5 min time interval. I used a simple for-loop to get my data in small chunks and appended the chunks into another empty dataframe inside for loop one after another. This worked out pretty smoothly and I see my output. But while I try to perform mathematical operations on this large dataframe , it gives me a Memory error stated below:\n\"Memory Error : Unable to allocate 6.95GiB for an array with shape (993407736) and datatype int64\"\nMy system has these info 8.00GB RAM, 64 bit OS x64 based processor.\nCould my system be not supporting this ?\nIs there an alternate way I can append small dataframes into another dataframe without these memory issues. I am new to this data stuff with python and I need to work with this large chunk of data.... may be an year","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":30,"Q_Id":66130596,"Users Score":0,"Answer":"Even though, your system has 8GB memory, it will be used by OS and other applications running in your system. Hence it is not able to allocate 6.95GiB only for this program. In case you are building a ML model & trying to run with huge data, You need to consider any of the below options\n\nUse GPU machines offered by any of the cloud provider.\nProcess the data in small chunks (If it is not ML)","Q_Score":0,"Tags":"python-3.x,pandas,dataframe,time-series,influxdb","A_Id":66130700,"CreationDate":"2021-02-10T03:40:00.000","Title":"Python Memory Error (After Appending DataFrame)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have one data frame with time in columns but not sorted order, I want to sort in ascending order, can some one suggest any direct function or code for data frames sort time.\nMy input data frame:\n\n\n\n\nTime\ndata1\n\n\n\n\n1 month\n43.391588\n\n\n13 h\n31.548372\n\n\n14 months\n41.956652\n\n\n3.5 h\n31.847388\n\n\n\n\nExpected data frame:\n\n\n\n\nTime\ndata1\n\n\n\n\n3.5 h\n31.847388\n\n\n13 h\n31.847388\n\n\n1 month\n43.391588\n\n\n14 months\n41.956652","AnswerCount":2,"Available Count":1,"Score":-0.0996679946,"is_accepted":false,"ViewCount":41,"Q_Id":66134616,"Users Score":-1,"Answer":"Firstly you have to assert the type of data you have in your dataframe.\nThis will indicate how you may proceed.\ndf.dtypes or at your case df.index.dtypes .\nPreferred option for sorting dataframes is df.sort_values()","Q_Score":0,"Tags":"python-3.x,pandas,dataframe,rows","A_Id":66134737,"CreationDate":"2021-02-10T09:57:00.000","Title":"Sorting data frames with time in hours days months format","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"My graduation project is to use transfer learning on a CNN model that can diagnose Covid-19 from Chest X-ray images. After spending days Fine tuning the hyper parameters such as the number of fully connected layers, the number of nodes in the layers, the learning rate, and the drop rate using Keras tuner library with Bayesian Optimizer, I got some very good results, A test accuracy of 98% for multi class classification and a 99% for binary class classification. However, i froze all the layers in the original base model. I only fine tuned the last Fully connected layers after exhaustive hyper parameter optimization. Most articles and papers out there say that they fine the fully connected layers as well as some of the convolutional layers. Am i doing something wrong? I am afraid that this is too good to be true.\nMy data set is not that big, only 7000 images taken from the Kaggle Covid-19 competition.\nI used image enhancement techniques such as N-CLAHE on the images before the training and the classification which improved the accuracy significantly compared to not enhancing the images.\nI did the same for multiple State of art models, such as VGG-16 and ResNet50, and they all gave me superb results.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":157,"Q_Id":66145265,"Users Score":0,"Answer":"If you mean by \"only fine tuned the last Fully connected layers\" then NO, you did not.\nYou can choose to fine-tune any layer of your choice but most importantly the final layers of the model, which is what you did, so you're good to go.","Q_Score":0,"Tags":"python,machine-learning,keras,deep-learning,transfer-learning","A_Id":66148625,"CreationDate":"2021-02-10T21:25:00.000","Title":"Do i Need to fine tune the last convolutional layers in a state of art CNN models like ResNet50?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have 100 images, I applied horizontal and vertical augmentation with a probability of 1 using Pytorch function RandomHorizontalFlip and RandomVerticalFlip. After this would my total number of images will be 300 or something else?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":272,"Q_Id":66147184,"Users Score":0,"Answer":"the Above illustration is precise.[to show if you want to increase the dataset size]\nbut when you are using transforms.Compose function it augment images in the runtime and dumps them after the operation. this is because storage redundant data is only a storage overhead.","Q_Score":2,"Tags":"python,pytorch","A_Id":66148651,"CreationDate":"2021-02-11T00:36:00.000","Title":"Number of images after image augmentation in pytorch","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am currently building a neural network to predict features such as temperature. So the output for this could be a positive or negative value. I am normalizing my input data and using the tanh activation function in each hidden layer.\nShould I use a linear activation function for the output layer to get an unbounded continuous output OR should I use tanh for the output layer and then inverse normalize the output? Could someone explain this I don't think my understanding of this is correct.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":186,"Q_Id":66178463,"Users Score":1,"Answer":"You are actually in the correct direction\nOption1:\nyou need to normalize the temperatures first and then fed it to the model let say your temperature ranges from [-100,100] so convert it into a scale of [-1,1] then use this scaled version of temp in your target variable.\nAt the time of prediction just inverse transform the output and you will get your desired result.\nOption2:\nYou create a regression kind of neural network and don't apply any activation function to the output layer (means no bonds for values it could be +ve or -ve).\nIn this case you are not required to normalize the values.\nSample NN Spec:\nInput Layer==> # neurons one per feature\nHidden Layer==>relu\/selu as activation function| # of neurons\/Hidden layers is as per your requirement\nOutput Layer==> 1 neuron\/ no Activation function required","Q_Score":0,"Tags":"python,machine-learning","A_Id":66185049,"CreationDate":"2021-02-12T20:13:00.000","Title":"How to get an unbounded continuous output from a neural network?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to solve a large MIP scheduling problem. Since it will take a long time to solve the problem, I want to run the same model with fewer event point and find its n-th solution. Use that solution as an initial solution\/seed for a bigger(more event points) model to find its n-th solution and use this to cascade up till the desired number of event points.\nUsing the solution from the small problem, I use its binary values in the mip start and let the newly added event point un touched. I save these values in a dictionary name seed_sol where the key is the binary variable(obtain when creating the varible) and the value is 0\/1 from the previous solve.\nm.add_mip_start(SolveSolution(m, seed_sol))\nUsing the above code, I warm start my larger runs. However, when I look at the output log I realised that the solution rarely improves and the gap is very low(I know for a fact that the actual optimal solution is much much higher). I suspect that the 'add_mip_start' function forces the solution values to my initial seed solution and tries to improve the solution by only adjusting the newly added binary variables.\nHow do i fix this to get the desired outcome?\nUsing:\n\nPython 3.6.8\ncplex 12.10.0.0\ndocplex 2.19.202","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":401,"Q_Id":66179181,"Users Score":0,"Answer":"The MIP start is used as a starting point, but its start values might be changed in the search, as opposed to a fixed start, where fixed values are considered as hard constraints.\nBTW, you can also implement fixed starts with constraints, this facilitates adding or removing these fixed starts.\nHowever, the interest of a MIP start resides in the quality of the initial solution. In your case, it seems the initial solution is much smaller than the large problem, so it might not help much.\nTo assess your MIP performance issues, can you indicate the size of the problem (as printed by Model.print_information()))\nand also the CPLEX log (at least the part where cplex stalls.)","Q_Score":0,"Tags":"python,cplex,docplex","A_Id":66198320,"CreationDate":"2021-02-12T21:20:00.000","Title":"DOCPLEX MIP warmstart","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm training a model with a 4 day look back and 4 days future forecast. The last 4 days will be acting as a feature for the next days.\nIn that case if i have x_test as [[1,2,3,4],[5,6,7,8]] and y_test[[0.1,0.2,0.3,0.4],[0.5,0.6,0.7,0.8]]\nif we do a model.predict(x_test[0]), the result y(hat) we need to comapare with y[1].\nSo how is model.evaluate() doing this comparison? if we comapre y(hat)[0] with y[0], it is wrong right?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":562,"Q_Id":66184612,"Users Score":0,"Answer":"As you mentioned, if we give values for consecutive days then we can use the second set of 4 values to evaluate model predictions of the first set of 4. [ it is called the rolling window validation method]\nBut, Since your dataset is in the form of input - [first 4 values] \/ label - [next 4 values], here we do not need to evaluate result of x_test[0] with y[1] because the actual y value for x_test[0] is in the y[0].","Q_Score":0,"Tags":"python,tensorflow,deep-learning,time-series,lstm","A_Id":66185823,"CreationDate":"2021-02-13T11:32:00.000","Title":"How does model.evaluate() work in tensorflow?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"So I'm starting to study RNN, particularly LSTM, and there is part of the theory that I just don't understand.\nWhen you stack LSTM cells, I see how everybody detaches the hidden state from history, but this makes no sense to me, aren't LSTM supposed to use hidden states from history to make better predictions?\nI read the documentation but it still not clear to me, so any explanation is welcomed","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":853,"Q_Id":66187443,"Users Score":3,"Answer":"You got it right, the hidden state in the LSTMs is there to serve as a memory. But this question arises, are we supposed to learn them? No, hidden state isn\u2019t suppose to be learned, so we detach it to let the model use those values but to not compute gradients.\nIf you don't detach, then the gradients will be really big.","Q_Score":0,"Tags":"python,lstm,recurrent-neural-network","A_Id":66187921,"CreationDate":"2021-02-13T16:37:00.000","Title":"LSTM- detach the hidden state","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am developing a robotics project which sends a livestream of images. The images are all published to the same topic. What I am finding is that a backlog is created and a delay starts to form between images being sent for publish and them actually being published.\nI am assuming there is some form of internal buffer \/ queueing system in PAHO MQTT which is causing this.\nGiven the nature of the project I am not precious about each image being published, ideally I'd be able to drop any messages that are waiting to be published to a certain topic and re-publish new content. Does anyone know if this is possible, and if so how?\nThank you","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":246,"Q_Id":66198205,"Users Score":2,"Answer":"No, this is not possible.\nThe only thing that would cause messages to back up on the client is if you are publishing them quicker than the client can send them to the broker, which under normal circumstances will be a product of the network speed between the client and the broker.\nThe only other thing that might have an impact would be if you are manually running the network loop and you are not calling it often enough.","Q_Score":1,"Tags":"python,mqtt,communication,paho","A_Id":66198616,"CreationDate":"2021-02-14T17:36:00.000","Title":"Paho MQTT Python - Clear topic queue if new message published","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have an array of numbers\na = [440, 320, 650]\nI am trying to write a .wav file that writes those frequencies in order. But I don't know if scipy.io.wavfile is able to write an array of frequencies to a wav file. All I can do right now is something like\nwavfile.write('Sine.wav', rate, a[0])\nI am thinking to do something like this though.\nfor x in range(0, len(a)):\n#wavfile.addFrequency('Sine.wav', rate, a[x])","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":178,"Q_Id":66200524,"Users Score":0,"Answer":"\"In order\" doesn't sound very clear to me. I guess you would like to mix those sine waves. For that you must make a single wave with the 3 sines by summation of their amplitude values. For each sample, three values must be added (one for each sine) taking care that the result never overflows -1.0 or 1.0 (for float values, for 16 bit integers the range would be -32768 to 32767 instead).\nNow if you plane to render the three waves successively instead, you have to determine the duration of each segment and take care that the junction between two waves is done at amplitude zero to prevent numeric clicks.","Q_Score":2,"Tags":"python,scipy,wav","A_Id":66200647,"CreationDate":"2021-02-14T21:56:00.000","Title":"Is there a way to write multiple frequencies to a .wav file?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I was originally running Tensorflow using PyCharm.\nIn PyCharm, the same phrase as the title did not appear.\nBut after I switched to VS Code and installed Python extension,\nWhen I write and execute import tensorflow as tf, the error like the title appears repeatedly.\n\nImportError: Could not load dynamic library 'cudart64_110.dll'\n\nConsidering that there was no problem in PyCharm, it does not seem to be an environmental variable problem.\nWhen I type the same command that was executed in VS Code in the command prompt window, another phrase appears,\n\n\"Connection failed because the target computer refused to connect.\"\n\nMy OS: Windows 10\nI am using Anaconda, and I created a virtual environment.\nvscode ver : 1.53.2\ntensorflow ver : 2.4.1\nCUDA : 11.2\ncudnn : 8.1","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":12553,"Q_Id":66206835,"Users Score":0,"Answer":"I copied \"cudart64_110.dll\" to the CUDA\/v11.2\/bin folder and it was resolved.","Q_Score":1,"Tags":"python,tensorflow,visual-studio-code","A_Id":66288429,"CreationDate":"2021-02-15T11:02:00.000","Title":"ImportError: Could not load dynamic library 'cudart64_110.dll'","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I started looking into Numpy using a 'Python for data analysis'. Why is the array dimension for arr2d is \"2\", instead of \"3\". Also why is the dimension for arr3d \"3\", instead of \"2\".\nI thought the dimension of the array is based on the number of rows? Or this doesn't apply to higher dimensional and multidimensional arrays?\narr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\narr2d.shape\nOutput: (3, 3)\narr2d.ndim\nOutput: 2\narr3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])\n arr3d.shape\nOutput: (2, 2, 3)\narr3d.ndim \nOutput: 3","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":107,"Q_Id":66210485,"Users Score":1,"Answer":"well see basically the dimension of the array is not based on the number of rows\nbasically it is based on the brackets i.e [] that you entered in np.array() method\nsee\narr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\nin arr2d there are 2 brackets([[]]) or there are 2 opening brackets([[) or its has 2 closing brackets(]]) so its an 2D array of (3,3) i.e 3 rows and 3 columns\nsimilarly\narr3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])\nin arr3d there are 3 brackets([[[]]]) or there are 3 opening brackets([[[) or or its has 3 closing brackets(]]]) so its an 3D array of (2,2,3) i.e its has 2 arrays of 2 rows and 3 columns","Q_Score":0,"Tags":"python,arrays,numpy","A_Id":66212428,"CreationDate":"2021-02-15T15:08:00.000","Title":"Understanding Numpy dimensions of arrays","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a csv file which has a column named population. In this CSV file the values of this column are shown as decimal (float) i.e. for e.g. 12345.00. I have converted whole of this file to ttl RDF format, and the population literal is shown as the same i.e. 12345.0 in the ttl file. I want it to show as integer (whole number) i.e. 12345 - Do I need to convert the data type of this column or what to do? Also, I would ask how can I check the data type of a column of a dataFrame in python?\n(A beginner in python)- Thanks","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":66,"Q_Id":66212917,"Users Score":0,"Answer":"csv_data['theColName'] = csv_data['theColName'].fillna(0)\ncsv_data['theColName'] = csv_data['theColName'].astype('int64') worked and the column is successfully converted to int64. Thanks everybody","Q_Score":0,"Tags":"python,pandas,dataframe,type-conversion","A_Id":66215372,"CreationDate":"2021-02-15T17:45:00.000","Title":"data type conversion in dataFrame","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Suppose I have two data frames. One with employee IDs. And one with employee IDs and a Boolean value that indicates if they were given a raise when they asked (they can ask multiple times).\n\n\n\n\nID\n\n\n\n\n5\n\n\n8\n\n\n9\n\n\n22\n\n\n\n\n\n\n\nID\nRaise\n\n\n\n\n5\nTrue\n\n\n5\nFalse\n\n\n5\nTrue\n\n\n8\nTrue\n\n\n9\nTrue\n\n\n22\nFalse\n\n\n\n\nHow can I create a dataframe that merges employee IDs and whether they were given a raise (regardless of how many times they asked)? Like the following.\n\n\n\n\nID\nRaise\n\n\n\n\n5\nTrue\n\n\n8\nTrue\n\n\n9\nTrue\n\n\n22\nFalse\n\n\n\n\nWhenever I try to merge normally, extra rows are created due to multiple of the same ID.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":62,"Q_Id":66214679,"Users Score":0,"Answer":"As @Paul H said, you need an aggregation on the second dataframe\ndf2.groupby(\"ID\")[\"Raise\"].any()\nThen you can merge with the first one using ID.","Q_Score":0,"Tags":"python,pandas,dataframe","A_Id":66214965,"CreationDate":"2021-02-15T20:02:00.000","Title":"Merging Dataframes and getting extra rows. (Python\/Pandas)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using the ResNet18 pre-trained model which will be used for a simple binary image classification task. However, all the tutorials including PyTorch itself use nn.Linear(num_of_features, classes) for the final fully connected layer. What I fail to understand is where is the activation function for that module? Also what if I want to use sigmoid\/softmax how do I go about that?\nThanks for your help in advance, I am kinda new to Pytorch","AnswerCount":3,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":854,"Q_Id":66222699,"Users Score":3,"Answer":"No you do not use activation in the last layer if your loss function is CrossEntropyLoss because pytorch CrossEntropyLoss loss combines nn.LogSoftmax() and nn.NLLLoss() in one single class.\nThey do they do that ?\nYou actually need logits (output of sigmoid) for loss calculation so it is a correct design to not have it as part of forward pass. More over for predictions you don't need logits because argmax(linear(x)) == argmax(softmax(linear(x)) i.e softmax does not change the ordering but only change the magnitudes (squashing function which converts arbitrary value into [0,1] range, but preserves the partial ordering]\nIf you want to use activation functions to add some sort of non-linearity you normally do that by using a multi-layer NN and having the activation functions in the last but other layers.\nFinally, if you are using other loss function like NLLLoss, PoissonNLLLoss, BCELoss then you have to calculates sigmoid yourself. Again on the same note if you are using BCEWithLogitsLoss you don't need to calculate sigmoid again because this loss combines a Sigmoid layer and the BCELoss in one single class.\ncheck the pytorch docs to see how to use the loss.","Q_Score":1,"Tags":"python,pytorch,resnet","A_Id":66222964,"CreationDate":"2021-02-16T10:32:00.000","Title":"ResNet family classification layer activation function","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am converting a code from Matlab to python.\nIn Matlab an s4p file (s-parameters of a 4 port network) is read and then the s-parameters of 4 single ports are converted to s-parameters of 2 differential ports using s2sdd method.\nI am using skrt (scikit-rf) in python to read in the s4p file but I am stuck when converting the s-parameters. Is there a method doing this?","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":107,"Q_Id":66226893,"Users Score":0,"Answer":"Eventually I ported the s2sdd from matlab to python. I could not find a suitable existing method.","Q_Score":0,"Tags":"python,matlab","A_Id":67063153,"CreationDate":"2021-02-16T15:02:00.000","Title":"Matlab network s2sdd for s-parameters in python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Good evening all. I know that we can groupby multiple columns by just df.groupBy('col1,'col2','col3')\nI think that this grouping means that it first groups by col1 and for each member of col1 it groups by col2 and so on. If this is wrong just correct me, I basically started yesterday with PySpark because a university project.\nI have the need to group the data by 4 members: 2 string columns and 2 time window.\ndf.groupBy('col1,'col2','1HourTimeWindow','15MinTimeWindow')\nI'm aware that can do a groupBy with a window like this\ndf.groupBy(window(\"timeCol\", \"1 hour\")) but can't have more than 1 window in the same groupBy.\nAny solution you can recommend to me would be awesome. Thanks in advance","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":177,"Q_Id":66229442,"Users Score":0,"Answer":"Solved by aggregating groupBy(col1, col2, 15Min) and after that grouping by 1 hour in subsequent tasks.","Q_Score":1,"Tags":"python,dataframe,apache-spark,pyspark,apache-spark-sql","A_Id":66262724,"CreationDate":"2021-02-16T17:42:00.000","Title":"PySpark groupby multiple time window","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"i have around 2000 tweet id's for which i have to extract respective tweets. first and foremost thing excel doesnt allow me to save those tweet id in the same format as it is supposed to be and last four digits of the tweet id is truncated to 0000 .\nex : tweet id 572330170108922545 is truncated to 572330170108920000 .\ni wanted to use twitter's tweepy library to extract tweets .. but seems that initial problem is not letting me start of the work. can i still use .txt file format to read each tweet id's line by line by using with open(filename.txt, 'r) as tweet_id : ?\nPlease let me know if there is any work around for this.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":144,"Q_Id":66229536,"Users Score":0,"Answer":"If your question is simply if this can be done, the answer is certainly yes. You just have to figure out how this data is structured. If you go line by line, you can use .split() or re (regular expression operations) to find the relevant parts of the lines.","Q_Score":0,"Tags":"python,excel,twitter,twitterapi-python","A_Id":66229734,"CreationDate":"2021-02-16T17:48:00.000","Title":"how to avoid tweet id's getting truncated when saved in excel as csv","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a 3D CT image of a car engine in raw form with no header information. When loaded into numpy array as 16 bit unsigned integer, I noticed that the values range between 0 to 52000. Is this normal for a CT Image? When viewing the image, I also noticed a lot of cloud like noise in every slice. I'm trying to extract features using a deep learning method. This is my first time working with CT Images. What pre processing is neccesary for such CT Images?","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":129,"Q_Id":66229988,"Users Score":0,"Answer":"From my experience in working with soft tissue CT medical images, I have seen CT having -1024 intensity for air and up to +3000 intensity for cancellous bone. When it comes to metal-like electrodes and even tooth images, it reaches up to +9000. So I guess for heavy metals like car engines the intensity value of 52000 is not aberration(though I never heard CT images of car engines so far!).\nPre-processing can include windowing or normalization operations and noise removals. Windowing is something already mentioned here to restructure the intensity range to a more workable one.","Q_Score":0,"Tags":"python,image-processing,medical-imaging","A_Id":68568420,"CreationDate":"2021-02-16T18:18:00.000","Title":"CT image preprocessing in python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a 3D CT image of a car engine in raw form with no header information. When loaded into numpy array as 16 bit unsigned integer, I noticed that the values range between 0 to 52000. Is this normal for a CT Image? When viewing the image, I also noticed a lot of cloud like noise in every slice. I'm trying to extract features using a deep learning method. This is my first time working with CT Images. What pre processing is neccesary for such CT Images?","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":129,"Q_Id":66229988,"Users Score":0,"Answer":"Since it is 16 uint format, the value range could be 0 ~ 2 ^ 16 which is up to 65535, so 0 to 52000 is very reasonable. If it is a car engine instead of soft tissue, chances are you don't need that big range, you could reduce your data to 12 bit or even 8 bit without losing much details, by applying windowing and leveling to it.\nFor the \"cloud like noise\", please upload some image to show exact problem. If my guess is correct, it is probably due to the endian-ness. Try opening the raw data using ImageJ and try 16 uint little-endian and big-endian, one of these might give you normal image.","Q_Score":0,"Tags":"python,image-processing,medical-imaging","A_Id":67696094,"CreationDate":"2021-02-16T18:18:00.000","Title":"CT image preprocessing in python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"i am new in this field and i need a small help.\ni just want to know that, what is the best way to append multiple data arrays in a variable of a xarray dataset?\neach data array has a different time and value but has the same x,y coordinates same as dataset.\ni tried ds[variable_name] = da but it works only for the first data array .\ni want to create a function that gets data arrays and put them into one variable of the dataset and updating the time dimension of the dataset.\nthanks for your help","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":223,"Q_Id":66258827,"Users Score":0,"Answer":"The best way for doing that is first to convert data arrays to datasets separately then merge datasets together (using xr.merge).\nHope it helps the others.","Q_Score":0,"Tags":"python,numpy,python-xarray,rasterio","A_Id":66500507,"CreationDate":"2021-02-18T11:14:00.000","Title":"How to append multiple data arrays into one varibale of xarray dataset?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm performing some (binary)text classification with two different classifiers on the same unbalanced data. i want to compare the results of the two classifiers.\nWhen using sklearns logistic regression, I have the option of setting the class_weight = 'balanced' for sklearn naive bayes, there is no such parameter available.\nI know, that I can just randomly sample from the bigger class in order to end up with equal sizes for both classes, but then the data is lost.\nWhy is there no such parameter for naive bayes? I guess it has something to do with the nature of the algorithm, but cant find anything about this specific matter. I also would like to know what the equivalent would be? How to achieve a similar effect (that the classifier is aware of the imbalanced data and gives more weight to the minority class and less to the majority class)?","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":1376,"Q_Id":66280588,"Users Score":2,"Answer":"I'm writing this partially in response to the other answer here.\nLogistic regression and naive Bayes are both linear models that produce linear decision boundaries.\nLogistic regression is the discriminative counterpart to naive Bayes (a generative model). You decode each model to find the best label according to p(label | data). What sets Naive Bayes apart is that it does this via Bayes' rule: p(label | data) \u221d p(data | label) * p(label).\n(The other answer is right to say that the Naive Bayes features are independent of each other (given the class), by the Naive Bayes assumption. With collinear features, this can sometimes lead to bad probability estimates for Naive Bayes\u2014though the classification is still quite good.)\nThe factoring here is how Naive Bayes handles class imbalance so well: it's keeping separate books for each class. There's a parameter for each (feature, label) pair. This means that the super-common class can't mess up the super-rare class, and vice versa.\nThere is one place that the imbalance might seep in: the p(labels) distribution. It's going to match the empirical distribution in your training set: if it's 90% label A, then p(A) will be 0.9.\nIf you think that the training distribution of labels isn't representative of the testing distribution, you can manually alter the p(labels) values to match your prior belief about how frequent label A or label B, etc., will be in the wild.","Q_Score":4,"Tags":"python,scikit-learn,logistic-regression,naivebayes","A_Id":66310760,"CreationDate":"2021-02-19T15:40:00.000","Title":"class_weight = 'balanced' equivalent for naive bayes","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"i got this message when i wanted run a beysian personalized ranking by GPU in colab, How can i resolve this problem ?\nmessage is :\nGPU training requires factor size to be a multiple of 32 - 1. Increasing factors from 100 to 127.","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":337,"Q_Id":66284758,"Users Score":0,"Answer":"It could be that google colab is running out of ram\nwhy?\nbecause we are loading all data at once.or generating all data at once.\nexample :\ngoogle colab having 12 GB of ram. and it running out of ram.\nSo what i would suggest is:\nwe can process that data in chunks. if the total size of the data is 12 GB. than we can divide it into chunk(file) of 1 Gb.\n12 GB data = 12 chunks(files) of 1 Gb\nso now we have to load only 1 GB file into ram. which won't crash our notebook.","Q_Score":0,"Tags":"python,google-colaboratory","A_Id":66284829,"CreationDate":"2021-02-19T20:44:00.000","Title":"my colab notebook crash, how can i resolve it?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"i got this message when i wanted run a beysian personalized ranking by GPU in colab, How can i resolve this problem ?\nmessage is :\nGPU training requires factor size to be a multiple of 32 - 1. Increasing factors from 100 to 127.","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":337,"Q_Id":66284758,"Users Score":0,"Answer":"On Colab a multitude of things could lead to crash. It's likely that you ran out of RAM or out of GPU memory.","Q_Score":0,"Tags":"python,google-colaboratory","A_Id":66284848,"CreationDate":"2021-02-19T20:44:00.000","Title":"my colab notebook crash, how can i resolve it?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"The elementary functions in numpy, like mean() and std() returns np.nan when encounter np.nan. Can I make them ignore it?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":320,"Q_Id":66289714,"Users Score":2,"Answer":"The \"normal\" functions like np.mean and np.std evalutates the NaN i.e the result you've provided evaluates to NaN.\nIf you want to avoid that, use np.nanmean and np.nanstd. Note that since you have only one non-nan element the std is 0, thus you are dividing by zero.","Q_Score":0,"Tags":"python,numpy","A_Id":66289750,"CreationDate":"2021-02-20T08:57:00.000","Title":"'ignore nan' in numpy functions","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Suppose I have a list of 100 numbers. I can find the mean by summing and dividing by the number of elements. But how can I find two values, one that gravitates towards the left of the list (assuming the list is ordered) and one towards the right, so that the list is equally divided into three blocks?\nSorting the array and taking the 33th and the 66th elements doesn't work because I could have all 1's before the 33th position and bigger values after, so the 33th position would be too early in the array. Those two 'means' depend on the values of the array and not solely on the indices.\nI'm sure what I'm trying to do has a proper naming but I can't really remember it now.","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":77,"Q_Id":66290266,"Users Score":0,"Answer":"You could try numpy.quantile for example np.quantile(your_list, [0.33, 0.66]) I think should do the trick","Q_Score":0,"Tags":"python,arrays,list,numpy,mean","A_Id":66290439,"CreationDate":"2021-02-20T10:01:00.000","Title":"How to find multiple equally distributed means of a numpy array?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am calculating similarity between 2 texts using universal sentence encoder\nMy question is whether embedding text at sentence level (which yields no of vectors equal to the no of sentences) and then average out scores instead of just creating a vector per text is a right way to do it?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":84,"Q_Id":66292655,"Users Score":0,"Answer":"As always, it depends on your data set. You can try it both ways and see which one gives the scores useful for your use case. In general, I have found that just feeding the whole text at one time to USE for text up to 100 words works just fine or even better. There is not a need to break into sentences and then average.","Q_Score":0,"Tags":"python,tensorflow,sentence-similarity","A_Id":66956358,"CreationDate":"2021-02-20T14:29:00.000","Title":"Universal sentence encoder for multi sentence text similarity","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a conceptual question and hoping someone can clarify. When running let's say CV=10 in GridSearchCV, the model is getting trained on 9 partitions and tested in the remaining 1 partition.\nThe question is what's more relevant here? The avg AUC results coming from the 9 partitions or the avg AUC of the testing partitions. What if the AUC's on these 2 (9 vs 1 partition) are far apart, let's say more than 20% apart. What does that say about the efficacy of the trained model? Any rule of thumb on how far the AUC's could be? What is generally reported as the measure of model performance, the 9 partition AUC (train) or the testing partitions?\nThank you!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":30,"Q_Id":66295030,"Users Score":0,"Answer":"I assume it is machine learning model (e.g. neural net)\n\nWhen running lets say CVfold =10 in gridsearchCV, the model is getting\ntrained on 9 partitions and tested in the remaining 1 partition.\nthe avg auc results coming from the 9 partitions or the avg\n\nUsually he model is trained on 1 partition (train set) composed from 9 arbitrary partitions. Therefore there is not such a thing as avg AUC from 9 partitions, there is only one train AUC. This words are not true if you are sure that you train on 1 partition, calculate metric, train on 2nd, caluclate metric and so on until you have got metrics results from 9 partitions and averaged them.\nThe key question:\n\nQuestion is what is more relevant here?\n\nDepends what is the question you are answering to.\nResults from test partitions should tell you about what performance can you more or less except when you release the model to the world (make predictions on unseen data). However it is easy to introduce some sort of data leakage when you use CV, data leakage makes the results less trustful.\nComparison between training and test should tell you if you are overfitting your model or if you should make model more fitted. I do not rule of thumb of how much the difference is fine (suggest further reading about overfitting) but I have never seen anyone accepting 20% difference.","Q_Score":0,"Tags":"python,gridsearchcv","A_Id":66295285,"CreationDate":"2021-02-20T18:18:00.000","Title":"GridsearchCV in Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Code:\nfrom matplotlib import animation\nOutput:\nImportError: cannot import name 'animation' from partially initialized module 'matplotlib' (most likely due to a circular import)\nThe motplotlib version is 3.3.4","AnswerCount":3,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":2132,"Q_Id":66298746,"Users Score":0,"Answer":"I finally solved the problem after tracking down the file path, I've always been using spyder of Anaconda, so i uninstalled and installed matplotlib using anaconda prompt over and over again, however, the problem is not error in anaconda, but python37 idle, it seems that if a packege is installed in idle, the spyder will run that one first(which is a bad one in my case), just by deleting matplotlib in python37 idle, the problem is solved at last","Q_Score":1,"Tags":"python,matplotlib,matplotlib-animation","A_Id":70274777,"CreationDate":"2021-02-21T03:03:00.000","Title":"cannot import name 'animation' from partially initialized module 'matplotlib'","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"Code:\nfrom matplotlib import animation\nOutput:\nImportError: cannot import name 'animation' from partially initialized module 'matplotlib' (most likely due to a circular import)\nThe motplotlib version is 3.3.4","AnswerCount":3,"Available Count":2,"Score":0.1325487884,"is_accepted":false,"ViewCount":2132,"Q_Id":66298746,"Users Score":2,"Answer":"simply update matplotlib using pip install --upgrade matplotlib worked for me.","Q_Score":1,"Tags":"python,matplotlib,matplotlib-animation","A_Id":67559932,"CreationDate":"2021-02-21T03:03:00.000","Title":"cannot import name 'animation' from partially initialized module 'matplotlib'","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I know that when you use numpy.random.seed(0) you get the same result on your own computer every time. I am wondering if it is also true for different computers and different installations of numpy.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":1038,"Q_Id":66299283,"Users Score":0,"Answer":"It all depends upon type of algorithm implemented internally by numpy random function. In case of numpy, which is operated by pseudo-random number generators (PRNGs) algorithm. What this means is that if you provide the same seed( as of starting input ), you will get the same output. And if you change the seed, you will get a different output. So this kind of algorithm is no system dependent.\nBut for a true random number generator (TRNG) these often rely on some kind of specialized hardware that does some physical measurement of something unpredictable in the environment such as light or temperature electrical noise radioactive material. So if an module implements t\nhis kind of algorithm then it will be system dependent.","Q_Score":0,"Tags":"python,numpy","A_Id":66299426,"CreationDate":"2021-02-21T04:57:00.000","Title":"Does numpy.random.seed make results fixed on different computers?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"This is a natural language processing related question.\nSuppose I have a labelled train and unlabelled test set. After I have cleaned my train data(stopword, stem, punctuations etc), I use this cleaned data to build my model.\nWhen fitting it on my test data, will I also have to clean the test data text using the same manner as I did with my train set? or should I not touch the test data completly.\nThanks!","AnswerCount":2,"Available Count":2,"Score":1.2,"is_accepted":true,"ViewCount":352,"Q_Id":66301306,"Users Score":0,"Answer":"Yes, you should do the same exact preprocessing on your training and testing dataset.","Q_Score":0,"Tags":"python,nlp,data-science,text-processing,train-test-split","A_Id":66302584,"CreationDate":"2021-02-21T10:29:00.000","Title":"Do you have to clean your test data before feeding into an NLP model?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"This is a natural language processing related question.\nSuppose I have a labelled train and unlabelled test set. After I have cleaned my train data(stopword, stem, punctuations etc), I use this cleaned data to build my model.\nWhen fitting it on my test data, will I also have to clean the test data text using the same manner as I did with my train set? or should I not touch the test data completly.\nThanks!","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":352,"Q_Id":66301306,"Users Score":0,"Answer":"Yes, data cleaning is a mandatory step in machine learning or NLP problem.\nSo you have to always first clean our data and then only have to feed it to the model.\nReg. Test and train data cleaning --> you can clean both data there is no harm of doing this.","Q_Score":0,"Tags":"python,nlp,data-science,text-processing,train-test-split","A_Id":68775998,"CreationDate":"2021-02-21T10:29:00.000","Title":"Do you have to clean your test data before feeding into an NLP model?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"New to learning code: I started an online learning program for Machine Learning and Data Science. I completed the first project linear regression using a Jupyter Notebook and Python 3 using Anaconda. It was saved as a ipynb file.\nI downloaded and saved it on laptop(PC) but now it will not open. I think maybe I need to download something on my laptop that recognizes the notebook application.\nOk thank you to those who responded to my question. File opens from Jupyter Notebook just fine, I was trying to open from document folder. Thanks again!!","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":543,"Q_Id":66304161,"Users Score":0,"Answer":"Have you installed it? ;-)\nIf you\u2019re using a menu shortcut or Anaconda launcher to start it, try opening a terminal or command prompt and running the command jupyter notebook.\nIf it can\u2019t find jupyter, you may need to configure your PATH environment variable. If you don\u2019t know what that means, and don\u2019t want to find out, just (re)install Anaconda with the default settings, and it should set up PATH correctly.\nIf Jupyter gives an error that it can\u2019t find notebook, check with pip or conda that the notebook package is installed.\nTry running jupyter-notebook (with a hyphen). This should normally be the same as jupyter notebook (with a space), but if there\u2019s any difference, the version with the hyphen is the \u2018real\u2019 launcher, and the other one wraps that.","Q_Score":0,"Tags":"python,jupyter-notebook","A_Id":66304323,"CreationDate":"2021-02-21T15:54:00.000","Title":"downloaded a jupyter notebook but it won't open","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have 2019a version of MATLAB and I am trying to explore the usage of Python from within MATLAB environment. I have Anaconda 3 installed for Python. In MATLAB, when I issue, pyenv, I get 'Undefined function or variable 'pyenv''\nThe documentation says that Python is supported, but I am not sure why this doesn't work. Any suggestions?\nEdit:\nThanks. Solution is to use pyversion, but also set the path with the entire path\npyversion 'C:\\Users\\newuser\\AppData\\Local\\Continuum\\anaconda3\\python.exe';","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":276,"Q_Id":66307112,"Users Score":3,"Answer":"pyenv was introduced in R2019b. In R2019a and older, you need to use the older pyversion function.","Q_Score":0,"Tags":"python,matlab","A_Id":66307421,"CreationDate":"2021-02-21T21:05:00.000","Title":"Use Python within MATLAB environment (2019a)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"Say you create your own custom word embeddings in the process of some arbitrary task, say text classification. How do you get a dictionary like structure of {word: vector} back from Keras?\nembeddings_layer.get_weights() gives you the raw embeddings...but it's unclear which word corresponds to what vector element.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":162,"Q_Id":66324507,"Users Score":1,"Answer":"This dictionary is not a part of keras model. It should be kept separately as a normal python dictionary. It should be in your code - you use it to convert text to integer indices (to feed them to Embedding layer).","Q_Score":1,"Tags":"python,keras,nlp,word-embedding","A_Id":66327719,"CreationDate":"2021-02-22T22:42:00.000","Title":"How to get word embeddings back from Keras?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I run training phase of TF2 model (based on object detection pre-trained models from TF2-Models Zoo) on GPU (Nvidia 3070).\nIs there some way to define evaluation phase (for checkpoints created by training) on CPU?\n\nCause train phase allocates almost all memory of GPU, I cant run both of them (train and eval) on GPU.\n\nOS - Ubuntu 20.04\n\nGPU - Nvidia 3070 (driver 460)\n\nTF - 2.4.1\n\nPython - 3.8.5\n\n\nThank you.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":144,"Q_Id":66328975,"Users Score":0,"Answer":"In my case, the solution is into evaluation function define:\nos.environ['CUDA_VISIBLE_DEVICES'] = '-1'","Q_Score":0,"Tags":"python-3.x,tensorflow,tensorflow2.0,cpu","A_Id":66329827,"CreationDate":"2021-02-23T07:44:00.000","Title":"TF2 Model: How run training on GPU, and evaluation on CPU","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am on data science. I have a .csv file with 5kk records and 3.9gigas of size. Whats the best pratice to deal with it? I normally use vscode or jupyter and even when i set max-memory to 10gigas the operations like load etc are taking too much time to complete.\nWhat do you recommend to improve my work?\nnotebook lenovo S145 20gigas ram i7-8565U - Ubuntu\nThanks","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":18,"Q_Id":66342822,"Users Score":1,"Answer":"If you want to bring a CSV into a database for reporting, one fairly quick and easy option is to use an external table. It uses syntax similar to SQLLDR in the create table definition. Once established, the latest saved CSV data will immediately be available as a table in the database.","Q_Score":1,"Tags":"sql,python-3.x,pandas,visual-studio-code,data-science","A_Id":66342911,"CreationDate":"2021-02-24T00:06:00.000","Title":"Best approach to work with .csv files with 4 gigas","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm adding this question because the internet had no answer. I'll answer it here.\n(google searching the error message led to only 2 pages, neither helpful, hopefully this is 3)\nWhen trying to\npython -m spacy download en_core_web_sm\nI got the following error message:\nnumpy.ndarray size changed, may indicate binary incompatibility. Expected 88 from C header, got 80 from PyObject\nAll subsequent error messages were misleading.\nthe solution that solved it was to downgrade spacy\n pip install spacy==2.3.0","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":130,"Q_Id":66343200,"Users Score":1,"Answer":"Downgrade spacy\n pip install spacy==2.3.0","Q_Score":0,"Tags":"python,pandas,numpy,spacy,pycaret","A_Id":66343201,"CreationDate":"2021-02-24T00:57:00.000","Title":"spacy pandas pycaret compatibility issues","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"By default scipy.io.wavfile.read(file) set sample rate 8000, where I in Librosa by default is 22.05k.\nI want to set a 22.05k sample rate in scipy.io.wavfile.read.\nIn the documentation, there is no way to define the sample rate explicitly.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":80,"Q_Id":66345606,"Users Score":0,"Answer":"No, that's not how it works. Each wave file HAS a sample rate. scipy.io.wavfile.read tells you what that rate is. If you want to change it, then you have to do a sample rate conversion.","Q_Score":0,"Tags":"python,scipy","A_Id":66346965,"CreationDate":"2021-02-24T06:15:00.000","Title":"How to define sample rate explicitly in scipy.io.wavfile.read?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am currently running 8 Random Forest models(each with grid search) on 8 different datasets for 1000 times. To save time, I opened up 8 different terminals and am running each models in parallel. Now, my question is\nIs it faster to train each random forest models with the argument n_jobs ==-1 or is it better to assign number of cores such as n_jobs=3? I have 26 cores available. Thus I may be able to assign at most 3 cores to each model.\nLooking at the cpu usage with htop, I can see that running with n_jobs=-1 already makes full use of all cpus. Would it be possible that setting the n_jobs=-1 actually results in bottleneck when distributing the data to each core?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":429,"Q_Id":66345860,"Users Score":0,"Answer":"The fastest in my opinion would be to use n_jobs=-1 in all 8 terminals and your computer will internally allocate as needed the necessary CPU resources to each worker.","Q_Score":1,"Tags":"python,scikit-learn,parallel-processing,cpu","A_Id":66348426,"CreationDate":"2021-02-24T06:39:00.000","Title":"Scikit Learn) is n_jobs=-1 still faster than n_jobs= c when we are running multiple Random Forest in Paralllel?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I was running a deep learning program on my Linux server and I suddenly got this error.\nUserWarning: CUDA initialization: Unexpected error from cudaGetDeviceCount(). Did you run some cuda functions before calling NumCudaDevices() that might have already set an error? Error 804: forward compatibility was attempted on non supported HW (Triggered internally at \/opt\/conda\/conda-bld\/pytorch_1603729096996\/work\/c10\/cuda\/CUDAFunctions.cpp:100.)\nEarlier when I just created this conda environment, torch.cuda.is_available() returned true and I could use CUDA & GPU. But all of a sudden I could not use CUDA and torch.cuda.is_available()returned false. What should I do?\nps. I use GeForce RTX 3080 and cuda 11.0 + pytorch 1.7.0. It worked before but now it doesn't.","AnswerCount":2,"Available Count":1,"Score":1.0,"is_accepted":false,"ViewCount":24066,"Q_Id":66371130,"Users Score":24,"Answer":"I just tried rebooting. Problem solved. Turned out that it was caused by NVIDIA NVML Driver\/library version mismatch.","Q_Score":26,"Tags":"python,linux,pytorch","A_Id":66385167,"CreationDate":"2021-02-25T15:04:00.000","Title":"CUDA initialization: Unexpected error from cudaGetDeviceCount()","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I was recently trying to solve a data science test. Part of the test was to get the number of observations in a dataset for which the variable X is less than the 4th 5-quantile of this variable X.\nI don't realy understand what they meant by the 4th 5-quantile! I tried using pandas df.quantile function but I wasn't able to figure out how to use it in my case","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":1216,"Q_Id":66372010,"Users Score":0,"Answer":"4th 5-quantile translates value = data.quantile(4\/5)","Q_Score":0,"Tags":"python,pandas,dataframe,statistics,data-science","A_Id":66394110,"CreationDate":"2021-02-25T16:00:00.000","Title":"Is there a pandas method to find the 4th 5-quantile of a dataset?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working with a data file of customer addresses. The source data contains foreign characters and is UTF-8 encoded.\nI import the data thus:\ncolumns = ['userid','email','firstname','lastname','phonenumber','fax','address','unit','city','province','postalcode','listing_geopoint','website','tier']\ndata = pd.read_csv(file, delimiter=',', usecols=columns, encoding='utf-8')\n...execute some manipulation (de-duping mainly)\nand then export the data thus:\nclinic.to_excel('clinic-'+revision+'.xlsx',index=False)\n(and I have tried this too)\nclinic.to_csv('clinic-'+revision+'.csv',sep=seperator,index=False, encoding='utf-8')\nIn both cases when I open the export file I get the raw unicode value for foreign chars and not the foreign character.\ne.g.\n3031 boul de la Gare Cliniques Sp\\u00e9cialis\\u00e9es 3eme \\u00e9tage\ninstead of the correct output\n3031 boul de la Gare Cliniques Sp\u00e9cialis\u00e9es 3eme \u00e9tage\nWhat am I missing?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":56,"Q_Id":66374325,"Users Score":1,"Answer":"Are you sure your initial data is encoded in UTF-8?\nI've encountered European characters in latin-1 encoding before so I would try reading in and exporting the csv with (... encoding='latin1')","Q_Score":1,"Tags":"python,pandas,csv,utf-8","A_Id":66374415,"CreationDate":"2021-02-25T18:22:00.000","Title":"Exporting Data to CSV Pandas - issue with Foreign Characters","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a table and I want to find the lowest number associated with each 'leadId' in my table. Here is a snapshot of it below:\n\n\n\n\nIndex\nleadId\nrepId\nhoursSinceContacted\n\n\n\n\n1\n261\n1111\n10391\n\n\n2\n261\n2222\n10247\n\n\n3\n261\n3333\n1149\n\n\n4\n261\n4444\n10247\n\n\n5\n262\n5555\n551\n\n\n6\n262\n6666\n982\n\n\n6\n262\n3333\n214\n\n\n\n\nIs there a groupby statement I can use to get a table that looks like this?:\n\n\n\n\nIndex\nleadId\nrepId\nhoursSinceContacted\n\n\n\n\n3\n261\n3333\n1149\n\n\n6\n262\n3333\n214\n\n\n\n\nAny suggestion will be much appreciated.","AnswerCount":3,"Available Count":1,"Score":0.0665680765,"is_accepted":false,"ViewCount":36,"Q_Id":66374908,"Users Score":1,"Answer":"You can do:\ndf.groupby('leadid').agg({'hoursSinceContacted' : 'min'}).reset_index()","Q_Score":1,"Tags":"python,python-3.x,pandas,dataframe,pandas-groupby","A_Id":66375321,"CreationDate":"2021-02-25T19:07:00.000","Title":"How to find the lowest number of a grouped dataframe in Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Let's say I have two complex images Z_1 and Z_2. I want to make a relative-phase map of the second image with respect to the first. This means:\nZ_2_relative = Z_2 * np.exp(-1j * np.angle(Z_1))\nThis creates a new complex valued matrix where the complex-phase should now be given by\nnp.angle(Z_2_relative) == np.angle(Z_2) - np.angle(Z_1)\nBut according to python these two are not equal. I bet it has something to do with the np.angle function.. but I cant pinpoint it, or know how to fix it...\nPS: Sorry, cant make a reproducible piece of code atm. Can do it later today","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":18,"Q_Id":66386086,"Users Score":0,"Answer":"Bah.. stupid question. Sorry for anyone that read it. If you do module 2pi, then everything is the same","Q_Score":0,"Tags":"python","A_Id":66386806,"CreationDate":"2021-02-26T12:47:00.000","Title":"Subtracting angles of complex valued matrix","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've trained a binary classification model that takes a (128x128x3) image and then gives a binary value of 0 or 1. I then want to take a larger image, say (nxmx3), and apply a windowing function and have the model run a prediction on each window.\nI used skimage.util.view_as_windows to convert a (1024x1024x3) image, into a (897,897,128,128,3) numpy array. I now want to run each (i, j, 128,128,3) window through my model, and then place it in the same location. In the end, I'd like a (897,897) array containing the probability of that class existing.\nThe way I'm doing it now requires a for-loop that takes nearly 1-2 minutes to run through, while slowing down as the list containing the model predictions gets larger.\nIs there a way to vectorize this process? Perhaps flattening the numpy array, running model.predict() on it, and then creating a 2d-array with the same previous dimensions?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":94,"Q_Id":66404904,"Users Score":0,"Answer":"You can use fully convolutional networks which uses sliding window to predict output and it's not dependent on the input shape. replace your fully connected layers with convolutional layers with same output_shape and train it on (128x128x3) datasets.\nif you predict on 1024x1024 input image the network predict one label for each 128x128 regions.","Q_Score":1,"Tags":"python,numpy,tensorflow,keras,scikit-image","A_Id":66406974,"CreationDate":"2021-02-28T00:50:00.000","Title":"How to run model.predict() on a 5 dimensional array in Keras?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to find the mean of each column, across all rows, given a set of data. I've opened the csv file using sata = np.genfromtxt('movieRatingsDeidentified.csv',delimiter=','), and am currently trying to find the mean of each column across all rows using D1 = numpy.nanmean(sata,axis=0)however I'm getting an error message saying that sata is not defined, and is also not showing up in my variable explorer. It's incredibly frustrating as I have relatively little experience in programming and have only started using Spyder a few weeks ago.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":56,"Q_Id":66410691,"Users Score":0,"Answer":"Well, if it says that sata is not defined, you are most likely not opening the file properly. My guess is that you are not in the proper folder path. Use the package os to find your current working folder and change to the appropriate folder. The function os.getcwd() will show you in which folder you are and os.chdir(\"your\/target\/folder\") will lead you to the appropriate folder. Alternatively, instead of passing only the file name to np.genfromtxtyou can pass the full path.\nAlso, unless you have missing values (NaN) in your dataset, you should probably use the regular np.mean instead of np.nanmean.","Q_Score":0,"Tags":"python,numpy","A_Id":66410766,"CreationDate":"2021-02-28T15:29:00.000","Title":"How to find mean of a numpy array?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a dataframe imported from Excel. After importing I have checked there are lots of NAN values in the dataframe. When I convert dataframe columns to Str Object. There are no NAN values remains. My mean is that dataframe can't be able to count NAN values anymore. Those NAN values showed as nan in the dataframe. I actually wants those NAN to be empty cells in the dataframe like Excel. Any suggestion?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":43,"Q_Id":66414167,"Users Score":0,"Answer":"Look at .fillna()\nYou can use that to edit the NaNs before converting the column values to strings.","Q_Score":0,"Tags":"python,pandas","A_Id":66414280,"CreationDate":"2021-02-28T21:47:00.000","Title":"Python Pandas: After converting dataframe to Str NAN is no more NAN","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm looking at some tensorflow stuff and I understand for loops or atleast I think I do, however I came across for _ in range(20) and was wondering what is the meaning of the _ in this case. I am used to for x in range or for i in range stuff and understand those but haven't been able to understand what i've read on the underscore","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":20818,"Q_Id":66425508,"Users Score":19,"Answer":"When you are not interested in some values returned by a function we use underscore in place of variable name . Basically it means you are not interested in how many times the loop is run till now just that it should run some specific number of times overall.","Q_Score":15,"Tags":"python,python-3.x,machine-learning","A_Id":66425545,"CreationDate":"2021-03-01T16:02:00.000","Title":"What is the meaning of 'for _ in range()","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"In a specific column of my dataframe it does not convert to json and it stays like that\n[{'self': 'https:\/\/servicedesk.com\/rest\/api\/2\/c', 'value': 'EXANDAS', 'id': '10120'}]\nHow can i grab only the value or convert that column two three more columns in the existing dataframe?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":66,"Q_Id":66429044,"Users Score":0,"Answer":"Assuming your column is a list of dicts you can do\ndf[col].map(lambda x: x[0]['value'])\nto get the values","Q_Score":0,"Tags":"json,python-3.x,dataframe","A_Id":66429193,"CreationDate":"2021-03-01T20:15:00.000","Title":"Jira Json to dataframe with Python. Issue with one column which stays as json","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working on a python script that is designed to process some data, create a table if not exists, and truncate the table before inserting a refreshed dataset. I am using a role that has usage, read, write, create table permissions, as well stage permissions set as follows:\ngrant usage, read, write on future stages in schema to role \nI am using the write_pandas function in python via the snowflake connector. The documentation says that this function uses PUT and Copy Into commands:\nTo write the data to the table, the function saves the data to Parquet files, uses the PUT command to upload these files to a temporary stage, and uses the COPY INTO command to copy the data from the files to the table. You can use some of the function parameters to control how the PUT and COPY INTO
statements are executed.\nI still get the error message that I am unable to operate on the schema, and I am not sure what else I need to add. Does someone have the list of permissions that are required to run the write_pandas command?","AnswerCount":5,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":7614,"Q_Id":66431601,"Users Score":5,"Answer":"write_pandas() does not create the table automatically. You need to create the table by yourself if the table does not exist beforehand. For each time you run write_pandas(), it will just append the dataframe to the table you specified.\nOn the other hand, if you use df.to_sql(..., method=pd_writer) to write pandas dataframe into snowflake, it will create the table automatically for you, and you can use if_exists in to_sql() to specify different behaviors - append, replace, or fail - if the table already exists.","Q_Score":3,"Tags":"python,permissions,snowflake-cloud-data-platform,database-schema,connector","A_Id":67380436,"CreationDate":"2021-03-02T00:27:00.000","Title":"write_pandas snowflake connector function is not able to operate on table","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have been trying to utilise mutual_info_regression method from sklearn, I have updated sklearn to latest build which is 0.24.1 and when I checked the source code inside my conda env path there is folder and files for feature_selection.mutual_info_regression, but when I try to import it in my Jupiter notebook it throws this error ImportError: cannot import name 'mutual_info_regression' from 'sklearn.model_selection' (\/opt\/anaconda3\/envs\/\/lib\/python3.8\/site-packages\/sklearn\/model_selection\/__init__.py)\nI tried restarting kernel as well, but it is still not working, has anyone else faced this issue? Im using macOS 11.2.1 and conda 4.8.3 with Python3\nThanks","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":256,"Q_Id":66432634,"Users Score":0,"Answer":"I found the solution,\nI just had to restart my terminal and then it started working for some reason.\nI hope this helps anyone facing such problem in future\nThanks SO!","Q_Score":0,"Tags":"python,scikit-learn,pip,anaconda,lib","A_Id":66432686,"CreationDate":"2021-03-02T02:52:00.000","Title":"sklearn.feature_selection.mutual_info_regression not found","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"In python, if there are two variables being assigned a value in the same line, for example here\nimg_tensor, label = dataset[0]\nWhere dataset[0] is an array, what is actually going on? What does this do?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":37,"Q_Id":66433401,"Users Score":0,"Answer":"There can be two major cases while executing the line img_tensor, label = dataset[0].\nCase 1: If dataset[0] has a length of 2. As per comments it would assign the first index of dataset[0] to img_tensor and second index to label.\nCase 2: If len(dataset[0]) > 2 or len(dataset[0]) < 2. The line would produce ValueError yelling either \"too many values to unpack\" or \"not enough values to unpack\".\nIt can also result in a TypeError if dataset[0] is not an iterable\nThere might be other scenarios that are possible depending upon the type of dataset[0].","Q_Score":0,"Tags":"python,arrays","A_Id":66435635,"CreationDate":"2021-03-02T04:34:00.000","Title":"Two variables being assigned at the same time","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm a bit of a noob when it comes to large datasets and was hoping someone could point me in the right direction.\nI have two large data frames that i need to merge based on datetime.\nDataframe 1:\n\n250 million rows of data\nDatetime index\nColums containing motion sensor values\n\nDataframe 2:\n\n50 million row of data\nDatetime index\nColumns containing easting and northings\n\nI want to add easting and northings from dataframe2 to dataframe 1 based on the closest datetime. I have tried a few different methods (i.e. df.index.get_loc, df.interpolate) but the processing time is huge and memory becomes unstable very quickly. Is there a way to process this without iterating through the dataframes? Any help would be great.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":39,"Q_Id":66434101,"Users Score":1,"Answer":"pd.merge_asof will help match based on the closest time.","Q_Score":1,"Tags":"python,python-3.x,pandas,dataframe","A_Id":66434301,"CreationDate":"2021-03-02T06:02:00.000","Title":"How to efficiently combine two large Pandas dataframes by datetime","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to operate(sum) two 2d-vectors(NumPy.array) in python 3.\nI know I can use functions in NumPy, but I still want to know is there any package to support SSE instruction opreation in python 3? or any existing package with high efficiency to do that?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":134,"Q_Id":66435407,"Users Score":1,"Answer":"There's numpy-mkl which is Numpy compiled against Intel's Math Kernel Library.","Q_Score":0,"Tags":"python-3.x,sse","A_Id":66435487,"CreationDate":"2021-03-02T07:57:00.000","Title":"How to use SSE instruction in Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using trimesh python library. I want to overlay face normals ontop of face centroids. Is there any easy way to do that?\nPerhaps if there is an external library or helper script that can do this quickly that would also help. thanks","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":152,"Q_Id":66437422,"Users Score":1,"Answer":"I'm not sure what you mean by overlaying face normals. If it's just for visualization use libraries that can visualize normals for you like meshlab or open3d.\nIf the question is how to get the face centroids in trimesh, there's mesh.triangles_center.","Q_Score":0,"Tags":"python,graphics,mesh,trimesh","A_Id":70830739,"CreationDate":"2021-03-02T10:18:00.000","Title":"Trimesh get faces centroids \/ centers","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am training a unet model. I started training with my pc, but it was too slow as it didn't run with GPU. Therefore I started using Google colab for faster training (using GPU).\nI have the same dataset saved locally and in Google Drive and I also have the exact same code in colab and in my pc, except paths as I need to change them to read from my Google Drive files.\nMy problem is that the results of training the unet in my computer differ a lot from those obtained training the unet with Google colab.\nI don't know why this happens (I use the same seed in both and I have tested that I always obtain the same results locally if I use that seed).\nWhen I train the unet in my pc I obtain more or less 90% accuracy. However, when I train it using colab with GPU I only obtain 65%. I've also tried to use CPU in colab and I get the same issue.\nThanks","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":1959,"Q_Id":66446056,"Users Score":0,"Answer":"I also went through the exact same problem. For me the problem was with random split into train and test, It was just a coincidence that random split on colab got the good performance while bad on the local machine. Then just using random_state fixed the issues for me.\nE.g.:\ntrain_test_split(data, target, test_size=0.1, random_state=30, stratify=target)","Q_Score":1,"Tags":"python,tensorflow,keras,google-colaboratory,unity3d-unet","A_Id":70819902,"CreationDate":"2021-03-02T19:40:00.000","Title":"Different results on Google colab than local","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am most likely missing something obvious, but what approach\/model was used to train the Token vectors in spacy's english medium model? Was it word2vec? A deep learning architecture? Just curious on what was used to estimate those embeddings.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":57,"Q_Id":66446435,"Users Score":2,"Answer":"The English vectors are GloVe Common Crawl vectors. Most other languages have custom fastText vectors from OSCAR Common Crawl + Wikipedia. These sources should be included in the model metadata, but it looks like the vector information has been accidentally left out in the 3.0.0 model releases.","Q_Score":1,"Tags":"python,spacy","A_Id":66452704,"CreationDate":"2021-03-02T20:11:00.000","Title":"What is the model architecture used in spacy's token vectors (english)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to use or tools to solve the CVRP problem and I know can use routing.IsVehicleUsed(assignment, vehicle_id) method know the vehicle is used or not.\nCan I reuse the used vehicle.\nBecause I have a problem ,when I set data['num_vehicles'] = 1 or-tools returns no result but when I set data['num_vehicles'] = 4 I got a solution.\nIt cannot be modified the data['vehicle_capacities'] so I want to the used vehicle can start again when it return start point","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":65,"Q_Id":66451830,"Users Score":0,"Answer":"Once a vehicle reach its end node, it's over. End node are always the last node of a vehicle route.\nYou should create some dummy node (duplicate of depot) to simulate an unload please take a look at the refuel station example in the sample directory on github...","Q_Score":1,"Tags":"python-3.x,or-tools","A_Id":66471423,"CreationDate":"2021-03-03T06:25:00.000","Title":"Ortools CVRP reuse the used vehicle","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using Tensorflow to solve a regression problem with known dynamic components, that is, we are aware that the (singular) label at time t depends on some dynamic state of the environment, but this feature is unknown. The initial attempt to solve the problem via simple regression has, understandably, failed, confirming our assumption that there is some kind of dynamic influence by a feature we have no access to.\nHowever, the state of the environment at time t should be reflected somewhere in the features and labels (and in particular their interplay) known at times t0-n, where n > 0. Unfortunately, because of the nature of the problem, the output at time t heavily depends on the input at time t, about as much as it depends on the dynamic state of the environment. I am worried that this renders the approach I wanted to try ineffective - time series forecasting, in my understanding, would consider features from previous timesteps, but no inputs on the current timestep. Additionally, I know labels from previous timesteps, but not at the time at which I want to make my prediction.\nHere is a table to illustrate the problem:\n\n\n\n\nt\ninput\noutput\n\n\n\n\n0\nx(t=0)\ny(t=0)\n\n\n...\n...\n...\n\n\nt0-1\nx(t=t0-1)\ny(t=t0-1)\n\n\nt0\nx(t=t0)\ny(t=t0)=?\n\n\n\n\n\nHow can I use all the information at my disposal to predict the value of y(t=t0), using x(t=t0) (where x is the array of input features) and a defined window of features and labels at previous timesteps?\nIs there an established method for solving a problem like this, either using a neural net or perhaps even a different model?\nDoes this problem require a combination of methods, and if so, which ones might be suitable for tackling it?\n\nThe final model is meant to be deployed and continue working for future time windows as well. We know the size of the relevant time window to be roughly 100 time steps into the past.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":39,"Q_Id":66461368,"Users Score":0,"Answer":"The kind of problem I have described is, as I have since learned, linked to so-called exogenous variables. In my case, I require something called NNARX, which is similar to the ARMAX model at its core, but (as a neural net) can take non-linearity into account.\nThe general idea is to introduce an LSTM layer which acts as an Encoder for the historical input, which is then coupled to another input layer with the exogenous variables. Both are coupled at the so-called Decoder - the rest of the NN architecture.","Q_Score":1,"Tags":"python,tensorflow,machine-learning,neural-network,time-series","A_Id":66527744,"CreationDate":"2021-03-03T16:45:00.000","Title":"Neural Network Regression - Considering a dynamic state","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"My machine learning model dataset is cleaveland data base with 300 rows and 14 attributes--predicting whether a person has heart disease or not..\nBut aim is create a classification model on logistic regression...\nI preprocessed the data and ran the model with x_train,Y_train,X_test,Y_test.. and received avg of 82 % accuracy...\nSo to improve the accuracy I did remove features that are highly correlated to each other [as they would give the same inforamtion]\nAnd I did RFE[recursive feature elimination]\nfollowed by PCA[principle component analysis] for dimensionality reduction...\nStill I didnt find the dataset to be be better in accuracy..\nWhy is that?\nAlso why does my model shows different accuracy each time? is it beacuse of taking different x_train,Y_train,X_test,Y_test each time?\nShould i change my model for better accuracy?\nIs 80 % average good or bad accuracy?","AnswerCount":3,"Available Count":1,"Score":0.0665680765,"is_accepted":false,"ViewCount":990,"Q_Id":66473248,"Users Score":1,"Answer":"Should i change my model for better accuracy?\n\nAt least you could try to. The selection of the right model is highly dependend on the concrete use case. Trying out other approaches is never a bad idea :)\nAnother idea would be to get the two features with the highest variance via PCA. Then you could plot this in 2D space to get a better feeling if your data is linearily separable.\n\nAlso why does my model shows different accuracy each time?\n\nI am assuming you are using the train_test_split method of scikit-learn so split your data?\nBy default, this method shuffels your data randomized. Your could set the random_state parameter to a fixed value to obtain reproducable results.","Q_Score":1,"Tags":"python,machine-learning,logistic-regression","A_Id":66473508,"CreationDate":"2021-03-04T10:32:00.000","Title":"How to Increase accuracy and precision for my logistic regression model?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to detect anomalies on a time series that controls battery voltage output. I find that my original dataset has some outliers. In this case do I need to remove those points using InterQuartile Range (IQR) or Zscore? of course before using the LSTM keras model","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":224,"Q_Id":66477338,"Users Score":1,"Answer":"Removing or not removing outliers all depends on what you are trying to achieve. You write here that your goal is anomaly detection...so at first glance it seems like a poor idea to remove points or values that you are trying to detect. However, if you detect values that are of such naturethat they cannot even be due to plausible anomalies, then yes, you should remove them. In all other cases you should consider to keep them.","Q_Score":0,"Tags":"python,pandas,jupyter-notebook,statistics,outliers","A_Id":66479588,"CreationDate":"2021-03-04T14:44:00.000","Title":"Is it necessary to discard outliers before applying LSTM on time series","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am training a pretty intensive ML model using a GPU and what will often happen that if I start training the model, then let it train for a couple of epochs and notice that my changes have not made a significant difference in the loss\/accuracy, I will make edits, re-initialize the model and re-start training from epoch 0. In this case, I often get OOM errors.\nMy guess is that despite me overriding all the model variables something is still taking up space in-memory.\nIs there a way to clear the memory of the GPU in Tensorflow 1.15 so that I don't have to keep restarting the kernel each time I want to start training from scratch?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":161,"Q_Id":66482194,"Users Score":0,"Answer":"It depends on exactly what GPUs you're using. I'm assuming you're using NVIDIA, but even then depending on the exact GPU there are three ways to do this-\n\nnvidia-smi -r works on TESLA and other modern variants.\nnvidia-smi --gpu-reset works on a variety of older GPUs.\nRebooting is the only options for the rest, unfortunately.","Q_Score":0,"Tags":"python-3.x,tensorflow,gpu","A_Id":66482805,"CreationDate":"2021-03-04T20:00:00.000","Title":"Clearing memory when training Machine Learning models with Tensorflow 1.15 on GPU","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I updated my R to the most recent version 4.0 and tried to install the 'umx' package which worked fine when I had the 3.6.3 version. I then changed my R back to 3.6.3 version and the 'umx' package still won't install. I get the below error:\n\ninstalling source package \u2018kableExtra\u2019 ...\n** package \u2018kableExtra\u2019 successfully unpacked and MD5 sums checked\n** using staged installation\n** R\n** inst\n** byte-compile and prepare package for lazy loading\nError in dyn.load(file, DLLpath = DLLpath, ...) :\nunable to load shared object '\/Library\/Frameworks\/R.framework\/Versions\/3.6\/Resources\/library\/gdtools\/libs\/gdtools.so':\ndlopen(\/Library\/Frameworks\/R.framework\/Versions\/3.6\/Resources\/library\/gdtools\/libs\/gdtools.so, 6): Library not loaded: \/opt\/X11\/lib\/libcairo.2.dylib\nReferenced from: \/Library\/Frameworks\/R.framework\/Versions\/3.6\/Resources\/library\/gdtools\/libs\/gdtools.so\nReason: image not found\nCalls: ... asNamespace -> loadNamespace -> library.dynam -> dyn.load\nExecution halted\nERROR: lazy loading failed for package \u2018kableExtra\u2019\nremoving \u2018\/Library\/Frameworks\/R.framework\/Versions\/3.6\/Resources\/library\/kableExtra\u2019\nWarning in install.packages :\ninstallation of package \u2018kableExtra\u2019 had non-zero exit status\n\nThe downloaded source packages are in\n\u2018\/private\/var\/folders\/88\/d4_sv_l174vcbkn5f8r6ytjc0000gn\/T\/RtmpSb59yk\/downloaded_packages\u2019\nNot sure why this is as everything was fine before I updated my R, and my expectation was that it would be fine again when going back to my original R version but this is not the case. Any help with this would be greatly appreciated!\nThanks,\nRionagh","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":162,"Q_Id":66494953,"Users Score":0,"Answer":"I was getting the same error for the last 2 days and then I wrote an issue in GitHub to the person who made this package. One of people answered my question by suggesting to update the version of R. Same like you, I was using 3.6.2 version of R and then I followed his suggestion, I updated my R version to 4.0.4 He also suggested me to upload \"systemfonts\" package before I upload the kableExtra by writing this code install.packages('systemfonts', dependencies = TRUE). Yet I think it was because of the old version that \u0131 was using. So the bottomline is, if you update your R to 4.0.4, and run these 2 codes;\ninstall.packages('systemfonts', dependencies = TRUE)\ninstall.packages('kableExtra', repos='https:\/\/cran.ma.imperial.ac.uk\/')\nit is just going to work I guess. I mean it worked for me.","Q_Score":2,"Tags":"python,r,installation","A_Id":66537632,"CreationDate":"2021-03-05T15:08:00.000","Title":"Not able to install umx packaging in R 3.6.3","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a Dataframe with the following structure\n\n\n\n\ntime_start\ntime_end\nlabel\n\n\n\n\ntime\ntime + 1\naction\n\n\ntime + 1\ntime + 2\nsome_other_action\n\n\n\n\nI would like to take see the diff of time_start and previous row time_end. in this case (time + 1) - (time + 1) = 0\nI have tried df.diff, but that only yields the diff within either columns or rows.\nAny ideas of how I can perform this \"jagged diff\"?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":89,"Q_Id":66494998,"Users Score":1,"Answer":"The solution was what @Quang Hoang mentioned in a comment.\ndf['time_start'] - df['time_end'].shift()","Q_Score":0,"Tags":"python,pandas,datetime","A_Id":66495298,"CreationDate":"2021-03-05T15:10:00.000","Title":"Pandas dataframe diff between rows with column offset","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"So I had to create a linear regression in python, but this dataset has over 800 columns. Is there anyway to see what columns are contributing most to the linear regression model? Thank you.","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":107,"Q_Id":66499686,"Users Score":0,"Answer":"Look at the coefficients for each of the features. Ignore the sign of the coefficient:\n\nA large absolute value means the feature is heavily contributing.\nA value close to zero means the feature is not contributing much.\nA value of zero means the feature is not contributing at all.","Q_Score":0,"Tags":"python","A_Id":66499816,"CreationDate":"2021-03-05T21:11:00.000","Title":"Top features of linear regression in python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Let's say I have a matrix M which looks like:\n[a b c l]\n[d e f k]\n[g h i o]\nI have to pick one element from every column such that I can minimise the maximum value of all those elements.\nFor eg. If I pick a,e,i,k my answer would be max(a,e,i,k)\nTo find the most optimum solution, is there any approach which is better than O(n^3)?\nI would appreciate some sort of pseudocode\/snippet of code if possible.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":43,"Q_Id":66505219,"Users Score":0,"Answer":"Pick the minimum value of each column and compute the maximum (M) of those. Althrough there would be other combinations that produce the same maximum value, M cannot be further reduced because any value in M's column would be larger and picking (smaller) values in other columns would not change M which is the smallest in its own column.\nIf you were looking to minimize the total of these values, then there would be a need for some additional optimization, perhaps using dynamic programming. As it is, the problem is simple math.","Q_Score":0,"Tags":"python,matrix,dynamic-programming","A_Id":66506270,"CreationDate":"2021-03-06T11:38:00.000","Title":"Pick optimal combination from matrix","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a dataset that I need to process batchwise (due to API restrictions).\nThe sum of the column text_lenth of a batch cannot exceed 1000. And the maximum number of rows in a batch cannot be greater than 5.\nFor that I would like to add batch numbers to the single batches in order to process the data based on batch_numbers later.\nHow can I achieve that in pyspark (in Databricks). I am pretty new to all of this that I don't even know what to look for online.\nI really appreciate your help.\nThe tables below illustrate what I am trying to achieve:\nOriginal table\n\n\n\n\nid\ntext_length\n\n\n\n\n1\n500\n\n\n2\n400\n\n\n3\n200\n\n\n4\n300\n\n\n5\n100\n\n\n6\n100\n\n\n7\n100\n\n\n8\n100\n\n\n9\n100\n\n\n10\n300\n\n\n\n\nResulting table\n\n\n\n\nid\ntext_length\nbatch_number\n\n\n\n\n1\n500\n1\n\n\n2\n400\n1\n\n\n3\n200\n2\n\n\n4\n300\n2\n\n\n5\n100\n2\n\n\n6\n100\n2\n\n\n7\n100\n2\n\n\n8\n100\n3\n\n\n9\n100\n3\n\n\n10\n300\n3","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":411,"Q_Id":66507942,"Users Score":1,"Answer":"Unlike mck states, this is not the \"partition problem\".\nWhat the issues are, are that 1) Spark works with partitions - not just 1 such partition in order to be effective and 2) there is not a grouping attribute to ensure that 'batches' can form naturally or be distilled naturally within a partition only. Moreover, can we have negative numbers or fractions? - this is not stated. Max 5 entries it is stated, however.\n\nThis means that processing would need to be just based on one partition, but it may not be big enough aka OOM.\n\nTrying to process per partition is pointless as all work would need to be done per partition N, N+1, and so on die to offset effects in the partition N-1. I have worked out a solution here on SO that took partition boundaries into account, but this is against the principle of Spark and the use case was more simplistic.\n\nActually not a Spark use case. It is a sequential algorithm as opposed to parallel algorithm, use PL\/SQL, Scala, JAVA, C++.\n\nThe only way would be:\n\nlooping over a fixed size partition that has had zipWithIndex applied globally (for safety)\n\nprocess with Scala into batches - temp result\ntake all items from last created batch and union with next partition\nremove last batch from temp results\nrepeat cycle\n\n\n\n\nNB: Approximations to get around partitioning boundary aspects of data seem not to work --> the other answer proves that in fact. You get a compromise result, not the actually answer. And to correct it is not on fact that easy as batches have gaps and may be in other partitions as result of grouping.","Q_Score":3,"Tags":"python,dataframe,apache-spark,pyspark","A_Id":66517929,"CreationDate":"2021-03-06T16:25:00.000","Title":"Add batch number to DataFrame based on moving sum in spark","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Why does the numpy.histogram return values of hist and bin_edges not have the same size? Instead bin_edges has (length(hist)+1). This becomes an issue when attempting a best fit line for the histogram because then the two operates have different sizes. What can I do to make the two match? Do I just trim off the last value from bin_edges? Which value from bin_edges doesn't correspond to its respective hist value?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":280,"Q_Id":66511554,"Users Score":0,"Answer":"If I ask you to count the number of people in a room by age ranges, you might tell me:\n\n10-17 years: one person\n18-29 years: three people\n30-50 years: two people\n\nThat's three bins but four edges (10, 18, 30, 50 in the way NumPy reports edges).\nIf you want to convert those four edges to three values which somehow identify the bins, you could:\n\nUse the lower value to represent each range (i.e. discard the last edge returned by NumPy).\nUse the upper value.\nUse the midpoint of each range.\nUse the mean, median or mode of each group's values.\n\nIt's up to you, NumPy isn't making this choice for you.","Q_Score":0,"Tags":"python,numpy","A_Id":66511605,"CreationDate":"2021-03-06T22:59:00.000","Title":"numpy.histogram return values aren't the same size","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Hello I have designed some algorithms that we would like to implement in our company's software (start-up) but some of them take too long (10-15 min) as it is handling big datasets.\nI am wondering if using for example Google Cloud to run my scripts, as it would use more nodes, it would make my algorithm to run faster.\nIs it the same to run a script locally in Jupyter for instance than running it within Cloud?\nThinking of using Spark too.\nThank you","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":35,"Q_Id":66535075,"Users Score":1,"Answer":"I think the only applicable answer is \"it depends\". The cloud is just \"someone else's computer\", so if it runs faster or not depends on the cloud server it's running on. For example if it is a data-intensive task with a lot of I\/O it might run faster on a server with a SSD than on your local machine with a HDD. If it's a processor intensive task, it might run faster if the server has a faster CPU than your local machine has. You get the point.","Q_Score":0,"Tags":"python,cloud","A_Id":66535186,"CreationDate":"2021-03-08T18:17:00.000","Title":"Does running scripts from Cloud (AWS\/Google\/Azure) make my algorithms faster?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":1,"Web Development":1},{"Question":"When I run test example: .\/bin\/run-example SparkPi 10 I get error below.\nEDIT:\nProblem is due to the fact, that I switched ti WIFI instead of Ethernet and this changed localhost. @mck direction to previous solutionhelped.\nSolution:\nAdd SPARK_LOCAL_IP in load-spark-env.sh file located at spark\/bin directory\nexport SPARK_LOCAL_IP=\"127.0.0.1\"\nI get error:\n\n WARNING: An illegal reflective access operation has occurred\n WARNING: Illegal reflective access by org.apache.spark.unsafe.Platform (file:\/home\/d\/spark\/jars\/spark-unsafe_2.12-3.1.1.jar) to constructor java.nio.DirectByteBuffer(long,int)\n WARNING: Please consider reporting this to the maintainers of org.apache.spark.unsafe.Platform\n WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations\n WARNING: All illegal access operations will be denied in a future release\n 2021-03-09 15:37:39,164 INFO spark.SparkContext: Running Spark version 3.1.1\n 2021-03-09 15:37:39,214 INFO resource.ResourceUtils: ==============================================================\n 2021-03-09 15:37:39,215 INFO resource.ResourceUtils: No custom resources configured for spark.driver.\n 2021-03-09 15:37:39,215 INFO resource.ResourceUtils: ==============================================================\n 2021-03-09 15:37:39,216 INFO spark.SparkContext: Submitted application: Spark Pi\n 2021-03-09 15:37:39,240 INFO resource.ResourceProfile: Default ResourceProfile created, executor resources: Map(cores -> name: cores, amount: 1, script: , vendor: , memory -> name: memory, amount: 1024, script: , vendor: , offHeap -> name: offHeap, amount: 0, script: , vendor: ), task resources: Map(cpus -> name: cpus, amount: 1.0)\n 2021-03-09 15:37:39,257 INFO resource.ResourceProfile: Limiting resource is cpus at 1 tasks per executor\n 2021-03-09 15:37:39,259 INFO resource.ResourceProfileManager: Added ResourceProfile id: 0\n 2021-03-09 15:37:39,335 INFO spark.SecurityManager: Changing view acls to: d\n 2021-03-09 15:37:39,335 INFO spark.SecurityManager: Changing modify acls to: d\n 2021-03-09 15:37:39,335 INFO spark.SecurityManager: Changing view acls groups to: \n 2021-03-09 15:37:39,335 INFO spark.SecurityManager: Changing modify acls groups to: \n 2021-03-09 15:37:39,335 INFO spark.SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set(d); groups with view permissions: Set(); users with modify permissions: Set(d); groups with modify permissions: Set()\n 2021-03-09 15:37:39,545 WARN util.Utils: Service 'sparkDriver' could not bind on a random free port. You may check whether configuring an appropriate binding address.\n 2021-03-09 15:37:39,557 WARN util.Utils: Service 'sparkDriver' could not bind on a random free port. You may check whether configuring an appropriate binding address.\n 2021-03-09 15:37:39,572 WARN util.Utils: Service 'sparkDriver' could not bind on a random free port. You may check whether configuring an appropriate binding address.\n 2021-03-09 15:37:39,585 WARN util.Utils: Service 'sparkDriver' could not bind on a random free port. You may check whether configuring an appropriate binding address.\n 2021-03-09 15:37:39,597 WARN util.Utils: Service 'sparkDriver' could not bind on a random free port. You may check whether configuring an appropriate binding address.\n 2021-03-09 15:37:39,608 WARN util.Utils: Service 'sparkDriver' could not bind on a random free port. You may check whether configuring an appropriate binding address.\n 2021-03-09 15:37:39,612 WARN util.Utils: Service 'sparkDriver' could not bind on a random free port. You may check whether configuring an appropriate binding address.\n 2021-03-09 15:37:39,641 WARN util.Utils: Service 'sparkDriver' could not bind on a random free port. You may check whether configuring an appropriate binding address.\n 2021-03-09 15:37:39,646 WARN util.Utils: Service 'sparkDriver' could not bind on a random free port. You may check whether configuring an appropriate binding address.\n 2021-03-09 15:37:39,650 WARN util.Utils: Service 'sparkDriver' could not bind on a random free port. You may check whether configuring an appropriate binding address.\n 2021-03-09 15:37:39,654 WARN util.Utils: Service 'sparkDriver' could not bind on a random free port. You may check whether configuring an appropriate binding address.\n 2021-03-09 15:37:39,658 WARN util.Utils: Service 'sparkDriver' could not bind on a random free port. You may check whether configuring an appropriate binding address.\n 2021-03-09 15:37:39,663 WARN util.Utils: Service 'sparkDriver' could not bind on a random free port. You may check whether configuring an appropriate binding address.\n 2021-03-09 15:37:39,673 WARN util.Utils: Service 'sparkDriver' could not bind on a random free port. You may check whether configuring an appropriate binding address.\n 2021-03-09 15:37:39,676 WARN util.Utils: Service 'sparkDriver' could not bind on a random free port. You may check whether configuring an appropriate binding address.\n 2021-03-09 15:37:39,682 WARN util.Utils: Service 'sparkDriver' could not bind on a random free port. You may check whether configuring an appropriate binding address.\n 2021-03-09 15:37:39,705 ERROR spark.SparkContext: Error initializing SparkContext.\n java.net.BindException: Cannot assign requested address: Service 'sparkDriver' failed after 16 retries (on a random free port)! Consider explicitly setting the appropriate binding address for the service 'sparkDriver' (for example spark.driver.bindAddress for SparkDriver) to the correct binding address.\n at java.base\/sun.nio.ch.Net.bind0(Native Method)\n at java.base\/sun.nio.ch.Net.bind(Net.java:455)\n at java.base\/sun.nio.ch.Net.bind(Net.java:447)\n at java.base\/sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:227)\n at io.netty.channel.socket.nio.NioServerSocketChannel.doBind(NioServerSocketChannel.java:134)\n at io.netty.channel.AbstractChannel$AbstractUnsafe.bind(AbstractChannel.java:550)\n at io.netty.channel.DefaultChannelPipeline$HeadContext.bind(DefaultChannelPipeline.java:1334)\n at io.netty.channel.AbstractChannelHandlerContext.invokeBind(AbstractChannelHandlerContext.java:506)\n at io.netty.channel.AbstractChannelHandlerContext.bind(AbstractChannelHandlerContext.java:491)\n at io.netty.channel.DefaultChannelPipeline.bind(DefaultChannelPipeline.java:973)\n at io.netty.channel.AbstractChannel.bind(AbstractChannel.java:248)\n at io.netty.bootstrap.AbstractBootstrap$2.run(AbstractBootstrap.java:356)\n at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:164)\n at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:472)\n at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:500)\n at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)\n at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)\n at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)\n at java.base\/java.lang.Thread.run(Thread.java:834)\n 2021-03-09 15:37:39,723 INFO spark.SparkContext: Successfully stopped SparkContext\n Exception in thread \"main\" java.net.BindException: Cannot assign requested address: Service 'sparkDriver' failed after 16 retries (on a random free port)! Consider explicitly setting the appropriate binding address for the service 'sparkDriver' (for example spark.driver.bindAddress for SparkDriver) to the correct binding address.\n at java.base\/sun.nio.ch.Net.bind0(Native Method)\n at java.base\/sun.nio.ch.Net.bind(Net.java:455)\n at java.base\/sun.nio.ch.Net.bind(Net.java:447)\n at java.base\/sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:227)\n at io.netty.channel.socket.nio.NioServerSocketChannel.doBind(NioServerSocketChannel.java:134)\n at io.netty.channel.AbstractChannel$AbstractUnsafe.bind(AbstractChannel.java:550)\n at io.netty.channel.DefaultChannelPipeline$HeadContext.bind(DefaultChannelPipeline.java:1334)\n at io.netty.channel.AbstractChannelHandlerContext.invokeBind(AbstractChannelHandlerContext.java:506)\n at io.netty.channel.AbstractChannelHandlerContext.bind(AbstractChannelHandlerContext.java:491)\n at io.netty.channel.DefaultChannelPipeline.bind(DefaultChannelPipeline.java:973)\n at io.netty.channel.AbstractChannel.bind(AbstractChannel.java:248)\n at io.netty.bootstrap.AbstractBootstrap$2.run(AbstractBootstrap.java:356)\n at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:164)\n at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:472)\n at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:500)\n at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)\n at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)\n at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)\n at java.base\/java.lang.Thread.run(Thread.java:834)\n 2021-03-09 15:37:39,730 INFO util.ShutdownHookManager: Shutdown hook called\n 2021-03-09 15:37:39,731 INFO util.ShutdownHookManager: Deleting directory \/tmp\/spark-b53dc8d9-adc8-454b-83f5-bd2826004dee","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":284,"Q_Id":66548256,"Users Score":0,"Answer":"Solution: Add SPARK_LOCAL_IP in load-spark-env.sh file located at spark\/bin directory export SPARK_LOCAL_IP=\"127.0.0.1\"","Q_Score":0,"Tags":"python,apache-spark,pyspark,apache-spark-sql","A_Id":66551389,"CreationDate":"2021-03-09T13:56:00.000","Title":"spark : Cannot assign requested address","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":1,"Web Development":0},{"Question":"I was using TensorFlow to train a machine learning model.\nI use the command model.save('my_model.h5') to save my model .\nWhere is the exact location path that the model file is saved?\nWill it simply overwrite the old one if I run the code again?\nMany thanks.","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":506,"Q_Id":66576166,"Users Score":0,"Answer":"Yes.Model will saved in the current directory and the model will overwrite the oldone when saving the same model with same name.if you need various model just change the name of the model while saving the model each time.","Q_Score":0,"Tags":"python,tensorflow","A_Id":66579179,"CreationDate":"2021-03-11T03:45:00.000","Title":"Where is the file that is saved by model.save() command","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":1},{"Question":"list = [['100', '88', '', ''], ['100', '', '68', ''], ['100', '', '', '58'],['102', '28', '', ''], ['102', '', '2', ''], ['104', '11', '', ''], ['104', '', '2', ''], ['110', '2', '', ''], ['202', '', '14', ''], ['202', '37429', '', '']]\nneed to merge the sub list on first index value.\noutput = [['100', 88, '68', '58'], ['102', 28, '2', ''],['104', 11, '2', ''],['110', 2, '', ''],['202', '37429', 14, '']]","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":136,"Q_Id":66576680,"Users Score":0,"Answer":"The more basic way is to make two nested loops, write a condition if the first index match, move them to a new list.\nYou can try to convert them to numpy array which will make them a 2d array then you can compare easier","Q_Score":0,"Tags":"python,data-structures","A_Id":66576735,"CreationDate":"2021-03-11T04:53:00.000","Title":"Merge sublists of nested list if first index element match","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have array:\nx = np.array([1, 41, 32, 2, -8, 0, -97, 11])\nIf x[i] > 0, x[i] = 1\nIf x[i] < 0, x[i] = -1\nIf x[i] == 0, x[i] = 0\nSo expected output:\nx = np.array([1, 1, 1, 1, -1, 0, -1, 1])\nIs there a way to do this with a one liner in numpy without any loops? I wanted to use np.where but it only takes 2 conditions whereas I have 3. Thanks.","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":93,"Q_Id":66581053,"Users Score":1,"Answer":"Indeed it takes 3 parameters:\nx = np.where(x > 0 , x, 1)","Q_Score":2,"Tags":"python,arrays,numpy","A_Id":66581174,"CreationDate":"2021-03-11T10:50:00.000","Title":"Replacing values in numpy array based on multiple conditions without using any loops","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a TXT and CSV files with delimiter as \" ^@ \" (was able to view this in VIM editor, in notepad++ it shows as null )\nI want to use this as column separator for dataframe in Python(pandas). What should i use?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":176,"Q_Id":66592081,"Users Score":0,"Answer":"df = pd.read_csv(fl, sep='\\^\\@',engine='python') \nTry this if it works!","Q_Score":1,"Tags":"python,pandas,dataframe","A_Id":66592172,"CreationDate":"2021-03-11T23:32:00.000","Title":"read TXT file with delimiter as ^@ using pandas","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to sort a array in place like [3,2,1,2,4,5,3] so that it is in sorted order ascending but with all duplicates grouped at the end in sorted order. So the result for the array would be [1,4,5,2,2,3,3]. How can I do this without using python built in sort()?","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":84,"Q_Id":66606418,"Users Score":1,"Answer":"Do it in two phases.\n\nJust sort the array in-place with your favorite in-place sorting algorithm\nScanning sorted array right to left, find the first DU subarray (where D is a bunch of duplicate values, and U is a tail of unique elements). Make it into UD. Keep going.\n\nThe second phase completes in O(n).","Q_Score":0,"Tags":"python,arrays,algorithm,sorting,data-structures","A_Id":66606869,"CreationDate":"2021-03-12T19:58:00.000","Title":"Sorting array ascending with duplicates at the end also sorted ascending","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"#Adjust Date Info\nTSLA['date'] = TSLA['date'].astype(str)\nTSLA['date'] = pd.to_datetime(TSLA['date'])\nThe datatype of both columns is object.\nIve tried using .astype(str) on the date column thenn using a lambda function to extract the YYYY-MM-DD but the datatype doesn't change. It doesn't throw up an error either when applying the .astype(str)\n.to_datetime doesn't work either.\nThere are no missing values in either column. I'd appreciate any opinions as to what i'm doing incorrectly?\nSince i am unable to add images for now, the date column has the following values: YYYY-MM-DD HH-MM-SS-HH-MM-SS","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":50,"Q_Id":66611315,"Users Score":1,"Answer":"Alright, it seems that\nTSLA['date'] = pd.to_datetime(TSLA['date'],utc = True)\nfollowed by:\nTSLA['date'] = TSLA['date'].dt.date\ngot me the values i wanted i.e. YYYY-MM-DD.","Q_Score":0,"Tags":"python,pandas,dataframe,data-preprocessing","A_Id":66611900,"CreationDate":"2021-03-13T08:03:00.000","Title":"I'm having trouble extracting the year from the date column of this particular dataset","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have the below columns in excel file i need to find the total runtime using python pandas.\n\n\n\n\nStage\nJobName\nBaseLineStartTime\nBaseLineEndTime\nStartTime-2Mar21\nEndTime-2Mar21\n\n\n\n\nApp1\nJobName1\n20:00:00\n20:11:45\n20:05:31\n20:18:43\n\n\nApp2\nJobName2\n20:00:00\n20:12:11\n20:05:31\n20:23:11\n\n\nApp9\nJobNamex\n20:11:46\n20:25:41\n20:23:12\n20:43:33\n\n\nDay1\nJobName1\n20:25:42\n20:30:42\n20:43:44\n20:48:44\n\n\nDay2\nJobName2\n20:30:43\n20:31:43\n20:48:45\n20:49:50\n\n\nDay2\nJobName3\n20:30:43\n20:40:43\n20:48:45\n20:58:45\n\n\n\n\nNote: I will have more columns based on the runtime dates.\nTo find the total run time using the logic (App9(EndTime) - App1 (StartTime) & (Day2(EndTime of jobname2 or jobname3 which runs later) - Day1(StartTime)\nI need to print the result in below format\n\n\n\n\nStage\nBaseLineRunTime\nRuntime-2Mar21\n\n\n\n\nApp\n00:25:41\n00:38:02\n\n\nDay\n00:15:01\n00:15:01","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":40,"Q_Id":66621093,"Users Score":0,"Answer":"I tried this using the below option not sure if its the best\nNewElapsedTime = time_csv[time_csv['Stage'].str.contains('App')] MaxEndTime = datetime.strptime(max(NewElapsedTime['EndTime'],'%H:%M:%S') MinStartTime = datetime.strptime(max(NewElapsedTime['StartTime'],'%H:%M:%S') print(MaxEndTime - MinStartTime)\nNext trying to loop the columns and store these results.","Q_Score":0,"Tags":"python,pandas,numpy","A_Id":66631198,"CreationDate":"2021-03-14T04:29:00.000","Title":"To determine total runtime from excel using python pandas","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I need a method to get mouse position without mouse movement or mouse click using OpenCV in python.\nEVENT_MOUSEMOVE returns the position only when there is movement, but as I mentioned above, I want to get position without movement or click.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":67,"Q_Id":66656165,"Users Score":1,"Answer":"Not sure I understand this. If you register a callback for EVENT_MOUSEMOVE you can get the current position and store it in a global variable. Then you can get the position as often as you like, say every 50ms on a timer, even without further movement, by looking at the global variable. By definition, the mouse must be still at the last place it was when it last moved if it hasn't moved since.","Q_Score":0,"Tags":"python,opencv","A_Id":66657719,"CreationDate":"2021-03-16T13:27:00.000","Title":"Is there a way to get mouse position in opencv without mouse movement or click?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"(This is a mix between code and 'user' issue, but since i suspect the issue is code, i opted to post in StackOverflow instead of SuperUser Exchange).\nI generated a .csv file with pandas.DataFrame.to_csv() method. This file consists in 2 columns: one is a label (text) and another is a numeric value called accuracy (float). The delimiter used to separate columns is comma (,) and all float values are stored with dot ponctuation like this: 0.9438245862\nEven saving this column as float, Excel and Google Sheets infer its type as text. And when i try to format this column as number, they ignore \"0.\" and return a very high value instead of decimals like:\n(text) 0.9438245862 => (number) 9438245862,00\nI double-checked my .csv file reimporting it again with pandas.read_csv() and printing dataframe.dtypes and the column is imported as float succesfully.\nI'd thank for some guidance on what am i missing.\nThanks,","AnswerCount":3,"Available Count":2,"Score":1.2,"is_accepted":true,"ViewCount":204,"Q_Id":66656487,"Users Score":0,"Answer":"By itself, the csv file should be correct. Both you and Pandas know what delimiter and floating point format are. But Excel might not agree with you, depending on your locale. A simple way to make sure is to write a tiny Excel sheet containing on first row one text value and one floating point one. You then export the file as csv and control what delimiter and floating point formats are.\nAFAIK, it is much more easy to change your Python code to follow what your Excel expects that trying to explain Excel that the format of CSV files can vary...\n\nI know that you can change the delimiter and floating point format in the current locale in a Windows system. Simply it is a global setting...","Q_Score":0,"Tags":"python,pandas,csv,floating-point","A_Id":66657153,"CreationDate":"2021-03-16T13:47:00.000","Title":"CSV cannot be interpreted by numeric values","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"(This is a mix between code and 'user' issue, but since i suspect the issue is code, i opted to post in StackOverflow instead of SuperUser Exchange).\nI generated a .csv file with pandas.DataFrame.to_csv() method. This file consists in 2 columns: one is a label (text) and another is a numeric value called accuracy (float). The delimiter used to separate columns is comma (,) and all float values are stored with dot ponctuation like this: 0.9438245862\nEven saving this column as float, Excel and Google Sheets infer its type as text. And when i try to format this column as number, they ignore \"0.\" and return a very high value instead of decimals like:\n(text) 0.9438245862 => (number) 9438245862,00\nI double-checked my .csv file reimporting it again with pandas.read_csv() and printing dataframe.dtypes and the column is imported as float succesfully.\nI'd thank for some guidance on what am i missing.\nThanks,","AnswerCount":3,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":204,"Q_Id":66656487,"Users Score":0,"Answer":"A short example of data would be most useful here. Otherwise we have no idea what you're actually writing\/reading. But I'll hazard a guess based on the information you've provided.\nThe pandas dataframe will have column names. These column names will be text. Unless you tell Excel\/Sheets to use the first row as the column name, it will have to treat the column as text. If this isn't the case, could you perhaps save the head of the dataframe to a csv, check it in a text editor, and see how Excel\/Sheets imports it. Then include those five rows and two columns in your follow up.","Q_Score":0,"Tags":"python,pandas,csv,floating-point","A_Id":66656683,"CreationDate":"2021-03-16T13:47:00.000","Title":"CSV cannot be interpreted by numeric values","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm in a text2voice(indonesian language) project.I installed g2p-seq2seq for text2phoneme, it contains some codes from tf.contrib so only run with tf1.\nRecently I got a new phoneme2voice model which only support tf2. Is there anyway to make them run in one project?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":517,"Q_Id":66672932,"Users Score":0,"Answer":"This depends on your ultimate goal. If you want to be able to run the Tensorflow 2 model eagerly in the same python instance or tensorflow instance as a Tensorflow 1 model running in compatibility mode, you will be in a world of trouble. Once you turn on compatibility mode or turn off eager execution, you cannot turn it back on.\nI tried to do this for my own project. My quick fix was making a temporary untrainable copy of the model using the weights and biases which have to be extracted and stored in a some format (I suggest pickle files) that can be opened in the script which makes temporary models without causing an instantiation of tensorflow 1 or tensorflow 2 running in compat mode.\nUltimately, I had to completely rebuild the Tensorflow 1.X model creation and training script in Tensorflow 2.\nIf you don't need to run them in the same exact script with eager execution for the Tensorflow 2 model then is might... might work to just use compat mode. I know that hearing this sucks, but there really isn't much you can do if the conditions I stated apply to you.\nTLDR - It depends on exactly what you want or need, but the foolproof method is just completely rebuilding the model in Tensorflow 2.","Q_Score":0,"Tags":"python,tensorflow,pip,tensorflow2.0","A_Id":66752785,"CreationDate":"2021-03-17T12:16:00.000","Title":"Is there anyway to run tensorflow1 and tensorflow2 in one project?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to convert a directory of RGB images to a numpy array but the resulting array is way bigger than the sum of sizes of all the images put together. What is going on here?","AnswerCount":2,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":399,"Q_Id":66682344,"Users Score":2,"Answer":"That's because image files are usually compressed, which means that the stored data will be smaller than the original file containing all pixel data, when you open a image using PIL, for example, you'll get access to all RGB values of all pixels, so, there's more data 'cus it's uncompressed.","Q_Score":1,"Tags":"python,python-3.x,numpy","A_Id":66682833,"CreationDate":"2021-03-17T22:47:00.000","Title":"Numpy array bigger than the total size of images it is made up of","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I use M1 Mac. But cv2 doesn't work in M1 Mac.\nI need to use the code below.\nimport cv2\nimgs_omni = np.array([cv2.resize(plt.imread(dirs), dsize=(58, 33)) for dirs in imgs_omni_dir])\nHow can I replace cv2.resize to other library or code?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":167,"Q_Id":66686059,"Users Score":0,"Answer":"please elaborate more on why exactly cv2 doesn't work in your M1 Mac. Did you install openCV packages? And what platform are you using to implement the code? And what have you done to make sure nothing you try is not working?\nThere's some replacement similar to cv2, but it may or may not help due to the vagueness of your question:\n\nnumpy.resize() which can be found after importing numpy.\nanother one is the resize() function from skimage.\n\nBoth of the mentioned packages have well elaborated documentations. Please do, go ahead and read.","Q_Score":0,"Tags":"python,replace,cv2,opencv-python,apple-m1","A_Id":66686292,"CreationDate":"2021-03-18T06:48:00.000","Title":"How to replace cv2.resize() in python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"My task is to use a given user-defined function to create a dataset for a specific region.\nI've insert my specific data in the function\nBut only got this error:\nKeyError: \"[' magType ' ' nst' ' gap' ' dmin ' ' rms' ' place ' ' type '\\n ' horizontalError ' ' depthError ' ' magError ' ' magNst ' ' status '\\n ' locationSource ' ' magSource ' ' net' 'id' ' updated '] not found in axis\"\nHow do I solve this problem? Because when I look at my data I got all this information (magType etc.)","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":40,"Q_Id":66688051,"Users Score":0,"Answer":"The problem is that the columns you have for the pd.DataFrame you fetch from the url are;\n['time', 'latitude', 'longitude', 'depth', 'mag', 'magType', 'nst', 'gap', 'dmin', 'rms', 'net', 'id', 'updated', 'place', 'type', 'horizontalError', 'depthError', 'magError', 'magNst', 'status', 'locationSource', 'magSource']\nWhich does not match with the column names you inserted into the drop function. Reformat the column names [\" magType \",\" nst\",\" gap\",\" dmin \",\" rms\",\" place \",\" type \" ,\" horizontalError \",\" depthError \",\" magError \",\" magNst \",\" status \",\" locationSource \",\" magSource \",\" net\",\"id\",\" updated \"] in the drop function exactly matching with your pd.DataFrame object data.\nPS: You might wanna look into fstrings or .format. That will make your code look a lot cleaner.\nSecond PS: You also might want to not recursively concatanate data. As data gets bigger, the process will be remarkable slower. The better way to do it is create a list (e.g. dfList) and append the list with the dataframes you fetch from the urls. And then use the function pd.concat(dfList). Cheers!","Q_Score":0,"Tags":"python","A_Id":66688216,"CreationDate":"2021-03-18T09:17:00.000","Title":"User-defined function to create a dataset","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"How can I load a dataset for person reidentification. In my dataset there are two folders train and test.","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":36,"Q_Id":66688472,"Users Score":0,"Answer":"Checkout modules csv (import csv) or load your dataset via open(filename, \u201er\u201c) or so. It might be easiest if you provide more context\/info.","Q_Score":0,"Tags":"python-3.x,tensorflow2.0,spyder","A_Id":66752753,"CreationDate":"2021-03-18T09:45:00.000","Title":"How can I load my own dataset for person?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"How can I load a dataset for person reidentification. In my dataset there are two folders train and test.","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":36,"Q_Id":66688472,"Users Score":0,"Answer":"I wish I could provide comments, but I cannot yet. Therefore, I will \"answer\" your question to the best of my ability.\nFirst, you should provide a general format or example content of the dataset. This would help me provide a less nebulous answer.\nSecond, from the nature of your question I am assuming that you are fairly new to python in general. Forgive me if I'm wrong in my assumption. With that assumption, depending on what kind of data you are trying to load (i.e. text, numbers, or a mixture of text and numbers) there are various ways to load the data. Some of the methods are easier than others. If you are strictly loading numbers, I suggest using numpy.loadtxt(). If you are using text, you could use the Pandas package, or if it's in a CSV file you could use the built-in (into Python that is) CSV package. Alternatively, if it's in a format that Tensorflow can read, you could use the provided load data functions.\nOnce you have loaded your data you will need to separate the data into the input and output values. Considering that Tensorflow models accept either lists or numpy arrays, you should be able to use these in your training and testing steps.","Q_Score":0,"Tags":"python-3.x,tensorflow2.0,spyder","A_Id":66752595,"CreationDate":"2021-03-18T09:45:00.000","Title":"How can I load my own dataset for person?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Basically I have two models to run in sequence. However, the first is a object-based model trained in TF2, the second is trained in TF1.x saved as name-based ckpt.\nThe foundamental conflict here is that in tf.compat.v1 mode I have to disable_eager_execution to run the mode, while the other model needs Eager execution (otherwise ~2.5 times slower).\nI tried to find a way to convert the TF1 ckpt to object-based TF2 model but I don't think it's an easy way... maybe I have to rebuild the model and copy the weights according to the variable one by one (nightmare).\nSo Anyone knew if there's a way to just temporarily turn off the eager_excution? That would solve everything here... I would really appreciate it!","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":410,"Q_Id":66695555,"Users Score":1,"Answer":"I regretfully have to inform you that, in my experience, this is not possible. I had the same issue. I believe the tensorflow documentation actually states that once it is turned off it stays off for the remainder of the session. You cannot turn it back on even if you try. This is a problem anytime you turn off eager execution, and the status will remain as long as the Tensorflow module is loaded in a particular python instance.\nMy suggestion for transferring the model weights and biases is to dump them to a pickle file as numpy arrays. I know it's possible because the Tensorflow 1.X model I was using did this in its code (I didn't write that model). I ended up loading that pickle file and reconstructing a new Tensorflow 2.X model via a for loop. This works well for sequential models. If any branching occurs the looping method won't work super well, or it will be hard successfully implement.\nAs a heads up, unless you want to train the model further the best way to load initialize those weights is to use the tf.constant_initializer (or something along those lines). When I did convert the model to Tensorflow 2.X, I ended up creating a custom initializer, but apparently you can just use a regular initializer and then set weights and biases via model or layer attributes or functions.\nI ultimately had to convert the Tensorflow 1.x + compat code to Tensorflow 2.X, so I could train the models natively in Tensorflow 2.X.\nI wish I could offer better news and information, but this was my experience and solution to the same problem.","Q_Score":0,"Tags":"python,tensorflow,computer-vision,tensorflow2.0","A_Id":66750043,"CreationDate":"2021-03-18T16:53:00.000","Title":"How to temporarily turn off\/on eager_execution in TF2.x?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using ubuntu 20.04. I created a new environment.\nconda create -n tfgpu python=3.8\nconda activate tfgpu\npip install tensorflow-gpu==2.3\njupyter notebook\nThen I open a previously created .ipynb file and I try to import tensorflow.\nimport tensorflow as tf\ntf.version\nversion is coming out to be 2.4.1\nI had an installation of tensorflow 2.4.1 in my base environment. Even if it is unrelated, I uninstalled that. I checked for tf 2.4.1 in other environment too but could not find any. When I write !pip uninstall tensorflow in that notebook, it says Skipping as no tensorflow installed. When I write !pip uninstall tensorflow-gpu, it uninstalled tensorflow==2.3. And after that it was still able to import tensorflow which was 2.4.1 version. I do not understand what is happening. I can say that I once also installed tf-nightly but was in a different environment. I am thinking it is something related to path of installation or does it have anything to do with environment name. It is really annoying, any help is appreciated. Thank you.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":142,"Q_Id":66705579,"Users Score":0,"Answer":"I missed installing jupyter notebook. I do not yet understand what was happening, but my mistake was that. The problem is resolved.","Q_Score":0,"Tags":"python,tensorflow,jupyter-notebook,version","A_Id":66705902,"CreationDate":"2021-03-19T09:28:00.000","Title":"Jupyter environment error, loading different tensorflow version than installed","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"How do I modify a np array based on the current value and the index? When I just want to modify certain values, I use e.g. arr[arr>target_value]=0.5 but how do I only modify the values of arr > target_value where also the index is greater than a certain value?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":74,"Q_Id":66706687,"Users Score":0,"Answer":"For that very specific example you would just use indexing I believe\neg arr[100:][arr[100:] > target_value]=0.5\nin general it could be conceptually easier to do these two things separately. First figure out which indices you want, then check whether they satisfy whatever condition you want.","Q_Score":0,"Tags":"python,arrays,numpy","A_Id":66706708,"CreationDate":"2021-03-19T10:45:00.000","Title":"Modify values in numpy array based on index and value","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I know to select subset of a data frame by condition we can use\ndf.loc[df['column1'] == 'ABC']\nHowever is there a way, where I can put something in the place of ABC which will give me whole table instead of a subset...\nI know you will say why to use .loc but am trying to use this as a user input ... Help much appreciated.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":28,"Q_Id":66725467,"Users Score":0,"Answer":"Am asking what can be put in place of ABC","Q_Score":0,"Tags":"python,pandas,dataframe","A_Id":66730319,"CreationDate":"2021-03-20T19:09:00.000","Title":"How to use df.loc and yet do no selection?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"A hyperboloid has the formula\n-x^2\/a^2 - y^2\/b^2 + z^2\/c^2 = 1.\nHow can I generate samples from this hyperboloid in Python? (Say, with a=b=c=1.)\nI was thinking to pick random x and y in [0,1] and then fill in the z value that would make the formula equal 1. However this would not sample uniformly. Is there a better way?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":90,"Q_Id":66728327,"Users Score":1,"Answer":"This is only a partial answer.\nJ.F. Williamson, \"Random selection of points distributed on curved surfaces\", Physics in Medicine & Biology 32(10), 1987, describes a general method of choosing a uniformly random point on a parametric surface. It is an acceptance\/rejection method that accepts or rejects each candidate point depending on its stretch factor (norm-of-gradient). To use this method for a parametric surface, several things have to be known about the surface, namely\u2014\n\nx(u, v), y(u, v) and z(u, v), which are functions that generate 3-dimensional coordinates from two dimensional coordinates u and v,\n\nThe ranges of u and v,\n\ng(point), the norm of the gradient (\"stretch factor\") at each point on the surface, and\n\ngmax, the maximum value of g for the entire surface.\n\n\nThe algorithm is then:\n\nGenerate a point on the surface, xyz.\nIf g(xyz) >= RNDU01()*gmax, where RNDU01() is a uniform random number in [0, 1), accept the point. Otherwise, repeat this process.\n\nIn the case of a hyperboloid with parameters a=b=c=1:\n\nThe gradient is [2*x, -2*y, 2*z].\nThe maximum value of the gradient norm is:2*sqrt(3), if x, y, and z are all in the interval [0, 1].\n\nThe only thing left is to turn the implicit formula into a parametric equation that is a function of two-dimensional coordinates u and v. I know this algorithm works for parametric surfaces, but I don't know if it still works if we \"pick random x and y in [0,1] and then fill in the z value that would make the formula equal\" in step 1.","Q_Score":1,"Tags":"python,plot,random,data-generation","A_Id":66728544,"CreationDate":"2021-03-21T02:33:00.000","Title":"Sample points from a hyperboloid","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using Pytorch. I got this RuntimeError while evaluating a model. Any idea how to solve this?","AnswerCount":2,"Available Count":2,"Score":1.0,"is_accepted":false,"ViewCount":8312,"Q_Id":66750391,"Users Score":8,"Answer":"SOLUTION: Just replace the view() function with reshape() function as suggested in the error and it works.\nI guess this has to do with how the tensor is stored in memory.","Q_Score":7,"Tags":"python,deep-learning,computer-vision,pytorch","A_Id":66750438,"CreationDate":"2021-03-22T16:50:00.000","Title":"RuntimeError: view size is not compatible with input tensor's size and stride (at least one dimension spans across two contiguous subspaces)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using Pytorch. I got this RuntimeError while evaluating a model. Any idea how to solve this?","AnswerCount":2,"Available Count":2,"Score":0.1973753202,"is_accepted":false,"ViewCount":8312,"Q_Id":66750391,"Users Score":2,"Answer":"SOLUTION2: change the .view(...) to .contiguous().view(...).\nActually, 'reshape()' does a similar job as contiguous() under the hood, if it needs.","Q_Score":7,"Tags":"python,deep-learning,computer-vision,pytorch","A_Id":71194270,"CreationDate":"2021-03-22T16:50:00.000","Title":"RuntimeError: view size is not compatible with input tensor's size and stride (at least one dimension spans across two contiguous subspaces)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a dataframe df\n\n\n\n\nname\n\n\n\n\nproject111\n\n\nproject212\n\n\n\n\n\nproject'09\n\n\nprojectws22\n\n\n\n\ntrying to replace the column that not numeric after 'project' to none, the output is as below:\n\n\n\n\nname\n\n\n\n\nproject111\n\n\nproject212\n\n\nnone\n\n\nnone\n\n\nnone","AnswerCount":4,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":68,"Q_Id":66751880,"Users Score":0,"Answer":"if those missing values are empty strings???, which Pandas doesn't recognise as null. To fix this, you can convert the empty stings (or whatever is in your empty cells) to np.nan objects using replace(), and then call dropna()on your DataFrame to delete rows with null tenants.","Q_Score":0,"Tags":"python,regex,pandas,format","A_Id":66751958,"CreationDate":"2021-03-22T18:29:00.000","Title":"python convert column format with numeric","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I use plt.savefig(pngpath, dpi=300), where the pngpath is the path where I want it to save. The png file as such is being created but is blank when I try and open it. Interestingly, the plt.show() right before this plt.savefig() works perfectly fine.\nEDIT 1: As ONDRO pointed out, I used plt.show() after plt.savefig() and the plot saved perfectly as intended. Also, I will make sure to add minimal reproduceable code next time. Thank you ONDRO and everyone else for helping me out!","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":69,"Q_Id":66754009,"Users Score":0,"Answer":"Using pyplot interface, you have to call plt.savefig() before plt.show(). If you change the order, the figure is destroyed once the window is closed and a new empty one is created by plt.savefig().","Q_Score":1,"Tags":"python,matplotlib","A_Id":66754992,"CreationDate":"2021-03-22T21:21:00.000","Title":"Problem with saving the plot using matplotlib","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I try to do point cloud semantic segmentation project, unfortunately I haven't dataset. So, I would like to train NN on point clouds, generated from 3d models, and than test it on real data from LIDAR","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":81,"Q_Id":66756468,"Users Score":0,"Answer":"Solved by sampling point cloud in Blender","Q_Score":0,"Tags":"python,cloud,point","A_Id":67715788,"CreationDate":"2021-03-23T02:32:00.000","Title":"How to generate point cloud from 3d model","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"How can I use XGBoost on Google AI Platform Unified for batch predictions?\nI can perform Online predictions with no problem, but when I submit a batch job request, it returns an error (\"Could not predict, DMatrix initialization error).\nI'm submiting a csv file with the same column names as the ones used for training. I try doing it with the dataframe formatted as jsonl file and have no result. Is that a bug or am I doing something wrong?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":219,"Q_Id":66765431,"Users Score":0,"Answer":"I found out: you can't. Perform batch predictions using Apache Beam running on Dataflow instead. Runs like a charm.","Q_Score":0,"Tags":"python,google-cloud-platform,xgboost,google-ai-platform","A_Id":69846485,"CreationDate":"2021-03-23T14:43:00.000","Title":"How can I do batch predictions on Google AI Platform Unified using a XGBoost model?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've come across this problem a few times now and it super frustrating but turns out to be easy to fix. Just wanted to put this here so others might find it because it's caused me lots of headaches in the past and I've never managed to find information about this.\nSymptoms of problem:\nEven with very good initial parameters for fitting data (based on the initial fit looking like a very close fit to data), running model.fit(...) either fails to fit the data completely, or does fit but with a warning in the fit.fit_report() ## Warning: uncertainties could not be estimated:.... Other very similar fits may run without error, so it seems like it is for no good reason at all.\nNote, this is not in the limit of data or any fit values being super tiny or huge which actually does make things more difficult for the minimizer to handle.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":158,"Q_Id":66772525,"Users Score":1,"Answer":"Answer:\nFor some reason, lmfit does not seem to like np.float64. Simply changing the type of data passed in to np.float32 first completely fixes the problem in many cases (for me at least).\nThis is true even when the values are only a few decimal points long and therefore do not change at all when casting to float32.","Q_Score":0,"Tags":"python,lmfit","A_Id":66772526,"CreationDate":"2021-03-23T23:05:00.000","Title":"lmfit fails to fit or fits without uncertainties calculated even with very good initial starting parameters, why?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I used GridSearchCV to get the optimized hyperparameter (e.g. learning rate, hidden layer size, activation) for MLPClassifier. but for some datasets, although I applied that parameter to the model, classification accuracy was not improved. for example, the accuracy of datasets1 that include learning rate = a, hidden layer size = b lowered than those of include learning rate = c, hidden layer size = d, optimized hyperparameter obtained from GridSearchCV.\nSo, I'm confused why this phenomenon happens.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":11,"Q_Id":66773417,"Users Score":0,"Answer":"No, it is not necessary that a gridsearchcv will always improve the model performance. It depends upon the hyperparameter range you select for the model and the underlying data.\nIn some cases, the default parameter itself will be the best, so the best way to further tune is to have the hyperparameters lying around that default range. If either doesn't work, you have to look at the data and preprocessing steps to figure out the problem.","Q_Score":0,"Tags":"python,optimization,classification,gridsearchcv","A_Id":71487491,"CreationDate":"2021-03-24T01:12:00.000","Title":"Does the GridSearchCV always improves model accuracy for classification or regression model?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Jupyter notebook with about 600 lines or so suddenly got very laggy this past week. Previously all cells would run instantly, the file is mostly just simple pandas aggregations and column functions.\nNow, when I reset kernel and outputs, even just clicking into a cell, not even running it, takes ~6 seconds. The screen freezes up, and goes back to normal after a bit. If I run the cell the same thing happens, even though the cell could just be a simple column renaming.\nAny ideas? I do not recall changing anything about my Python or Jupyter installation, same packages and everything from a week ago when it worked fine.\nEdit: I should add that I restarted computer several times as well but still same poor performance\nI created a new notebook, it runs fine, but after a couple hours it slows down as well, even if memory usage is low (just a small dataframe)","AnswerCount":2,"Available Count":2,"Score":0.1973753202,"is_accepted":false,"ViewCount":2032,"Q_Id":66774322,"Users Score":2,"Answer":"If you use nbextension for Jupyter try to disable Variable Inspector (Edit -> nbextensions config)","Q_Score":3,"Tags":"python,jupyter-notebook","A_Id":69892150,"CreationDate":"2021-03-24T03:25:00.000","Title":"Jupyter notebook is slow\/laggy, even with refreshed kernel and no outputs\/cells running","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"Jupyter notebook with about 600 lines or so suddenly got very laggy this past week. Previously all cells would run instantly, the file is mostly just simple pandas aggregations and column functions.\nNow, when I reset kernel and outputs, even just clicking into a cell, not even running it, takes ~6 seconds. The screen freezes up, and goes back to normal after a bit. If I run the cell the same thing happens, even though the cell could just be a simple column renaming.\nAny ideas? I do not recall changing anything about my Python or Jupyter installation, same packages and everything from a week ago when it worked fine.\nEdit: I should add that I restarted computer several times as well but still same poor performance\nI created a new notebook, it runs fine, but after a couple hours it slows down as well, even if memory usage is low (just a small dataframe)","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":2032,"Q_Id":66774322,"Users Score":0,"Answer":"The following reasons are possible:\n\nChanges of other software within your systems.\nThe data to be handled by Pandas is much bigger now and it consume more memory.\n\nPossible ways to find out the cause(s)\n\nTry out same Jupyter Notebook using smaller datasets.\nTry out the same Python code using command line instead of from within Jupyter Notebook.\n\nIn both cases, you should restart your computer before performing the test. You should also monitor CPU, disk and memory utilization before, during and after.","Q_Score":3,"Tags":"python,jupyter-notebook","A_Id":66774408,"CreationDate":"2021-03-24T03:25:00.000","Title":"Jupyter notebook is slow\/laggy, even with refreshed kernel and no outputs\/cells running","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I was trying to apply a deep learning algorithm(CNN) in python but after separating training-testing data and transforming time series to image step my Colab Notebook crashed and restarted itself again.\nIt gives an error like \"Your session crashed after using all RAM\" and when I checked app.log I saw something about tcmalloc: large alloc. I didn't find anything to fix this crashed.\nDo you have any idea how to prevent this warning and fixed this situation?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":1324,"Q_Id":66787279,"Users Score":3,"Answer":"Your session ran out of all available RAM. You can purchase Colab Pro to get extra RAM or you can use a Higher RAM machine and use the Neural Network there","Q_Score":5,"Tags":"python,tensorflow,memory-management,google-colaboratory,tcmalloc","A_Id":66789185,"CreationDate":"2021-03-24T18:35:00.000","Title":"tcmalloc: large alloc python in Google Colab","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"After installing the latest version of the FastAI library (2.2.7) with the latest installations of torch and torchvision (1.8.0, 0.9.0 respectively), the statement from fastai.vision.all import * seems to return the error NameError: name 'CrossEntropyLossFlat' is not defined.\nI just wanted to see if this was a problem with my installation, or if this was happening to everyone.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":134,"Q_Id":66789928,"Users Score":0,"Answer":"Fastai latest version is not compatible with torch 1.8, try with 1.7.1.\nThe fastai installation installs the correct version of torch if you hadn't it installed.","Q_Score":0,"Tags":"python,importerror,fast-ai","A_Id":67222590,"CreationDate":"2021-03-24T21:52:00.000","Title":"\"NameError: name 'CrossEntropyLossFlat' is not defined\" when trying to import FastAI vision","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"There are two methods when we make a model on sklearn.cluster.KMeans. First is fit() and other is fit_predict(). My understanding is that when we use fit() method on KMeans model, it gives an attribute labels_ which basically holds the info on which observation belong to which cluster. fit_predict() also have labels_ attribute.\nSo my question are,\n\nIf fit() fulfills the need then why their is fit_predict()?\nAre fit() and fit_predict() interchangeable while writing code?","AnswerCount":2,"Available Count":2,"Score":0.2913126125,"is_accepted":false,"ViewCount":1374,"Q_Id":66793419,"Users Score":3,"Answer":"KMeans is just one of the many models that sklearn has, and many share the same API. The basic functions ae fit, which teaches the model using examples, and predict, which uses the knowledge obtained by fit to answer questions on potentially new values.\nKMeans will automatically predict the cluster of all the input data during the training, because doing so is integral to the algorithm. It keeps them around for efficiency, because predicting the labels for the original dataset is very common. Thus, fit_predict adds very little: it calls fit, then returns .labels_. fit_predict is just a convenience method that calls fit, then returns the labels of the training dataset. (fit_predict doesn't have a labels_ attribute, it just gives you the labels.)\nHowever, if you want to train your model on one set of data and then use this to quickly (and without changing the established cluster boundaries) get an answer for a data point that was not in the original data, you would need to use predict, not fit_predict.\nIn other models (for example sklearn.neural_network.MLPClassifier), training can be a very expensive operation so you may not want to re-train a model every time you want to predict something; also, it may not be a given that the prediction result is generated as a part of the prediction. Or, as discussed above, you just don't want to change the model in response to new data. In those cases, you cannot get predictions from the result of fit: you need to call predict with the data you want to get a prediction on.\nAlso note that labels_ is marked with an underscore, a Python convention for \"don't touch this, it's private\" (in absence of actual access control). Whenever possible, you should use the established API instead.","Q_Score":1,"Tags":"python,scikit-learn,k-means","A_Id":66793593,"CreationDate":"2021-03-25T05:10:00.000","Title":"fit() vs fit_predict() metthods in sklearn KMeans","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"There are two methods when we make a model on sklearn.cluster.KMeans. First is fit() and other is fit_predict(). My understanding is that when we use fit() method on KMeans model, it gives an attribute labels_ which basically holds the info on which observation belong to which cluster. fit_predict() also have labels_ attribute.\nSo my question are,\n\nIf fit() fulfills the need then why their is fit_predict()?\nAre fit() and fit_predict() interchangeable while writing code?","AnswerCount":2,"Available Count":2,"Score":0.0996679946,"is_accepted":false,"ViewCount":1374,"Q_Id":66793419,"Users Score":1,"Answer":"In scikit-learn, there are similar things such as fit and fit_transform. \nFit and predict or labels_ are essential for clustering. \nThus fit_predict is just efficient code, and its result is the same as the result from fit and predict (or labels).\nIn addition, the fitted clustering model is used only once when determining cluster labels of samples.","Q_Score":1,"Tags":"python,scikit-learn,k-means","A_Id":66793467,"CreationDate":"2021-03-25T05:10:00.000","Title":"fit() vs fit_predict() metthods in sklearn KMeans","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Hello I know that the key to analyzing data and working with artificial intelligence is to use the gpu and not the cpu. The problem is that I don't know how to use it with Python in the visual studio code, I use Ubuntu, I already have nvidia installed","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":1242,"Q_Id":66801401,"Users Score":1,"Answer":"You have to use with the libraries that are designed to work with the GPUs.\nYou can use Numba to compile Python code directly to binary with CUDA\/ROC support, but I don't really know how limiting it is.\nAnother way is to call APIs that are designed for parallel computing such as OpenCL, there is PyOpenCL binding for this.\nA bit limiting, but sometimes valid way - OpenGL\/DirectX compute shaders, they are extremely easy, but not so fast if you need to transfer data back and forth in small batches.","Q_Score":0,"Tags":"python,python-3.x,pandas,dataframe,visual-studio-code","A_Id":66802239,"CreationDate":"2021-03-25T14:18:00.000","Title":"how can i work with my GPU in python Visual Studio Code","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I would like to know how to convert annotations in YOLO format (e.g., center_X, center_y, width, height = 0.069824, 0.123535, 0.104492, 0.120117) to x1, y1, x2, y2 coordinates?","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":489,"Q_Id":66801530,"Users Score":1,"Answer":"Given that the upper-left corner of the image is [0,0]: For the upper-left corner you have to do [x,y] = [center_X, center_Y] - 1\/2 * [width, height] . For the bottom-right corner [x,y] = [center_X, center_Y] + 1\/2 * [width, height] .","Q_Score":1,"Tags":"python,computer-vision,yolo","A_Id":66801978,"CreationDate":"2021-03-25T14:24:00.000","Title":"How to convert YOLO format annotations to x1, y1, x2, y2 coordinates in Python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have some data in excel that I imported into a dataframe in Python (Base_Eventos). I need to summarize a variable (PartyID), so I use:\nBase_Eventos.groupby (by = 'partyID'). Size ()\nSince the result comes out with a part of the counter without a variable name. And I will need to use this count output to make a filter. How can I transform this output with a name for a newly created variable? base ex:\nidPartida count (I want to add this variable name because it comes null)\nx123 67\nx124 86\nx135 54","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":47,"Q_Id":66802257,"Users Score":0,"Answer":"You can use Base_Eventos.groupby(by='idPartida').count() instead.","Q_Score":0,"Tags":"python-3.x,dataframe","A_Id":66808235,"CreationDate":"2021-03-25T15:04:00.000","Title":"How to create a name for a var in output of groupby - Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to detect anomalies in a time series dataset. I am classifying the predicted values based on thresholds.\nHere is a detailled description about what I did:\nI splitted my total dataset into training and testing dataset then I fitted my ARIMA model on training dataset. I used the founded model to predict the testing observations than I calculated the error between actual and predicted values:\nError = actual_testing - predicted_testing\nNormally, I must choose the threshold to classify each observation, based on the calculated error.\nif the Error> threshold ==> it is an anomaly\nis there any method to choose this threshold value?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":93,"Q_Id":66804038,"Users Score":0,"Answer":"One approach is to compute errors across your training or validation set. Then to fit a statistical distribution to the errors, for example a Gaussian (normal distribution). This has the effect of normalizing the range of the scores, and to allow to interpret a score as a probability. Then one can set a threshold for example at 2-6 standard deviations, depending on how many anomalies you want to flag.","Q_Score":0,"Tags":"python,time-series,arima,anomaly-detection","A_Id":66940968,"CreationDate":"2021-03-25T16:49:00.000","Title":"Which threshold to adapt to detect anomaly using ARIMA model","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I ran a h2o gradient boosting classifier model to predict probabilities for three classes 0,1 and 2. There is a heavy class imbalance (93:5:2) in the training data.\nAlthough the individual classes 1 & 2 are not correctly predicted in confusion matrix (as expected), the AUC is decent for these classes individually.\nI plan to manually predict the final classes\nMy understanding is that the resulting probabilities (P0,P1 & P2) are calibrated and sum up to 1.\nSince multinomial model in h2o is essentially one vs many approach, but the scores are summing up to 1, is it correct to add or compare probabilities?\nSo if P0 = 0.40 , P1 =0.35 and P2=0.25, the predicted class will be 0 (based on max probability)\n\nDoes this mean P(1,2) = 0.6\nOr p(not 0) = 0.6? (Since the model for class 0 is actually 0 against all other classes)\n\nCan I then compare the probabilities of 1&2 and say P1 (0.35) > P2 (0.25), so the predicted class should be 1?\n(Since the resulting classes are mutually exclusive and probabilities add up to 1, will these be comparable?)","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":145,"Q_Id":66805422,"Users Score":0,"Answer":"For imbalanced target column, I would avoid AUC (since it will generally be high). Consider using AUC-PR or Logloss.\nFor multiclass\/multinomial, you would have one-vs-all predictions. So each prediction is based on its class vs the rest. So P0 is probability of class_0 vs class_1 + class_2. So P(1,2) = 0.6 would make sense.\nFor comparing probabilities, yes, you can select the predicted class with the highest probability output P1 (0.35) > P2 (0.25) -> Class = 1.","Q_Score":0,"Tags":"python,h2o,multiclass-classification,multinomial,gbm","A_Id":66821410,"CreationDate":"2021-03-25T18:18:00.000","Title":"Comparing predicted probabilities from multinomial models in h2o gbm","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to root find a scalar function using scipy.optimize.root_scalar. For my problem, the error function becomes poorly defined on some areas of the domain. Unfortunately, I don't know what these regions are beforehand (that's part of the purpose of this root-finding). I am able to provide a bracketing interval, but in general there will be some poorly-defined regions within that bracket.\nThe behavior I'd ideally like is to return NaN for the error function whenever these regions are encountered, and to have some root finding algorithm \"learn\" to avoid them. This doesn't work with root_scalar though, so I've been returning a fixed large error of the correct sign when these regions are encountered. Any suggestions for a less-hacky solution would be appreciated.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":106,"Q_Id":66811738,"Users Score":0,"Answer":"I'll go ahead and post the solution I've implemented. I wasn't able to solve the above problem for any root-finding method that numerically computes derivatives. However, I realized a much simpler solution is to use the bisection method, and then return an error of +\/- infinity, as appropriate, in those regions where the error is poorly defined. This is pretty slow but seems to work every time so far, and speed is not critical in my application.","Q_Score":0,"Tags":"python,scipy,scipy-optimize","A_Id":66823542,"CreationDate":"2021-03-26T05:59:00.000","Title":"Constrained root finding with scipy","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am getting tick price whenever trade is executed. Now i need to convert this tick data to ohlc data using python such that doji's (shadows) will not be missing when ohlc data is plotted. The plot must be similar to zerodha's range bar plot.\nInitially, I tought that range bars are similar to renko bars except the doji is created when there is an trend reversal after the given time frame. After looking into zerodha's range bar plot, I have identified that there is an possibility for presence of 2 different trends in the same time frame and there will be multiple doji's created in these trends. Now, I completely stuck to create range bars.\nPlease help me out.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":323,"Q_Id":66812446,"Users Score":0,"Answer":"Use the tick data and time module to create range bars.\nfor every 5mins or whatever timeframe get the open of the candle using the first tick data that comes in. Now monitor the high and lows using two variables.\nThe close will be the last tick that you get in the time frame.\nnow you have the OHLC for your plot.","Q_Score":0,"Tags":"python,stock","A_Id":67134624,"CreationDate":"2021-03-26T07:12:00.000","Title":"Convert tick price to range bars ohlc data using python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a trained word2vec model which I need to train further with more data. I want to use the same hyperparameters that is used while training the model for the new model as well. But I don't want to hardcode it. Is there a method which I can use to get the hyperparameters used while training the existing model.\nI am using Gensim word2vec.","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":219,"Q_Id":66813857,"Users Score":1,"Answer":"Any full Word2Vec model has every metaparameter that was supplied at its initial creation somewhere in its object properties.\nIt's almost always on the model itself, using the exact same name as was used for the constructor parameters. So, model.window will return the window, etc - and thus you can just create a new model pulling each value from the old model.\nNote that continuing training on an already-trained model involves a lot of thorny tradeoffs.\nFor example, the .build_vocab(..., update=True) on an existing model won't be applying min_count consistently against all word totals from all prior calls, but only those in the latest 'batch'.\nThe proper learning-rate (alpha to min_alpha values) for incremental updates isn't well-defined by theory or rules-of-thumb. And if the vocabulary & word-balance in the new texts mainly train some words, not all, those recently-updated words can be pulled arbitrarily out of strong-comparability-alignment with earlier words that didn't get more training. (The underlying method of mdoel optimization, stochastic gradient descent, is best-grounded when all training texts are given equal training attention, without any subset begin intensely trained later.)","Q_Score":0,"Tags":"python,gensim,word2vec,hyperparameters","A_Id":66825689,"CreationDate":"2021-03-26T09:05:00.000","Title":"How to get back hyperparameters from a trained world2vec model gensim?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I need to calculate the sales correlation of 5000 products which will results in 5000 by 5000 correlation matrix. I am trying to accomplish this in pandas using df.corr() but it is causing memory issues. Any ideas of more efficient ways to achieve this?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":169,"Q_Id":66823451,"Users Score":0,"Answer":"Use np.corrcoef...I was able to process the matrix in under a minute using this.","Q_Score":0,"Tags":"python,pandas,matrix,correlation,pearson","A_Id":66861362,"CreationDate":"2021-03-26T19:51:00.000","Title":"Most efficient way to calculate correlation matrix in python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"My understanding of GANs is:\n\nWhen training your generator, you need to back-propagate through the discriminator first so you can follow the chain rule. As a result, we can't use a .detach() when working on our generators loss calculation.\n\nWhen updating discriminator, since your generator weight update doesn't affect discriminator weight updates, we can .detach() the generator output from your computation, my understanding tells me that since this generator is no longer a part of computation graph, we don't update it during back prop any longer.\n\n\nSo when we update your discriminator losses with:\ndisc_loss.backward(retain_graph=True) at each mini-batch, we don't have to worry about your generator being part of the pipeline thanks to the .detach() function call.\nBut what about when we work on our generator? What is keeping our model from constantly changing our discriminator weights in accordance to generator? That isn't what we want after all right? The discriminator shouldn't learn when it is told that fake samples are real.\nWhy does such a model work in the first place","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":214,"Q_Id":66841054,"Users Score":1,"Answer":"backward doesn't update the weights, it updates the gradients of the weights. Updating weights is the responsibility of the optimizer(s). There are different ways to implement GANs, but often you would have two optimizers, one that is responsible for updating the weights (and resetting the gradients) of the generator and one that is responsible for updating the weights (and resetting the gradients) of the discriminator. Upon initialization, each optimizer is provided only the weights of the model it will update. Therefore, when you call an optimizer's step method it only updates those weights. Using separate optimizers is what prevents the discriminator weights from being updated while minimizing the generator's loss function.","Q_Score":1,"Tags":"python,pytorch,generative-adversarial-network","A_Id":66843773,"CreationDate":"2021-03-28T11:42:00.000","Title":"When using torch.backward() for a GANs generator, why doesn't discriminator losses change in Pytorch?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm working on a NLP classification problem over a large database of emails (~1 million). I need to use spacy to parse texts and I'm using the nlp.pipe() method as nlp.pipe(emails,n_process=CPU_CORES, batch_size=20) to loop over the dataset.\nThe code works but I'm facing a (maybe not so)weird behavior:\nthe processes are being created but they are all in SLEEP state but one, casually some of them go in RUN state for a few seconds and then back to sleep. So I find myself with one single process using one core at 100% but of course the script not using all the CPU cores.\nIt's like the processes don't get \"fed\" input data from pipe.\nDoes anybody know how to properly use spacy nlp pipe or anyway how to avoid this situation? no way to use nlp.pipe with the GPU?\nThank you very much!\nSandro\nEDIT: I still have no solution but i've noticed that if I set the batch_size=divmod(len(emails),CPU_CORES), the processes all starts running at 100% CPU and after a few seconds they all switch to sleeping state but one. It really looks like some element in spacy pipe gets locked while waiting for something to end.... any idea??\nEDIT2: Setting batch_size=divmod(len(emails),CPU_CORES) while processing a large dataset leads inevitably to a spacy memory error:\n\nMemoryError: Unable to allocate array with shape (1232821, 288) and data type float32\n\n*thing that is maybe not so weird as my machine has 10GB of RAM and (1232821\u00d7288\u00d732)bits \/ 8 = 1.4GB multiplied by 6 (CPU_CORES) leads to a 8.5GB of RAM needed. Therefore I guess that, having other stuff in memory already, it turns out to be plausible. *","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":1341,"Q_Id":66844380,"Users Score":0,"Answer":"Ok, I think I found an improvement but honestly the behavior it's not really clear to me. Now the sleeping processes are way less, with most of them stable running and a few sleeping or switching between the two states.\nWhat I've done was to clean and speedup all the code inside the for loop and set the nlp.pipe args like this:\nfor e in nlp.pipe(emails,n_process=CPU_CORES-1, batch_size=200):\nIf anybody have any explanation about this or any suggestion on how to improve even more, it's of course more than welcome :)","Q_Score":2,"Tags":"python,multiprocessing,sleep,spacy","A_Id":66922559,"CreationDate":"2021-03-28T17:46:00.000","Title":"Spacy, using nlp.pipe on large dataset in python, multiprocessing leads to processes going in sleep state. How to proper use all CPU cores?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm working on a NLP classification problem over a large database of emails (~1 million). I need to use spacy to parse texts and I'm using the nlp.pipe() method as nlp.pipe(emails,n_process=CPU_CORES, batch_size=20) to loop over the dataset.\nThe code works but I'm facing a (maybe not so)weird behavior:\nthe processes are being created but they are all in SLEEP state but one, casually some of them go in RUN state for a few seconds and then back to sleep. So I find myself with one single process using one core at 100% but of course the script not using all the CPU cores.\nIt's like the processes don't get \"fed\" input data from pipe.\nDoes anybody know how to properly use spacy nlp pipe or anyway how to avoid this situation? no way to use nlp.pipe with the GPU?\nThank you very much!\nSandro\nEDIT: I still have no solution but i've noticed that if I set the batch_size=divmod(len(emails),CPU_CORES), the processes all starts running at 100% CPU and after a few seconds they all switch to sleeping state but one. It really looks like some element in spacy pipe gets locked while waiting for something to end.... any idea??\nEDIT2: Setting batch_size=divmod(len(emails),CPU_CORES) while processing a large dataset leads inevitably to a spacy memory error:\n\nMemoryError: Unable to allocate array with shape (1232821, 288) and data type float32\n\n*thing that is maybe not so weird as my machine has 10GB of RAM and (1232821\u00d7288\u00d732)bits \/ 8 = 1.4GB multiplied by 6 (CPU_CORES) leads to a 8.5GB of RAM needed. Therefore I guess that, having other stuff in memory already, it turns out to be plausible. *","AnswerCount":2,"Available Count":2,"Score":0.0996679946,"is_accepted":false,"ViewCount":1341,"Q_Id":66844380,"Users Score":1,"Answer":"I've found that using n_process=n works well for some models, like en_core_web_lg, but fails with others, such as en_core_web_trf.\nFor whatever reason, en_core_web_trf seems to use all cores with just a batch_size specified, whereas en_core_web_lg uses just one unless n_process=n is given. Likewise, en_core_web_trf fails with a closure error if n_process=n is specified.","Q_Score":2,"Tags":"python,multiprocessing,sleep,spacy","A_Id":67037039,"CreationDate":"2021-03-28T17:46:00.000","Title":"Spacy, using nlp.pipe on large dataset in python, multiprocessing leads to processes going in sleep state. How to proper use all CPU cores?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I recently switched from Windows 10 to Linux-Fedora, to be more accurate. I normally mainly use the matplotlib module. Today, I wanted to copy a plot I had in the plot panel in Spyder, and it didn't work. I can do Ctrl+C - or click \"Copy image\", it won't help. Once I go on say a conversation where I want to paste the plot - it doesn't do anything. I'd like to know if someone could help me...\nCheers.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":305,"Q_Id":66845670,"Users Score":1,"Answer":"Spyder will let you copy but not paste within Spyder, unless you paste your copied plot somewhere else , so try pasting it somewhere else ( like notepad ) then pasting it into spyder .","Q_Score":1,"Tags":"python,matplotlib,spyder","A_Id":66845854,"CreationDate":"2021-03-28T19:57:00.000","Title":"Copy Paste not working for plots in spyder","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Given an arbitrary array with real numbers as entries, I want to return an array with the same shape, whose entries are the average over the closest neighbours of the original array.\nWhat I mean by this in the case of a given array of dimension 2, is that if the array has shape (n,m) with entries a_{i,j}, then on the entry (i,j) the value of the new array should be:\naverage(i,j)=1\/4 (a_{i+1,j} + a_{i-1,j} + a_{i,j+1} + a_{i,j-1}),\nwhere the first index is taken mod n and the second mod m.\nI would like to create a function whose argument is an arbitrary array, and returns an array of the same shape and entries the averages over the entries on the closest neighbours of the given array (for a d-dimensional array there are 2d closest neighbours, obtained by summing +1 and -1 on each index)\nI know how to do this for a fixed dimension d (just generalising the above equation), using d nested for loops, but I don't know how to do it when the dimensions are not fixed.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":291,"Q_Id":66846086,"Users Score":0,"Answer":"Scipy has a scipy.ndimage.convolve function, which can do exactly this. it takes the array, and a matrix of values to multiply the neighbors with. It should work for any number of dimensions.\nHowever if you are trying to write this function manually, I'd suggest trying an iterative or recursive approach, where each iteration or layer of recursion handles a dimension. In a 3D case, you would first handle the first dimension, and have the one sixth of the value of the neighbors in that dimension. The next iteration would do the same for dimension 2, etc.\nThe factor to multiply each neighbor with is 1\/(2n), since each entry has 2 neighbors in each dimension. This should scale up to any arbitrary number of dimensions.","Q_Score":0,"Tags":"python,arrays,numpy,numpy-ndarray","A_Id":66846266,"CreationDate":"2021-03-28T20:50:00.000","Title":"How to calculate average of closest neighbours in an array in numpy","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"What is the difference between these two functions provided in OpenCV?\nWhy is there cv2.fisheye.calibrate() function we need?\nI tried using cv2.calibrateCamera() for barrel distorted images and I think it is giving me good results, so why would I want to use fisheye.calibrate()?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":232,"Q_Id":66855107,"Users Score":1,"Answer":"Distortion in fisheye lenses is really high. At least in older versions cv2.calibrateCamera() did not fit polynomials with sufficiently high order, so results were poor or the calibration failed altogether. So cv2.fisheye.calibrate() implemented a camera model with higher order polynomials.","Q_Score":0,"Tags":"python,opencv,computer-vision,camera-calibration","A_Id":66856525,"CreationDate":"2021-03-29T13:28:00.000","Title":"What is the difference between cv2.calibrateCamera and cv2.fisheye.calibrate?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a following Pandas DataFrame:\n\ndf = pd.DataFrame({'a': ['2020-01-02', '2020-01-02']})\n\nObviously, the column 'a' is string. I want to convert it to 'Date' type; and here is what I did:\n\ndf['a'] = df['a'].apply(pd.to_datetime).dt.date\n\nIt works, but in reality my DataFrame has 500,000 + rows. It seems to be very inefficient. Is there any way to directly and more efficiently convert string column to Date column?","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":1573,"Q_Id":66862261,"Users Score":1,"Answer":"use df['a'] = pd.to_datetime(df['a'], format='%Y-%m-%d')\nspecify the format if you know they are all following the same format.","Q_Score":1,"Tags":"python,pandas,dataframe","A_Id":66862338,"CreationDate":"2021-03-29T22:07:00.000","Title":"Convert String Column directly to Date format (not Datetime) in Pandas DataFrame","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have two matrices A and B both with shape (N,M). I would like to perform the following operation: C = np.sum(A[:,None,:]*B[:,:,None],axis=(1,2)), which corresponds to performing the sum of the outer product of each row of A with each row of B. C would then have a shape of (N,).\nThe problem is that I get a MemoryError when using this form because N=12000 and M=4000.\nIs there a way to perform this operation without having to first build the (huge) intermediary array to be summed ?\nI suspect a solution with np.einsum would do the trick, but I'm not familiar with it !","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":89,"Q_Id":66901045,"Users Score":1,"Answer":"For future readers: this operation is mathematically equivalent to multiplying the sum of each row of A with the sum of each row of B. In other words, the fastest solution is C = np.sum(A,axis=-1) * np.sum(B,axis=-1).\nThis is much faster than np.einsum and any other way of computing it.","Q_Score":3,"Tags":"python,numpy,matrix,vectorization","A_Id":66917064,"CreationDate":"2021-04-01T08:31:00.000","Title":"Sum of many outer products in NumPy","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a numpy array with a shape similar to (3114, 7, 36, 64, 1). This example is a batch of 3114 sets of 7 images, each image 36 by 64 grayscale pixels. This is for a 3d Convolutional Neural Network, but what I want to do is double the batch size for more data for my model. Basically, I want to take these 3114 sets of 7 and duplicate each one to create a batch of size 6228. I know this is a pretty basic question, but I am not too familiar with numpy arrays. Thanks in advance!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":90,"Q_Id":66904760,"Users Score":0,"Answer":"You can use either numpy's .repeat() or .concatenate() functions","Q_Score":0,"Tags":"python,arrays,numpy","A_Id":66904876,"CreationDate":"2021-04-01T12:43:00.000","Title":"How to double elements in numpy array","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"So, i entered code below to round a column to the nearest integer, though it still shows up with decimals.\nEg. I want to round 62.040 to just 62 though once the code is entered it shows 62.0 in the output\ndata['Final'] = np.ceil(data['Total'].round())","AnswerCount":3,"Available Count":1,"Score":0.1325487884,"is_accepted":false,"ViewCount":209,"Q_Id":66912904,"Users Score":2,"Answer":"This should work pretty ok data['Final'] = round(data['Total'])\nThis converts the decimal number to it nearest integer and the returned number doesn't have a decimal point\nNote: I'm assuming that data is just dictionary that contains float numbers, since no more information was provided","Q_Score":2,"Tags":"python,python-3.x,pandas,dataframe","A_Id":66913053,"CreationDate":"2021-04-01T23:56:00.000","Title":"how can i stop showing the decimal .0 after the whole number? python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm working in python and I have an image that is represented by the shape (4,386,258), I would like to represent it with the shape (3,386,258). Is there a way to do that? I don't know how to combine the information in order to get the right map","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":25,"Q_Id":66917084,"Users Score":0,"Answer":"Assuming your image is 386 pixels by 258 pixels and you have 4 channels, it means you want to convert the colour representation to one using only 3 channels, probably RGB. You haven't specified what libraries you used to read-in the image or where it is from, but most would have methods to handle this for you, so you don't have to write the conversion manually. They should also have methods of finding what the current colour representation is.","Q_Score":1,"Tags":"python,arrays,numpy","A_Id":66917203,"CreationDate":"2021-04-02T09:17:00.000","Title":"How to map an array of shape (4,386,258) to an array of shape (3, 386,258) in python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I had some issues about using\n'''\ntensorflow.reset_default_graph\n'''\n,so I tried to downgrade the tensorflow version to 1.4.\nAnd I had problem about:\n'''\nModuleNotFoundError: No module named 'tensorflow.compat'\n'''\n.\nThe problem about reset_default_graph was in the version of tensorflow 2.0, and the version about tensorflow.compat was 1.4.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":79,"Q_Id":66921394,"Users Score":0,"Answer":"From comments\n\nIn TF 2.x, you can use tf.compat.v1.reset_default_graph() instead of\nreset_default_graph().\nAfter disabling eager execution using\ntensorflow.compat.v1.disable_eager_execution() has resolved the\nissue.","Q_Score":0,"Tags":"python,tensorflow","A_Id":67216260,"CreationDate":"2021-04-02T15:13:00.000","Title":"Both reset_default_graph and tensorflow.compat have version difference to use tensorflow in Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"So i was trying to make a voice classifier, the challenge was to predict if the person talking is me or is other person, i already build a simple code that converts .wav file into an array, so all my datasets of audio files of me talking will be converted into arrays, the thing is that I am a beginner and i dont know how to only use one variable for predicting(my voice), is like saying true or false, how can i make a neural network(CNN) that works like that?\nOr should i use another type of machine learning? And not deep learning? I would like to use deep learning for this project.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":61,"Q_Id":66925505,"Users Score":0,"Answer":"Because it seems that you are relatively new to the topic, I would propose that you start with an easier machine learning model for this simple classification task. Maybe for the first model a Logistic Regression could be enough.\nSo, you say you collected some samples of your own voice (your positve class), but did you also collect some negative samples from other people?\nAfter this, I would suggest to chunk the converted samples into equal siced sequences and label them (your voice or another?).\nNow with this as basis, you can test some easier models like the Logistic Regression or the KNN. You then might move forward to some simple Feed-Forward-Neural-Networks and then go on to some advanced models like CNN's or RNN's.","Q_Score":1,"Tags":"python,machine-learning,deep-learning,conv-neural-network,classification","A_Id":66926217,"CreationDate":"2021-04-02T21:34:00.000","Title":"CNN classified only one variable if it is true or false","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am looking for a simple way for to do real-time face detection and capture using open-cv and Picamera in Python. I figured out how to recognize the face from and image file, but I dont' know the rest. I am trying to have a real-time stream of video, and when a face is detected in that video, the camera takes a picture of the face. Is this possible using open-cv and Python? NOTE: there is a difference between face recognition and face detection. I am asking for help on how to detect the face and take a picture of it, not the recognition part. Thanks for any help!","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":79,"Q_Id":66946105,"Users Score":2,"Answer":"my two cents are, if you have the original frame from the live video stream, and you can detect which frame has a face. Then can you just save that frame as a png or jpeg image file, no need to take any further image again? I know there can be situations where we need to take a new image, but just one solution I thought of is this.","Q_Score":0,"Tags":"python,opencv,face-detection,raspberry-pi4,picamera","A_Id":66946163,"CreationDate":"2021-04-04T21:37:00.000","Title":"How to capture face with open-cv and Picamera?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am extending my own data types from numpy and almost everything works. I have both __array_ufunc__ and __array_finalize__ that converts all the universal functions to my own type. However for argmin and argmax the __array_ufunc__, __array_finalize__, or __array_wrap__ is not called. what mechanism should be used for extending these functions and why this is not happening ?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":45,"Q_Id":66955582,"Users Score":1,"Answer":"I just realized that argmin and argmax use __array_function__ mechansim and not universal function one.","Q_Score":0,"Tags":"python,numpy,numpy-ufunc","A_Id":66956079,"CreationDate":"2021-04-05T15:38:00.000","Title":"Extending numpy argmin argmax","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a python project that gives outputs as csv. These outputs sometimes can be large as 15-16gb. When I try to save it with scipy, ram and cpu can't handle the data and closes the program so I need to convert csv file to mat file without reading the file. Is there a way to do that?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":452,"Q_Id":66967370,"Users Score":1,"Answer":"Yes and no. You can't do anything with the file unless you read it, but it's not necessary that you finish all the reading. I don't know all the details but usually you can use fopen and fscanf to read just a few lines of the csv file, process however you like and save the partial result, then repeat from fscanf for some more lines again and again.","Q_Score":0,"Tags":"python,matlab,csv","A_Id":66979698,"CreationDate":"2021-04-06T11:00:00.000","Title":"Converting .csv file to .mat file without reading the csv","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"From my understanding, when using Lasso regression, you can use GridSearchCV or LassoCV in sklearn to find the optimal alpha, the regularization parameter. Which one is preferred over the other?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":1010,"Q_Id":66978038,"Users Score":2,"Answer":"You can get the same results with both. LassoCV makes it easier by letting you pass an array of alpha-values to alphas as well as a cross validation parameter directly into the classifier.\nTo do the same thing with GridSearchCV, you would have to pass it a Lasso classifier a grid of alpha-values (i.e. {'alpha':[.5, 1, 5]}) and the CV parameter.\nI would not recommend one over the other though. The only advantage I can see is that you can access results_ as well as many other attributes if you use GridSearchCV. This may be helpful if you want a summary of all the models returned by the alphas you tried. On the other hand, as pointed out by @amiola, LassoCV can take advantage of using pre-computed results in previous steps of the cross-validation process (aka warm-starting), which may result in faster fitting times.","Q_Score":0,"Tags":"python,scikit-learn,lasso-regression","A_Id":66986977,"CreationDate":"2021-04-07T00:12:00.000","Title":"Should I use LassoCV or GridSearchCV to find an optimal alpha for Lasso?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Can healpy compute the spherical harmonic transform of a complex-valued map?\nWhen I try this using healpy.sphtfunc.map2alm, there is no warning, but the function gives a_{l,m} only for m>0. This makes sense for real-valued maps, for which a_{l,-m} = (-1)^m * a_{l,m}^*. But for complex-valued functions, this symmetry does not exist.\nThanks!","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":56,"Q_Id":66982208,"Users Score":1,"Answer":"Asked Martin Reinecke, developer of HEALPix C++, here his answer:\nWhat you can do is to run map2alm separately on the real and imaginary\nparts of your map; the resulting a_lm coefficients are then simply\na_lm,real + i*a_lm,imag. If you want the coefficients with negative m\nas well, you need to use the symmetry relation separately on a_lm,real\nand a_lm, imag first and then combine them as described.\nThe reason why there is no direct support for complex-valued maps is\nthat this would make a_lm handling and spherical harmonic transforms\nmuch more complicated, just to cover a case that is rarely needed (at\nleast in the area where healpy was originally used) and that can be\nemulated by the workaround above if really needed.\nAll a_lm objects in Healpix and healpy are designed in a way that there\nis the mentioned symmetry between +m and -m. For quantities with spin!=0\nthis symmetry doesn't exist either, so we introduce the linear\ncombinations alm_E and alm_B, for which it exists again.","Q_Score":1,"Tags":"python,healpy","A_Id":66989853,"CreationDate":"2021-04-07T08:24:00.000","Title":"Spherical harmonic transform of complex-valued map?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm new to Python and Pandas, and i'm struggling to create a frequency distribution table form my df.\nMy dataframe is something like this:\n\n\n\n\nBalances\nWeight\n\n\n\n\n10\n7\n\n\n11\n15\n\n\n12\n30\n\n\n13\n20\n\n\n10\n15\n\n\n13\n20\n\n\n\n\nedit: The balance numbers are its respective ID\nI need the frequency of each balance used (in this example, balance 10 would be 2 and so on) the min, max and mean of the measurements results.\nI was to use df.groupby(['balances']) but how can i use the results form using df.groupby to creat a new table? Is that the way?","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":573,"Q_Id":66988987,"Users Score":1,"Answer":"df.groupby(['balances']).count() should solve what you're looking for","Q_Score":2,"Tags":"python,pandas,frequency-distribution,frequency-table","A_Id":66989052,"CreationDate":"2021-04-07T15:12:00.000","Title":"Creating a frequency distribution table in Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Stack Overflow Family,\nI have recently started learning Python and am using Pandas to handle some factory data. The csv file is essentially a large dataframe (1621 rows \u00d7 5633 columns). While I need all the rows as these are data of each unit, I need to filter many unwanted columns. I have identified a list of strings in these column names that I can use to find only the wanted columns, however, I am not able to figure out what a good logic here would be or any built in python functions.\ndropna is not an option for me as some of these wanted columns have NA as values (for example test limit)\ndropna for columns with all NA is also not good enough as I will still end up with a large number of columns.\nLooking for some guidance here. Thank you for your time.","AnswerCount":4,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":661,"Q_Id":66998824,"Users Score":0,"Answer":"You can drop columns from a dataframe by applying string contains with regular expression. Below is an example\ndf.drop(df.columns[df.columns.str.contains('^abc')], axis=1)","Q_Score":0,"Tags":"python,pandas,data-analysis","A_Id":66999094,"CreationDate":"2021-04-08T07:00:00.000","Title":"Filtering a large Pandas DataFrame based on a list of strings in column names","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Using Tensorflow's Custom Object Classification API w\/ SSD MobileNet V2 FPNLite 320x320 as the base, I was able to train my model to succesfully detect classes A and B using Training Data 1 (about 200 images). This performed well on Test Set 1, which only has images of class A and B.\nI wanted to add several classes to the model, so I constructed a separate dataset, Training Data 2 (about 300 images). This dataset contains labeled data for class B, and new classes C, D and E. However it does NOT include data for class A. Upon training the model on this data, it performed well on Test Set 2 which contained only images of B, C, D and E (however the accuracy on B did not go up despite extra data)\nConcerned, I checked the accuracy of the model on Test Set 1 again, and as I had assumed, the model didn't recognize class A at all. In this case I'm assuming I didn't actually refine the model but instead retrained the model completely.\nMy Question: Am I correct in assuming I cannot refine the model on a completely separate set of data, and instead if I want to add more classes to my trained model that I must combine Training Set 1 and Training Set 2 and train on the entirety of the data?\nThank you!","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":372,"Q_Id":67013225,"Users Score":0,"Answer":"It mostly depends on your hyperparameters, namely, your learning rate and the number of epochs trained. Higher learning rates will make the model forget the old data faster. Also, be sure not to be overfitting your data, have a validation set as well. Models that have overfit the training data tend to be very sensitive to weight (and data) perturbations.\nTLDR. If not trained on all data, ML models tend to forget old data in favor of new data.","Q_Score":0,"Tags":"python,api,tensorflow,object,detection","A_Id":67013295,"CreationDate":"2021-04-08T23:44:00.000","Title":"Question about finetuning model to increase number of classes w\/additional data using Tensor Flow Custom Object Detection","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Getting below validation error on opening my notebook :\n{\n\"metadata\": {\n\"trusted\": true\n},\n\"id\": \"comparative-import\",\n\"cell_type\": \"code\",\n\"source\": \"import numpy as np\\nimport pandas as pd\\nimport matplotlib.pyplot as plt\\nimport seaborn as sns\\nimport nltk\\nimport re\\nimport gensim \\nfrom gensim.utils import simple_preprocess\\nfrom gensim.models.word2vec import Word2Vec\\nfrom nltk.stem.porter import PorterStemmer\\nfrom nltk.corpus import stopwords\\nfrom sklearn.decomposition import PCA,TruncatedSVD\\nfrom sklearn.manifold import TSNE\\nfrom sklearn.model_selection import train_test_split\\nfrom sklearn.linear_model import LogisticRegression\\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\\n\",\n\"execution_count\": 10,\n\"outputs\": []\n}","AnswerCount":4,"Available Count":2,"Score":1.2,"is_accepted":true,"ViewCount":3164,"Q_Id":67015684,"Users Score":5,"Answer":"I fixed the above issue by copying the content of the cell instead of the cell itself . I had been using multiple notebook , there had been some cope paste issue","Q_Score":1,"Tags":"python,jupyter-notebook","A_Id":67579587,"CreationDate":"2021-04-09T05:46:00.000","Title":"Notebook validation failed: Additional properties are not allowed ('id' was unexpected):","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Getting below validation error on opening my notebook :\n{\n\"metadata\": {\n\"trusted\": true\n},\n\"id\": \"comparative-import\",\n\"cell_type\": \"code\",\n\"source\": \"import numpy as np\\nimport pandas as pd\\nimport matplotlib.pyplot as plt\\nimport seaborn as sns\\nimport nltk\\nimport re\\nimport gensim \\nfrom gensim.utils import simple_preprocess\\nfrom gensim.models.word2vec import Word2Vec\\nfrom nltk.stem.porter import PorterStemmer\\nfrom nltk.corpus import stopwords\\nfrom sklearn.decomposition import PCA,TruncatedSVD\\nfrom sklearn.manifold import TSNE\\nfrom sklearn.model_selection import train_test_split\\nfrom sklearn.linear_model import LogisticRegression\\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\\n\",\n\"execution_count\": 10,\n\"outputs\": []\n}","AnswerCount":4,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":3164,"Q_Id":67015684,"Users Score":0,"Answer":"Try clear the output of all cells of your Jupyter Notebook.\nIn Jupyter Notebook, Goto: cell>All Output>Clear","Q_Score":1,"Tags":"python,jupyter-notebook","A_Id":70031662,"CreationDate":"2021-04-09T05:46:00.000","Title":"Notebook validation failed: Additional properties are not allowed ('id' was unexpected):","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to find the correlation between categorical and numerical columns in my dataset using Python, can anyone help?\nHere is the data that I have.\nThank you in advance.\n\n\n\n\nLight_Sensor_Reading\nLight_Sensor_Status\n\n\n\n\n231\nDim\n\n\n231\nDim\n\n\n231\nDim\n\n\n231\nDim\n\n\n231\nDim\n\n\n231\nDim\n\n\n231\nDim\n\n\n231\nDim\n\n\n231\nDim\n\n\n232\nDim\n\n\n950\nVery_bright\n\n\n988\nVery_bright\n\n\n987\nVery_bright\n\n\n986\nVery_bright\n\n\n986\nVery_bright\n\n\n986\nVery_bright\n\n\n986\nVery_bright\n\n\n986\nVery_bright\n\n\n986\nVery_bright\n\n\n986\nVery_bright\n\n\n986\nVery_bright\n\n\n986\nVery_bright\n\n\n986\nVery_bright\n\n\n985\nVery_bright\n\n\n985\nVery_bright","AnswerCount":4,"Available Count":1,"Score":0.049958375,"is_accepted":false,"ViewCount":5742,"Q_Id":67021061,"Users Score":1,"Answer":"it doesn't mean anything to calculate the correlation between two variables if they are not quantitative.\nI think what you want to do is to study the link between them.\nThe purpose is to explain the first variable with the other one through a model.\nYou can use the logistic regression.\nBut you will only know if there is a link between these two variables with a T-Test or a wilcoxon test depending on the normality of the data","Q_Score":2,"Tags":"python,correlation","A_Id":67024223,"CreationDate":"2021-04-09T12:20:00.000","Title":"how to find the correlation between categorical and numerical columns","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Can I have a one-hot encoding like [none, 1, 0, 0, none];\ni.e. I don't know if the sample class is 0 or 4, but I know its class 1, but not class 2 or 3\nThe loss function would then ignore where there's a none so we don't provide false-negatives.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":40,"Q_Id":67029738,"Users Score":0,"Answer":"The original case has categories: 0,1,2,3,4. To solve your question you can create the categories as follows:\n\n0, 1, 2, 3, 4, 5\nwhere the 5th category represents unsure nature of label, that is, its value will be 1 if you are unsure about the data point belonging to 0 or 4th label.\n\nNow you will have one-hot encoding in the form of [0,0,0,0,0,1] for the data points where it might belong to 0th or 4th category. You can filter these rows out and perform training on the remaining rows.","Q_Score":0,"Tags":"python,tensorflow,keras","A_Id":67031000,"CreationDate":"2021-04-10T00:24:00.000","Title":"Nullable one-hot encoding","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to load my dataset. I have been using colab's TPU for many times,but the colab gets disconnected every time. I have tried all the methods to keep it connected, still it doesn't work. I have been training for more than 10 hours and still the colab gets disconnected. What do I do??","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":224,"Q_Id":67042143,"Users Score":0,"Answer":"There could be many possibilities why your session is crashing.\n\nThere is a time limit for the free tier in Google Colab. If your execution gets over the time, it disconnects.\n\nAlso check the RAM usage, if that exceeds the session will crash.\n\nThe storage limits might exceed.\n\n\nRun and keep an eye on these factors. And try to optimise the code or use aws for training.","Q_Score":0,"Tags":"python,deep-learning,conv-neural-network,google-colaboratory","A_Id":67042207,"CreationDate":"2021-04-11T06:42:00.000","Title":"Why does colab disconnect?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm facing this issue in my college project which is a clickbait news classifier, i.e., it classifies between clickbait headlines and non-clickbait headlines. I'm using a dataset which has 16000 headlines of each type. Now, the main issue I'm facing is on training my network on 70% data, with 30% as my test set size. My validation set is 30% of the training set. But after fitting and evaluating the model on my test set, and I get this\nAfter fitting:\n\nEpoch 10\/10 131\/131 [==============================] - 1s 6ms\/step - loss: 0.2098 - accuracy: 0.9457 - val_loss: 0.3263 - val_accuracy: 0.9417\n\nAfter evaluating on test set:\n\n300\/300 [==============================] - 1s 2ms\/step - loss: 0.3030 - accuracy: 0.9432\n\nConfusion Matrix:\n\narray([[4638, 162], [ 383, 4417]])\n\nNow I'm very new to neural networks and i'm not sure if these accuracies are supposed to be this similar to each other. Is this something that I should be concerned about or am I missing something? I appreciate all the help I can get... Thanks!","AnswerCount":2,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":32,"Q_Id":67048165,"Users Score":2,"Answer":"your results look fine. Your test set and validation set have probability distributions which must be a close match to each other consequently the similarity in the validation and test data accuracies.","Q_Score":0,"Tags":"python,tensorflow,keras,nlp","A_Id":67049627,"CreationDate":"2021-04-11T17:30:00.000","Title":"Confusion regarding the accuracy of my model","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"In Keras, if I want to predict on my LSTM model for multiple instances, that are based on independent and new data from the training data, does the input array need to include the amount of time steps used in training? And, if so, can I expect that the shape of the input array for model.predict to be the same as the training data? (Ie [number of samples to be predicted on, their timesteps, their features])?\nThank you :)","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":256,"Q_Id":67054435,"Users Score":0,"Answer":"You need to distinguish between the 'sample' or 'batch' axis and the time steps and features dimensions.\nThe number of samples is variable - you can train (fit) your model on thousands of samples, and make a prediction for a single sample.\nThe times steps and feature dimensions have to be identical for fit and predict - that is because the weights etc. have the same dimensions for the input layer.\nIn that, an LSTM is not that much different from a DNN.\nThere are cases (eg. one-to-many models) in which the application is different, but the formal design (i.e. input shape, output shape) is the same.","Q_Score":3,"Tags":"python,tensorflow,keras,predict","A_Id":67054845,"CreationDate":"2021-04-12T07:47:00.000","Title":"How do I predict on multiple samples on an LSTM model?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I use the below statement, extracting cell content as legend name (I have 3 set of values to plot on y-axis, thus need 3 legend parameters)\nplt.legend(df.iat[0, 0], df.iat[0, 1], df.iat[0, 2])\nthe compiled error says that 'legend only accepts two non-keyword arguments'\nI print out the df.iat[0, 0], df.iat[0, 0], df.iat[0, 0], all these 3 are the cell content I expect.\nAnyone know how I can fix it?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":316,"Q_Id":67055120,"Users Score":0,"Answer":"You have to put the values in a list:\nplt.legend([df.iat[0, 0], df.iat[0, 1], df.iat[0, 2]])","Q_Score":0,"Tags":"python,pandas,csv,matplotlib","A_Id":67055221,"CreationDate":"2021-04-12T08:34:00.000","Title":"pandas plt.legend issue. error says that 'legend only accepts two non-keyword arguments'","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"Is it possible for a search algorithm for linked lists to be O(log\u00a0n)? From my understanding, linked lists could have either O(n) or O(1) since you can choose where to start, from the start of the link list to the end. Knowing this, can you start in the middle for a searching algorithm that runs in O(log\u00a0n) time?","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":868,"Q_Id":67071621,"Users Score":1,"Answer":"An O(log n) algorithm would require to\n\ndivide the list into a fixed number of parts in constant time, and\ndetermine in which of the parts the searched item is in constant time.\n\ne.g. for a binary search algorithm for a sorted indexed array data structure which keeps track of its size, the split point can be calculated directly from the size of the array, and it can be determined whether the searched item is in the first or second half by a comparison with the item at the split point.\nBut for a linked list, you don't know its size and would have to traverse it in order to find the split points. This is an O(n) operation, so the overall algorithm can't be O(log\u00a0n).\nIn general, the second requirement is also not satisfied.","Q_Score":2,"Tags":"python,algorithm,linked-list","A_Id":67071874,"CreationDate":"2021-04-13T08:50:00.000","Title":"Is an O(log n) linked list search algorithm possible?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm using OS X now and got a problem with importing tensorflow.\nI'm using anaconda and made a new virtual environment with python 3.7 and tensor flow 1.15.0.\nI've no problem so far but from yesterday I got error massages like below\n\nimport tensorflow as tf\nTraceback (most recent call last): File \"\", line 1, in\n File\n\"\/usr\/local\/anaconda3\/envs\/python3.7_tf1\/lib\/python3.7\/site-packages\/tensorflow\/init.py\",\nline 99, in \nfrom tensorflow_core import * File \"\/usr\/local\/anaconda3\/envs\/python3.7_tf1\/lib\/python3.7\/site-packages\/tensorflow_core\/init.py\",\nline 28, in \nfrom tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import ImportError: cannot import name\n'pywrap_tensorflow' from 'tensorflow_core.python' (unknown location)\n\nI tried to make a new virtual environment and set the same setting but it didn't work neither.\nwhat should I do?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":31,"Q_Id":67085037,"Users Score":0,"Answer":"Problem solved.\nThe main issue was a directory of python file that I tried to run by using conda.\nI moved that file out of problematic folder and it worked.","Q_Score":0,"Tags":"python,tensorflow","A_Id":67101790,"CreationDate":"2021-04-14T03:18:00.000","Title":"Tensorflow import issues on the anaconda virtual environment","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"currently I learning the subject of camera calibration. In context of extrinsic camera calibration I read a lot about cv2.rodrigues(). For example to obtain the pose of the camera. But I dont understand why we have to use this function? What is realy the aim of it?\nThanks","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":490,"Q_Id":67088230,"Users Score":2,"Answer":"Rodrigues is a way to parameter a rotation in the 3d space. It's good because it takes 3 parameters and a rotation in 3d space has 3 degree of freedom. Rotation matrix has 9 parameters and quaternion 4, euler angles have other problems.\nA rotation in 3d space is a screwing, it's a rotation around an axis. You put the normalized axis in a vector then you multiply by the angle of rotation in radian and you get the rodrigues. It makes the Rodrigues understandable by human.","Q_Score":1,"Tags":"python,opencv,camera-calibration","A_Id":67089489,"CreationDate":"2021-04-14T08:34:00.000","Title":"What is the aim of cv2.Rodrigues() applying on rvec in context of camera calibration","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Usually any search engine software creates inverted indexes to make searches faster. The basic format is:-\nword: , , .....\nWhenever there is a search query inside quote like \"Harry Potter Movies\" it means there should be exact match of positions of word and in searches like within k word queries like hello \/4 world it generally means that find the word world in the range of 4 word distance either in left or right from the word hello. My question is that we can employ solution like linearly checking the postings and calculating distances of words like in query, but if collection is really large we can't really search all the postings. So is there any other data structure or kind of optimisation lucene or solr uses?\nOne first solution can be only searching some k postings for each word. Other solution can be only searching top docs(usually called champion list sorted by tf-idf or similar during indexing), but more better docs can be ignored. Both solutions have some disadvantage, they both don't ensure quality. But in Solr server we get assured quality of results even in large collections. How?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":166,"Q_Id":67103440,"Users Score":2,"Answer":"The phrase query you are asking about here is actually really efficient to compute the positions of, because you're asking for the documents where 'Harry' AND 'Potter' AND 'Movies' occur.\nLucene is pretty smart, but the core of its algorithm for this is that it only needs to visit the positions lists of documents where all three of these terms even occur.\nLucene's postings are also sharded into multiple files:\nInside the counts-files are: (Document, TF, PositionsAddr)+\nInside the positions-files are: (PositionsArray)\nSo it can sweep across the (doc, tf, pos_addr) for each of these three terms, and only consult the PositionsArray when all three words occur in the specific document. Phrase queries have the opportunity to be really quick, because you only visit at most all the documents from the least-frequent term.\nIf you want to see a phrase query run slowly (and do lots of disk seeks!), try: \"to be or not to be\" ... here the AND part doesn't help much because all the terms are very common.","Q_Score":1,"Tags":"python,solr,lucene,information-retrieval,inverted-index","A_Id":67111257,"CreationDate":"2021-04-15T06:39:00.000","Title":"How Lucene positional index works so efficiently?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"So, I recently converted my custom object detection model from Tensorflow '1.15.0' to Tensorflow lite so I can implement it on a raspberry PI 3\nBut, when I tryed to test it using a camera and opencv '4.5.1' I got this error 'Unsupported data type 13 in tensor'.\nCan anyone help me understand this error?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":396,"Q_Id":67106790,"Users Score":0,"Answer":"I recommend using the latest TensorFlow Lite runtime version, for example, TensorFlow 2.5 or beyonds in the Raspberry Pi.\nThe data type 13 is TFLite resource type, which is supported from the TensorFlow 2.5 version.","Q_Score":0,"Tags":"python,tensorflow,tensor,tensorflow-lite","A_Id":67107083,"CreationDate":"2021-04-15T10:29:00.000","Title":"ValueError: Unsupported data type 13 in tensor","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"In Python I have a masked array, mask_array, and I want to set all remaining (unmasked) values to 1. When I do mask_array[(mask_array >= 0) & (mask_array < 0)= 1, the cells keep their original values and do not change to 1. When I do mask_array[mask_array>=0]=1, all cells including those I had masked originally change to 1. Why is this the case?\nIs there a solution?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":27,"Q_Id":67107580,"Users Score":1,"Answer":"The condition (mask_array >= 0) & (mask_array < 0) can't match any cell. No value inside mask_array can be bigger or equal to 0 and smaller than 0 at the same time, so nothing matches => no changes","Q_Score":0,"Tags":"python,numpy","A_Id":67107618,"CreationDate":"2021-04-15T11:26:00.000","Title":"How to set all unmasked values to a certain value?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to find a fast method to compare every DataFrame row with the next N without using a \"for cycle\" (due to time computational problems).\nHere an example. My dataframe df is:\nindex | col 1 | col 2 \n0 c \n1 a \n2 b \n3 b \n4 c \n... \nI want to insert True\/False in col 2 (i-th rows) if, in one of the next N, the col 1 value is the same as the one in the i-th row.\nHere the results for N=3.\nindex | col 1 | col 2 \n0 c False \n1 a False \n2 b True \n3 b False \n4 c True \n5 a ... \n6 c \n... \nNB I've tried to create new columns with shift and compare with .loc, but with big N I still have computational problems","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":68,"Q_Id":67112330,"Users Score":0,"Answer":"So, a python equivalent would look something like: col2[i] = col1[i] in col1[i+1:i+N+1] in a loop?","Q_Score":0,"Tags":"python,pandas,dataframe,numpy","A_Id":67113186,"CreationDate":"2021-04-15T16:26:00.000","Title":"How to compare different rows of the same DataFrame in Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm doing a segmentation task. Now I successfully segmented the area of interest and find the contour of the area. How can I calculate the min\/max axis length of the contour? The axis does not have to be orthogonal.\nWhat I already got are:\ncoordinates of points on the contour.\ncentroid of the contour.\nWhat I already tried:\nI have found a fitting-ellipse of the contour. However, fitting-ellipse can only find the orthogonal axis which might not be the minimum or maximum length across the centroid.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":58,"Q_Id":67118098,"Users Score":0,"Answer":"Since you already have the contour, you might want to do this:\nfor alpha = 0 to 45 degrees, rotate the contour by alpha, draw a line over the centroid of your contour that is parallel to X-axis, find out the intersection points of this line and the contour, that is one \"axis\" at current angle alpha. continue rotating the contour and find more of such \"axis\", find the longest one as your max axis, shortest one as your min axis.","Q_Score":0,"Tags":"python,geometry,medical-imaging","A_Id":67711250,"CreationDate":"2021-04-16T01:53:00.000","Title":"how to find min\/max axis length across the centroid of a closed curve","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using canvas.mpl_connect mouse click listener for my e.g. 100x100 contourf plot with xlim from 0 to 99. Doing so I get e.g [x,y]= 10,20 as desired. However I have to display a second x-axis with different coordinates (e.g. xlim from 0.01 to 1) but I dont want event.xdata to return the coordinates in the style of the second axis. Is there a possibility to do so?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":188,"Q_Id":67122599,"Users Score":0,"Answer":"thanks, I implemented something like this as well. The problem is that there is actually no direct linear transformation behind my data. I solved the issue by just calling the second axis in a function after I finished setting the marker or choosing points. It's not beautiful but should be fine for a Master's thesis!","Q_Score":1,"Tags":"python,matplotlib","A_Id":67160521,"CreationDate":"2021-04-16T09:25:00.000","Title":"Python mouse click event.xdata using twinx()","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"from statsmodels.tsa.statespace.sarimax import SARIMAX\nfrom math import sqrt\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error\nfrom multiprocessing import Pool\nfrom tool.utils import Util\nI have downloaded Util, tools moule still it shows ModuleNotFoundError: No module named 'tool'","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":393,"Q_Id":67124465,"Users Score":0,"Answer":"If you have multiple python installations, make sure you are installing the package for the correct python version. To install a package for python3.x use python3.x -m pip install {package}","Q_Score":1,"Tags":"python-3.x","A_Id":67126167,"CreationDate":"2021-04-16T11:33:00.000","Title":"ModuleNotFoundError: No module named 'tool'","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"since i couldn't find the best way to deal with my issue i came here to ask..\nI'm a beginner with Python but i have to handle a large dataset.\nHowever, i don't know what's the best way to handle the \"Memory Error\" problem.\nI already have a 64 bits 3.7.3 Python version.\nI saw that we can use TensorFlow or specify chunks in the pandas instruction or use the library Dask but i don't know which one is the best to fit with my problem and as a beginner it's not very clear.\nI have a huge dataset (over 100M observations) i don't think reducing the dataset would decrease a lot the memory.\nWhat i want to do is to test multiple ML algorithms with a train and test samples. I don't know how to deal with the problem.\nThanks!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":61,"Q_Id":67126819,"Users Score":0,"Answer":"This question is high level, so I'll provide some broad approaches for reducing memory usage in Dask:\n\nUse a columnar file format like Parquet so you can leverage column pruning\nUse column dtypes that require less memory int8 instead of int64\nStrategically persist in memory, where appropriate\nUse a cluster that's sized well for your data (running an analysis on 2GB of data requires different amounts of memory than 2TB)\nsplit data into multiple files so it's easier to process in parallel\n\nYour data has 100 million rows, which isn't that big (unless it had thousands of columns). Big data typically has billions or trillions of rows.\nFeel free to add questions that are more specific and I can provide more specific advice. You can provide the specs of your machine \/ cluster, the memory requirements of the DataFrame (via ddf.memory_usage(deep=True)) and the actual code you're trying to run.","Q_Score":0,"Tags":"python,pandas,tensorflow,out-of-memory,dask","A_Id":69481669,"CreationDate":"2021-04-16T14:12:00.000","Title":"Import and work with large dataset (Python beginners)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I was learning, working of object detection models Faster R CNN,YOLOv3 and SSD.I got confusion with anchor box size refining.","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":587,"Q_Id":67129505,"Users Score":1,"Answer":"Of course anchor boxes size (and position) get refined during training. As you said in a comment anchor boxes are nothing more than a set of reference boxes present at fixed positions on the output grid. Each grid cell additionally predicts the object-ness score as well as the label and the exact coordinates of the bounding box.\nThese last coordinates correspond to the box size refining you are talking about. The implementation of such regression differs upon networks (SSD, Yolo, Faster-RCNN, ...).\nI encourage you to read the literature, and especially the Yolo papers that are very clear. In \"YOLO9000: Better, Faster, Stronger\" (available for free online), bounding box refining is explained in great detail page 3.\nOf course all of this is learnt during training, take a look at the loss function of Yolo in \"You Only Look Once: Unified, Real-Time Object Detection\" paper page 4.","Q_Score":1,"Tags":"python,object-detection,yolo,faster-rcnn","A_Id":67158095,"CreationDate":"2021-04-16T17:12:00.000","Title":"Do anchor box size gets refined during training object detection models like Faster R CNN,YOLO and SSD?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm new to LDA and I want to calculate the topic similarity between words. Can I get the topic distribution of a word? If so, how can I do this in gensim.ldamodel?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":92,"Q_Id":67148633,"Users Score":0,"Answer":"Gensim's LDA mallet wrapper has a load_word_topics() function (I would assume this is true for its python LDA implementation as well). It returns a matrix that is words X topics. From that, you can get a vector of frequencies each word in each topic. That would be the topic-word distribution for a given word.","Q_Score":0,"Tags":"python,gensim,lda,topic-modeling","A_Id":67153031,"CreationDate":"2021-04-18T12:40:00.000","Title":"Can I get topics distribution of a word in LDA?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm taking an entry level ML course and I'm working on analysing the iris dataset from the sklearn library, and one thing I need to do is print out the third feature associated with the list of data. I also need to make sure that the shape is (150,).\nWhat I tried:\nx = iris.data[:, 2:3] Which does give me the third feature, but the shape is (150,1) rather than (150,) and I don't quite understand why.\nWould appreciate some help, thanks in advance.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":145,"Q_Id":67155413,"Users Score":1,"Answer":"iris.data[:, 2:3] gives you a view of features 2 (incl) to 3 (excl), think of that as a list of 1 feature, hence the last 1 in your shape. Just use iris.data[:, 2] directly to make it a 1 dimensional array (whose shape has length 1).","Q_Score":0,"Tags":"python,numpy,machine-learning","A_Id":67155434,"CreationDate":"2021-04-19T02:56:00.000","Title":"Numpy Arrays, wrong shape","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am building a custom stat space model using statsmodels' MLEModel class, and fitting the unknown parameters with the .fit() method. I thought that it was using Expectation Maximization, but I am not sure of that and I cannot find any hint to this in the documentation. Moreover, the verbose output of the .fit() method shows the steps of a single optimization, and this makes me even more doubtful.\nIf it is not using EM, what is it doing? maybe I am missing something here, but I thought that for models with hidden variables (like state space models) you cannot directly minimize the likelihood (since you don't know and don't observe the hidden states).\nthanks for any suggestion","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":138,"Q_Id":67160062,"Users Score":0,"Answer":"In general, fit() is a method of the model class. Depending on the class object the method fit() from that class will be called. In general, fit() estimates parameters via maximum likelihood and return a results object.\nThe expectation maximization (EM) algorithm requires and uses the Kalman smoother for models with hidden variables if I'm not mistaken.\nEDIT: fit() will cal the fit() of its parent class which in this case is tsbase.TimeSeriesModel as seen in class MLEModel(tsbase.TimeSeriesModel). In turn, class TimeSeriesModel(base.LikelihoodModel) will call its parent class which is base.LikelihoodModel. class LikelihoodModel(Model)'s fit() function default method argument is 'newton'. Thus, Maximum likelihood (ML) estimation will be estimated using Newton's method in this custom state space model.","Q_Score":1,"Tags":"python,statsmodels,expectation-maximization","A_Id":67160460,"CreationDate":"2021-04-19T10:14:00.000","Title":"is statsmodels' MLEModel class using Expectation Maximization for fitting?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"OOBPermutedVarDeltaError states that\n\nFor any variable, the measure is the increase in prediction error if the values of that variable are permuted across the observations. This measure is computed for every tree, then averaged over the entire ensemble and divided by the standard deviation over the entire ensemble\n\nTo find its equivalent would I need to calculate the increase in prediction error across observations and then average it across the entire ensemble? Being fairly new to ML, I am not sure how I would implement it even. Any help would be most appreciated.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":26,"Q_Id":67172243,"Users Score":0,"Answer":"No, there arent any. Python and Matlab, does not scale 1:1","Q_Score":1,"Tags":"python,matlab","A_Id":72350666,"CreationDate":"2021-04-20T03:57:00.000","Title":"Is there any python equivalent of OOBPermutedVarDeltaError from Matlab?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"recently I made a little program that generates a country with a bit of info, like the country name, size and most importantly cities.\nIt generates a random number of cities and towns and villages based on the country's size, this is all text based so that is why I would give it a nice flare with some graphics.\nNow, I have been researching a bit and it seems that my best option would be Perlin noise or some form of noise, so my question is, how would I go about doing this? Where do I start? Are there other ways of accomplishing this?\nSo, in short, how do I take the randomly generated text cities and towns and villages in my program and randomly generate them on some form of map? I hope this all makes sense. Also, my program is written in python.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":181,"Q_Id":67176945,"Users Score":1,"Answer":"There is lots of problem in what you saying. What platform are you using? Arcade? PyGame? etc. I will write the arcade code for you so you can use. To use arcade, type pip install arcade in Windows, or pip3 install arcade on Linux.\nEdit:\nPlease can you post your code so I can implement?","Q_Score":0,"Tags":"python,noise","A_Id":67177343,"CreationDate":"2021-04-20T10:17:00.000","Title":"How would I go about generating cities and countries with perlin noise?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I would like to generate some data (position of the snake, available moves, distance from the food...) to create a neural network model so that it can be trained on the data to play the snake game. However, I don't know how to do that. My current ideas are:\n\nPlay manually (by myself) the game for many iterations and store the data (drawback: I should play the game a lot of times).\nMake the snake do some random movements track and track their outcomes.\nPlay the snake with depth-fist search or similar algorithms many times and store the data.\n\nCan you suggest to me some other method or should I choose from one of those? Which one in that case?\nP.S. I don't know if it is the right place to ask such a question. However, I don't know whom\/where to ask such a question hence, I am here.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":109,"Q_Id":67177184,"Users Score":1,"Answer":"If using a neural network, start simple. Think inputs and outputs and keep them simple too.\nInputs:\n\nHow many squares to the left of the head are free\nHow many squares to the right of the head are free\nHow many squares forward of the head are free\nRelative position of next food left\/right\nRelative position of next food forward\/back\nLength of snake\n\nkeep inputs normalized to the minimum and maximum possible values to keep inputs in range -1.0 to 1.0\nOutputs:\n\nTurn Left\nTurn Right\nStraight Ahead\n\n(choose the output with highest activation)\nNext problem is training. Typical application might be use a genetic algorithm for all the weights of the above neural network. This randomizes and tests new versions of the neural network every life. After X attempts, create a new evolution and repeat to improve. This is pretty much doing random moves automatically (your second choice)\nNext problem is fitness for training. How do you know which neural network is better? Well you could simply use the length of the snake as a fitness factor - the longer the snake, the better and more 'fit'","Q_Score":0,"Tags":"python,neural-network,reinforcement-learning","A_Id":67346604,"CreationDate":"2021-04-20T10:33:00.000","Title":"Generate the data for A.I. to play the Snake game","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a deep learning model which consists of various layers. I am running it for 20 epochs. I want to divide the whole data into 20 batches and each batch will go in each epoch. So, if I have 20 slices of the data, is there a way to fit each slice in each epoch.\ntext_model.fit(x_train, y_train, epochs=20)\nThe name of the model class is text_model which I want to fit each epoch.\nI will appreciate any help with this.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":463,"Q_Id":67183694,"Users Score":0,"Answer":"Why would you need to pass a different batch for each epoch? By definition, an epoch is a pass through the whole dataset, and at each step of the epoch we pass a different batch of data. This is what you want to do, except it happens automatically within each epoch.\nIf for some strange reason you still want to use a unique batch per epoch, every time different, you can just call .fit() in a loop, using every time a different slice of the original dataset as input. It will be unnecessarily slow tho, and won't provide any additional feature with respect to just fit the entire dataset with batches of size (number of samples \/ number of batches you want)","Q_Score":0,"Tags":"python,tensorflow,keras,deep-learning","A_Id":67183798,"CreationDate":"2021-04-20T17:32:00.000","Title":"Fitting a deep learning model with a different batch of data every epoch Keras Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have some unsupervised data (100.000 files) and each file has a paragraph containing one sentence. The preprocessing went wrong and deleted all stop points (.).\nI used word2vec on a small sample (2000 files) and it treated each document as one sentence.\nShould I continue the process on all remaining files? Or this would result to a bad model ?\nThank you","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":81,"Q_Id":67185941,"Users Score":1,"Answer":"Did you try it, and get bad results?\nI'm not sure what you mean by \"deleted all stop points\". But, Gensim's Word2Vec is oblivious to what your tokens are, and doesn't really have any idea of 'sentences'.\nAll that matters is the lists-of-tokens you provide. (Sometimes people include puntuation like '.' as tokens, and sometimes it's stripped - and it doesn't make a very big different either way, and to the extent it does, whether it's good or bad may depend on your data & goals.)\nAny lists-of-tokens that include neighboring related tokens, for the sort of context-window training that's central to the word2vec algorithm, should work well.\nFor example, it can't learn anything from one-word texts, where there are no neighboring words. But running togther sentences, paragraphs, and even full documents into long texts works fine.\nEven concatenating wholly-unrelated texts doesn't hurt much: the bit of random noise from unrelated words now in-each-others' windows is outweighed, with enough training, by the meaningful relationships in the much-longer runs of truly-related text.\nThe main limit to consider is that each training text (list of tokens) shouldn't be more than 10,000 tokens long, as internal implementation limits up through Gensim 4.0 mean tokens past the 10,000th position will be ignored. (This limit might eventually be fixed - but until then, just splitting overlong texts into 10,000-token chunks is a fine workaround with negligible effects via the lost contexts at the break points.)","Q_Score":1,"Tags":"python,nlp,gensim,word2vec","A_Id":67186195,"CreationDate":"2021-04-20T20:32:00.000","Title":"Word2vec on documents each one containing one sentence","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have an equation, solved using FiPy, where my results are stored in a matrix result\n--> result[t][-1] indicates the outlet value (1D mesh) in time t\nI would like to use this outlet value as an inlet value (constrain) in another equation. Note that this value will vary in time. Is that possible to do so in FiPy?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":47,"Q_Id":67187902,"Users Score":0,"Answer":"I don't think you can do this with FiPy's lazy evaluation, but you can call .setValue() on the variable defining the constraint at each time step.","Q_Score":0,"Tags":"python,fipy","A_Id":67188494,"CreationDate":"2021-04-21T00:37:00.000","Title":"Variable constrain in FiPy","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am looking for suggestions or best practices to follow in terms of converting a 12-bit (0-4096) grayscale image to a 3-channel 8-bit color image in Python in order to pass it into a convolutional neural network.\nWith 8-bit RGB, I essentially have 24-bit colour, so I see no reason to lose data in the conversion, although most other posts suggest simply dividing the pixel value by 16 in order to squeeze it into 8-bits and then replicating this over all three channels in a lossy way.\nSome ideas I have come up with include creating some kind of gradient function that converts the 12-bit uint to a corresponding colour on the gradient, but my understanding of the RGB colour space is that this would be tricky to implement using Numpy or other such libraries.\nDo any of the common libraries such as OpenCV \/ Scikit offer this kind of functionality? I cannot find anything in the docs. Other ideas include using some kind of intermediary color space such as HSL\/L*AB but I don't really know enough about this.\nPlease note that I am ultimately trying to create an 8-bit RGB image, not a 16-bit RGB image. Simply trying to colorize the grayscale image in a way that retains the original 12-bit data across the colour range.\nHope somebody can help!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":592,"Q_Id":67188037,"Users Score":0,"Answer":"My first question would be: Why do you need to convert it to color in any specific way?\nIf you are training the CNN on these images, any arbitrary transformation should work and give you similar performance. You just need to convert the training images and input images in the same manner.\nYou could probably just split the 16 bits and put the bottom half in R, the top half in G, and leave B with zeroes.\nIt kinda depends on how black-box this CNN is. But you can always test this by running a few training\/testing cycles with the conversion I mentioned above and then do that again with the \"compressed\" versions.","Q_Score":4,"Tags":"python,opencv,python-imaging-library,scikit-image","A_Id":67188063,"CreationDate":"2021-04-21T01:00:00.000","Title":"Converting a 12-bit grayscale image to 8-bit per channel color image in Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to make a small data science tool (kinda like a mini version of WEKA). Now, I have these datasets that have large amounts of features (70-100+), and they're mostly categorical. I'm using Python sklearn for the Machine Learning logic and I need to convert these categories into numeric values according to the sklearn errors I've gotten.\nGiven this, One Hot Encoding isn't an option because it will enlarge the dimensionality too much.\nI've researched other ways that may work like frequency encoding, label encoding, etc. But I'm not really sure what to choose in my case.\nAlso, would anyone know how WEKA actually handles these? I inputted my datasets in WEKA and they worked fine, they gave me good results!\nAny help would be greatly appreciated. Thanks!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":147,"Q_Id":67197522,"Users Score":0,"Answer":"That depends on the algorithm: Some handle categorical attributes natively, like J48 (Weka's C4.5 implementation), which performs multi-way splits on categorical attributes. Others have to convert the data, like SMO (support vector machine), which binarizes nominal attributes and increases the number of attributes to learn from.","Q_Score":0,"Tags":"python,machine-learning,scikit-learn,weka,categorical-data","A_Id":67203824,"CreationDate":"2021-04-21T14:07:00.000","Title":"What is the best way to encode a large number of categorical features?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have used skikit-learn ColumnTransformer and OneHotEncoder to encode a dataframe containing categorical and continuous data (I did not use OneHotEncoder on the continuous data) but this has completely reordered the columns and removed the names. Can I use this reordered array to develop a model or will I need to reorder them back to the original order so I can interpret the data later?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":45,"Q_Id":67209798,"Users Score":0,"Answer":"If you are training a fresh model (no transfer learning), columns order should not be a problem.","Q_Score":0,"Tags":"python-3.x,scikit-learn,one-hot-encoding","A_Id":67210164,"CreationDate":"2021-04-22T08:44:00.000","Title":"Will column reordering following ColumnTransformer and OneHotEncoder affect model?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Any information on how to resize the numpy arrays to be of same shape for training would be very helpful.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":32,"Q_Id":67225826,"Users Score":0,"Answer":"your input matrix os of size(101,150) means the total element is 15150, but the Your NN is taking only 3204 elements as input. To solve this either you have to add an extra input layer in NN which has 15150 input nodes either you have to remove some features from the matrix. Depending on your input you can use Principal Component Analysis (PCA) Algorithm. It is sed to for dimensionality reduction. you can use numpy.shape() to reshape your input matrix.","Q_Score":0,"Tags":"python,numpy,tensorflow","A_Id":67226865,"CreationDate":"2021-04-23T07:38:00.000","Title":"My input npy files are of size (101,150) and my (target)label npy files are (801,4). How should I feed this type of data to neural network?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"can anyone tell me how to fix this?\nModuleNotFoundError: No module named 'sklearn.linear_model._logistic'\nFile \"c:\\users\\chintan\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\streamlit\\script_runner.py\", line 332, in _run_script\nexec(code, module.dict)\nFile \"C:\\Users\\chintan\\Desktop\\streamlit\\Final_year_project\\App.py\", line 329, in \nmain()\nFile \"C:\\Users\\chintan\\Desktop\\streamlit\\Final_year_project\\App.py\", line 264, in main\nloaded_model = load_model(\"logistic_regression_hepB_model.pkl\")\nFile \"C:\\Users\\chintan\\Desktop\\streamlit\\Final_year_project\\App.py\", line 96, in load_model\nloaded_model = joblib.load(open(os.path.join(model_file),\"rb\"))\nFile \"c:\\users\\chintan\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\sklearn\\externals\\joblib\\numpy_pickle.py\", line 588, in load\nobj = _unpickle(fobj)\nFile \"c:\\users\\chintan\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\sklearn\\externals\\joblib\\numpy_pickle.py\", line 526, in _unpickle\nobj = unpickler.load()\nFile \"c:\\users\\chintan\\appdata\\local\\programs\\python\\python37\\lib\\pickle.py\", line 1088, in load\ndispatchkey[0]\nFile \"c:\\users\\chintan\\appdata\\local\\programs\\python\\python37\\lib\\pickle.py\", line 1376, in load_global\nklass = self.find_class(module, name)\nFile \"c:\\users\\chintan\\appdata\\local\\programs\\python\\python37\\lib\\pickle.py\", line 1426, in find_class\nimport(module, level=0)","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":131,"Q_Id":67235806,"Users Score":0,"Answer":"Try to install a version like: pip install scikit-learn==0.22","Q_Score":0,"Tags":"python,scikit-learn","A_Id":67241490,"CreationDate":"2021-04-23T19:24:00.000","Title":"getting an issue in sklearn.linear_model._logistic in ml","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a regression problem having 1 target and 10 features. When I look at the outliers for each feature by box-plot, they have different number of outliers. While removing outliers, do I need to also remove the associated target values with those outliers?\nI mean, let's say: for #1 feature I have 12 outliers and I removed them with 12 target values. Then, for #2 feature I have 23 outliers and I removed them with 23 target values, as well, and so on. The procedure would be like this, or how should I proceed?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":172,"Q_Id":67241536,"Users Score":0,"Answer":"I imagine each row of your data contains an ID, the value of the target and 10 feature values, one of each feature. To answer our question: if you want to remove the outliers, you have to remove the whole observation\/row - the value that you classify as an outlier, the corresponding target value, as well as all other 9 corresponding feature values. So you would have to filter each row for the entry of feature_i being smaller than the threshold_i that you defined as an outlier.\nThe reason is that a multilinear regression calculates the influence of an incremental change in one feature on the target, assuming all other 9 features being constant. Removing a single feature value without removing the target and the other features of this observation simply does not work in such a model (assuming you are using an OLS).\nHowever, I would be cautious with removing outliers. I don't know about your sample size and what you consider an outlier and it would help to know more about your research question, data and methodology.","Q_Score":0,"Tags":"python,regression","A_Id":67241632,"CreationDate":"2021-04-24T10:05:00.000","Title":"Removing Outliers in a Multi-feature Regression Problem","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Python: how to get unique ID and remove duplicates from column 1 (ID), and column 3 (Description), Then get the median for column 2\n\n\n\n\nID\nValue\nDescription\n\n\n\n\n123456\n116\nxx\n\n\n123456\n117\nxx\n\n\n123456\n113\nxx\n\n\n123456\n109\nxz\n\n\n123456\n108\nxz\n\n\n123456\n98\nxz\n\n\n121214\n115\nabc\n\n\n121214\n110\nabc\n\n\n121214\n103\nabc\n\n\n121214\n117\nabz\n\n\n121214\n120\nabz\n\n\n121214\n125\nabz\n\n\n151416\n114\nzxc\n\n\n151416\n135\nzxc\n\n\n151416\n127\nzxc\n\n\n151416\n145\nzxm\n\n\n151416\n125\nzxm\n\n\n151416\n121\nzxm\n\n\n\n\nProcced table should look like:\n\n\n\n\nID\nxx\nxz\nabc\nabz\nzxc\nzxm\n\n\n\n\n123456\n110\n151\n0\n0\n0\n0\n\n\n121214\n0\n0\n132\n113\n0\n0\n\n\n151416\n0\n0\n0\n0\n124\n115","AnswerCount":4,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":180,"Q_Id":67243543,"Users Score":0,"Answer":"Well you have e.g. 6 'ID' with value '123456'. If you only want unique 'ID', you need to remove 5 'ID' rows, by doing this you will not have duplicate 'Description' values anymore. The question is, do you want unique ID or unique Description values (or unique combination of both)?","Q_Score":0,"Tags":"python","A_Id":67244109,"CreationDate":"2021-04-24T13:54:00.000","Title":"Python: how to get unique ID and remove duplicates from column 1 (ID), and column 3 (Description), Then get the median for column 2 (Value) in Pandas","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to use Python to do some forecasting on 1 year wind speed, one of the method is fbprophet. After sometime browsing I found out that I need to istall it with Conda Forge.\nI am completely new in this, but it seems by changing channel I need to instal some packages(panda, numpy) again using Conda forge.\nOne of the missing pakcage is tbats, unfortunately I could not find a way to install it with COnda-forge, only the usual pip install tbats\nIs there a way I could use both tbats and fbprophet at python together?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":369,"Q_Id":67247816,"Users Score":0,"Answer":"Yes you can use both packages, conda environment can install packages using either conda install or pip install. In this case, after you install prophet just install TBATS using pip install tbats","Q_Score":2,"Tags":"python,forecasting,arima,moving-average","A_Id":68281962,"CreationDate":"2021-04-24T21:58:00.000","Title":"Installing TBATS using Conda forge","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've got 2 long numpy arrays, both having 508 elements. I would like to get the indices of where they differ. Most of the solutions I've seen determining difference here sort the arrays which is not suitable in my case.\nExample\narr_1 = [0, 1, 4, 0, 2, 2, 0, 3, 5, ... , 5, 5, 6]\narr_1 = [0, 1, 0, 0, 0, 2, 0, 3, 0, ... , 5, 0, 6]\nHopefully returning something like:\nsolut = [0, 0, 1, 0, 1, 0, 0, 0, 1, ... , 0, 1, 0]\nor even\nsolut = [2, 4, 8, ..., n-2]\nIs there an efficient way to do this in numpy?","AnswerCount":2,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":51,"Q_Id":67263585,"Users Score":2,"Answer":"You can just write arr = arr_1 == arr_2. This code gives you a boolean array with true if they are equal and false if not. Then you can use np.where to find the indices where the arrays are equal or not.","Q_Score":2,"Tags":"python,numpy,array-difference","A_Id":67263699,"CreationDate":"2021-04-26T08:53:00.000","Title":"Determining the indicies where 2 numpy arrays differ","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm building a python application that uses AI to scan a live feed with OpenCV and tracks people with or without masks.\nI wanted to ask if there was a good way to send a unique dataframe for every unique entity tracked in the feed in order to create a procedural entry on a database of each person tracked as they entered the frame and whether they were wearing a mask.\nAny advice?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":90,"Q_Id":67265618,"Users Score":1,"Answer":"You could make a pandas dataframe with two columns: Name and isWearingMask, and append that dataframe with a new row every time a person is detected. Then use the time module to know to save the pandas database as a .CSV file at the end of a day. The next day, clear the pandas dataframe and repeat the process.","Q_Score":0,"Tags":"python,dataframe,tensorflow,opencv,object-recognition","A_Id":67266434,"CreationDate":"2021-04-26T11:13:00.000","Title":"How do I trigger a JSON or pd Dataframe report from each Object detected by a TensorFlow\/OpenCV object detection","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I need to make a script for NLP in python. Given a string, I need to identify the food and output the calories. I thought of using a csv dataset and creating a model with tensorflow to identify the food. it's correct? do you think we can do another way?\nDo you have examples or suggestions?\nthank you","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":77,"Q_Id":67265819,"Users Score":0,"Answer":"You will have to use NER model to identify food in the string, and then you use the identified food to check the repository which has food calories for respective food item and share the output.","Q_Score":0,"Tags":"python,tensorflow,keras,nlp,named-entity-recognition","A_Id":67266969,"CreationDate":"2021-04-26T11:28:00.000","Title":"NLP in python for food","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm currently dealing with a material science dataset having various information.\nIn particular, I have a column 'Structure' with several pymatgen.core.Structure objects.\nI would like to save\/store this dataset as .csv file or something similar but the problem is that after having done that and reopening, the pymatgen structures lose their type becoming just formatted strings and I cannot get back to their initial pymatgen.core.Structure data type.\nAny hints on how to that? I'm searching on pymatgen documentation but haven't been lucky for now..\nThanks in advance!","AnswerCount":2,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":104,"Q_Id":67283018,"Users Score":2,"Answer":"pymatgen.core.structure object can be stored with only some sort of fixed format, for example, cif, vasp, xyz... so maybe you, first, need to store your structure information to cif or vasp. and open it and preprocess to make it \"csv\" form with python command.(hint : using python string-related command).","Q_Score":0,"Tags":"python,pandas,dataframe,encoding,pymatgen","A_Id":69388052,"CreationDate":"2021-04-27T12:25:00.000","Title":"Saving\/Storing pymatgen Structures","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a Dataproc cluster to transform many CSV files stored in GCS, but when I write the CSV to a GCS bucket this takes too much time, 7h for one file (12 go).\nThis is the code that I used to read & write the CSV:\ndf = spark.read.options(delimiter='\u00a4',header=\"true\").csv('gs:\/\/'+bucket_name+'\/'+file_name)\ndf.write.format('csv').option(\"header\",\"True\").option('sep','\u00a4').save('gs:\/\/'+bucket_name+'\/'+target_obj_name+'_tmp'+'\/'+filename)\nHow can i optimise this operation?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":53,"Q_Id":67292451,"Users Score":0,"Answer":"The read will be a single Spark task, but the transformation and write will be parallelised by Spark, so increasing the size of your cluster will increase the parallelism and correspondingly decrease the execution time.","Q_Score":1,"Tags":"python,csv,apache-spark,pyspark","A_Id":67303061,"CreationDate":"2021-04-28T01:03:00.000","Title":"How do I reduce the time to write large CSV (12 Go) to GCS bucket with Pyspark? (>6h)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"What is the difference between vectorSize in Word2Vec and numFeatures in HashingTF? I refer to class Word2Vec and HashingTF in pyspark:\nWORD2VEC: class pyspark.ml.feature.Word2Vec(*, vectorSize=100, minCount=5, numPartitions=1, stepSize=0.025, maxIter=1, seed=None, inputCol=None, outputCol=None, windowSize=5, maxSentenceLength=1000)\nHashingTF: class pyspark.ml.feature.HashingTF(*, numFeatures=262144, binary=False, inputCol=None, outputCol=None)","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":84,"Q_Id":67297183,"Users Score":1,"Answer":"They're both the dimensionality of the representation, but the values will be in different ranges and useful in different ways.\nIn Word2Vec, each word gets a vector of vectorSize dimensions - where each dimension is a floating-point number (rather than a whole number). The values will be both positive and negative, and essentially never zero. Thus all words have coordinates in a fuzzy 'cloud' of space around the origin point.\nThus a word2vec vector is considered a 'dense embedding' of the word: it represents the word into a smaller vector space ('embeds' it) in a way where every dimension varies and holds some of the info ('dense'). As a result, all (100 in your example) dimensions will be used to represent any one item (word).\nIn HashingTF (which probably stands for 'hashing term frequency' or 'hashing trick frequency'), a text document of many words gets a vector of numFeatures dimensions - where each dimension is a non-negative integer count of how many times certain words appear in the document.\nBy using a technique called the 'hashing trick', it ensures any word, whether seen before or not, is assigned (by a hash value) to one of a fixed-set of counting buckets. The value of each dimension in the vector is the count of the words assigned to one bucket. In typical cases, many if not nearly-all of the buckets will be empty \u2013 and thus have zero values in the corresponding dimensions.\nThus a HashingTF vector is considered a 'sparse embedding' of a document: it represents the document into a smaller vector sapce ('embeds' it) in a way where most dimensions often stay zero, but a small relevant subset of dimensions become nonzero ('sparse'). As a result, the (262,144 in your example) dimensions might only be represented by a short list of which dimensions are non-zero and their value.","Q_Score":1,"Tags":"python,gensim,word2vec,tf-idf","A_Id":67303785,"CreationDate":"2021-04-28T09:09:00.000","Title":"Difference between VectorSize in word2Vec and numFeatures in TF-IDF","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have an HxWxN image arr that I want to Gaussian blur.\nscipy.ndimage.gaussian_filter seems to treat the image as a generic array and also blur along the final channel dimension. The desired behavior is Gaussian blurring arr[:, :, i] independently for all is and then concatenating the resultant slices back into an HxWxN result array.\nIs there a better library or function that I can use to directly achieve that, or do I really need to just put scipy.ndimage.gaussian_filter in a for-loop over i?\nA bonus question is what if I have M images organized as an MxHxWxN array? How do I blur over just the H and W dimensions?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":137,"Q_Id":67302611,"Users Score":0,"Answer":"I figured it out.\ncv2.GaussianBlur() does exactly that: it blurs each channel independently, and the image can have an arbitrary number of channels.","Q_Score":0,"Tags":"python","A_Id":67302770,"CreationDate":"2021-04-28T14:54:00.000","Title":"Python: Gaussian filtering an N-channel image along only spatial dimensions?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working on binary classification problem on a dataset with extreme class imbalance. To help the model learn the signals of the minority class, I downsampled the majority class such that the training set has 20% of minority class and 80% majority class.\nNow there is one other parameter \"scale_pos_weight\" . I am not sure how to set this parameter after downsampling.\nShould i set this based on the actual class ratios or should i use the class ratios after downsampling?","AnswerCount":3,"Available Count":1,"Score":0.0665680765,"is_accepted":false,"ViewCount":1271,"Q_Id":67303447,"Users Score":1,"Answer":"The class weights are used when computing the loss function to prevent the model from giving importance to the major class. If one class dominates the dataset, then the model will be biased to learn that class better because the loss is mainly determined by the model's performance on that dominant class.\nLet's consider an extreme case where the dataset contains 99 percent positive samples. If a model just predicts 1 for every sample, it will have 99 percent accuracy. The idea behind class weights is that you want every sample to contribute to the loss equally. Therefore, you should compute this ratio based on your training set because the loss is computed on your training set. Your model has no idea about the samples that you dropped.\nIf you make a correct prediction, the loss is 0, and otherwise not. Coming to your case, to make sure that every sample contributes to the loss equally, a false prediction for the minority class should be penalized 4 times more than a false prediction for the majority class. So that, the model can not ignore a certain class or have a bias towards the majority class.\nIt is generally a good idea to set the class weight anti-proportional to the number of samples you have for that particular class. So, in your case, that would be 4. However, in practice, you should probably try out few different values to find the best weights.\nAnother important aspect is the ratio of these samples in the wild. You said that you made down-sampling, if the ratio of classes differs in the wild compared to your training dataset, then you might observe worse scores when you deploy your model or when you are testing it on unseen samples. That is why you should ideally also split your validation and test sets with realistic ratios using your domain knowledge","Q_Score":4,"Tags":"python,machine-learning,xgboost","A_Id":67540029,"CreationDate":"2021-04-28T15:41:00.000","Title":"How to use downsampling and configure class weight parameter when using XGboost for imbalanced classification?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"For a text classification, I have data of 1000 reviews and I tried different neural networks. For the CNN I got an accuracy of 0.94 but with the LSTM I got a lower accuracy (0.88) is this normal because as far as I know the LSTM is specialized for text classification and it preserves the order of the word sequence?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":144,"Q_Id":67316090,"Users Score":1,"Answer":"Yes, this isn't abnormal and was shown in a lot of researches.\nThe performance of these models depends on many factors like the data you have and the task you are dealing with it.\nFor example, CNN can perform well if your task cares more about detecting some substantial features (like the sentiment).\nHowever, RNN-based models can show their superiority when the sequential aspect of the data is matters, like in Machine Translation and Text Summarization tasks.\nI don't believe that the \"LSTM specialized for text classification\" is true. It's better to say LSTM specialized to learn sequential data. LSTM can learn the texts and the relation between the tokens very well, but the task you defined maybe doesn't care about these linguistic features. For example, in sentiment classification, a model (like CNN) can care about just the presence of some words and achieves good results.","Q_Score":1,"Tags":"python,deep-learning,nlp,conv-neural-network,lstm","A_Id":67319248,"CreationDate":"2021-04-29T11:03:00.000","Title":"it is normal that CNN give me better accuracy compared to LSTM in text classification?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have been browsing the documentation for the tensorflow.keras.save_model() API and I came across the parameter include_optimizer and I am wondering what would be the advantage of not including the optimizer, or perhaps what problems could arise if the optimizer isn't saved with the model?\nTo give more context for my specific use-case, I want to save a model and then use the generated .pb file with Tensorflow Serving. Is there any reason I would need to save the optimizer state, would not saving it reduce the overall size of the resultant file? If I don't save it is it possible that the model will not work correctly in TF serving?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":62,"Q_Id":67321942,"Users Score":2,"Answer":"Saving the optimizer state will require more space, as the optimizer has parameters that are adjusted during training. For some optimizers, this space can be significant, as several meta-parameters are saved for each tuned model parameter.\nSaving the optimizer parameters allows you to restart training in exactly the same state as you saved the checkpoint, whereas without saving the optimizer state, even the same model parameters might result in a variety of training outcomes with different optimizer parameters.\nThus, if you plan on continuing to train your model from the saved checkpoint, you'd probably want to save the optimizer's state as well. However, if you're instead saving the model state for future use only for inference, you don't need the optimizer state for anything. Based on your description of wanting to deploy the model on TF Serving, it sounds like you'll only be doing inference with the saved model, so are safe to exclude the optimizer.","Q_Score":1,"Tags":"python,keras,deep-learning,tensorflow2.0,tensorflow-serving","A_Id":67322774,"CreationDate":"2021-04-29T17:00:00.000","Title":"Tensorflow 2x: What exactly does the parameter include_optimizer affect in tensorflow.keras.save_model","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I had this doubt, often datasets have the Age column values in either int or float datatype (Eg Titanic).\nSo suppose the column has all float values, should you convert them all to int or let it be just like that while feeding it to ML Model,\nDoes it have any harm or adverse effects in prediction results and what's the right way?","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":544,"Q_Id":67329095,"Users Score":0,"Answer":"Its better to convert the age column in to int. If some junk values would come, it would impact the model. We both knows quite well that age is an integer.\nIf data quality is superior and you are sure that age wont come in float then you can proceed without conversion too.","Q_Score":0,"Tags":"python-3.x,pandas,dataframe,numpy,data-science","A_Id":67329156,"CreationDate":"2021-04-30T06:21:00.000","Title":"When should you convert Age column in float or int?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I had this doubt, often datasets have the Age column values in either int or float datatype (Eg Titanic).\nSo suppose the column has all float values, should you convert them all to int or let it be just like that while feeding it to ML Model,\nDoes it have any harm or adverse effects in prediction results and what's the right way?","AnswerCount":2,"Available Count":2,"Score":1.2,"is_accepted":true,"ViewCount":544,"Q_Id":67329095,"Users Score":0,"Answer":"age is a continuous variable, ie people age all the time, they don't just age once a year, so the data type which most closely reflects the aging process should be a float and not an integer. However using a float or an integer depends on the use case, eg:\n\nAre you using age as a feature describing how old people are? Better use float (eg a person who is 59.9 is older than a person who is 59.1 and may be more likely to develop certain medical conditions, or maybe less physically fit and less likely to survive in an event of a sinking ship)\nAre you reporting on age groups? Might be better off rounding to nearest integer (eg 39.9 -> 40, 34.2 -> 34) and potentially binning (eg 25-34, 35-45)\nAre you working on a project to evaluate under-aged drinking (from a legal standpoint)? Then you should use the rounded down int value (eg if legal age is 16 and a person is 15.9, legally they are 15 and therefore under-aged drinking)\netc...\n\nAs a general remark you'll often find that there is no single \"right way\" of dealing with data, it all depends on the use case.","Q_Score":0,"Tags":"python-3.x,pandas,dataframe,numpy,data-science","A_Id":67330917,"CreationDate":"2021-04-30T06:21:00.000","Title":"When should you convert Age column in float or int?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"Observing KeyError:'CaseFoldUTF8' while loading the model when loading the model that I had fine-tuned using pre trained BERT from tf-hub","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":1489,"Q_Id":67333235,"Users Score":9,"Answer":"I got the same error. Adding import tensorflow_text at the top worked for me.","Q_Score":4,"Tags":"python-3.x,tensorflow2.0","A_Id":67691003,"CreationDate":"2021-04-30T11:38:00.000","Title":"How to fix the following error when trying to load a model \"KeyError: 'CaseFoldUTF8' while loading the model\"","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":1},{"Question":"In the book \"Spark Definitive Guide\" Bill says that read is a transformation and its a narrow transformation,\nNow if I run the below spark code and try and go look at the spark UI I see a job created\ndf = spark.read.csv(\"path\/to\/file\")\nNow to my understanding, a Job is an action called. also if I try to put in some options while reading a CSV I see one more job in spark UI, so when if we, for example, run the below code, there are 2 jobs in spark UI\ndf = spark.read.option(\"inferSchema\", \"true\").csv(\"path\/to\/file\")\nso my question is if spark.read is a transformation why is it creating Job?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":1485,"Q_Id":67339570,"Users Score":0,"Answer":"Spark Dataframes via Catalyst have some smarts built in compared to RDDs.\nOne of them is when you state infer schema, then as that can take a long time, underwater Spark already launches a Job to do the schema inferring. It's that simple. It's something that is in the optimization & performance aspect and cannot be seen as Action or Transformation. Another example is the pivoting of a dataframe.","Q_Score":2,"Tags":"python,apache-spark,pyspark","A_Id":67349300,"CreationDate":"2021-04-30T19:38:00.000","Title":"Is Spark.read.csv() an Action on Transformation","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"last week, my teacher asks us: when storing integers from one to one hundred, what the differences between using list and using ndarray. I never use numpy before, so I search this question on the website.\nBut all my search result told me, they just have dimension difference. Ndarray can store N dimension data, while list storge one. That doesn't satisfy me. Is it really simple, just my overthinking, Or I didn't find the right keyword to search?\nI need help.","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":73,"Q_Id":67342405,"Users Score":2,"Answer":"There are several differences:\n-You can append elements to a list, but you can't change the size of a \u00b4numpy.ndarray\u00b4 without making a full copy.\n-Lists can containt about everything, in numpy arrays all the elements must have the same type.\n-In practice, numpy arrays are faster for vectorial functions than mapping functions to lists.\n-I think than modification times is not an issue, but iteration over the elements is.\nNumpy arrays have many array related methods (\u00b4argmin\u00b4, \u00b4min\u00b4, \u00b4sort\u00b4, etc).\nI prefer to use numpy arrays when I need to do some mathematical operations (sum, average, array multiplication, etc) and list when I need to iterate in 'items' (strings, files, etc).","Q_Score":0,"Tags":"python,list,numpy,numpy-ndarray","A_Id":67342429,"CreationDate":"2021-05-01T02:33:00.000","Title":"what the differences between ndarray and list in python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I tried to download Hdbscan using pip install hdbscan , I get this :\nERROR: Failed building wheel for hdbscan\nERROR: Could not build wheels for hdbscan which use PEP 517 and cannot be installed directly\nI've tried several solutions, it didn't work tho.","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":4015,"Q_Id":67342665,"Users Score":1,"Answer":"Try to install the equivalent python3.[x]-dev package.\nFor ex, for python3.8 use: sudo apt install python3.8-dev","Q_Score":9,"Tags":"python,pip,hdbscan","A_Id":69949503,"CreationDate":"2021-05-01T03:39:00.000","Title":"how do I solve \" Failed building wheel for hdbscan \"?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to formulate an optimization problem using scipy minimize function. However, I am having the following problem that I can't work around:\nI want X = [x1, x2, x3, x4, x5] that minimizes a cost function F(X). This X vector, however, are percentage values that must add to 1, i.e., np.sum(X) = 1.\nThe problem is: if I use, for instance, the \"SLSQP\" method with some initial values (such as X0 = [0.2, 0.2, 0.2, 0.2, 0.2]), it will try to increment each value to find some convergence direction. For example, the algorithm will make X0 -> [0.21, 0.2, 0.2, 0.2, 0.2]. But that cannot happen, because np.sum(X) = 1 is a requirement for me to compute the objective function.\nUsing constraints does not help either! I could make a constraint with np.sum(X) = 1. However, the minimize algorithm will only check the constraint after computing the objective function.\nAnyone have an idea on how to deal with such a problem?\nThanks a lot!","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":290,"Q_Id":67348027,"Users Score":0,"Answer":"The NLP solvers I typically use will not ask for function and gradient evaluations when X is outside its bounds. That means we can protect things like sqrt(x) and log(x) by adding appropriate lower bounds.\nConstraints can not be assumed to hold when we evaluate functions and gradients.\nIf your function assumes sum(X)=1, you could call F(X\/sum(X)). The only complication is when X=0. In that case, return a large value for F so that the solver will move away from it.","Q_Score":0,"Tags":"python,optimization,scipy","A_Id":67365273,"CreationDate":"2021-05-01T15:40:00.000","Title":"Optimization with \"add to 1\" constraint in optimization variable","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to add null values at random to a pandas data for a specific column to perform testing on the data.\nFor example if i have a dataframe with below values.\n\n\n\n\nid\ntotal_distance\n\n\n\n\n1\n1000\n\n\n1\n2000\n\n\n3\n4000\n\n\n4\n5000\n\n\n5\n10000\n\n\n\n\nHow to pass null values at random like below\n\n\n\n\nid\ntotal_distance\n\n\n\n\n1\n1000\n\n\n1\n2000\n\n\n3\n4000\n\n\n4\nNaN\n\n\n5\n10000","AnswerCount":4,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":415,"Q_Id":67352615,"Users Score":0,"Answer":"Something like this on column of interest\npd.Series(range(10)).mask(np.random.random(10)<0.5)","Q_Score":1,"Tags":"python,pandas","A_Id":67352705,"CreationDate":"2021-05-02T03:01:00.000","Title":"How to update null values at Random in pandas","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a dataset with thousands of rows. Each row is a person, that I need to insert into 4 clusters. I know that have many possibles to do that and to find the best clusters, but in this case, I know the characteristics of each cluster. Generally, with ML, the clusters are find with IA.\nFor example, imagine that I have 4 columns to look: money_spending, salary, segment, days_to_buy. Also, I have:\nCluster 1 -> money_spending: 350-700\nsalary: 700-1000\nsegment: farmacy\ndays_to_buy: 12\nCluster 2 -> money_spending: 500-950\nsalary: 1000-1300\nsegment: construction material\ndays_to_buy: 18\nCluster 3 -> money_spending: 900-1400\nsalary: 1200-2000\nsegment: supermarket\ndays_to_buy: 20\nCluster 4 -> money_spending: 250-600\nsalary: 550-1000\nsegment: farmacy\ndays_to_buy: 30\nWhat's the best way to apply this to my dataset? I would use k-nearest, but I don't know how to use my cluster information.\nCan someone help me?\nPlus: If I have more columns or more clusters the solution keeps works?\nEdit: My original dataset only have the columns. The clusters are knowing, but are not in dataset. The job is exactly apply this cluster information to dataset. I don't have any idea how to do that.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":73,"Q_Id":67363770,"Users Score":0,"Answer":"You can try the following approach:\n\nRun K means and find the best number of k using the Elbow method or Silhouette graph.\n\nUse the cluster labels as a class.\ne.g. if 4 is the optimal number of the cluster then class=0,1,2,3 ( which will be the cluster labels)\n\nMerge the class with the original dataset and treat it as a supervised learning problem\n\nTry running any classification model after the train test split.\n\nSee the classification report to check model performance.\n\n\nPS\n\nTry using data with normalization too as many clustering algorithms are sensitive to outliers.\n\nPlease see if the class is somewhat equally distributed like 1000,800,1150,890 and not 1500,80,150,..etc as it will create data imbalance for the classifiers.","Q_Score":3,"Tags":"python,machine-learning,jupyter-notebook,artificial-intelligence,cluster-analysis","A_Id":67363871,"CreationDate":"2021-05-03T05:13:00.000","Title":"Clustering in Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am getting the following error when executing the below code:\nCode:\nfrom fbprophet.plot import plot_plotly, plot_components_plotly\nError:\nImporting plotly failed. Interactive plots will not work.","AnswerCount":2,"Available Count":1,"Score":1.0,"is_accepted":false,"ViewCount":4960,"Q_Id":67371645,"Users Score":8,"Answer":"run pip install --upgrade plotly\nIt worked for me","Q_Score":4,"Tags":"python,plotly,facebook-prophet","A_Id":69440775,"CreationDate":"2021-05-03T15:30:00.000","Title":"I am getting error in plotly module of FB prophet","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"We are trying to build flexible schema where, for example, we might have single units that come from one of two places, either a SpikeSorting pipeline that begins from raw data, or imported from a file where spike sorting has already been done.\nWe'd like to be able to feed the data from whichever of those tables is relevant into the same analysis functions \/ tables downstream.\nWe have considered making the SpikeSorting table a hybrid of computed and imported entries, but that seems a bit ugly. Is there a better way?","AnswerCount":1,"Available Count":1,"Score":0.537049567,"is_accepted":false,"ViewCount":173,"Q_Id":67377072,"Users Score":3,"Answer":"For this particular case (varying ingest), I'd probably create an upstream dj.Imported table representing the state of ingest from the different sources, containing something like the session and the source path. The make logic would take care of determining the source type and loading the data into the real SpikeData (or whatever name) table, and mark the source type as a flag there, either as a direct value or a foreign key into some kind of 'tag' table.\nThe same \"upstream disambiguation table and tags\/flags into a downstream\" kind of approach works more generically in other situations, or, depending on the case, just store the data in the combining table directly.","Q_Score":1,"Tags":"python,datajoint,upstream","A_Id":67377912,"CreationDate":"2021-05-03T23:43:00.000","Title":"Is there a preferred way to have a downstream table that can take data from one of two upstream tables in datajoint?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am writting my data to a csv using to_csv(\"file_name\") method which makes the first raw of the csv file 0, 1, 2, 3, ..... etc. Is there a way to keep the same method but just change the first raw to first_name, second_name, third_name?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":23,"Q_Id":67389411,"Users Score":0,"Answer":"I solved it. I created a list and wrote the list to row using csv python library. Then I change the to_csv(\"file_name\", method=\"a\").","Q_Score":0,"Tags":"python-3.x","A_Id":67390127,"CreationDate":"2021-05-04T17:26:00.000","Title":"In python is it possible to change the first line of the csv file using to_csv() method?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to know the difference between a pyspark dataframe and a createOrReplaceTempView\nI know that with pyspark dataframe I have to use python, and with the createOrReplaceTempView it is SQL, but in terms of memory, using the cluster, parallelizing, both are the same?\nFor example if I use .toPandas() I will put all the data in memory, does something similar happends with createOrReplaceTempView ? or is still distributed?\nAlso I would like to know, if I use CREATE OR REPLACE TEMP VIEW tablename how do I pass this table to a pyspark dataframe\nRegards","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":64,"Q_Id":67408249,"Users Score":0,"Answer":"I want to know the difference between a pyspark dataframe and a createOrReplaceTempView\n\n\nI know that with pyspark dataframe I have to use python, and with the createOrReplaceTempView it is SQL, but in terms of memory, using the cluster, parallelizing, both are the same?\n\nThey're both should be similar\n\nFor example if I use .toPandas() I will put all the data in memory, does something similar happends with createOrReplaceTempView ? or is still distributed?\n\n.toPandas() collect all data and return to driver's memory, createOrReplaceTempView is lazy","Q_Score":0,"Tags":"python,sql,pyspark","A_Id":67645843,"CreationDate":"2021-05-05T20:19:00.000","Title":"What is the difference between createOrReplaceTempView and pyspark dataframe","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to run my code in Solaris environment with Python 3.7.4 [GCC 7.3.0] on sunos5. When importing necessary libraries from scipy import stats I face this issue. Does anybody know how can I fix this?\nThank you in advance.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":70,"Q_Id":67415061,"Users Score":0,"Answer":"This is a library linking issue. Try the following, as it may need re-installing, or updated:\npip install pyhull\nIf that doesn't work, you may have to recompile python, and any additional libraries or utilities (coreutils, binutils, glibc, even gcc).\nIf you have the Oracle C compiler, you can try that by using cc, or gcc if that is easier. The Oracle C compiler would be specific to your Solaris installation and may work better.\nIf you do not want to do that, you might want to try a packaged version of python for your version of SunOS \/ Solaris and then install pyhull or qhull using pip.","Q_Score":0,"Tags":"python,scipy,statistics,solaris,sunos","A_Id":71289568,"CreationDate":"2021-05-06T09:08:00.000","Title":"ImportError: relocation error: R_AMD64_32: \/scipy-1.6.2-py3.7-solaris-2.11-i86pc.64bit.egg\/scipy\/spatial\/qhull.cpython-37m.so: symbol (unknown)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am doing a project on multi-class text classification and could do with some advice.\nI have a dataset of reviews which are classified into 7 product categories.\nFirstly, I create a term document matrix using TF-IDF (tfidfvectorizer from sklearn). This generates a matrix of n x m where n in the number of reviews in my dataset and m is the number of features.\nThen after splitting term document matrix into 80:20 train:test, I pass it through the K-Nearest Neighbours (KNN) algorithm and achieve an accuracy of 53%.\nIn another experiment, I used the Google News Word2Vec pretrained embedding (300 dimensional) and averaged all the word vectors for each review. So, each review consists of x words and each of the words has a 300 dimensional vector. Each of the vectors are averaged to produce one 300 dimensional vector per review.\nThen I pass this matrix through KNN. I get an accuracy of 72%.\nAs for other classifiers that I tested on the same dataset, all of them performed better on the TF-IDF method of vectorization. However, KNN performed better on word2vec.\nCan anyone help me understand why there is a jump in accuracy for KNN in using the word2vec method as compared to when using the tfidf method?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":333,"Q_Id":67417706,"Users Score":0,"Answer":"By using the external word-vectors, you've introduced extra info about the words to the word2vec-derived features \u2013 info that simply may not be deducible at all to the plain word-occurrece (TF-IDF) model.\nFor example, imagine just a single review in your train set, and another single review in your test set, use some less-common word for car like jalopy \u2013 but then zero other car-associated words.\nA TFIDF model will have a weight for that unique term in a particular slot - but may have no other hints in the training dataset that jalopy is related to cars at all. In TFIDF space, that weight will just make those 2 reviews more-distant from all other reviews (which have a 0.0 in that dimension). It doesn't help or hurt much. A review 'nice jalopy' will be no closer to 'nice car' than it is to 'nice movie'.\nOn the other hand, if the GoogleNews has a vector for that word, and that vector is fairly close to car, auto, wheels, etc, then reviews with all those words will be shifted a little in the same direction in the word2vec-space, giving an extra hint to some classifiers, especially, perhaps the KNN one. Now, 'nice jalopy' is quite a bit closer to 'nice car' than to 'nice movie' or most other 'nice [X]' reviews.\nUsing word-vectors from an outside source may not have great coverage of your dataset's domain words. (Words in GoogleNews, from a circa-2013 training run on news articles, might miss both words, and word-senses in your alternative & more-recent reviews.) And, summarizing a text by averaging all its words is a very crude method: it can learn nothing from word-ordering\/grammar (that can often reverse intended sense), and aspects of words may all cancel-out\/dilute each other in longer texts.\nBut still, it's bringing in more language info that otherwise wouldn't be in the data at all, so in some cases it may help.\nIf your dataset is sufficiently large, training your own word-vectors may help a bit, too. (Though, the gain you've seen so far suggests some useful patterns of word-similarities may not be well-taught from your limited dataset.)\nOf course also note that you can use blended techniques. Perhaps, each text can be even better-represented by a concatenation of the N TF-IDF dimensions and the M word2vec-average dimensions. (If your texts have many significany 2-word phrases that mean hings different than the individual words, adding in word 2-grams features may help. If your texts have many typos or rare word variants that still share word-roots with other words, than adding in character-n-grams \u2013 word fragments \u2013 may help.)","Q_Score":1,"Tags":"python,nlp,word2vec,knn,tfidfvectorizer","A_Id":67422025,"CreationDate":"2021-05-06T12:02:00.000","Title":"Why does KNN algorithm perform better on Word2Vec than on TF-IDF vector representation?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working with a legacy project of Kubeflow, the pipelines have a few components in order to apply some kind of filters to data frame.\nIn order to do this, each component downloads the data frame from S3 applies the filter and uploads it into S3 again.\nIn the components where the data frame is used for training or validating the models, download from S3 the data frame.\nThe question is about if this is a best practice, or is better to share the data frame directly between components, because the upload to the S3 can fail, and then fail the pipeline.\nThanks","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":235,"Q_Id":67433776,"Users Score":1,"Answer":"The question is about if this is a best practice\n\nThe best practice is to use the file-based I\/O and built-in data-passing features. The current implementation uploads the output data to storage in upstream components and downloads the data in downstream components. This is the safest and most portable option and should be used until you see that it no longer works for you (100GB datasets will probably not work reliably).\n\nor is better to share the data frame directly between components\n\nHow can you \"directly share\" in-memory python object between different python programs running in containers on different machines?\n\nbecause the upload to the S3 can fail, and then fail the pipeline.\n\nThe failed pipeline can just be restarted. The caching feature will make sure that already finished tasks won't be re-executed.\nAnyways, what is the alternative? How can you send the data between distributed containerized programs without sending it over the network?","Q_Score":0,"Tags":"python,dataframe,amazon-s3,kubeflow,kubeflow-pipelines","A_Id":67898132,"CreationDate":"2021-05-07T11:04:00.000","Title":"What is the correct way for share dataframes between components?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have three boolean mask tensors that I want to create a boolean mask that if the value matches in three tensors then it is 1, else 0.\nI tried torch.where(A == B == C, 1, 0), but it doesn't seem to support such.","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":269,"Q_Id":67444564,"Users Score":0,"Answer":"AFAIK, the tensor is basically a NumPy array bound to the device. If not too expensive for your application and you can afford to do it on CPU, you can simply convert it to NumPy and do what you need with the comparison.","Q_Score":3,"Tags":"python,pytorch,comparison","A_Id":67444632,"CreationDate":"2021-05-08T06:04:00.000","Title":"PyTorch: compare three tensors?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"This is a Python question. I have a csv file and would like to read that in. The first row in the file are strings and I would like to use them as variable names. The other rows are integers and I would like them to be a vector of the name of the respective variable.\nThanks,\nTim","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":276,"Q_Id":67450466,"Users Score":0,"Answer":"you need to first extract your first row I suggest to count the characters of first row and use this code to read them\nf = open(\"demofile.txt\", \"r\")\nprint(f.read(5))#put your desired counted charactor inside f.read(n)\nwhen you successfully read it save it on variable and after saving use regex to split them with respect to \",\"\nimport re\ntxt = \"The rain in Spain\"\nx = re.split(\"[,]\", txt, 1)\nprint(x)\nafter that use dictionary methods to attain your desired result.","Q_Score":0,"Tags":"python,csv","A_Id":67450566,"CreationDate":"2021-05-08T17:43:00.000","Title":"How can I read in csv files with columns as variable names in Python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a confusion matrix that I generated via Scikit-Learn. I was wondering if it were possible to reverse engineer it and get the y_true and y_pred given only the confusion matrix in Python. If there is nothing built in (like in Scikit-Learn), would someone mind providing a code snippet?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":109,"Q_Id":67450869,"Users Score":3,"Answer":"Its not possible to reverse-engineer y_true and y_pred from a given confusion matrix, as the confusion matrix is invariant to permutations of the elements of y_pred and y_true.\nAn easy example would be the following: Consider y_true=[0,1] and y_pred=[1, 0]. The confusion matrix is exactly the same than for y_true=[1, 0] and y_pred=[0, 1].","Q_Score":2,"Tags":"python,scikit-learn,data-science","A_Id":67451154,"CreationDate":"2021-05-08T18:26:00.000","Title":"Distill y_true and y_pred from a confusion matrix","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"This may seem like a bit of a funny question, but is there a way to program a LP equation with two 'lower' bounds?\nBasically my problem is, rather than having conventional bounds (0,x) for some variable 'a', i want to have bounds ((0 or i),x) where i and x is a range of floats. So if zeroing it out doesn't optimize it, it finds the optimal value between i and x; e.g. (0,5,100) where optimal value can either be zero or a float somewhere between 5 and 100.\nIs there a way of programming this in scipy linprog or PuLP? or is there a more sophisticated solver that can handle such constraints?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":69,"Q_Id":67457871,"Users Score":2,"Answer":"The exact scenario you describe is not possible using only LP (so you wouldn't be able to solve this with linprog), but you can do something like this with MILP. You would introduce a binary variable, say b, which would be 0 if the lower and upper bound is 0 and 1 if you have the other bound, then you would add constraints b*i <= a and a <= b*x. This way when b is zero, a must be zero and when b is 1, you recover your bound of i <= a <= x. You would be able to solve this with Pulp.","Q_Score":0,"Tags":"python,pulp,scipy-optimize","A_Id":67458049,"CreationDate":"2021-05-09T12:46:00.000","Title":"Linear programming - bounds with intervals?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Is there a way to run sklearn's logistic regression with tanh?\nI know tanh is better when labels are {-1,1} and sigmoid is better when labels are {0,1}\nif I can't implement logistic regression would converting labels from {-1,1} -> {0, 1} would improve the performance of logistic regression with sigmoid activation function?","AnswerCount":2,"Available Count":2,"Score":1.2,"is_accepted":true,"ViewCount":403,"Q_Id":67466668,"Users Score":1,"Answer":"There is no such thing as tanh is better when labels are {-1,1} and sigmoid is better when they are {0,1}.\nAt the end, the model has no idea about the labels and their meaning. It just learns a probability distribution for binary classification. tanh(x) maps the input to the interval [-1, 1] and sigmoid(x) maps the input to the interval [0, 1]. What you do is basically, you consider this as a probability and say, if the output is larger than 0.5, it belongs to class 1 otherwise to 0. (in case of sigmoid)\nSo, yes you can convert your labels {-1,1} to {0,1}, or even to {9,10}","Q_Score":1,"Tags":"python,machine-learning,logistic-regression,activation-function","A_Id":67466784,"CreationDate":"2021-05-10T07:49:00.000","Title":"How to use tanh instead of sigmoid in sklearn logistic regression","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Is there a way to run sklearn's logistic regression with tanh?\nI know tanh is better when labels are {-1,1} and sigmoid is better when labels are {0,1}\nif I can't implement logistic regression would converting labels from {-1,1} -> {0, 1} would improve the performance of logistic regression with sigmoid activation function?","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":403,"Q_Id":67466668,"Users Score":0,"Answer":"Think again what a logistic regression is doing: logistic regression models a probability and a probability only ranges from 0 to 1.\nLogistic regression is a little bit different from other ML classification models like SVM or tree-based models. Others try to find the decision boundaries directly while logistic regression actually models a probability and then use a threshold which can be any number from 0 to 1 to make the final classification.\nActually you can replace sigmoid function with any mathematical function turns a number into the range of 0 to 1. Examples would be the CDF of a normal distribution or complementary log-log.\nIf you change the sigmoid to tanh, that regression would no longer be a \"logistic regression\" because you are not modelling a probability.","Q_Score":1,"Tags":"python,machine-learning,logistic-regression,activation-function","A_Id":67785068,"CreationDate":"2021-05-10T07:49:00.000","Title":"How to use tanh instead of sigmoid in sklearn logistic regression","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Fatal Python error: Py_Initialize: unable to load the file system codec\nModuleNotFoundError: No module named 'encodings'\nCurrent thread 0x000030fc (most recent call first):","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":93,"Q_Id":67468240,"Users Score":0,"Answer":"Nevermind, uninstalled and extracted DeepFaceLab again. first installation corrupted the files.","Q_Score":0,"Tags":"python","A_Id":67468381,"CreationDate":"2021-05-10T09:46:00.000","Title":"I'm trying to run \"3) extract images from video data_dst FULL FPS.bat\" from DeepFaceLab and it only shows this message","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to figure a way to know how to differentiate between methods and property\/attribute, and how to use them correctly without getting mixed up (when to use parenthesis when not to)\nFrom what I understand, (correct me if I am wrong):\n\nMethods are functions that takes in an input (exp a value) and returns an output; *exp .sum()\n\n\nProperty\/attribute tells you additional information or describe the characteristics *exp .index .shape .columns\n\nMy question is, .info() and .describe() are somewhat similar to .shape and .index which give you the description and info but why is it a method and not an attribute\/property?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":42,"Q_Id":67469800,"Users Score":0,"Answer":"The rough rule of thumb I would offer is to use an attribute for data that can be used as stored, and a function for data that needs to have something done to it before it's returned.\nIn your example, .shape just returns the tuple as it is stored by the system. It's a straightforward attribute.\nBy comparison, .info() and .describe() both apply filtering\/formatting etc to the data before it is returned. You can also optionally pass them parameters to specify how the data is filtered\/formatted before it is returned to you.\nThere are other reasons why attributes might be accessed through functions, such as using getters and setters to access protected attributes, but in your present examples it's because the functions don't just return the data, they do something to the data first.","Q_Score":0,"Tags":"python,methods,attributes","A_Id":67470473,"CreationDate":"2021-05-10T11:42:00.000","Title":"Why does.info() and .describe() in pandas have ()?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a vector of floats V with values from 0 to 1. I want to create a histogram with some window say A==0.01. And check how close is the resulting histogram to uniform distribution getting one value from zero to one where 0 is correlating perfectly and 1 meaning not correlating at all. For me correlation here first of all means histogram shape.\nHow one would do such a thing in python with numpy?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":31,"Q_Id":67474375,"Users Score":0,"Answer":"You can create the histogram with np.histogram. Then, you can generate the uniform histogram from the average of the previously retrieved histogram with np.mean. Then you can use a statistical test like the Pearson coefficient to do that with scipy.stats.pearsonr.","Q_Score":0,"Tags":"python,numpy","A_Id":67478274,"CreationDate":"2021-05-10T16:39:00.000","Title":"How to check if a vector hirogramm correlates with uniform distribution?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm using the unscented kalman filter class of filterpy.kalman library.\nEven when I initialize both of the process noise Q and the initial covariance P with off-diagonal entries that are all equal to zero, I still get P and S with non-zero off-diagonal entries, is there a way to ensure that P and S have off-diagonal entries that are all equal to zero?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":76,"Q_Id":67475545,"Users Score":1,"Answer":"I suspect you might get better answers elsewhere, though I'm not sure where.\nYou can ensure a diagonal state error covariance matrix only in the case that the state is in fact a collection of independent 1 dimensional states with no dynamics (ie the prediction of the state at time t' is the state at time t) and no measurements involve more than one state element.\nThe essential point of the Kalman filter is that it estimates the correlations between the state errors.","Q_Score":1,"Tags":"python,covariance,noise,kalman-filter","A_Id":67483880,"CreationDate":"2021-05-10T18:06:00.000","Title":"non-zero elements in the covariance matrix P of unscented kalman filter","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am building a neural network from scratch. Currently having a batch of 32 training examples, and for each individual example, I calculate the derivatives (gradient) and sum them.\nAfter I sum the 32 training examples' gradients, I apply:weight += d_weight * -learning rate;\nThe question is:\nShould I sum (as of now) or average the 32 gradients?\nOr alternative solution:\nShould I calculate each 32 gradients for each loss output (as of now), or average the cross entropy loss outputs and then calculate a single gradient?\nI have looked at multiple sources and it's not clear what the answer is. Also the optimal learning rate in my software is lower than 0.0001 for Mnist training. That is different than the 0.01 to 0.05 that I have seen in other neural networks.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":285,"Q_Id":67482379,"Users Score":1,"Answer":"Well, it depends on what you want to achieve. The loss function acts as a guide to train the neural network to become better at a task.\nIf we sum the cross entropy loss outputs, we incur more loss in proportion to the batch size, since our loss grows linearly in proportion to the mini-batch size during training.\nWhereas, if we take the average, our loss is indifferent to the batch size since we are taking an average.\nFor your use case, I recommend taking the average, as that ensures that your loss function is decoupled from hyperparameters such as the aforementioned batch size.\nAnother intuitive example is that by averaging the loss, we normalize the loss output and that also helps stabilize training, since our network becomes less sensitive to learning rate. If in the case we use sum, we might get exploding gradient issues, which forces us to use a much lower learning rate, thus making our network more sensitive to hyperparameter values.","Q_Score":0,"Tags":"python,tensorflow,math,neural-network","A_Id":67482455,"CreationDate":"2021-05-11T07:35:00.000","Title":"Are individual gradients in a batch summed or averaged in a Neural Network?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm really new to this and fairly confused. I'm training my model with a random forest (classification) and am trying to fully grasp the following concepts.\nAs far as I understand: you split you model with train\/test split or cross validation or oob (bootstrapping methods)\n.\nThen the accuracy score or f1 score represents how well your model performs on the test set (accuracy being better for balances classes, f1 being better for unbalanced classes).\nBut then OOB score is a representation for how good your validation set is, so for how well the model is training on your data?\nAm I misunderstanding soemthing here?\nI'm mostly confused between the difference between accuracy\/f1 scores and OOB scores.\nAny input would be appreciated","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":244,"Q_Id":67485948,"Users Score":0,"Answer":"These are 2 different aspects you're looking at:\n\nMetrics, those are the mathematical formulas that you use to evaluate a model's performance on a set of data, so you'd give it the ground truth (real labels) and the predicted labels, and a metric score is computed, these metrics include:\n\nAccuracy\nPrecision\nRecall\nF1\nMSE\netc.\n\n\nVariance-reduction, those are methods that you'd use to reduce the variance of the model, that is: prevent overfitting the model to the data, these methods include:\n\nUsing 2 different sets (i.e. train\/test split)\nCross-validation (e.g. K-fold cross-validation, LOOCV, etc.)\nOut of Bag, this one is particularly used in Random Forest algorithms to bootstrap the data that's used for each learner in the ensemble (forest).\netc.\n\n\n\nSo, basically, you use a method to try to reduce the variance of your model such that you'd improve the metrics.\nAs for your specific question: what is OOB score to the accuracy score? the OOB algorithm creates subsets of data that are used for training then computes the score using the metric against the predicted labels of these subsets.","Q_Score":0,"Tags":"python,machine-learning,cross-validation","A_Id":67487598,"CreationDate":"2021-05-11T11:36:00.000","Title":"OOB score on train\/test, accuracy and f1 score","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to filter dataframe and copy back the result to the same dataframe. Basically want to ignore all rows which doesn't fit my criteria.\ndf = df[df.temperature>30] #I only want data\/rows with temperature column above 30.\nWhen I print df I get desired result but I get following error when I further work on the df.\nException has occurred: KeyError\n0","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":63,"Q_Id":67491292,"Users Score":0,"Answer":"Answer is:\ndf.reset_index(drop=True, inplace=True)\nThanks Sarath Gadde for the hint!","Q_Score":0,"Tags":"python,pandas,dataframe","A_Id":67492440,"CreationDate":"2021-05-11T17:02:00.000","Title":"Copy filtered data back to same data frame in Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to get in house made transformers pass the check_estimator tests and there is one test, that I am not too sure what it is intended for.\nThe transformers fail the check_transformer_data_not_an_array because the input is a _NotAnArray class, and my package transformers don't like that. The transformers are intended to work only with dataframes, and I added a workaround to transform numpy arrays into df to pass most of the check_estimators tests.\n_NotAnArray is a class developed in the Scikit-learn library, which purpose I do not know. And I guess the test check_transformer_data_not_an_array also has a purpose, unbeknownst to me.\nMy question is:\nWhat is check_transformer_data_not_an_array intended for? Or in other words, why is it important?\nAnd if anybody knows as well, why the class _NotAnArray was created \/ needed, that would also help.\nThank you!","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":48,"Q_Id":67500110,"Users Score":0,"Answer":"Scikit-learn estimators should validate X and y. This validation will convert the input X and y into a NumPy array to do the numerical operation of the estimator.\ncheck_transformer_data_not_an_array makes sure that passing an array-like (but\nnot a NumPy array) is still working as if passing an array.\nIt basically ensures that the validation under the hood happen. The validation is done by the check_X_y class\nThis was actually an answer I got from one of Scikit-learn developers through the mailing list :)","Q_Score":0,"Tags":"python,scikit-learn,package","A_Id":67903041,"CreationDate":"2021-05-12T08:41:00.000","Title":"what is the check_transformer_data_not_an_array test from sklearn's check_estimator intended to?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working on developing a text classifier and have found some solid options. However the one thing I am struggling with is handling text that does not fit into any predefined categories. This is definitely going to be something we see with real data so I need to understand how to handle it.\nI have noticed that when I look at the predict_proba output, (for naive bayes\/boosting) the values need to add up to 1. I think this is a problem because if the text meets no category, the algorithms still require that output to equal one, and it will still assign some arbitrary label to that text, even though it really should not.\nI have come up with some solutions to take the max probability if within a .90 threshold and assign that category, but I feel this is probably not the best approach.\nDoes any one have any suggestions on some methods I may be able to try to solve for this?\nThanks","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":91,"Q_Id":67508664,"Users Score":0,"Answer":"Do a texts sometimes have multiple categories? -> Check multi-label classification\n\nIn multi-label classification a text can be either in zero, one, or more than one categories. A simple implementation is a One-VS-Rest Approach. (Think of a classifier for each Category, classifying either True or False, if all these classifiers classify False, the sample isn't in any category.) You can also select to class with the highest confidence when multiple classes were predicted and you only want to have a single one.\n\nDo a text only have zero or one category? -> Add a No Category Class,\n\nthis no category class shall be predicted for samples without category. Of course you need to have training samples for this approach.\nAnd of course your approach with a threshold makes sense as well, but it is difficult to tune this threshold to a perfect level, so I would use either a no category class or a multi label approach.","Q_Score":0,"Tags":"python,nlp,text-classification","A_Id":67509379,"CreationDate":"2021-05-12T17:47:00.000","Title":"Text Classification - Handling text that does not fit into any category","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"listX = [['0,0,0,3,0,4,0,3'], ['0,0,0,0,0,3,0,7'], ['0,0,1,0,0,5,0,4'], ['0,0,0,1,3,1,0,5'], ['1,1,1,0,0,0,2,5'], ['0,0,0,1,1,5,0,3'], ['0,0,0,5,3,0,0,2']]\nI need it to output\n[[0, 0, 0, 3, 0, 4, 0, 3], [0, 0, 0, 0, 0, 3, 0, 7], [0, 0, 1, 0, 0, 5, 0, 4], [0, 0, 0, 1, 3, 1, 0, 5], [1, 1, 1, 0, 0, 0, 2, 5], [0, 0, 0, 1, 1, 5, 0, 3], [0, 0, 0, 5, 3, 0, 0, 2]]\nwhen I use listX = [[int(float(o)) for o in p] for p in listX] I get ValueError: could not convert string to float: '0,0,0,3,0,4,0,3'","AnswerCount":5,"Available Count":1,"Score":0.0399786803,"is_accepted":false,"ViewCount":54,"Q_Id":67513096,"Users Score":1,"Answer":"You need to firs split every string you have listX[i].split(\",\") and then apply the casting","Q_Score":2,"Tags":"python,list","A_Id":67513117,"CreationDate":"2021-05-13T02:11:00.000","Title":"Converting list of list of strings into list of list of integers","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have read some literature about time series forecasting with ML. I get the concepts of\n\ntrend\nseasonality\ncyclic\nnoise\n\nI would like to use scikit-learn's LinearRegression() as a start to make predictions. If I get it right, I can capture seasonality and cyclic with some feature engineering like day_of_week, month or seasons. I don't get it though, how to capture trend in the data. Is it lag features or a column calculating differences instead of totals?","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":315,"Q_Id":67522483,"Users Score":1,"Answer":"Linear regression fits the data into a linear model basically a function Y = W*X with coefficients w = (w1, \u2026, wp) with minimized residual sum of squares between the true values and its corresponding predicted values.\nObviously, time-series data, by nature, is not linear. In order to capture seasonality and cyclic patterns, I would suggest you to use polynomial function, at least with the power of n > 2. You can use more advance regression models such as support vector and random forest models.\nBut for sure, you can start from linear model. Then later, you can easily shift to other advance models after realizing the limitations of linear models.","Q_Score":0,"Tags":"python,scikit-learn,time-series,linear-regression","A_Id":67524672,"CreationDate":"2021-05-13T16:06:00.000","Title":"How to capture trend in time-series data for forecasting using scikit-learn's LinearRegression()","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am making an explainable model with the past data, and not going to use it for future prediction at all.\nIn the data, there are a hundred X variables, and one Y binary class and trying to explain how Xs have effects on Y binary (0 or 1).\nI came up with DecisionTree classifier as it clearly shows us that how decisions are made by value criterion of each variable\nHere are my questions:\n\nIs it necessary to split X data into X_test, X_train even though I am not going to predict with this model? ( I do not want to waste data for the test since I am interpreting only)\n\nAfter I split the data and train model, only a few values get feature importance values (like 3 out of 100 X variables) and rest of them go to zero. Therefore, there are only a few branches. I do not know reason why it happens.\n\n\nIf here is not the right place to ask such question, please let me know.\nThanks.","AnswerCount":2,"Available Count":2,"Score":0.0996679946,"is_accepted":false,"ViewCount":28,"Q_Id":67528915,"Users Score":1,"Answer":"No, it isn't. However, I would still split train-test and measure performance separately. While an explainable model is nice, it is significantly less nicer if it's a crap model. I'd make sure it had at least a reasonable performance before considering interpretation, at which point the splitting is unnecessary.\nThe number of important features is data-dependent. Random forests do a good job providing this as well. In any case, fewer branches is better. You want a simpler tree, which is easier to explain.","Q_Score":1,"Tags":"python,machine-learning,decision-tree","A_Id":67529319,"CreationDate":"2021-05-14T04:01:00.000","Title":"Question regarding DecisionTreeClassifier","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am making an explainable model with the past data, and not going to use it for future prediction at all.\nIn the data, there are a hundred X variables, and one Y binary class and trying to explain how Xs have effects on Y binary (0 or 1).\nI came up with DecisionTree classifier as it clearly shows us that how decisions are made by value criterion of each variable\nHere are my questions:\n\nIs it necessary to split X data into X_test, X_train even though I am not going to predict with this model? ( I do not want to waste data for the test since I am interpreting only)\n\nAfter I split the data and train model, only a few values get feature importance values (like 3 out of 100 X variables) and rest of them go to zero. Therefore, there are only a few branches. I do not know reason why it happens.\n\n\nIf here is not the right place to ask such question, please let me know.\nThanks.","AnswerCount":2,"Available Count":2,"Score":1.2,"is_accepted":true,"ViewCount":28,"Q_Id":67528915,"Users Score":1,"Answer":"No it is not necessary but it is a way to check if your decision tree is overfitting and just remembering the input values and classes or actually learning the pattern behind it. I would suggest you look into cross-validation since it doesn't 'waste' any data and trains and tests on all the data. If you need me to explain this further, leave a comment.\n\nGetting any number of important features is not an issue since it does depend very solely on your data. \nExample:\nLet's say I want to make a model to tell if a number will be divisible by 69 (my Y class).\nI have my X variables as divisibility by 2,3,5,7,9,13,17,19 and 23.\nIf I train the model correctly, I will get feature importance of only 3 and 23 as very high and everything else should have very low feature importance. \nConsequently, my decision tree (trees if using ensemble models like Random Forest \/ XGBoost) will have less number of splits.\nSo, having less number of important features is normal and does not cause any problems.","Q_Score":1,"Tags":"python,machine-learning,decision-tree","A_Id":67529254,"CreationDate":"2021-05-14T04:01:00.000","Title":"Question regarding DecisionTreeClassifier","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am having values like \\xc2\\xa0Bluestone\n\\xc2\\xa0CloudCherry\n\\xc2\\xa0Footprints Education\nin my dataset and i have been trying to remove these using some methods but unable to do so. PLease help out.\nTill now i have tried:\n1.df=df[df['Startup_Name']!='\\xc2\\xa0Ameyo']\n2.Droping the rows having these values","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":43,"Q_Id":67546841,"Users Score":1,"Answer":"The C2AO is utf8 for nonbreaking space. Have you tried setting encoding=\u201cutf_8\u201d parameter for read_csv()?","Q_Score":0,"Tags":"python,pandas","A_Id":67546917,"CreationDate":"2021-05-15T12:41:00.000","Title":"Cleaning Data using pandas","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"My Time series data has a feature similar to Zipcode with 300+ unique codes. How to encode this high cardinality categorical feature which has no inherent order. I am trying to train a time series model which has data points with repeated zip codes and doesn't want to lose any information.\nI've gone through mean\/Target encoding but it has some disadvantages like overfitting etc. Are there any other encoding techniques apart from that exclusively for time series data?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":68,"Q_Id":67548428,"Users Score":0,"Answer":"One Idea: use the word embeddings of the corresponding cities from a Wikipedia word2vec model.","Q_Score":1,"Tags":"python,encoding,time-series,categorical-data","A_Id":67917331,"CreationDate":"2021-05-15T15:33:00.000","Title":"Nominal Encoding techniques for high cardinality categorical variables in time series analysis","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm currently working on a python programm that matches an input image with the closest image in a database. Im using python opencv with SIFT descriptors to do so. I have a working prototype with the following steps:\n\nExtract SIFT descriptors of the input image\n\nFor each image:\n\ncompare with input and find matching keypoints between the two using flann.knnMatch\n\nusing Lowe's ratio test identify good keypoint matches\n\ncompute a score for each image by calculating the average distance per good keypoint match\n\n\nThe image with the lowest score would then be the best match. My aproach seems very slow, especially with larger databases.\nIs there a faster way to match an image with a database if this is even the correct way?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":432,"Q_Id":67548836,"Users Score":2,"Answer":"There are better approaches than SIFT for searching images. Since i do not know the images in your database, I am just going to say you what would i do instead of SIFT approach.\nLBP (Local binary patterns) or GLCM (Gray Level Co-occurrence Matrix) can speed up your solution. Calculate stastics (GLCM or LBPs ) for each image in the database and store them with indexing.Lets call them image signs from now on. On search, calculate the CCC (cross correlation coefficent) between image of interest sign and database image sign. Sort them by CCC at descending order. I am just assuming the images you are going match has relatively small baseline and camera angle difference. SIFT like approaches do not work well with highly rotated images.\nThere are lots of papers about your problem. Some of them uses optical flow to find images. You should find the best one for your situation.","Q_Score":1,"Tags":"python,database,opencv,matching,sift","A_Id":67549208,"CreationDate":"2021-05-15T16:16:00.000","Title":"Match image with database using SIFT","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a general question regarding\ntf.random.shuffle()\nWhat is the use of shuffling a tensor in a neural network model ??","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":61,"Q_Id":67549931,"Users Score":0,"Answer":"Off the top of my head, here is an example usage:\nImagine you are passing the validation_split parameter (or similar) to the model. This parameter always splits the data in the same way.\nBut, if your data is ordered, e.g. by type, then the model will only be trained on a skewed subset. I.e. it will become specialised to data which is not fully representative of the population.\nThus, you could use the shuffle function to remove any orderings\/biases in the subset before feeding it to the model.\nAnother similar purpose could be to prevent the model from learning the order of the data instead of inferring connections between data points.","Q_Score":0,"Tags":"python,tensorflow,neural-network,tensor","A_Id":67549998,"CreationDate":"2021-05-15T18:15:00.000","Title":"What is the use of Shuffling a Tensor","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a project with a couple thousand lines of code.\nI'm getting this message when it runs:\n\n(e.g. obj[:, None]) is deprecated and will be removed in a future version. Convert to a numpy array before indexing instead. y = y[:, np.newaxis]\n\nThe error message doesn't give me any line number to go look at and I have no idea what to look for to try to debug this.\nAny suggestions would be appreciated.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":722,"Q_Id":67563737,"Users Score":0,"Answer":"I also encountered this problem when using Python's matplotlib.pyplot library, where I converted the input data from the plot() function to numpy Array, such a warning is not availabled, just for reference.","Q_Score":0,"Tags":"python,deprecated","A_Id":70140118,"CreationDate":"2021-05-17T03:40:00.000","Title":"_base.py:251: FutureWarning: Support for multi-dimensional indexing - WHAT?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I just wonder, what happen if i have dataset with duplicate text value for my LSTM model, it will affect training, or it can make overfit? thanks in advance","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":58,"Q_Id":67575284,"Users Score":0,"Answer":"Depending on how much duplicate you have the effect can be quite transparent for the training. At the extreme if you have too many of them it won't generalize well because your dataset will be artificially large but will lack diversity to generalize well.\nMost problematic effect of duplicate is when their labels (or targeted value) are different but their features are identical. This can throw off training and prediction badly if there're too many of them.","Q_Score":1,"Tags":"python,database,deep-learning,lstm,recurrent-neural-network","A_Id":67576350,"CreationDate":"2021-05-17T18:34:00.000","Title":"Duplicate values on text feature with deep learning e.g LSTM","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"We want to implement attribute prediction and image search model in single application.\nStep1. Upload of image ,will give attribute details.\nexample ,If we upload dog image, then attribute details will display like color, breed.\nstep2. On click of any attribute will show similar matching result.\nexample on click of attribute like breed it will display matching breed dog images from image data.\nPlease suggest ,how we can achieve that","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":47,"Q_Id":67581498,"Users Score":1,"Answer":"With step 1, I recommend you should use a multi-label images classification. It will help you get attribute of input image like what object in in the image, what color is it,...\nWith step 2, you can query the attribute in your database or you can use a recommendation system for more advance.","Q_Score":0,"Tags":"python,machine-learning,computer-vision,artificial-intelligence","A_Id":67582589,"CreationDate":"2021-05-18T07:10:00.000","Title":"How we can implement attribute prediction and image search model as one?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":1},{"Question":"i have been working with Abaqus python recently to solve some stress\/strain problems. I wish to process the data from .odb file directly in python and then output it to excel. But turned out that these 2 libraries are not installed in Abaqus python. Since Abaqus python is a bit outdated. its still using python 2.7 Im wondering if there is any way I can install these external libraries into my Abaqus?\nand furthermore, can I for example use VScode or other commonly used IDE instead of Abaqus Command prompt or GUI to run the script?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":510,"Q_Id":67581647,"Users Score":0,"Answer":"You can use IDEs for development, but not debugging of Abaqus Python.\nYou have to point to the abaqus python library in your IDE for it to recognize the imports. I have an image of how to do that in PyCharm.\n[Pycharm add Abaqus code library to project][1]\nYou could probably insert \"import pdb; pdb.set_trace()\"\nin your code to pause the execution and interactively debug, or use Abaqus PDE.\nRun scripts via \"abaqus python AbaqusPythonFile.py\" if you don't need the session object (viewports and display groups and such).\nIf you need the session object, run via abaqus cae nogui=AbaqusPythonFile.py if you don't need the UI physically active.","Q_Score":0,"Tags":"python,pandas,matplotlib,visual-studio-code,abaqus","A_Id":71745173,"CreationDate":"2021-05-18T07:22:00.000","Title":"Is there a way to integrate matplotlib\/Pandas in Abaqus Python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am looking for any NER model train to extract entity from rap lyrics. Presently I am using Spacy models for NER, but there's a lot of misclassification. This is because spacy models are pretrained on newspaper articles. So, the initial question; Is there any model that I can use for NER on rap lyrics.\nThis is how the present spacy model classifying some of the words\n\n('kanye west', 'GPE'),('2pac', 'PRODUCT'),('hoochie coochie', 'ORG'),('valley', 'LOC'),('talkin', 'NORP'),('nothin', 'PERSON'),('100k', 'PRODUCT')\n\n(In case if u are wondering what lyrics are these, these are from Kendrick Lamar)","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":34,"Q_Id":67586277,"Users Score":1,"Answer":"You may need to generate your own training data, as the words you are trying to classify are very specific to the American rap industry, and most probably not covered by any existing nlp package.","Q_Score":1,"Tags":"python,nlp,named-entity-recognition,named-entity-extraction","A_Id":67586513,"CreationDate":"2021-05-18T12:33:00.000","Title":"NER model for lyrics[rap]","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I was guessing whether there are some build-in options using SpaCy 3 in combination with k-folds cross-validation.\nI would like to run a 10 folds cross validation on a dataset of approx. 17.5k job descriptions to receive the best performing model in the end.\nDocumentation isn't telling anything about these options.\nI think I can do some workaround by hand if the option does not exist.\nThanks in advance!","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":410,"Q_Id":67589186,"Users Score":2,"Answer":"spaCy does not have any built-in handling for cross validation, no.\nWith v3 using the config training, you'd probably want to generate train\/dev split .spacy files before several training runs to do cross validation.","Q_Score":3,"Tags":"python,spacy,named-entity-recognition","A_Id":67597133,"CreationDate":"2021-05-18T15:17:00.000","Title":"SpaCy 3 Cross validation","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":1},{"Question":"I am detecting hand gestures using tensorflow object detection api but I want to apply condition to this detection means I want to detect hand gesture of a person when a person is wearing a whistle otherwise no detection. Can I achieve this using Tensorflow object detection api. If no suggest me some good methods of achieving this. thanks :)","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":89,"Q_Id":67590552,"Users Score":0,"Answer":"the first thing that you should perform is customizing a pre-trained Tensorflow model with one class, using this technique you can generate a model which has only one class, named \"hand\" for example. but how to do this? don't worry, just simply follow the below steps:\n\ndownload Tensorflow model master from GitHub and build it. (you can clone it using git instead of downloading it).\nafter your building is accomplished, you have to label your train image using label image software as well. the output of the label image is a CSV file.\nin the next step you have to convert this CSV file to the record file.\nand then train your own model.\nafter that your model is being trained, you have to export your model and do the target detection simply.\n\nit is good to say that if you don't have an Nvidia GPU, use google Colab because this process is very time-consuming by making use of CPU.\nbest wishes to you.","Q_Score":0,"Tags":"python,tensorflow,object,real-time,object-detection","A_Id":67685173,"CreationDate":"2021-05-18T16:45:00.000","Title":"Conditional Detection using Tensorflow Object Detection API","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to run a Docker container with some Python bots inside. These scripts need libraries like pandas, numpy and matplotlib.\nEverything works great in an x86 environment, but building the image on a Arm environment takes ages.\nFrom what I understood, it seems like it needs to compile the libraries for Arm instead of just downloading the compiled files. I am trying to find a way to avoid all of this.\n\nMatplotlib, pandas, numpy: They're pretty heavy packages, but I need just a few functionalities. Is the a slim version of these libraries?\nAny way to store the compiled stuff in a permanent cache somewhere in the pipeline? (I am using both GitHub and GitLab to build this)\n\nAny help is appreciated\nRegards","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":463,"Q_Id":67591231,"Users Score":1,"Answer":"As @Itamar Turner-Trauring mentioned, matplotlib, numpy, pandas and many more libraries store wheels for aarch64 as well as for x86.\nIn my case, pip was downloading the x86 wheels by default, and then it must compile them during the build and it takes ages.\nAfter changing the pandas version I was using from 1.1.5 to 1.3.5, pip logs changed\nfrom:\nDownloading https:\/\/****\/pypi\/download\/pandas\/1.1.5\/pandas-1.1.5.tar.gz (5.2 MB)\nTo:\nDownloading https:\/\/****\/pypi\/download\/pandas\/1.3.5\/pandas-1.3.5-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl (10.9 MB)\nAnd the entire build time changed from 58 to 8 minutes.","Q_Score":1,"Tags":"python,docker,arm,gitlab-ci,github-actions","A_Id":70644911,"CreationDate":"2021-05-18T17:29:00.000","Title":"Python ARM in Docker - Installing requirements takes ages","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":1,"Web Development":0},{"Question":"I have a string that I would like to check for comparison.\ndf['ACCOUNTMANAGER'][0] this value has some special character that I cannot compare using string comparison. I tried to compare using bytes but it failed. I would like to check how the data is stored there for comparison. Is there a way to do this?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":43,"Q_Id":67597520,"Users Score":0,"Answer":"I figured it out. It was being stored as utf-8 encoded format and now comparison works. I used for comparison byte b'\\x8a' in if statement.","Q_Score":0,"Tags":"python,pandas,dataframe","A_Id":67601588,"CreationDate":"2021-05-19T05:39:00.000","Title":"how to check python bytes for dataframe string field?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I wrote some code to combine multiple CSV's that are interpretered with Pandas and appended to one combined CSV.\nThe issue I have is that the CSV files are delivered by multiple parties (monthly) and often contain differences with regard to column names, while they essentially contain the same information. For instance:\nCSV 1\n| ID | Instance number |\n| -------- | -------------- |\n| 1 | 401421 |\n| 2 | 420138 |\nCSV 2\n| ID | Instance NO |\n| -------- | -------------- |\n| 1 | 482012 |\n| 2 | 465921 |\nThis will result in two columns in the combined file, Instance Number & Instance NO unless I rename the column beforehand while the idea is to automatically process all files without intervention beforehand.\nThe solution that should work is to use combine_first or fillna, but next time the column may be entered as e.g. Instance No\/number.\nSince improving data delivery isn't an option, is there any smart way to solve issues like this without having to write out all possible variations and remap them to one leading column?\nThanks in advance!","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":72,"Q_Id":67600423,"Users Score":0,"Answer":"The short answer is no, as your asking the computer to think for itself. You do however have multiple options to deal with common scenarios.\nIf the column order and\/or positions are fixed you can make use of the header=0, names=['ID', 'Instance'] to ignore the headers sent in the file and make use of known data\nYou can also generate a config file that maps all possible wrong header names to the right one","Q_Score":0,"Tags":"python,pandas,csv,merging-data","A_Id":67600669,"CreationDate":"2021-05-19T09:23:00.000","Title":"How to merge multiple raw input CSV's with pandas containing similar columns with slightly different names?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I try to create a dataframe in a Python function used by Labview. In each LabView loop, I want to concat a DataFrame in a Python function. How can I reuse the output of the last function for the next Python function using Dataframe as output? When I connect the function output, I get the error in LabView: \"Polymorphic terminal cannot accept this datatype\".\nOther DataTypes (e.g. array) are not a problem.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":359,"Q_Id":67601600,"Users Score":0,"Answer":"LabVIEW specifically calls out that the only options allowed for passing data to\/from Python Nodes are:\n\nNumerics\nArrays, including multi-dimensional arrays\nStrings\nClusters\n\nGiven this list of options I would suggest passing your data back\/forth to LabVIEW as strings using the option provided by:\n\nDataFrame.to_json\npandas.read_json\n\nWith the addition of a few lines of code to the python segment you get your data frame out into LabVIEW in a human readable and parsable datatype.","Q_Score":0,"Tags":"python,pandas,dataframe,labview","A_Id":67611432,"CreationDate":"2021-05-19T10:34:00.000","Title":"Get result of Python function in Labview and reuse as value for next function","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Trying to run---\nfrom keras.optimizers import SGD, Adam,\nI get this error---\n\nTraceback (most recent call last):\n\u2007 File \"C:\\Users\\usn\\Downloads\\CNN-Image-Denoising-master ------after the stopping\\CNN-Image-Denoising-master\\CNN_Image_Denoising.py\", line 15, in \n\u2007 \u2007 from keras.optimizers import SGD, Adam\nImportError: cannot import name 'SGD' from 'keras.optimizers'\n\nas well as this error, if I remove the SGD from import statement---\n\nImportError: cannot import name 'Adam' from 'keras.optimizers'\n\nI can't find a single solution for this.\nI have Keras and TensorFlow installed. I tried running the program in a virtualenv (no idea how that would help, but a guide similar to what I want mentioned it) but it still doesn't work. If anything, virtualenv makes it worse because it doesn't recognize any of the installed modules. I am using Python 3.9. Running the program in cmd because all the IDEs just create more trouble.\nI am stumped. My knowledge of Python is extremely basic; I just found this thing on GitHub. Any help would be greatly appreciated.","AnswerCount":5,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":57731,"Q_Id":67604780,"Users Score":0,"Answer":"from tensorflow.keras.utils import to_categorical\nIt works just as well for to_categorical.","Q_Score":14,"Tags":"python,tensorflow,keras","A_Id":71200113,"CreationDate":"2021-05-19T14:02:00.000","Title":"Unable to import SGD and Adam from 'keras.optimizers'","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am a newbie in data science domain.\nI have a data set, which has both numerical and string data.The interesting fact is both type of data make sense for the outcome. How to choose the relevant features from the data set?\nShould I be using the LabelEncoder and convert the data from string to numerical and continue with the correlation? I am taking the right path? Is there any better way to solve this crisis?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":268,"Q_Id":67609743,"Users Score":0,"Answer":"Kind of a cop out but you could simply use a random forest and happily mix numerical and categorical data. Encoding with LabelEncoder on OneHotEncoding would allow you to use a wider variety of algorithms.","Q_Score":0,"Tags":"python,feature-selection","A_Id":67609864,"CreationDate":"2021-05-19T19:30:00.000","Title":"Feature Selection from Mixed dataset","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Can I create another index on an existing column of pandas DataFrame? Just like what CREATE INDEX in SQL does. For example: My DataFrame has two columns id_a and id_b, both of them are unique for each row, and I'd like to index rows sometimes with id_a while other times with id_b (so I think MultiIndex won't work for me). I want these operations to be fast, so \"index\" must be created for both id_a and id_b.\nIs it possible I can do this in pandas currently?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":66,"Q_Id":67625273,"Users Score":0,"Answer":"You can't have 2 indices in a Pandas DataFrame object.\nYou will have to workaround this limitation, for example:\n\nby code logic,\nusing other Pandas features,\nusing columns and flags depending which column needs to be used to index a given row\n\nThe operations should be fast. For additional performance, you can adjust the dtypes according to your needs. To match hashmap lookups or similar, you will have to add more thought into your use case and perhaps use a different logical approach with a separate mapping\/dict or similar.","Q_Score":4,"Tags":"python,pandas,indexing","A_Id":67626563,"CreationDate":"2021-05-20T17:26:00.000","Title":"create another index for pandas DataFrame like CREATE INDEX in SQL","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working on time series VARMAX model in python with 18000 rows of data and 6 parameters. Repeatedly while fitting the VARMAX model, it says \" leading minor is not positive definite\" or \"matrix is not positive definite\". Can somebody help in recognizing the problem?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":327,"Q_Id":67637941,"Users Score":1,"Answer":"The error suggests that there are linear dependencies among your variables. You can investigate these linear relationships using the correlation matrix df.corr() and\/or PCA.","Q_Score":0,"Tags":"python,statsmodels,arima,varmax","A_Id":68421592,"CreationDate":"2021-05-21T13:37:00.000","Title":"While implementing VARMAX model in python, the error comes that leading minor is not positive definite","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a Lenovo as computer, but there is no GPU installed. So when I run a machine learning program written in python, it runs it on my local CPU. I know that Colab provides us a GPU for free. To use it, I need to take the content of all the python files from my ML program and put it in this Colab notebook. It is not very convenient at this point. Is it possible to run in any ways my ML program from my computer using directly the Colab GPU without using the Colab Notebook directly.\nEDIT\nBe aware that I don't want to work from Jupiter Notebook. I would like to work in Visual Studio Code and run the code on the Colab GPU directly instead of my CPU","AnswerCount":3,"Available Count":2,"Score":0.0665680765,"is_accepted":false,"ViewCount":643,"Q_Id":67641883,"Users Score":1,"Answer":"Not that I know of. Colab's GPU and notebook runs on Google's computers. Your local jupyter notebook runs on your computer alone and sort of can't communicate to Google's computers. This is not a physics limitation or anything. It's just that no one has integrated them before.\nWhat you can do though, to make the transfers quickly, is to create a git repo for all of your files, commit them to GitHub, then pull them down in colab's notebooks. It's relatively quick, syncs well, and serves as a backup.","Q_Score":0,"Tags":"python,google-colaboratory","A_Id":67641988,"CreationDate":"2021-05-21T18:01:00.000","Title":"Run a ML program locally using the Colab GPU","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a Lenovo as computer, but there is no GPU installed. So when I run a machine learning program written in python, it runs it on my local CPU. I know that Colab provides us a GPU for free. To use it, I need to take the content of all the python files from my ML program and put it in this Colab notebook. It is not very convenient at this point. Is it possible to run in any ways my ML program from my computer using directly the Colab GPU without using the Colab Notebook directly.\nEDIT\nBe aware that I don't want to work from Jupiter Notebook. I would like to work in Visual Studio Code and run the code on the Colab GPU directly instead of my CPU","AnswerCount":3,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":643,"Q_Id":67641883,"Users Score":0,"Answer":"Be aware that I don't want to work from Jupiter Notebook. I would like to work in Visual Studio Code and run the code on the Colab GPU directly instead of my CPU\n\nNope, not possible.\nUpdate reason:\nColab itself is a jupyter notebook, you can't take away the machine resources to link to your pc and use other software with it.\nIf this possible, people will already abuse it and use it for mining crypto, run-heavy load programs, etc.\nColab is a free product by Google to introduce you to their cloud compute services. This mean colab have its own limitation\n\"Colab resources are not guaranteed and not unlimited, and the usage limits sometimes fluctuate. \" -Colab FAQ\nIf you are a fan of colab, you might want to try the pro version for just $10\/month","Q_Score":0,"Tags":"python,google-colaboratory","A_Id":67861140,"CreationDate":"2021-05-21T18:01:00.000","Title":"Run a ML program locally using the Colab GPU","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm struggling to understand when and when not to use compute() in Dask dataframes. I usually write my code by adding\/removing compute() until the code works, but that's extremely error-prone. How should I use compute() in Dask? Does it differ in Dast Distributed?","AnswerCount":2,"Available Count":2,"Score":0.0996679946,"is_accepted":false,"ViewCount":156,"Q_Id":67660286,"Users Score":1,"Answer":"Each partition in a Dask DataFrame is a Pandas DataFrame.\ncompute() combines all the partitions (Pandas DataFrames) into a single Pandas DataFrame.\nDask is fast because it can perform computations on partitions in parallel. Pandas can be slower because it only works on one partition.\nYou should avoid calling compute() whenever possible. It better to have the data spread out in multiple partitions, so it can be processed in parallel.\nIn rare cases you can compute to Pandas (e.g. when doing a large to small join or after a huge filtering operation), but it's best to learn how to use the Dask API to run computations in parallel.","Q_Score":1,"Tags":"python,dask,dask-distributed,dask-dataframe","A_Id":69450923,"CreationDate":"2021-05-23T13:26:00.000","Title":"What is the logic behind \"compute()\" in Dask dataframes?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm struggling to understand when and when not to use compute() in Dask dataframes. I usually write my code by adding\/removing compute() until the code works, but that's extremely error-prone. How should I use compute() in Dask? Does it differ in Dast Distributed?","AnswerCount":2,"Available Count":2,"Score":1.2,"is_accepted":true,"ViewCount":156,"Q_Id":67660286,"Users Score":1,"Answer":"The core idea of delayed computations is to delay the actual calculation until the final target is known. This allows:\n\nincreased speed of coding (e.g. as a data scientist, I don't need to wait for every transformation step to complete before designing the workflow),\ndistribution of work across multiple workers,\novercoming resource constraints of my client, e.g. if I am using a laptop with limited memory, I can run heavy computations on dask workers that are in the cloud or another machine with more resources,\nbetter efficiency if the final target requires only some tasks to be done (e.g. if the final calculation requires only a subset of the dataframe, then dask will load only the relevant columns\/partitions).\n\nSome of the alternatives to calling .compute are:\n\n.visualize(): this helps visualize the task graph. The DAG can become hairy when there are lots of tasks, so this is useful to run on smaller subsets of the data (e.g. only loading two\/three partitions of the dataframe)\nusing client.submit: this launches computations right away providing you with a future, an object that refers to results of a task being computed. This gives the advantages of scaling work across multiple workers, but it can be a bit more resource intensive (since dask doesn't know the full workflow, it might run computations that are not needed to achieve the final target).\n\nWith regards to distributed, I don't think there is a difference except for where the result will be: dask.compute will put the result in local machine, while client.compute will keep the result on a remote worker.","Q_Score":1,"Tags":"python,dask,dask-distributed,dask-dataframe","A_Id":67660779,"CreationDate":"2021-05-23T13:26:00.000","Title":"What is the logic behind \"compute()\" in Dask dataframes?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to install opencv in the terminal but every time I try installing it an error comes up saying ERROR: Failed building wheel for numpy Failed to build numpy ERROR: Could not build wheels for numpy which use PEP 517 and cannot be installed directly\nI tried installing with pip install opencv-python and pip install opencv-contrib-python","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":47,"Q_Id":67660828,"Users Score":0,"Answer":"Opencv apparently doesn't work well with M1 chip macs, so I advise using conda instead of venv or pip, things that showed errors with pip doesn't show in conda. For me atleast :)","Q_Score":0,"Tags":"python,opencv","A_Id":67731693,"CreationDate":"2021-05-23T14:28:00.000","Title":"Opencv not installing for python in terminal","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have an excel sheet(.xlsx file) with the following data:\n\n\n\n\nDate 1\nDate 2\n\n\n\n\n03\/26\/2010\n3\/31\/2011\n\n\nNULL\nNULL\n\n\n03\/26\/2010\n3\/31\/2011\n\n\nNULL\nNULL\n\n\n03\/26\/2010\n3\/31\/2011\n\n\nNULL\nNULL\n\n\n01\/01\/2010\n6\/30\/2010\n\n\n01\/01\/2010\n6\/30\/2010\n\n\n01\/12\/2011\n4\/15\/2012\n\n\n\n\nWhen I convert it to dataframe using\npd.read_excel(\"file.xlsx\",header=0,dtype=str,engine='openpyxl')\nIt is reading all data properly except for the row items 3,4,5,6 which are being read as below:\n\n\n\n\nDate 1\nDate 2\n\n\n\n\n03\/26\/2010\n3\/31\/2011\n\n\nNULL\nNULL\n\n\n01\/01\/2010\n6\/30\/2010\n\n\n01\/01\/2010\n6\/30\/2010\n\n\n01\/12\/2011\n4\/15\/2012\n\n\nNULL\nNULL\n\n\n\n\nIt is causing an unnecessary data shift and hence affecting my furthur steps. Any reasons why only at this place it is happening and nowhere else in the data?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":543,"Q_Id":67666768,"Users Score":0,"Answer":"The problem is now resolved.\nIt was the issue with the index given by pandas to the Dataframe.\nMy table had headers, but the pandas' index starts from 0 for the first row data.\nSo I was being shown the next index number's data, which deceived me into thinking that read_excel has a bug.\nThanks for your support.","Q_Score":0,"Tags":"python,excel,pandas","A_Id":67668432,"CreationDate":"2021-05-24T04:42:00.000","Title":"Pandas read_excel function incorrectly reading data from excel file","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"My dataframe has a nested column (people_info) that contains cells like the sample below.\n[{\"institution\":\"some_institution\",\"startMonth\":1,\"startYear\":2563,\"course\":\"any\",\"id\":1111,\"formation\":\"any\",\"endMonth\":12,\"endYear\":2556,\"status\":\"complete\"}]\nAs far I know this can be solved using dictionary\/json concepts.\nI'm trying to split this column in new columns, considering that each key of this nested cell will be a new column with their respective values.\nI tried json_normalize, but I'm getting this error: \"AttributeError: 'str' object has no attribute 'values'\"\nI tried to transform those cells in a dict, but I never was able to make python understand that \"institution\" is a key and \"some_institution\" is a value in this created dict. It's seems python understand the whole cell as a string.\nCan you help me? If I wasn't clear, please tell me. Tks!","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":154,"Q_Id":67677408,"Users Score":0,"Answer":"Maybe this helps.\nimport pandas as pd\ndata = [{\"institution\":\"some_institution\",\n\"startMonth\":1,\n\"startYear\":2563,\n\"course\":\"any\",\n\"id\":1111,\n\"formation\":\"any\",\n\"endMonth\":12,\n\"endYear\":2556,\n\"status\":\"complete\"}]\nl = next(item for item in data)\ndf = pd.DataFrame(l, index=[0])\ndf","Q_Score":0,"Tags":"python,json,pandas,dictionary,nested","A_Id":67678174,"CreationDate":"2021-05-24T18:47:00.000","Title":"Split nested column into new columns","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to create a magic Square function out of 2d list: [[8, 1, 6], [3, 5, 7], [4, 9, 2]], where It checks if all the columns adds up to 15 from a 3x3 square. I'm stuck on how to write function checks for the sum of columns if anyone can help out that will be highly appreciative. Without using numpy","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":41,"Q_Id":67683262,"Users Score":0,"Answer":"My advice would be compare the two answers thus far and pick the performance and readability answer and write a test for the method ensuring people do not break it.","Q_Score":0,"Tags":"python","A_Id":67691762,"CreationDate":"2021-05-25T07:08:00.000","Title":"How to Count columns from a 3x3 square","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Can somebody help me in solving the below problem\nI have a CSV, which is relatively large with over 1 million rows X 4000 columns. Case ID is one of the first column header in csv. Now I need to extract the complete rows belonging to the few case Ids, which are documented in list as faulty IDs.\nNote: I dont know the indices of the required case IDs\nExample > the CSV is - production_data.csv and the faulty IDs, faulty_Id= [ 50055, 72525, 82998, 1555558]\nNow, we need to extract the complete rows for faulty_Id= [ 50055, 72525, 82998, 1555558]\nBest Regards","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":34,"Q_Id":67703948,"Users Score":0,"Answer":"The best way for you is to use a database like Postgres or MySQL. You can copy your data to the database first and then easily operate rows and columns. The file in your case is not the best solution since you need to upload all the data from the file to the memory to be able to process it. And file opening takes a lot of time in addition.","Q_Score":0,"Tags":"python,python-3.x,list","A_Id":67706187,"CreationDate":"2021-05-26T11:28:00.000","Title":"Extraction of complete rows from CSV using list , we dont know row indices","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Is there anyway to install a lightweight version of TensorFlow for prediction only?\nI built a Docker image with TensorFlow 2.5 and python 3.8 slim. The image size is 1.8Gb but I need it to be 1Gb maximum.\nAs I will only use this Docker image for prediction, I guess there must be a way to reduce TensorFlow and install only the needed modules.\nIf you know if TF lite or TF serving can help me to reach this out, please tell me how.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":93,"Q_Id":67708131,"Users Score":0,"Answer":"I think the only way yo use TF in a lightweight mode is using TFlite or TFLite Micro. For this to work yo need to convert your frozen inference graph to a .tflite file.","Q_Score":1,"Tags":"python,docker,tensorflow","A_Id":67716146,"CreationDate":"2021-05-26T15:32:00.000","Title":"TensorFlow lightweight for prediction","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am getting some results in the form of np.arrays of size (no_of_rows, 2), where no_of_rows varies from array to array.\nI want to save these results to disk for later usage (plotting). In any way, it doesn't matter how, but if possible in the most efficient way in terms of REOPENING\/USING time-consumed-wise.\nI can do anything with these 2D arrays. My thought was to create a .npy file containing a 3D tensor of shape (no_of_matrices, ? , 2), but that ? is my problem. Each 2D array can potentially have a different no_of_rows. So I abandoned this idea.\nI now made a list of these 2D np.arrays. I now want to save that list to disk.\nI have read about np.savez, but this doesn't preserve the order of saving. That is, when loading back in memory, I won't know which array is which, apart from many if's statements to check the no_of_lines of each array and match it to what it means for when plotting it later.\nDo I have any chance to store these arrays in 1 SINGLE file, or do I just have to resort to creating multiple files, named in a distinctive way, one for each 2D array, and then access these files individually when plotting?\n[PS: I can only have a maximum of 100-ish of such 2D arrays, usually having less than 10.]\nThanks","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":59,"Q_Id":67719039,"Users Score":0,"Answer":"You can save these 2D arrays to CSV files.\nConcatenating all the arrays into one is up to you: you can concatenate all the arrays into a single one and save only one file, or you can save all the arrays you receive.","Q_Score":1,"Tags":"python,arrays,numpy,file-io,data-science","A_Id":67719724,"CreationDate":"2021-05-27T09:05:00.000","Title":"How to save to disk several 2D np.arrays each having the second dimension variable in size?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Is any possible way to reshape an array of size [129, 14] into [128, 15]?\nThanks in advance!","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":30,"Q_Id":67724071,"Users Score":0,"Answer":"No it\u2019s not possible because 129 x 14 != 128 x 15 so you cannot end up with a structure that will contain the same amount of information. You can do a lot of things to go from one shape to another for example simply remove a row and add a column but you cannot make it reversible (assuming finite number types).","Q_Score":0,"Tags":"python,numpy","A_Id":67724166,"CreationDate":"2021-05-27T14:18:00.000","Title":"Reshape NumPY array increasing and decreasing axes size","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Is any possible way to reshape an array of size [129, 14] into [128, 15]?\nThanks in advance!","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":30,"Q_Id":67724071,"Users Score":0,"Answer":"When you use np.reshape on an array, data do not change. Element count is unchanged.\nWith this property in mind, you can see that 129x14!=128x15. So it's impossible without making choices i.e. adding or deleting data.","Q_Score":0,"Tags":"python,numpy","A_Id":67724217,"CreationDate":"2021-05-27T14:18:00.000","Title":"Reshape NumPY array increasing and decreasing axes size","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I need some help with this problem:\nI have two tables and I want to filter the rows on the second table (Table B) so that it only shows the one's that have matching 'names' with the Table A.\nAn exemple:\nTable A\n\n\n\n\nA\nb\nc\n\n\n\n\nAnne\nTwo\nThree\n\n\nAnne\nFour\nFive\n\n\nJhon\nFour\nFive\n\n\nOlivia\nFour\nFive\n\n\n\n\nTable. B\n\n\n\n\nA\nMoney\nRent\n\n\n\n\nAnne\nTwo\nThree\n\n\nAnne\nFour\nFive\n\n\nAnne\nFour\nFive\n\n\nKristian\nFour\nFive\n\n\nPaul\nFour\nFive\n\n\nOlivia\nFour\nFive\n\n\nOlivia\nFour\nFive\n\n\n\n\nThe result that I want to achieve is\n\n\n\n\nA\nMoney\nRent\n\n\n\n\nAnne\nTwo\nThree\n\n\nAnne\nFour\nFive\n\n\nAnne\nFour\nFive\n\n\nJhon\nNan\nNan\n\n\nOlivia\nFour\nFive\n\n\nOlivia\nFour\nFive","AnswerCount":4,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":117,"Q_Id":67725254,"Users Score":0,"Answer":"Assuming you are using pandas, you could try this: dfC = dfB[dfB['A'].isin(dfA['A'].unique())]\nThis way, you will be filtering table B, based on it's A column, looking for values that are in the column A of table A.","Q_Score":3,"Tags":"python,jupyter-notebook","A_Id":67725441,"CreationDate":"2021-05-27T15:23:00.000","Title":"keeping table rows that match the other table","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I need some help with this problem:\nI have two tables and I want to filter the rows on the second table (Table B) so that it only shows the one's that have matching 'names' with the Table A.\nAn exemple:\nTable A\n\n\n\n\nA\nb\nc\n\n\n\n\nAnne\nTwo\nThree\n\n\nAnne\nFour\nFive\n\n\nJhon\nFour\nFive\n\n\nOlivia\nFour\nFive\n\n\n\n\nTable. B\n\n\n\n\nA\nMoney\nRent\n\n\n\n\nAnne\nTwo\nThree\n\n\nAnne\nFour\nFive\n\n\nAnne\nFour\nFive\n\n\nKristian\nFour\nFive\n\n\nPaul\nFour\nFive\n\n\nOlivia\nFour\nFive\n\n\nOlivia\nFour\nFive\n\n\n\n\nThe result that I want to achieve is\n\n\n\n\nA\nMoney\nRent\n\n\n\n\nAnne\nTwo\nThree\n\n\nAnne\nFour\nFive\n\n\nAnne\nFour\nFive\n\n\nJhon\nNan\nNan\n\n\nOlivia\nFour\nFive\n\n\nOlivia\nFour\nFive","AnswerCount":4,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":117,"Q_Id":67725254,"Users Score":0,"Answer":"SELECT * FROM table_B WHERE A IN (SELECT A FROM table_A)","Q_Score":3,"Tags":"python,jupyter-notebook","A_Id":67725455,"CreationDate":"2021-05-27T15:23:00.000","Title":"keeping table rows that match the other table","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I setup the linux computer with tensorflow 2.3 with cuda 11.0 & cudnn 8.\nI was keras and torch,\nbut this time I tried to use tensorflow 1.15 from the virtual environment, but whenever I typed\nwith Seesion:\nCould not load dynamic library 'libcudart.so.10.0'; dlerror :libcudart.so.10.0 : cannot open shared object file; dlerror : libcudart.so.10.0 cannot open shard object file: No such file or directory ; LD_LIBRARY_PATH:\/usr\/local\/cud-10.1\/lib64\ni want to ask if there is new version of tensorflow, we cannot use older tensorflow for it?\nif we can, then is it fine just download cuda 10.0 in to my desktop?","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":79,"Q_Id":67734027,"Users Score":0,"Answer":"Different versions of tensorflow are built with different cuda versions.\nThe prebuilt Tensorflow 1.15 needs cuda 10.0.\nYou can either build Tensorflow from source on your machine, in which case you can build it with the version of cuda you have available, or install cuda 10.0 alongside version cuda 11","Q_Score":0,"Tags":"python,tensorflow","A_Id":67734574,"CreationDate":"2021-05-28T06:43:00.000","Title":"tensorflow 1.15 compatibility with tensorflow 2.3?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I setup the linux computer with tensorflow 2.3 with cuda 11.0 & cudnn 8.\nI was keras and torch,\nbut this time I tried to use tensorflow 1.15 from the virtual environment, but whenever I typed\nwith Seesion:\nCould not load dynamic library 'libcudart.so.10.0'; dlerror :libcudart.so.10.0 : cannot open shared object file; dlerror : libcudart.so.10.0 cannot open shard object file: No such file or directory ; LD_LIBRARY_PATH:\/usr\/local\/cud-10.1\/lib64\ni want to ask if there is new version of tensorflow, we cannot use older tensorflow for it?\nif we can, then is it fine just download cuda 10.0 in to my desktop?","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":79,"Q_Id":67734027,"Users Score":0,"Answer":"Tensorflow<2 is not supported by cuda>9.\nYou can build tensorflow from source with cuda10","Q_Score":0,"Tags":"python,tensorflow","A_Id":67734517,"CreationDate":"2021-05-28T06:43:00.000","Title":"tensorflow 1.15 compatibility with tensorflow 2.3?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am thinking to the problem of doing regression on a scalar function f:R^n->R, where I have a set of training samples (x1,y1),...,(xN,yN), with yi = f(xi).\nI know I could in principle apply any neural network architecture to do regression on this function, however I want to exploit a property I know about it to design the network.\nPrecisely, I know that f(x)= x^TA(x)x$ for a nxn matrix valued function A(x) which I don't know clearly, but I know is symmetric and positive definite.\nI think that since I know this structure of the function, it is not an efficient approach to apply a \"standard\" architecture to this problem. This problem in fact looks like the one of finding and approximation of a metric on R^n.\nSince A(x) is symmetric positive definite, I thought to rewrite it as A(x) = B(x)^TB(x) for an unknown matrix valued function B(x). Thus, the function f(x) rewrites in a much simpler way: f(x) = |B(x)x|^2, where the only unknown is the matrix function B(x).\nNow, is there some known architecture which is well suited for this context?\nGenerating the training data with B(x) constant, I have solved the problem very easily defining a weight to be optimized and it works very well. However if the matrix B(x) is x-dependent I am not completely sure on how to proceed.\nUp to now I have implemented a NN which goes from R^n to R^{n^2}, where the output is reshaped into the nxn matrix B(x) to learn. However, this works well just for simple B(x)s and to me it is still not clear why.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":40,"Q_Id":67740146,"Users Score":0,"Answer":"You can write the expression f(x) = |B(x)x|^2 in tensorflow and solve for B via standard gradient descent minimization. Tensorflow can minimize anything you can write in tensorflow.","Q_Score":0,"Tags":"python,neural-network,regression,non-linear-regression","A_Id":67740584,"CreationDate":"2021-05-28T13:51:00.000","Title":"Learn the matrix function of a sort of bilinear form (Neural Networks)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to split one dataframe into two different data frames based on one of the columns value\nEg: df(parents dataframe)\ndf has a column MODE with values swiggy , zomato\ndf1 with all the columns which has common with MODE = swiggy\ndf2 with all the columns which has common with MODE= Zomato\nI know its simple, I am beginner, Please help. Thanks.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":24,"Q_Id":67742324,"Users Score":1,"Answer":"df1 = df[df['MODE'] == 'swiggy'] and df2 = df[df['MODE'] == 'Zomato'].\nThis way, you will be filtering the dataframe based on the MODE column and assigning the resulting dataframe to new variables.","Q_Score":0,"Tags":"python,pandas,dataframe","A_Id":67742366,"CreationDate":"2021-05-28T16:15:00.000","Title":"Make two different dataframes using parent dataframe","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Would we use char, signed char, unsigned char or import some header for a byte type?\nMy code is going to be seen\/used by other C developers and I want to use whatever standard they're most likely used to seeing.\nAlso, I may be allocating memory for this function from python as a numpy array and calling it through ctypes. Is there a preferred way to allocate a byte array in numpy?\nIs np.zeros(size, dtype=np.byte) the normal way, if the corresponding C type is char, for example?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":97,"Q_Id":67746138,"Users Score":0,"Answer":"The most common way is using a char array.\nHowever, it really depends on the needs of the code.","Q_Score":0,"Tags":"python,arrays,c,ctypes","A_Id":67748224,"CreationDate":"2021-05-28T22:40:00.000","Title":"What is the most common way to represent a byte array in C?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":1,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have been trying to feed a dataset of brain MRI images (IXI dataset) to a ConvNet, however, some of the images have 140 channels some others 150 channels. How can I make all the images have the same number of channels so that I won't run into trouble with a fixed CNN input shape? I am using nibabel lib for reading the .nii files.\nEDIT:\nI don't have much knowledge about MRI images, what channels should be discarded?","AnswerCount":2,"Available Count":2,"Score":0.0996679946,"is_accepted":false,"ViewCount":91,"Q_Id":67748053,"Users Score":1,"Answer":"I assume by \"channels\" you mean number of slices, am I right? Then another approach is to duplicate some of the images to make all of them have 150 channels. If you think about data augmentation, duplicating (and probably make minor alterations) might be a good idea. Of course, depends on the actual content of your images, this may or may not be applicable.","Q_Score":3,"Tags":"python,neural-network,conv-neural-network,medical-imaging,neuro-image","A_Id":67825014,"CreationDate":"2021-05-29T05:28:00.000","Title":"How can I reduce the number of channels in an MRI (.nii format) image?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have been trying to feed a dataset of brain MRI images (IXI dataset) to a ConvNet, however, some of the images have 140 channels some others 150 channels. How can I make all the images have the same number of channels so that I won't run into trouble with a fixed CNN input shape? I am using nibabel lib for reading the .nii files.\nEDIT:\nI don't have much knowledge about MRI images, what channels should be discarded?","AnswerCount":2,"Available Count":2,"Score":1.2,"is_accepted":true,"ViewCount":91,"Q_Id":67748053,"Users Score":1,"Answer":"The obvious approach is definitely:\n\nFind the minimum number of channels in the sample.\n\nDiscard all the other channels for any sample.\nNow, the discarding can happen from the middle of the slice which will probably contain better details. But this is based on the specific domain.\n\n\nOr, 2. you can select a mean from the number of channels. and try to discard for the images with higher number of channels and add a black slice for images with lower number of channels.","Q_Score":3,"Tags":"python,neural-network,conv-neural-network,medical-imaging,neuro-image","A_Id":67748223,"CreationDate":"2021-05-29T05:28:00.000","Title":"How can I reduce the number of channels in an MRI (.nii format) image?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I would like to know how to do the average, standard deviation and mode statistics of an NxN matrix.\nCan anybody suggest how to do this in python?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":59,"Q_Id":67757234,"Users Score":0,"Answer":"As pointed out in a comment, this is easily found by a search.\nThe scipy library offers functions for all of these, either for the whole array or for specified axes. scipy.stats.describe will give the mean and variance all at once, and standard deviation is easily computed from variance. For mode use scipy.stats.mode\nAlternatively for mean and standard deviation, there are numpy.mean and numpy.std respectively.","Q_Score":0,"Tags":"python,matrix,statistics,mean,standard-deviation","A_Id":67757331,"CreationDate":"2021-05-30T02:44:00.000","Title":"How to make the mean, standard deviation and mode statistics of an NxN matrix","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"The effect of the class weights parameter internally in the algorithm","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":37,"Q_Id":67789044,"Users Score":0,"Answer":"When working with RandomForestClassifier, impurity (Gini or Entropy) is used to measure how mixed the groups of samples are given a split within your tree. This calculation can be biased as it depends on the distribution of your y variable.\nIf your y distribution is unbalanced, the impurity measurements will be biased as well. Therefore, to counter that effect, you can use the class_weight parameter to adjust those measurements so that the majority class is not favored.","Q_Score":0,"Tags":"python,scikit-learn,random-forest","A_Id":67791801,"CreationDate":"2021-06-01T12:40:00.000","Title":"How does the class weight parameter work in sklearn RandomForestClassifier?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have this 3D-list:\narray = [[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]]\nWhen I want to print a specific element, for example with:\nprint(array[1][1][1])\nI would get h.\nBut as soon as I want to pop this element with array.pop([1][1][1]), I just get an IndexError: IndexError: list index out of range","AnswerCount":3,"Available Count":1,"Score":0.1325487884,"is_accepted":false,"ViewCount":75,"Q_Id":67790974,"Users Score":2,"Answer":"You want to use array[1][1].pop(1). pop only takes one argument, the position of the element to pop. The reason why your code was crashing is because you had [1], a one element list, and tried to access the second element with [1][1].","Q_Score":1,"Tags":"python,list","A_Id":67791051,"CreationDate":"2021-06-01T14:42:00.000","Title":"How do I pop an element in an 3D-list?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"When I try to calculate something like 599! in Matlab, the answer is inf and not useful, but I am able to do that fine in python in google collab. Even when I try using stirling approximation for these large factorials I still get inf as an answer and I can't do anything with that (I'm trying to calculate multiplicity).\nWhy is it this way, especially since google collab isn't even on my computer its in the cloud or whatever. Can someone explain how this is possible?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":48,"Q_Id":67813171,"Users Score":1,"Answer":"Very simply, MATLAB has a hard limit on the size of integers and floats, and returns inf when you pass that value. Python implements a long-integer mode, an unlimited digital mode for computation. When you pass the \"normal\" 64-bit limit, Python converts to that long integer mode and continues operation -- at a very reduced speed.","Q_Score":0,"Tags":"python,matlab","A_Id":67813196,"CreationDate":"2021-06-02T22:12:00.000","Title":"Factorials in Matlab vs Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":1,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I currently have a data set where im trying to group up rows based on a column and sum the columns where the values are integers.\nHowever, the catch is I would like to create a new row once the sum has reached a certain threshhold\nFor example, in the below dataframe, I am trying to group the rows based on company name and sum up the weights, however, I do not want weight to exceed 100.\nInput dataframe:\n\n\n\n\nCompany\nWeight\n\n\n\n\na\n30\n\n\nb\n45\n\n\na\n27\n\n\na\n40\n\n\nb\n57\n\n\na\n57\n\n\nb\n32\n\n\n\n\nOutput dataframe:\n\n\n\n\nCompany\nWeight\n\n\n\n\na\n97\n\n\na\n57\n\n\nb\n89\n\n\nb\n45\n\n\n\n\nI have tried using group by and sum, however, it cannot detect whether or not I have reached a maximum amount.\nIs there any way I can achieve this?\nAny help would be greatly appreciated!","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":576,"Q_Id":67815908,"Users Score":1,"Answer":"well, it depends, you're asking an NP problem currently unless you don't want the optimum weight in under 100, there are a few algoritems you can do,\nbut none are o(n) which is what group by and the sum does, lets say you iterate with iterrows() (try to avoid that), would you be able to do so in one iteration? if you are not looking for an optimum solution (closest to 100 each match) there is an option.\nfor every company, you have to sort it by increasing values.\nusing iteration to open a new row every time sum is reaching a 100, at a side variable, and replacing the origin at the end\nThere isn't a pandas \/ Numpy standard solution that I know of.","Q_Score":5,"Tags":"python,pandas,pandas-groupby","A_Id":67816783,"CreationDate":"2021-06-03T05:36:00.000","Title":"Pandas group by and sum, but create a new row when a certain amount is exceeded","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've been tasked to do an ETL job to get JSON data out of Elasticsearch into an Azure Blob. I've set up a batch job for current indexes using elasticsearch-py's search, search_after and pit for active Indices. We are running on ES 7x but up until recently, we've been running on ES 5x and stored a snapshot of all indices before deleting them from the cluster. I need to get the historical data and have access to the S3 bucket where the team stored the snapshots.\nThe question is: Without having to set up a separate 5x cluster, restoring the snapshots and running the batch extract from there, is there an efficient method (maybe a python package) that will allow me to read the indices stored on the S3 bucket and extract the data directly?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":54,"Q_Id":67821484,"Users Score":0,"Answer":"Closing this question as the answer is NO (at this time). I've just restored all snapshots on separate VM's and pulled the data out.","Q_Score":0,"Tags":"python,elasticsearch,elasticsearch-py","A_Id":72459564,"CreationDate":"2021-06-03T12:26:00.000","Title":"How to read snapshots in python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a pd.DataFrame created by parsing a large number of excel spreadsheets (too many to reformat them manually) and one of my columns should contain only numbers but in this case also contains some reference information at the end in the form of strings.\nEx: df['column1'] = [\"12\", \"83\", \"1\", \"Metric\", \"40 Day Metric\"]\nI want to drop all of the columns that contain non-numeric values (in this case metric and 40 day metric). I tried ascii comparison:\ndf.drop(df[df['column1'] > \":\"].index, inplace=True)\nThis gets rid of \"Metric\" but not \"40 Day Metric\" because it starts with a number. My next thought was to try to sort based on length (none of the numbers are more than 2 digits) but I got the error that series didn't have a length attribute.\nAny suggestions?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":47,"Q_Id":67829550,"Users Score":0,"Answer":"Find the unique values of the column. Assign them to a list, then drop them off of a copy and work with that data frame. I'm new to this so I hope this helps.\ndrop_columns = ['metric', '40 day metric', 'etc']\ndf_copy.drop(drop_columns, axis=1)","Q_Score":0,"Tags":"python,pandas","A_Id":67829737,"CreationDate":"2021-06-03T22:53:00.000","Title":"drop rows from pandas not containing ONLY a number","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am loading an .xlsx file into a dataframe. When I run the program from Pycharm or Jupyter notebook, it runs without any problems.\ndf = pd.read_excel(file_name)\nBut, when I create an executable file through Pyinstaller, the program hangs soon after I run pd.read_excel(file) command. I tried to read the file as .csv (after converting the excel to csv) as well and faced the same problem.\nFollowing is the pyinstaller command I am using:\npyinstaller --onefile --noconsole --icon=icon.ico main.py\nLet me know if anyone could help!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":147,"Q_Id":67834744,"Users Score":0,"Answer":"I figured out the issue. The xlrd library need to be installed from command prompt for python interpreter. I am sure this will help others who may face similar issue!","Q_Score":0,"Tags":"python,pandas,dataframe","A_Id":67848900,"CreationDate":"2021-06-04T09:22:00.000","Title":"pd.read_excel hangs when I run from executable program","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"My problem is that when I use google collab to display graphs they are much bigger, but recently I have switched from google collab to vs code jupyter notebook but when I try to display a graph is much smaller. Is there a way to change the graph size on vs code jupyter notebook. BTW I am using plotly.","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":2656,"Q_Id":67837572,"Users Score":0,"Answer":"You can use props width=[int], height=[int] after x, y params of the graph. If omit width the graph will fill whole cells width. Tested on VSC 1.63.2","Q_Score":1,"Tags":"python,visual-studio-code,jupyter-notebook,jupyter","A_Id":70495442,"CreationDate":"2021-06-04T12:52:00.000","Title":"How to change size of VS Code jupyter notebook graphs?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a 10x10 numpy matrix and I have a list containing indices of elements I want to query.\nmatrix = np.zeros((10, 10), dtype=int)\nindices = [[2,3], [3,4]]\nthe issue I'm facing is, what I actually want is the element matrix[2,3] but matrix[indices[0]] gives a different output because the latter actually means matrix[[2,3]]. the output is 2 different rows.\nHow do I get around this problem?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":19,"Q_Id":67852096,"Users Score":1,"Answer":"I ended up finding a solution.\nstoring the indices as tuples inside of a list works\nindices = [(2,3), (3,4)] and then matrix[indices[0]] gives the desired output","Q_Score":0,"Tags":"python,numpy","A_Id":67852182,"CreationDate":"2021-06-05T17:15:00.000","Title":"accessing an element in a numpy matrix using a list (python)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have two tables as below\nTable 1: AllTablesInDatabase\nTable 2: RequiredTablesInDatabase\nNow, i want to drop all the table at a time which is not matching between these two tables using python or scala.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":266,"Q_Id":67870222,"Users Score":0,"Answer":"Iterate through you AllTablesInDatabase as a list and issue a drop table statement if it doesn't exist in your RequiredTablesInDatabase list","Q_Score":0,"Tags":"python,azure-databricks","A_Id":67889202,"CreationDate":"2021-06-07T10:47:00.000","Title":"DROP multiple tables at once in Azure Databricks","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am new to databricks and sql and want to add some data there.\nI am using python notebook in azure databricks. I have created a very big empty delta table. Columns here:\nId| A| B| C| D| E| F| G| H| I| J| K (A,B,C.... are column names)\nI will parse log files as they will appear them in blob and create dataframes. The dataframes could like this.\nDF1\nA| B| C| D| (A,B,C.... are column names)\nDF2\nA| B| D| E| (A,B,C.... are column names)\nDF3\nA| B| D| F| (A,B,C.... are column names)\nI want to insert all of these data frames in the delta table. In addition I will also need to add Id(log_file_id). Is there a way to insert data in this manner to the tables?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":121,"Q_Id":67871278,"Users Score":0,"Answer":"Create an empty dataframe having all the columns let say X. Then you can concatenate all the other dataframes into X. Then save X directly.","Q_Score":0,"Tags":"python,pandas,azure,databricks","A_Id":67879315,"CreationDate":"2021-06-07T12:02:00.000","Title":"databricks: Add a column and insert rest of the data in a table","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":1,"Web Development":0},{"Question":"I am trying to install the hdf5 library from Homebrew. Running brew install hdf5 in the terminal returns the following error message:\n\n==> Searching for similarly named formulae...\nError: No similarly named formulae found.\nError: No available formula or cask with the name \"hdf5\".\n==> Searching for a previously deleted formula (in the last month)...\nError: No previously deleted formula found.\n==> Searching taps on GitHub...\nError: No formulae found in taps.\n\nI am running this on a mac with Mojave version 10.14.6. What next steps should I try to download the hdf5 library?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":803,"Q_Id":67876124,"Users Score":1,"Answer":"It seems that at least part of my Homebrew download was in the wrong location. Running brew doctor, I got Warning: Homebrew\/homebrew-core was not tapped properly!. This was fixed by running rm -rf \"\/usr\/local\/Homebrew\/Library\/Taps\/homebrew\/homebrew-core\" and then brew tap homebrew\/core.","Q_Score":0,"Tags":"python,homebrew,hdf5","A_Id":67879103,"CreationDate":"2021-06-07T17:22:00.000","Title":"Unable to install hdf5 library from homebrew","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":1,"Web Development":0},{"Question":"I have a dataset of postal codes for each store and nearby postal codes for each. It looks like the following:\n\n\n\n\nPostalCode\nnearPC\nTravel Time\n\n\n\n\nL2L 3J9\n[N1K 0A1', 'N1K 0A2', 'N1K 0A3', 'N1K 0A4', '...\n[nan,nan,9,5,nan...]\n\n\n\n\nI know I can explode the data but that would result in tons more rows ~40M. Another preprocessing step I can perform is to remove the values in each list where the travel time is not available. However, then I would need to remove it from the nearPC list.\nIs there a way to incorporate networkx to create this graph? I've tried using\nG = nx.from_pandas_edgelist(df,'near_PC','PostalCode',['TravelTime'])\nbut I don't think it allows lists as the source or targets.\nTypeError: unhashable type: 'list'\nIs there a way around this? If not how can I remove the same indices of a list per row based on a conditional in an efficient way?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":37,"Q_Id":67876969,"Users Score":0,"Answer":"You've identified your problem, although you may not realize it. You have a graph with 40M edges, but you appropriately avoid the table explosion. You do have to code that explosion in some form, because your graph needs all 40M edges.\nFor what little trouble it might save you, I suggest that you write a simple generator expression for the edges: take one node from PostalCode, iterating through the nearPC list for the other node. Let Python and NetworkX worry about the in-line expansion.\nYou switch the nx build method you call, depending on the format you generate. You do slow down the processing somewhat, but the explosion details get hidden in the language syntax. Also, if there is any built-in parallelization between that generator and the nx method, you'll get that advantage implicitly.","Q_Score":0,"Tags":"python,pandas,networkx","A_Id":67877145,"CreationDate":"2021-06-07T18:30:00.000","Title":"What is the best way to create a graph from a compact pandas dataframe?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"The given data frame 'customer' has a column 'Cust_id' which has values Cust_1, Cust_2 and so on.\nRemove the repeated 'Cust_' from the column Cust_id so that the output column Cust_id have just numbers like 1, 2, 3 and so on.\ne.g. Column Heading is \"Customer Info\"\nCUSTOMET INFO\nCust_1\nCust_2\nCust_3\n*\n*\n*\n*\nCust_100\nDesired Output is:\nCUSTOMET INFO\n1\n2\n3\n4\n*\n*\n*\n*\n100","AnswerCount":4,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":395,"Q_Id":67882771,"Users Score":0,"Answer":"Cust_id = customer['Cust_id']\nl = [x[5:] for x in Cust_id]\ncustomer['Cust_id'] = l\ncustomer","Q_Score":0,"Tags":"python-3.x","A_Id":70821302,"CreationDate":"2021-06-08T06:56:00.000","Title":"How to remove common letters from elements of same column","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I can manually access some Quicksight dashboards and hit \"export to CSV\", but I want to automate that task (as it is the first of many steps to updating some reports). Can this be done automatically using Python?\nNote: I did not create the dashboards in Quicksight, I just have privileges to see them.","AnswerCount":1,"Available Count":1,"Score":-0.537049567,"is_accepted":false,"ViewCount":199,"Q_Id":67894175,"Users Score":-3,"Answer":"Since you approach datasets stored in a different locations (quicksight is injected with them, from S3, Athena tables etc., exporting from quicksight is not the way. if you'll know location of dataset\/datasource, go there. for example, S3 to csv","Q_Score":0,"Tags":"python,boto3,amazon-quicksight","A_Id":69614246,"CreationDate":"2021-06-08T20:28:00.000","Title":"Extracting CSV from Quicksight dashboard using Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to create a function that will accept a dataframe and will parse that dataframe into a sql server table. I am stuck as to what needs go in the select statement below the insert query.\ndf- dataframe\ndesttable - destination table that needs to be parsed.\ntablecols - An array of the table columns for the table\n\n # Insert DataFrame to Table\n def InsertintoDb(self, df, desttable, tablecols):\n tablecolnames = ','.join(tablecols)\n qmark = ['?' for s in tablecols]\n allqmarks = ','.join(qmark)\n #rowappendcolname = ','.join(['row.' + s for s in tablecols])\n for index, row in df.iterrows():\n cursor.execute(\n '''INSERT INTO [Py_Test].[dbo].''' + desttable + ''' ( ''' + tablecolnames + ''')VALUES (''' + allqmarks + ''')''',\n )\n self.conn.commit()\n\n Any help is much appreciated.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":61,"Q_Id":67896137,"Users Score":0,"Answer":"As suggested by the gentleman in the comment, I was able to do it using df.to_sql . Here is the working code -\n\nclass DbOps:\n def __init__(self):\n self.username = ''\n self.password = ''\n self.ipaddress = 'localhost'\n # self.port = 5439\n self.dbname = ''\n\n # A long string that contains the necessary Postgres login information\n self.engine = sqlalchemy.create_engine(\n f\"mssql+pyodbc:\/\/{self.username}:%s@{self.ipaddress}\/{self.dbname}?driver=SQL+Server+Native+Client+11.0\" % urlquote(f'\n {self.password }'))\n\n def InsertintoDb(self, df, desttable, tablecols):\n df.to_sql(desttable, self.engine, index=False, if_exists='append')","Q_Score":0,"Tags":"python-3.x,pandas,dataframe,pyodbc","A_Id":67906973,"CreationDate":"2021-06-09T00:50:00.000","Title":"Function to parse a dataframe into a SQL table","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"So here is my first question here. I am preparing a dataset for object detection. I have done the following things so far:\n\nI have an original picture (size w4000 x h3000).\nI used the annotation platform Roboflow to annotate it in COCO format, with close to 250 objects in the picture.\nRoboflow returned a downscaled picture (2048x1536) with a respective json file with the annotations in COCO format.\nThen, to obtain a dataset from my original picture (as I have a lot of objects and the picture is big enough), I decided to tile the original picture in patches of 224x224. For this purpose, I upscaled a bit (4032x3136) to be able to slice it properly, obtaining 252 pictures.\n\nQUESTIONS\n\nHow can I resize the bounding boxes of the Roboflow 2048x1536 picture to my original picture (4032x3136)?\n\nOnce the b.boxes are resized to my original size picture, how can I resize them again, adapting the size to each of my patches (224x224) created by slicing the original picture?\n\n\nThank you!!","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":775,"Q_Id":67900731,"Users Score":1,"Answer":"It sounds like the ultimate goal is to have tiled 224x224 images from the source 4032x3136 images with bounding boxes correctly updated.\nIn Roboflow, at least, you can add tiling as a preprocessing step to your original 4032x3136 images. The images will be broken into the number of tiles you select (2x2, 3x3, NxY). The bounding boxes will be correctly updated to cover the objects across each individual tile as well.\nTo reimplement in code from what you've described, you would need to:\n\nUpscale your 2048x1536 images to 4032x3136\nScale the bounding boxes accordingly\nBreak the images into 224x224 tiles using something like Pil\nUpdate the annotations to be broken into the coordinates on the respective tiles; one annotation per tile","Q_Score":0,"Tags":"python,object-detection,bounding-box,coco,roboflow","A_Id":67903682,"CreationDate":"2021-06-09T08:52:00.000","Title":"Resize COCO bounding boxes for object detection","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":1,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a list = [D1, D2, D3, ...] where each DX is a 2d Array of simmilar dimensions (let's say 4x5). I now want to average the DX. So my result 2d Array should for example be:\n result[0,0] = (D1[0,0] + D2[0,0] + ...) \/ len(list)\n result[0,1] = (D1[0,1] + D2[0,1] + ...) \/ len(list)\netc.\nIs there a neat function for this? I somehow can't find the correct terms for googeling this..","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":74,"Q_Id":67900753,"Users Score":0,"Answer":"You should try to use numpy.mean() . Probably you can create the same list with numpy, and then calculate the mean for axis=None, and you can get the average of the whole list of matrices.","Q_Score":3,"Tags":"python","A_Id":67900933,"CreationDate":"2021-06-09T08:53:00.000","Title":"average across list of 2d arrays [python]","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"May I know how to merge 2 excel into 1 like this in python.\nI've tried Pandas to merge it by \"name\" and keep the sequence \"index\", but no luck. as there are more than 1 location. so, the result should have 2or more location in row.\nMany thanks\n\n\n\n\nindex\nname\nprice\n\n\n\n\n1\napple\n2\n\n\n2\norange\n3\n\n\n3\ngrape\n7\n\n\n4\nbanana\n1\n\n\n5\nkiwi\n2.5\n\n\n6\nlemon\n1\n\n\n\n\n\n\n\nindex\nname\nlocation\n\n\n\n\n1\napple\nUS\n\n\n2\napple\nUK\n\n\n3\nbanana\nColumbia\n\n\n4\nbanana\nCosta Rica\n\n\n5\nkiwi\nItaly\n\n\n6\nlemon\nUS\n\n\n\n\n\n\n\nindex\nname\nprice\nlocation_1\nlocation_2\n\n\n\n\n1\napple\n2\nUS\nUK\n\n\n2\norange\n3\nN\/A\nN\/A\n\n\n3\ngrape\n7\nN\/A\nN\/A\n\n\n4\nbanana\n1\nColumbia\nCosta Rica\n\n\n5\nkiwi\n2.5\nItaly\n\n\n\n6\nlemon\n1\nUS","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":26,"Q_Id":67901251,"Users Score":0,"Answer":"you can try pd.concat to combine them.","Q_Score":0,"Tags":"python,excel","A_Id":67901292,"CreationDate":"2021-06-09T09:23:00.000","Title":"Python Merge 2 excel table in row, with not unique key","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"When checking the installed pytorch version you can do that in two ways:\n\npip3 show torch (or similar python3 -m pip freeze for all packages)\nimport torch; torch.__version__\n\nInterestingly the first option (using pip3) returns 1.8.1+cu111, while the second option (torch.__version__) returns 1.7.1 (without the cuda version support string, but cuda is available).\nWhy do these two methods show different results and which one is the \"valid\" one?\nImportant\nWhen I installed pytorch with cuda support I installed the latest version, but downgraded a few weeks ago for different reasons.\nSome info:\n\nOS: ubuntu\npython installed natively (not in conda, also not using jupyter)","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":481,"Q_Id":67903040,"Users Score":1,"Answer":"This typically happens when you have multiple versions of the same library installed for some reason (normally mixing conda install and pip install in my experience). I recommend uninstalling oldest versions using the appropriate package manager until you see the expected behavior.","Q_Score":0,"Tags":"python,pip,pytorch","A_Id":67903300,"CreationDate":"2021-06-09T11:12:00.000","Title":"pytorch different versions with \"pip3 show torch\" VS \"torch.__version__\"","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"----> 6 from mrcnn.model import MaskRCNN\n\/usr\/local\/lib\/python3.7\/dist-packages\/mrcnn\/model.py in ()\n253\n254\n--> 255 class ProposalLayer(KE.Layer):\n256 \"\"\"Receives anchor scores and selects a subset to pass as proposals\n257 to the second stage. Filtering is done based on anchor scores and\nAttributeError: module 'keras.engine' has no attribute 'Layer'","AnswerCount":8,"Available Count":1,"Score":0.024994793,"is_accepted":false,"ViewCount":30657,"Q_Id":67905185,"Users Score":1,"Answer":"You should write keras.layers\ninstead keras.engine at import section in model.py file","Q_Score":12,"Tags":"python,machine-learning,keras,conv-neural-network,artificial-intelligence","A_Id":72203343,"CreationDate":"2021-06-09T13:32:00.000","Title":"module 'keras.engine' has no attribute 'Layer'","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I used a spacy blank model with Gensim custom word vectors. Then I trained the model to get the pipeline in the respective order-\nentityruler1, ner1, entity ruler2, ner2\nAfter training it, I saved it in a folder through\nnlp.to_disk('path to folder')\nHowever, if I try to load the same model using\nnlp1 = spacy.load('path to folder')\nIt gives me this error-\nValueError: [E109] Model for component 'ner' not initialized. Did you forget to load a model, or forget to call begin_training()?\nI cannot find any solution online. What might be the reason I am getting this? How do I successfully load and use my pretrained model?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":59,"Q_Id":67915131,"Users Score":0,"Answer":"Upgrading to spacy version 2.3.7 resolved this error. :)","Q_Score":1,"Tags":"python,machine-learning,nlp,spacy,named-entity-recognition","A_Id":68175725,"CreationDate":"2021-06-10T05:14:00.000","Title":"Spacy error in loading pretrained custom model with entity rulers and ner pipeline","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am creating a Pandas Profiling Report. Under \"Variable\" detailed information of each column is displayed. When I press \"Toggle details\" and navigate to \"categories\" the most common values appear ending with \"Other values\" which are about 50% in my dataset. Is there a possibility to print all values in that report, so the other values are not combined?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":230,"Q_Id":67922542,"Users Score":1,"Answer":"Set the amount of displayed rows (in this example 250):\nprofile = ProfileReport(df, n_freq_table_max=250)","Q_Score":1,"Tags":"python,pandas,dataframe,pandas-profiling","A_Id":67935246,"CreationDate":"2021-06-10T13:50:00.000","Title":"Show \"Other Values\" in Pandas Profiling Report","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using the google's ortools library in python to find an optimal path between a set of points. The set of points is broken up into subsets. For example, set A may contain 10 points, set B contains 6 points, set C contains 48 points. The sets of points must be visited in order, i.e. all points in A must be visited before moving to the points in set B, and all points in B must be visited before the points in C. I have a working solution by running the algorithm on set A, noting the end location (which is arbitrarily chosen by using a dummy node and setting the distance to this node from any point to zero). Then starting from the last point in A and using it as the start for B.\nIs there a way I can allow the algorithm to optimize for all of the sets and apply the order constraints?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":115,"Q_Id":67930329,"Users Score":0,"Answer":"Just forbid any arc B->A, C->B or C->A.\nYou can do it by returning a value greater than the vehicle capacity OR by directly removing the nodes from the NextVar() list. routing.NextVar(index).RemoveValues([...])","Q_Score":1,"Tags":"python,algorithm,or-tools,traveling-salesman,vehicle-routing","A_Id":67934502,"CreationDate":"2021-06-11T01:45:00.000","Title":"google ortools traveling salesman visit in ordered sets","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to read an excel csv file, and after researching, I realized I need to import pandas as pd. Is there a way to install it into the visual studio code? I have tried typing import pandas as pd, but it shows a red line. I'm still new to python.\nThank you","AnswerCount":5,"Available Count":2,"Score":0.0798297691,"is_accepted":false,"ViewCount":28684,"Q_Id":67946868,"Users Score":2,"Answer":"I think the above answers are very well put already.\njust to add to that.\nWindows:\n1.open cmd\n2.type python -m pip install pandas\n3.restart your visual studio code\nLinux or macOS:\n1.open terminal\n2.type pip install pandas\n3.restart your visual studio code","Q_Score":3,"Tags":"python,visual-studio-code","A_Id":67947394,"CreationDate":"2021-06-12T08:06:00.000","Title":"How do I install pandas into visual studios code?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to read an excel csv file, and after researching, I realized I need to import pandas as pd. Is there a way to install it into the visual studio code? I have tried typing import pandas as pd, but it shows a red line. I'm still new to python.\nThank you","AnswerCount":5,"Available Count":2,"Score":0.1194272985,"is_accepted":false,"ViewCount":28684,"Q_Id":67946868,"Users Score":3,"Answer":"you can install using pip \npip install pandas","Q_Score":3,"Tags":"python,visual-studio-code","A_Id":67946914,"CreationDate":"2021-06-12T08:06:00.000","Title":"How do I install pandas into visual studios code?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've been trying to save the state_dict of a Pytorch model with \ntorch.save(agent.qnetwork_local.state_dict(), filename) where filename = datetime.now().strftime('%d-%m-%y-%H:%M_dqnweights.pth')\ntype(filename) returns str which shouldn't be a problem with torch.save() and it should output a non-empty file. Instead I get an empty file with just the date and time and nothing after that. Putting the date and in the middle of the filename results in an empty file with everything after the date and time cut off.\ntorch.save(agent.qnetwork_local.state_dict(), 'checkpoint1.pth') and any time I hardcode the string works and gives me the expected non-empty file.\nWhat is going on and how do I fix this?\nI am running this code in a Python v3.6.8 virtualenv with Pytorch v1.8.1+cpu on Windows 10.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":354,"Q_Id":67958129,"Users Score":0,"Answer":"The colon was the problem in filename = datetime.now().strftime('%d-%m-%y-%H:%m_dqnweights.pth') since it was running on windows.\nChanging it to filename = datetime.now().strftime('%d-%m-%y-%H_%M_dqnweights.pth') works as expected.","Q_Score":0,"Tags":"python,pytorch,state-dict","A_Id":68005440,"CreationDate":"2021-06-13T12:14:00.000","Title":"Save Pytorch model state_dict with datetime in filename","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to train Mask-RCNN model on custom dataset. But, after few seconds my program stops with \"exit code 137 (interrupted by signal 9 sigkill)\" error.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":61,"Q_Id":67971715,"Users Score":0,"Answer":"This error occur when our model is using excessive memory. Setting small batch size will help.","Q_Score":0,"Tags":"python-3.x,tensorflow,deep-learning,object-detection","A_Id":67972060,"CreationDate":"2021-06-14T14:04:00.000","Title":"Sigkill error: training Mask RCNN model on custom dataset","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm using train_test_split to split image data for a convolutional neural network in Python:\nx_train, x_test, y_train, y_test = train_test_split(X, Y)\nFor each image in X, how can I figure out whether it was sent to the x_train or x_test set? Since all the data in the x_train or x_test datasets are in tensor form and randomized, I'm not sure how to relate a given instance in x_train\/x_test back to its original place in X. My confusion matrix is printing inconsistent information, so I'm trying to figure out if the way the data is split being training and testing is the reason.\nEdit 1: Folder Structure\nAll the images are in one array (X = np.array(X_images)) which I derived from collecting image from folders such that:\nData\n\nClass_1\nClass_2\n...\nClass_n\n\nI then used: Y = np_utils.to_categorical(labels, num_classes) to get the Y values","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":53,"Q_Id":67972398,"Users Score":0,"Answer":"The following solved my problem. I created a numpy array from the original image data:\nindices = np.arange(X.shape[0])\nFed this into the train_test_split function call and added two more that created an index corresponding to the image's respective X index:\nx_train, x_test, y_train, y_test, x_train_ind, x_test_ind = train_test_split(X, Y, indices, test_size=0.2, random_state=2)\nAfter getting the index of an image in the x_train dataset, we can plug that into x_train_ind to get the index in the original X dataset","Q_Score":0,"Tags":"python,numpy","A_Id":67974691,"CreationDate":"2021-06-14T14:44:00.000","Title":"How to determine if data point was placed in training or testing set?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I know that TextBlob ignore the words that it doesn\u2019t know, and it will consider words and phrases that it can assign polarity to and averages to get the final score.\nAre there any other problems and defects that I don't know about?\nAlso, I would like to know how it is possible to fix them.\nConsidering that we can use TextBlob both with a dictionary and through machine learning, I think a solution could be to use a larger dictionary and improve the train set.\nAre my intuitions right?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":191,"Q_Id":67977030,"Users Score":0,"Answer":"Most of the Challenges in NLP sentiment analysis tasks are semantic ones like Irony and sarcasm ambiguity in th text,Multipolarity...\nThay why TextBlob may not yield the best resulat depending on your text and if it contains multiples languges , you can add new models or languages through extensions .","Q_Score":0,"Tags":"python,sentiment-analysis,textblob","A_Id":67977101,"CreationDate":"2021-06-14T20:48:00.000","Title":"What are the cons and potenzial problems of using TextBlob to perform sentiment analysis? How could they be solved?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a dataset with a large number of predictive variables and I want to use them to predict a number of output variables. However, some of the things I want to predict are categorical, and others are continuous; the things I want to predict are not independent. Is it possible with scikit-learn to, for example, mix a classifier and a regressor so that I can predict and disentangle these variables? (I'm currently looking at gradient boosting classifiers\/regressors, but there may be better options.)","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":603,"Q_Id":67977797,"Users Score":0,"Answer":"I don't think there's a builtin way. There are ClassifierChain and RegressorChain that allow you to use earlier predictions as features in later predictions, but as the names indicate they assume either classification or regression. Two options come to mind:\n\nManually patch those together for what you want to do. For example, use a ClassifierChain to predict each of your categorical targets using just the independent features, then add those predictions to the dataset before training a RegressorChain with the numeric targets.\n\nUse those classes as a base for defining a custom estimator. In that case you'll probably look mostly at their common parent class _BaseChain. Unfortunately that also uses a single estimator attribute, whereas you'd need (at least) two, one classifier and one regressor.","Q_Score":1,"Tags":"python,machine-learning,scikit-learn","A_Id":67988521,"CreationDate":"2021-06-14T22:11:00.000","Title":"How can you predict a combination of categorical and continuous variables with Scikit learn?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am new to deep learning, and I am trying to train a ResNet50 model to classify 3 different surgical tools. The problem is that every article I read tells me that I need to use 224 X 224 images to train ResNet, but the images I have are of size 512 X 288.\nSo my questions are:\n\nIs it possible to use 512 X 288 images to train ResNet without cropping the images? I do not want to crop the image because the tools are positioned rather randomly inside the image, and I think cropping the image will cut off part of the tools as well.\n\nFor the training and test set images, do I need to draw a rectangle around the object I want to classify?\n\nIs it okay if multiple different objects are in one image? The data set I am using often has multiple tools appearing in one image, and I wonder if I must only use images that only have one tool appearing at a time.\n\nIf I were to crop the images to fit one tool, will it be okay even if the sizes of the images vary?\n\n\nThank you.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":607,"Q_Id":67995015,"Users Score":2,"Answer":"Is it possible to use 512 X 288 images to train ResNet without cropping the images? I do not want to crop the image because the tools\nare positioned rather randomly inside the image, and I think cropping\nthe image will cut off part of the tools as well.\n\n\n\nYes you can train ResNet without cropping your images. you can resize them, or if that's not possible for some reason, you can alter the network, e.g. add a global pooling at the very end and account for the different input sizes. (you might need to change kernel sizes, or downsampling rate).\nIf your bigest issue here is that resnet requires 224x224 while your images are of size 512x228, the simplest solution would be to first resize them into 224x224. only if that`s not a possibility for you for some technical reasons, then create a fully convolutional network by adding a global pooling at the end.(I guess ResNet does have a GP at the end, in case it does not, you can add it.)\n\n\n\nFor the training and test set images, do I need to draw a rectangle around the object I want to classify?\n\n\n\nFor classification no, you do not. having a bounding box for an object is only needed if you want to do detection (that's when you want your model to also draw a rectangle around the objects of interest.)\n\n\n\nIs it okay if multiple different objects are in one image? The data set I am using often has multiple tools appearing in one image, and I\nwonder if I must only use images that only have one tool appearing at\na time.\n\n\n3.Its ok to have multiple different objects in one image, as long as they do not belong to different classes that you are training against. That is, if you are trying to classify apples vs oranges, its obvious that, an image can not contain both of them at the same time. but if for example it contains anything else, a screwdriver, key, person, cucumber, etc, its fine.\n\n\nIf I were to crop the images to fit one tool, will it be okay even if the sizes of the images vary?\n\n\nIt depends on your model. cropping and image size are two different things. you can crop an image of any size, and yet resize it to your desired dimensions. you usually want to have all images with the same size, as it makes your life easier, but its not a hard condition and based on your requirements you can have varying images, etc as well.","Q_Score":0,"Tags":"python,deep-learning,resnet,image-classification","A_Id":67996455,"CreationDate":"2021-06-16T00:45:00.000","Title":"What type of input does ResNet need?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm writing a python code and using pandas' read_csv and display functions, the code must have O(n) time complexity, when using these two functions, assuming the the rest of the code doesn't exceed this complexity, and with the fact that these two functions are not in any loop, is their complexity more than O(n) ?\nThank you","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":158,"Q_Id":68006152,"Users Score":0,"Answer":"They are both O(n), where n is the length of the input.","Q_Score":0,"Tags":"python,pandas,time-complexity","A_Id":68007069,"CreationDate":"2021-06-16T15:54:00.000","Title":"What is the time complexity of pandas' read_csv and display functions?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working on finding statistical outliers in weather-related data. More specifically, I have the temperature and the location(longitude and latitude)of 10000 data points where the temperature was recorded at a specific time. What would be the best method to locate geographical-weather-related outliers and visualize the data in a way where the outliers become dominantly visible. For the visualization part, a python tool would be most appreciated and the locating the outliers part an algorithm or technique would be most useful. (I am thinking of cluster)","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":31,"Q_Id":68029433,"Users Score":0,"Answer":"It really depends how you would use it. You do mention outliers, thus DBSCAN could be used (it essentially creates clusters, and points not in a cluster is considered an outlier).\nIf all you care about is which points are outliers, and not which points are clustered, you can use e.g Isolation Forrest","Q_Score":0,"Tags":"python,data-visualization,graph-data-science","A_Id":68029726,"CreationDate":"2021-06-18T04:43:00.000","Title":"Which Clustering algorithm and data visualization tool should I use to locate and visualize geographical weather data","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a 1 dimensional array. I want to get a certain percentile(say,5%) of the fitting of this data(Monte Carlo method is best, guassian KDE method is also OK) as fast as possible. Because this function is used millions of times.\nMy way is using the scipy gaussian_kde.\nMy question is:\n\nAny other ways to get higher speed of gaussian_kde?\nMain cost is kde = gaussian_kde(x, bw_method=0.02) #about 220us","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":143,"Q_Id":68029471,"Users Score":0,"Answer":"You seems to rewrite a well-optimized function of Numpy called np.quantile. Calling np.quantile(x, 0.05) provide the exact\/accurate 5% quantile and is 4 times faster than your optimized implementation! Note that if you need to call this functions a lot of time on different independent arrays, then you can speed up the computation even more thanks to Numba parallelism.","Q_Score":0,"Tags":"python,performance,numba,data-fitting,processing-efficiency","A_Id":68039465,"CreationDate":"2021-06-18T04:50:00.000","Title":"How to speed up data fitting and get percentile function","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am quite new to PySpark, I am trying to read and then save a CSV file using Azure Databricks.\nAfter saving the file I see many other files like \"_Committed\",\"_Started\",\"_Success\" and finally the CSV file with a totally different name.\nI have already checked using DataFrame repartition(1) and coalesce(1) but this only deals when the CSV file itself was partitioned by Spark. Is there anything that can be done using PySpark?","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":130,"Q_Id":68038622,"Users Score":0,"Answer":"You can do the following:\n\ndf.toPandas().to_csv(path\/to\/file.csv)\n\nIt will create a single file csv as you expect.","Q_Score":1,"Tags":"python,csv,pyspark","A_Id":68039876,"CreationDate":"2021-06-18T16:30:00.000","Title":"Save only the required CSV file using PySpark","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am quite new to PySpark, I am trying to read and then save a CSV file using Azure Databricks.\nAfter saving the file I see many other files like \"_Committed\",\"_Started\",\"_Success\" and finally the CSV file with a totally different name.\nI have already checked using DataFrame repartition(1) and coalesce(1) but this only deals when the CSV file itself was partitioned by Spark. Is there anything that can be done using PySpark?","AnswerCount":2,"Available Count":2,"Score":-0.0996679946,"is_accepted":false,"ViewCount":130,"Q_Id":68038622,"Users Score":-1,"Answer":"Those are default Log files created when saving from PySpark . We can't eliminate this.\nUsing coalesce(1) you can save in a single file without partition.","Q_Score":1,"Tags":"python,csv,pyspark","A_Id":68039116,"CreationDate":"2021-06-18T16:30:00.000","Title":"Save only the required CSV file using PySpark","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm quoting from the paper BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding,\n\"we simply mask some percentage of the input tokens at random, and then predict those masked tokens\".\nWhat exactly does it mean???\nIs it that the loss is calculated for masked token alone while ignoring predictions from rest of the tokens. If so what would be the right way to do this i.e. are we passing weights to the model to ignore prediction from tokens except \"MASK\". It will be helpful if someone can provide a link regarding same.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":157,"Q_Id":68043950,"Users Score":0,"Answer":"Is it that the loss is calculated for masked token alone while\nignoring predictions from rest of the tokens.\n\nThe quick answer \"YES\"\nSuppose given the following sentence:\n\"The red apple is my favourite fruit.\"\nI can mask the above sentence as:\n\"The red apple is my favourite [MASK].\"\nEssentially you are expecting the model to prediction [MASK] as \"fruit\".\nEach of the words above would be tokenized to its ids(more complicated than this actually), including the token [MASK], which has its special id = 103.\n\nare we passing weights to the model to ignore prediction from tokens except \"MASK\".\n\nYou don't have to pass weights, for BertForMaskLM, the model handle the masking for you as long as you provide the attention_mask array, indicating which are the token that is unmasked, thus not included in loss calculation. What it does is that it basically returns \"-100\" as the output, and when you compute loss = CrossEntropyLoss(prediction, groundTruth), PyTorch will ignore the elements that is \"-100\". You can adjust this behaviour by changing the default parameter:\nnn.CrossEntropyLoss(ignore_index=-100).","Q_Score":0,"Tags":"python,bert-language-model","A_Id":71792933,"CreationDate":"2021-06-19T05:34:00.000","Title":"How are we making prediction for masked tokens alone in BERT?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"In timeseries analysis I want to set date as an index but one date has 500 entries 50 for each item and 10 for each store. In such case how can I make date as an index.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":45,"Q_Id":68045820,"Users Score":0,"Answer":"How are you! First off, why do you need de time as index, maybe you can reconsider that idea?\nAnyway using datetime should work and the chances to get a duplicate record is minimal","Q_Score":0,"Tags":"python,time-series,data-science","A_Id":68046143,"CreationDate":"2021-06-19T10:18:00.000","Title":"How to make date as an index in timeseries analysis if I have duplicate dates for each item and store in dataset","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am calculating daily returns of a stock, as you can see in the first day (06\/01) there is no return, that is ok, but i want to replace that NaN for a 0, I tried the fillna() function but it does not work\nAttributes Adj Close Close High Low Open Volume\nSymbols nvda nvda nvda nvda nvda nvda\nDate\n2021-06-01 NaN NaN NaN NaN NaN NaN\n2021-06-02 0.031587 0.031587 0.032371 0.020892 -0.001091 0.256690\n2021-06-03 0.011414 0.011414 0.020111 0.021404 0.027596 -0.023832\n2021-06-04 0.035858 0.035858 0.023292 0.030905 0.024655 0.062834\n2021-06-07 0.002318 0.002318 0.008578 0.005689 0.026808 -0.066016","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":31,"Q_Id":68046017,"Users Score":0,"Answer":"Working with Pandas, it works just by using\ndf.fillna(0)","Q_Score":0,"Tags":"python,finance","A_Id":68046080,"CreationDate":"2021-06-19T10:46:00.000","Title":"How can I replace the NaN in my table for daily stock return?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"We have an experiment we are running where subjects play a video game and we record various data related to the gameplay. While the game is playing, we make a screen capture of the gameplay. One of the data we capture is when they push a button to request information during the game.\nWe are trying to understand if there are conditions related to lighting, decision points, etc. that are causing the button to be pushed. Ultimately the goal is to build a predictive model that will present the data before the subject asks for it.\nMy question is what is the best approach to analyze the video vs. the button push for information? We have timestamped csv files with the button push data and a video of the gameplay. Originally I thought of using Matlab to do the analysis, but I couldn't find a good example of how to approach the problem. I have a couple folks skilled at python on the team that I could ask for help as well, but I had wanted to see if I could understand what needed to be done before tasking them to do it.\nAny help is appreciated!\nThanks","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":29,"Q_Id":68050613,"Users Score":0,"Answer":"I think it is best if you consult a professional data scientist. However, I can think of one way to approach your problem.\nBecause a video is what data scientists call unstructured data, you'll have a hard time analyzing it raw.\nWhat I would do is to define some key points during the gameplay (ie. beginning of a new level or confronting a new puzzle), create a time interval around that key point, and chart the button pushed based on these intervals.\nConsider a set of gameplay videos with 2 key points. For example, the key point in one of the videos is set in times 04:13 and 32:00. So the video's timeline should look something like this.\n\n(Begining) 00:00 --------> 04:13 --------> 32:00 --------> 45:00 (End)\n\nNow for each key point, define a time interval of say, 2 minutes and record if the button is pushed in the obtained time intervals. So for key point number one, you will have 02:13 until 06:13. After doing so for every video and adding up all the data obtained, You'll end up with a table like below:\n\n\n\n\nTime Intervals\nTime interval for 1 player\n#Buttons Pushed\n\n\n\n\nInterval No.1\n00:00 - 02:13\n5\n\n\nKey Point No.1\n02:13 - 06:13\n19\n\n\nInterval No.3\n06:13 - 30:00\n7\n\n\nKey Point No.2\n30:00 - 34:00\n25\n\n\nInterval No.4\n34:00 - 45:00\n9\n\n\n\n\nThis basically means that for example, 7 people pushed the button during the time interval no.3 which in the above example (for that one player) is around times 06:13 - 30:00.\nAfter doing a small binary classification on the obtained data set, you'll end up with two classes for each key point, High Number of Buttons Pushed and Low Number of Buttons Pushed.\nNow add a listener to your game code and determine when the player enters a new KeyPoint. Use a simple search algorithm to find that if the KeyPoint is in the first class High Number of Buttons Pushed or in the second class, Low Number of Buttons Pushed. If it was in the first class, suggest pressing the key if not pass.","Q_Score":0,"Tags":"python,matlab,unity3d,video,data-science","A_Id":68051095,"CreationDate":"2021-06-19T20:45:00.000","Title":"What is the best way to compare a subjects video file to a csv file of data we have?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm using sklearn's decision tree for a binary class problem. However it turns out that after optimizing everything (optimizing hyper parameters and using the optimal number of selected features), the best I can do is get an accuracy and f1-score that's as good as baseline (no feature selection and use all features).\nSure now it's less messy (less features), and the code runs faster. But is this expected? Or is the point of feature selection to improve performance metrics of the classifier?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":24,"Q_Id":68057640,"Users Score":1,"Answer":"That's right. Feature selection will mostly give you performance benefits and might help a little against overfitting if relevant. It's not really supposed to improve the training metrics as you are essentially trying to solve the same problem with less information in your hands.\nIt doesn't mean you shouldn't do it though. If you can achieve the same performance with fewer features - use fewer features :)","Q_Score":0,"Tags":"python,machine-learning,scikit-learn,decision-tree","A_Id":68057731,"CreationDate":"2021-06-20T15:57:00.000","Title":"Do we expect baseline (all features) and selected features to perform the same with decision trees?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"i have this old DataFrame:\n\n\n\n\n\u00c9nergie(keV)\nIntensit\u00e9(%)\nType\nParent\nP\u00e9riode\nUnit\u00e9\n\n\n\n\n13.31275\n2.18\nXL\nFr-221\n4.79\nmin\n\n\n78.94000\n0.96\nXK\u03b12\nFr-221\n4.79\nmin\n\n\n81.51000\n1.59\nXK\u03b11\nFr-221\n4.79\nmin\n\n\n92.30930\n0.55\nXK\u03b21\nFr-221\n4.79\nmin\n\n\n\n\ni want update the 3 first columns with;\n\n\n\n\n\u00c9nergie(keV)\nIntensit\u00e9(%)\nType\nParent\n\n\n\n\n13.31275\n18\n\u03b3\nFr-221\n\n\n75.94000\n25\n\u03b3\nFr-221\n\n\n89.51000\n1.09\nXK\u03b11\nFr-221\n\n\n99.00000\n0.85\n\u03b3\nFr-221\n\n\n\n\nI have a big dataframe , but they havn't a same dimensions;","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":36,"Q_Id":68058526,"Users Score":0,"Answer":"it look like this the old one:\n|\u00c9nergie(keV)| Intensit\u00e9(%)| Type | Parent | P\u00e9riode| Unit\u00e9|\n|:-----------|:------------:|:-------:|:------:|:---------:|:-------:|\n|0.381 |0.019 |XL |Sc-44 |3.97 |h |\n|10.408 |0.45 |XL |Ti-44 |60.0 |a |\n|0.430 |0.00013 |XL |Fr-221 |83.788 |d |\nthe forth row mus be updated from the new dataframe","Q_Score":0,"Tags":"python-3.x,dataframe","A_Id":68059651,"CreationDate":"2021-06-20T17:41:00.000","Title":"how to update an old dataframe from newest one","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am currently working on a financial data problem. I want to detect trades for which anomalous theta values are being generated by the models (due to several factors).\nMy data mainly consists of trade with its profile variables like dealId, portfolio, etc. along with different theta values along with the theta components for different dates(dates back to 3 years).\nData that I am currently using looks like this:\n\n\n\n\nTradeid\nDate1\nDate 2 and so on\n\n\n\n\nid1\n1234\n1238\n\n\nid2\n1289\n1234\n\n\n\n\nCurrently, I am Tracking daily theta movement for all trades and sending trades whose theta has moved more than 20k (absolute value).\nI want to build an ML model which tracks theta movement and detects that for the current date this(or these) particular deal id\/s are having anomalous theta.\nSo far, I have tried clustering trades based on their theta movement correlation using DBSCAN with a distance matrix. I have also tried using Isolation forest but it is not generalizing very well on the dataset.\nAll the examples that I have seen so far for anomaly detection are more like finding a rotten apple from a bunch of apples. Is there any algorithm that would be best suitable for my case or can be modified to best suit my problem?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":24,"Q_Id":68069275,"Users Score":0,"Answer":"Your problem seems to be too simple for the machine learning world.\nYou can manually define a threshold, for which the data is anomalous and identify them.\nAnd to do that, you can easily analyze your data using pandas to find out the mean, max, min etc. and then proceed to define a threshold.","Q_Score":0,"Tags":"python-3.x,machine-learning,anomaly-detection","A_Id":68070825,"CreationDate":"2021-06-21T13:59:00.000","Title":"Anomaly Detection in option Theta values","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"My org is using utilizing Zendesk for work orders. To do this, we have created custom fields to manage statuses and various other information. I want to be able to export this data for reporting purposes to see what is completed, what is in progress, etc. but the 10 column limitation in Zendesk is an issue. Can I use the API to export these work order tickets with a column for each custom field and get it into CSV?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":287,"Q_Id":68101074,"Users Score":0,"Answer":"Can you be more specific on which Zendesk product are you using? They have lots of different products (Zendesk Support, Zendesk Talk, Zendesk Chat, etc.).\nFeel free to contact me through email.","Q_Score":1,"Tags":"python,csv,zendesk,zendesk-api","A_Id":68447386,"CreationDate":"2021-06-23T13:45:00.000","Title":"How can I export data from Zendesk?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a compatibility issue when running :\npip install numpy==1.19.4\npip install tensorflow=2.5.0\npip install gensim==4.0.1\nOn Ubuntu 18.04, with Python 3.9.5 (installs made inside docker container).\nI get the following exception when trying to import gensim:\nValueError: numpy.ndarray size changed, may indicate binary incompatibility. Expected 88 from C header, got 80 from PyObject. \nNot sure how i can make this work, I tried downgrading several libraries but still not achieved to make it work in Ubuntu.\nEdit : it works on Python 3.8.10","AnswerCount":2,"Available Count":2,"Score":0.0996679946,"is_accepted":false,"ViewCount":1459,"Q_Id":68106023,"Users Score":1,"Answer":"Tensorflow is currently not compatible with numpy 1.20.\nAlso, many changes happened from gensim 3.X to 4.X, which may lead to some problems.\nTry installing the following setup:\n\nnumpy 1.19.2\ngensim 3.8.3\ntensorflow 2.3.0","Q_Score":2,"Tags":"python,numpy,tensorflow2.0,gensim","A_Id":69700092,"CreationDate":"2021-06-23T19:24:00.000","Title":"Tensorflow 2.5.0 and Gensim 4.0.1 compatibility with numpy","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a compatibility issue when running :\npip install numpy==1.19.4\npip install tensorflow=2.5.0\npip install gensim==4.0.1\nOn Ubuntu 18.04, with Python 3.9.5 (installs made inside docker container).\nI get the following exception when trying to import gensim:\nValueError: numpy.ndarray size changed, may indicate binary incompatibility. Expected 88 from C header, got 80 from PyObject. \nNot sure how i can make this work, I tried downgrading several libraries but still not achieved to make it work in Ubuntu.\nEdit : it works on Python 3.8.10","AnswerCount":2,"Available Count":2,"Score":0.0996679946,"is_accepted":false,"ViewCount":1459,"Q_Id":68106023,"Users Score":1,"Answer":"It is the numpy version , downgrade numpy to 1.19.2 or lower and see.","Q_Score":2,"Tags":"python,numpy,tensorflow2.0,gensim","A_Id":68225538,"CreationDate":"2021-06-23T19:24:00.000","Title":"Tensorflow 2.5.0 and Gensim 4.0.1 compatibility with numpy","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"How do I extract multiple frames from a video streaming using ROS ?\nI subscribed to my camera topic :\nself.image_sub = rospy.Subscriber('\/bebop2\/image_raw',Image, self.image_callback)\nAnd then :\nframe = self.bridge.imgmsg_to_cv2(msg,desired_encoding='bgr8')\nThis way I have the actual frame from my streaming. How can I store N frames (the actual and previous ones) ?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":80,"Q_Id":68108469,"Users Score":1,"Answer":"Write a class, create a buffer and buffer the images. Each time you get a new one, add it to the buffer. now you have all previous ones as well.\nMake sure to also empty the buffer once there are enough frames, otherwise you'll run out of memory at some point.","Q_Score":1,"Tags":"python,ros,opencv3.0,rospy","A_Id":68116429,"CreationDate":"2021-06-24T01:05:00.000","Title":"Extract multiple frames from camera using ROS","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have pandas data frame with int64 , object , and datetime64[ns] data types. How to preserve those data types when exporting pandas DataFrame.to_Excel option?\nI want exported Excel file columns looks like this:\nint64 Number format in Excel\nobject Text format in Excel\ndatetime64[ns] Date format in Excel\nRight now all of my Excel column format shows as General","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":614,"Q_Id":68111864,"Users Score":0,"Answer":"I have pandas data frame with int64 , object , and datetime64[ns] data types. How to preserve those data types when exporting pandas DataFrame.to_Excel option?\n\nThe short answer is that you can't.\nExcel does't have as many datatypes as Python and far fewer than Pandas. For example the only numeric type it has is a IEEE 754 64bit double. Therefore you won't be able be able to store a int64 without losing information (unless the integer values are <= ~15 digits). Dates and times are are also stored in the same double format and only with millisecond resolution. So you won't be able to store datetime64[ns].\nYou could store them in string format but you won't be able to use them for calculations and Excel will complain about \"Numbers stored as strings\".","Q_Score":1,"Tags":"python,excel,pandas","A_Id":68128988,"CreationDate":"2021-06-24T08:06:00.000","Title":"How to keep data frame data types when exporting to Excel file?","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I had an issue where pandas would report an import error, upon attempting to use a buffer from io's StringIO class, during the use of read_csv() from pandas.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":2117,"Q_Id":68118223,"Users Score":1,"Answer":"Installing fsspec (an optional package for pandas) alone is not enough for pandas to be able to import fsspec. The dependecies for fsspec need also be installed, I don't know why the maintainers are not handling this with install.py, but here we are. I'll send them a message, but if you find your self in this condition, try:\npip install tox tox-conda","Q_Score":0,"Tags":"python,pandas,import,tox,fsspec","A_Id":68118224,"CreationDate":"2021-06-24T15:01:00.000","Title":"Import error when using pandas for fsspec in python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've built a network (In Pytorch) that performs well for image restoration purposes. I'm using an autoencoder with a Resnet50 encoder backbone, however, I am only using a batch size of 1. I'm experimenting with some frequency domain stuff that only allows me to process one image at a time.\nI have found that my network performs reasonably well, however, it only behaves well if I remove all batch normalization from the network. Now of course batch norm is useless for a batch size of 1 so I switched over to group norm, designed for this purpose. However, even with group norm, my gradient explodes. The training can go very well for 20 - 100 epochs and then game over. Sometimes it recovers and explodes again.\nI should also say that in training, every new image fed in is given a wildly different amount of noise to train for random noise amounts. This has been done before but perhaps coupled with a batch size of 1 it could be problematic.\nI'm scratching my head at this one and I'm wondering if anyone has suggestions. I've dialed in my learning rate and clipped the max gradients but this isn't really solving the actual issue. I can post some code but I'm not sure where to start and hoping someone could give me a theory. Any ideas? Thanks!","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":104,"Q_Id":68122785,"Users Score":0,"Answer":"To answer my own question, my network was unstable in training because a batch size of 1 makes the data too different from batch to batch. Or as the papers like to put it, too high an internal covariate shift.\nNot only were my images drawn from a very large varied dataset, but they were also rotated and flipped randomly. As well as this, random Gaussain of noise between 0 and 30 was chosen for each image, so one image may have little to no noise while the next may be barely distinguisable in some cases. Or as the papers like to put it, too high an internal covariate shift.\nIn the above question I mentioned group norm - my network is complex and some of the code is adapted from other work. There were still batch norm functions hidden in my code that I missed. I removed them. I'm still not sure why BN made things worse.\nFollowing this I reimplemented group norm with groups of size=32 and things are training much more nicely now.\nIn short removing the extra BN and adding Group norm helped.","Q_Score":3,"Tags":"python,tensorflow,image-processing,pytorch,autoencoder","A_Id":68492092,"CreationDate":"2021-06-24T21:11:00.000","Title":"Why is Normalization causing my network to have exploding gradients in training?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to make a np.array that creates a 25x3 array gradually building up each time. Starting from [0,0,0] and ending with [1,0,0].\nThe purpose is making a color parameter NumPy (n,3) array, where n(25) is the number of data points and each of the three columns corresponds to an RGB value in the range [0,1]\nExample:\narray([[0,0,0],\n...\n...\n...\n...\n[1,0,0]])\nI've gotten close but am having trouble with decimals.\nWhat I've tried:\narray = np.array([[i for i in range(3)] for j in range(25)])\narray = np.linespace(0,1,25) # this was close but wasn't the right format.","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":40,"Q_Id":68123674,"Users Score":1,"Answer":"I believe that you are looking for np.linspace((0, 0, 0), (1, 0, 0), 25)\nThis works because we can pass in \"array_like\" objects in for start and stop if we like.","Q_Score":1,"Tags":"python,arrays,numpy","A_Id":68123791,"CreationDate":"2021-06-24T23:16:00.000","Title":"python create 25 separate arrays with ranges [0,0,0] to [1,0,0]","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"i was trying to install tensorflow-gpu on my pycharm (pip install tensorflow-gpu), but unfortunately im getting a Error Message. How can i install this package on my pycharm? What is wrong here? Should i install it directly with cmd? How can I install them with pycharm? However, I was able to install the tenserflow Version 2.5.0 without any problems. Only the Tenserflow gpu I cannot install. Im using python Version 3.7.9","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":30186,"Q_Id":68133846,"Users Score":12,"Answer":"You need to run the command prompt or terminal as an administrator. This will permit you to install packages. And also, you need to upgrade pip to the latest version - python -m pip install \u2013-upgrade pip in cmd or terminal.","Q_Score":4,"Tags":"python,tensorflow,pip,pycharm","A_Id":68134030,"CreationDate":"2021-06-25T15:53:00.000","Title":"ERROR: Could not install packages due to an OSError: [WinError 5]","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"For example, suppose I have created a kdtree from the points in a 2-d array. Then I run a nearest neighbor query on some point (represented as a pair of x-y coordinates) asking for the 8 nearest neighbors to that point. This returns two lists: (1) a list of 8 distances to neighbors of the given pint, and (2) a list of tree indices for those neighbors.\nSuppose now that I want to take one of those tree indices and get the x-y coordinates of that point? How can I do this?","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":222,"Q_Id":68138948,"Users Score":1,"Answer":"In case anyone is interested, one of my students provided the answer. There is no kdtree method that returns this information, but you can get it from the original lists used to create the tree. The x-y coordinates of the points used to construct the tree are taken from two lists, one of the x coordinates, and one of the y-coordinates. Then, when you do a kdtree query, the list of indexes returned by the query can be used as indexes into the two original lists to get back the original x-y pairs.","Q_Score":3,"Tags":"python,kdtree","A_Id":68143097,"CreationDate":"2021-06-26T03:23:00.000","Title":"How can I retrieve the coordinates of a point in a kdtree given that point's tree index?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"When using the SciKit learn PolynomialFeatures package it is possible to do the following:\n\nTake features: x1, x2, x3\nCreate interaction variables: [x1, x2, x3, x1x2, x2x3, x1x3] using PolynomialFeatures(interaction_only=True)\n\nMy problem is that I only want the interaction terms between x1 and all other terms meaning:\n[x1, x2, x3, x1x2, x1x3], I do not want x2x3.\nIs it possible to do this?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":70,"Q_Id":68146847,"Users Score":0,"Answer":"You could just make them yourself no? PolynomialFeatures doesn't do anything particularly innovative.","Q_Score":0,"Tags":"python,pandas,numpy,scikit-learn","A_Id":68148291,"CreationDate":"2021-06-26T23:03:00.000","Title":"How to create interaction variable between only 1 variable with all other variables","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Just as a background, I am an R user but learning python:\nI have installed python libraries I want to get familiar with (pandas, numpy, Pytorch, tensorflow...), but when I start a new project, it does not detect the packages when I try to import and requests that I install them, even though I definitely did at one point. I am obviously making mistakes when installing them, but don't know what.\nI use pip as a package manager if that is relevant","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":22,"Q_Id":68155530,"Users Score":0,"Answer":"Have you attempted installing pip3 and using that in place of pip? I know I had some issues a while back where pip would install my packages for python 2.X and not 3.X.","Q_Score":0,"Tags":"python-3.x,pip","A_Id":68155601,"CreationDate":"2021-06-27T21:45:00.000","Title":"Packages in python with pip-installed but new projects don't detect package","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"Is there a way to increase the value of objective_convergence_tolerance for Solver=2 (BPOPT)?\nIt seems to be working only for Solver = 1 and 2.\nThanks.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":59,"Q_Id":68165985,"Users Score":0,"Answer":"There are 4 parts that are checked for convergence including:\n\nmax(abs(g + a^T * lam - zL + zU))\/s_d\nmax(abs(c))\nmax(abs(diag[x-xL s-sL]*zL - mu))\/s_c\nmax(abs(diag[xU-x sU-s]*zU - mu))\/s_c\n\nThe maximum of these 4 parts must be less than the convergence tolerance. Right now there is no separate objective function convergence criterion. Gekko has 3 solvers that are included with the publicly available version including:\n\nAPOPT\nBPOPT\nIPOPT\n\nThe BPOPT solver isn't typically one one of the best solvers if you'd like to try m.options.SOLVER=1 (APOPT) or m.options.SOLVER=3 (IPOPT).","Q_Score":2,"Tags":"python-3.x,gekko","A_Id":68250039,"CreationDate":"2021-06-28T15:20:00.000","Title":"Python Gekko: Increasing value of objective_convergence_tolerance for Solver=2 (BPOPT)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"Suppose I have y = [1,2,3] (1 X 3 matrix) then np.transpose(y) should be a (3 X 1) matrix but the function transpose is returning the same (1 X 3) matrix.\nIf I run np.transpose([y]) then it's returning expected (3 X 1) matrix.\nCan anyone explain what's happening here?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":26,"Q_Id":68172765,"Users Score":0,"Answer":"transpose reverses the axes order. if y = [1,2,3] there is only one axis: y.shape = (3,). So transpose won't do anything.\nIf y=[[1,2,3]] the there are 2 axes: y.shape = (1,3) and transpose will work as you expect.","Q_Score":0,"Tags":"python,numpy,matrix,data-analysis,numpy-ndarray","A_Id":68172814,"CreationDate":"2021-06-29T04:47:00.000","Title":"Difference between np.transpose(y) and np.transpose([y])","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"When we are encoding a column using LabelEncoder object is it possible for us to change the encoded values while encoding.\nEg : encoding a column with three class ['a', 'b', 'c' ] it will be encoded as [1,2,3] but what if we want to encode it as [2,1,3].\nis it possible to do it with label encoder or there is some different way to do this?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":136,"Q_Id":68182641,"Users Score":0,"Answer":"You should only use LabelEncoder for labels (i.e. the target variable). Use OrdinalEncoder instead, and specify the categories parameter.","Q_Score":0,"Tags":"python,pandas,dataframe,scikit-learn","A_Id":68185816,"CreationDate":"2021-06-29T16:40:00.000","Title":"Using LabelEncoder from scikit learn, is there any way to change the way of encoding the values of a particular column?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using Yake (Yet Another Keyword Extractor) to extract keywords from a dataframe.\nI want to extract only bigrams and trigrams, but Yake allows only to set a max ngram size and not a min size. How do you would remove them?\nExample df.head(0):\nText:\n'oui , yes , i mumbled , the linguistic transition now in limbo .'\nKeywords:\n'[('oui', 0.04491197687864554),\n('linguistic transition', 0.09700399286574239),\n('mumbled', 0.15831692877998726)]'\nI want to remove oui, mumbled and their scores from keywords column.\nThank you for your time!","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":216,"Q_Id":68192949,"Users Score":1,"Answer":"If you need the handle the mono-gram case from Yake just pass the output through a filter that adds the n-grams to the result list only if there is a space in the first element of that tuple or if the str.split() of that element results in more than 1 sub-element. If you're using a function and applying it to the dataframe, include this step in that function.","Q_Score":3,"Tags":"python,dataframe,keyword,n-gram","A_Id":68193556,"CreationDate":"2021-06-30T10:21:00.000","Title":"Remove keywords which are not bigram or trigram (Yake)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Working on my local computer, I've created a Tensorflow Object Detector. I have exported the model (which I've tested using the checkpoints) to a protobuf file as well as several others (TF lite, TF js, etc). I now need to transfer this trained model to another computer that doesn't have the Object Detection API or other things I needed to build the model.\nDo I need all these dependencies on the new machine? Or, does the protobuf file contain everything that the machine will need? The new machine only has the basic anaconda environment packages as well as tensorflow.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":24,"Q_Id":68198797,"Users Score":0,"Answer":"Protobuf files most commonly contains both model and weights. So in theory you can load your model on any machine with TensorFlow.\nThe only problem that I can think of is saving custom layers\/losses\/optimizers and data pre\/postprocessing.","Q_Score":0,"Tags":"python,tensorflow,object,package,detection","A_Id":68201149,"CreationDate":"2021-06-30T16:54:00.000","Title":"Do I need the Tensorflow Object Detection API to use a trained model I made on a different computer?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a database containing about 2.8 million texts (more precisely tweets, so they are short texts). I put clean tweets (removing hashtags, tags, stop words...) in a list of lists of tokens called sentences (so it contains a list of tokens for each tweet).\nAfter these steps, if I write\nmodel = Word2Vec(sentences, min_count=1)\nI obtain a vocabulary of about 400,000 words.\nThis was just an attempt, I would need some help to set the parameters (size, window, min_count, workers, sg) of Word2Vec in the most appropriate and consistent way.\nConsider that my goal is to use\nmodel.most_similar(terms) (where terms is a list of words)\nto find, within the list of lists of tokens sentences, the words most similar to those contained in terms.\nThe words in terms belong to the same topic and I would like to see if there are other words within the texts that could have to do with the topic.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":66,"Q_Id":68225624,"Users Score":2,"Answer":"Generally, the usual approach is:\n\nStart with the defaults, to get things initially working at a baseline level, perhaps only on a faster-to-work-with subset of the data.\nDevelop an objective way to determine whether one model is better than another, for your purposes. This might start as a bunch of ad hoc, manual comparisons of results for some representative probes - but should become a process that can automatically score each variant model, giving a higher score to the 'better' model according to some qualitative, repeatable process.\nEither tinker with parameters one-by-one, or run a large search over many permutations, to find which model does best on your scoring.\n\nSeparately: the quality of word2vec results is almost always improved by discarding the very rarest words, such as those appearing only once. (The default value of min_count is 5 for good reason.)\nThe algorithm can't make good word-vectors from words that only appear once, or a few times. It needs multiple, contrasting examples of its usage. But, given the typical Zipfian distribution of word usages in a corpus, there are a lot of such rare words. Discarding them speeds training, shrinks the model, & eliminates what's essentially 'noise' from the training of other words - leaving those remaining word-vectors much better. (If you really need vectors for such words \u2013 gather more data.)","Q_Score":0,"Tags":"python,nlp,gensim,word2vec,word-embedding","A_Id":68229590,"CreationDate":"2021-07-02T12:56:00.000","Title":"Set the parameters of Word2Vec for a practical example","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Supposing you have the current price (current live price) and its history, is it possible to calculate indicators such as RSI, MACD, etc ... at any time? I am using python and the pandas library.","AnswerCount":2,"Available Count":2,"Score":1.2,"is_accepted":true,"ViewCount":56,"Q_Id":68239840,"Users Score":0,"Answer":"Of course you can, I am sure there are plenty of API's from finance websites that can give you that data exactly, so you would not even need to calculate.\nBut if you prefer, as long as you have the data, absolutely.","Q_Score":0,"Tags":"python,pandas,finance","A_Id":68240210,"CreationDate":"2021-07-03T20:43:00.000","Title":"Calculate financial indicators on live prices","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Supposing you have the current price (current live price) and its history, is it possible to calculate indicators such as RSI, MACD, etc ... at any time? I am using python and the pandas library.","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":56,"Q_Id":68239840,"Users Score":0,"Answer":"Yes if you have the data it is very easy to do simply find the formulas on investopedia or another well known finance website and you can go from there!","Q_Score":0,"Tags":"python,pandas,finance","A_Id":68265314,"CreationDate":"2021-07-03T20:43:00.000","Title":"Calculate financial indicators on live prices","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have two rasters that I clipped using the same shapefile. I then used gdal to resample them into the same resolution but now I have an issue where the shapes are very similar but not quite the same. How do you suggest fixing this? I've been stuck on this for the last couple of hours so help would be greatly appreciated.\nHere's the output I get:\nprint(dsm.shape,ortho.shape)\n(1, 13110, 14640) (4, 13111, 14641)\nAs you can see one of the rasters only has one band, whereas the other one has 4. I tried doing this:\ndsm = np.resize(dsm,(dsm.shape[0],ortho.shape[1],ortho.shape[2]))\nBut this just distorted the raster. I've also tried building a VRT but was running into issues since one of the rasters has multiple bands. I think that'll be my next method of attack, but I figured I'd drop by here first in case someone could offer some help.\nThanks!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":271,"Q_Id":68256758,"Users Score":0,"Answer":"The easiest way to solve this problem was to just find the maximum height and width of the raster arrays and pad both rasters to make sure they have these dimensions.\nLargest deviation I saw was a difference of 2 pixels, and visually I can tell no difference when comparing these images after padding the arrays.","Q_Score":0,"Tags":"python,gis,raster,gdal,rasterio","A_Id":68332741,"CreationDate":"2021-07-05T13:12:00.000","Title":"Combining rasters with a slightly different size","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've just been trying to dabble in AI in the past few weeks, I've tried installing pytorch with conda and it all seems to work but then I get the error:\nImportError: \/home\/lp35791\/.local\/lib\/python3.8\/site-packages\/torch\/lib\/libtorch_cuda.so: cannot read file data\nI've been trawling through the web but can't seem to find the answer to this error. I've uninstalled and reinstalled anaconda and when I made a new environment and installed numpy along with pytorch, numpy imported successfully but pytorch did not. I'm just wondering what the problem is. Any help would be greatly appreciated!","AnswerCount":2,"Available Count":2,"Score":0.0996679946,"is_accepted":false,"ViewCount":91,"Q_Id":68267305,"Users Score":1,"Answer":"You seem to have installed PyTorch in your base environment, you therefore cannot use it from your other \"pytorch\" env.\nEither:\ndirectly create a new environment (let's call it pytorch_env) with PyTorch: conda create -n pytorch_env -c pytorch pytorch torchvision\nswitch to the pytorch environment you have already created with: source activate pytorch_env and then install PyTorch in it: conda install -c pytorch pytorch torchvision","Q_Score":0,"Tags":"python,pytorch","A_Id":68268048,"CreationDate":"2021-07-06T08:44:00.000","Title":"Installing pytorch with conda","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've just been trying to dabble in AI in the past few weeks, I've tried installing pytorch with conda and it all seems to work but then I get the error:\nImportError: \/home\/lp35791\/.local\/lib\/python3.8\/site-packages\/torch\/lib\/libtorch_cuda.so: cannot read file data\nI've been trawling through the web but can't seem to find the answer to this error. I've uninstalled and reinstalled anaconda and when I made a new environment and installed numpy along with pytorch, numpy imported successfully but pytorch did not. I'm just wondering what the problem is. Any help would be greatly appreciated!","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":91,"Q_Id":68267305,"Users Score":0,"Answer":"It seems like you need to reinstall it-\nGo to terminal type\npip uninstall pytorch\nthen again type\npip install pytorch\nif you are unable to install you will get solution there itself.","Q_Score":0,"Tags":"python,pytorch","A_Id":68267970,"CreationDate":"2021-07-06T08:44:00.000","Title":"Installing pytorch with conda","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to use string fuzzy-matching with both R and Python.\nI am actually using two packages:\n\nstringdist from R\nfuzzywuzzy from Python\n\nWhen I try amatch(\"PARI\", c(\"HELLO\", \"WORLD\"), maxDist = 2) on R, I get NA as a result, which is intuitive.\nBut when I try the same thing with Python : process.extract(\"PARI\", [\"HELLO\", \"WORLD\"], limit = 2), I get [('world', 22), ('HELLO', 0)]\nCould anyone tell me why I have a 22 as a ratio matching between \"PARI\" and \"WORLD\" ?\nHow could I get the same result as in R ?\nThanks in advance","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":56,"Q_Id":68270849,"Users Score":1,"Answer":"The problem here is limit = 2 specifically says you want 2 results regardless of the score, whereas in R you are specifying that you only want a result if the strings are very close to one another. The score here is a measure from 0 to 100 of how similar the words are. You can see PARI and world both have R as their third letter, which is why you get a non-zero score, but it still isn't a very good one.","Q_Score":1,"Tags":"python,r","A_Id":68270975,"CreationDate":"2021-07-06T12:46:00.000","Title":"String fuzzy-matching From R to Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Matplotlib has released 3.4.2 version but my version is stuck in 3.3.4.\nI removed pip cache and tried, didn't work.\n\n$pip3 install -U matplotlib==3.4.2\nERROR: Could not find a version that\nsatisfies the requirement matplotlib==3.4.2 (from versions: 0.86,\n0.86.1, 0.86.2, 0.91.0, 0.91.1, 1.0.1, 1.1.0, 1.1.1, 1.2.0, 1.2.1, 1.3.0, 1.3.1, 1.4.0, 1.4.1rc1, 1.4.1, 1.4.2, 1.4.3, 1.5.0, 1.5.1, 1.5.2, 1.5.3, 2.0.0b1, 2.0.0b2, 2.0.0b3, 2.0.0b4, 2.0.0rc1, 2.0.0rc2, 2.0.0, 2.0.1, 2.0.2, 2.1.0rc1, 2.1.0, 2.1.1, 2.1.2, 2.2.0rc1, 2.2.0, 2.2.2, 2.2.3, 2.2.4, 2.2.5, 3.0.0rc2, 3.0.0, 3.0.1, 3.0.2, 3.0.3, 3.1.0rc1, 3.1.0rc2, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.2.0rc1, 3.2.0rc3, 3.2.0, 3.2.1, 3.2.2, 3.3.0rc1, 3.3.0, 3.3.1, 3.3.2, 3.3.3, 3.3.4)\nERROR: No matching distribution found for matplotlib==3.4.2\n\npython: 3.6.9\npip: 21.1.3","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":800,"Q_Id":68291267,"Users Score":0,"Answer":"Instead of this, you can try pip install matplotlib==3.4.2. It should work fine","Q_Score":0,"Tags":"python,matplotlib","A_Id":68291711,"CreationDate":"2021-07-07T18:18:00.000","Title":"Can't update Matplotlib using pip under Python 3.6","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have dataframe with 3 columns (id, parentId, version) and I need to add new column parentVersion (version from parentid) :\n\n\n\n\nid\nparentid\nversion\nparentVersion\n\n\n\n\n1\n2\n1.1\n2.1\n\n\n2\n2\n2.1\n2.1","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":83,"Q_Id":68293199,"Users Score":0,"Answer":"Define a dictionary containing the data : data = {\"id\":[1,2], \"parentid\":[2,2], \"version\":[1.1,2.1], }\nConvert the dictionary into DataFrame:df = pd.DataFrame(data)\nDeclare a list that is to be converted into a column: parentVersion= [2.1, 2.1]\nUsing 'parentVersion' as the column name: df['parentVersion'] = parentVersion\nObserve the result: print(df)","Q_Score":0,"Tags":"python,pandas","A_Id":68293347,"CreationDate":"2021-07-07T21:32:00.000","Title":"pandas create column (assign value from other row)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"For root finding of scalar functions,scipy.optimize.root_scalar provides a very useful bracket argument that I can use to set the interval bracketing my root to ensure the root that I find is the one that I want. I want to do the same thing for a vector function of (x1, x2), where the only roots meaningful to me lie between (0, 1) for both variables. However, the vector root finding function in scipy scipy.optimize.root does not have any way for me to specify bounds, and it doesn't seem that I can specify this as an option to any of the solver methods either.\nAre there any ways around this or other packages\/functions that do what I want? I'm very new to root finding, but I'm surprised this feature is hard to find since intuitively root finding seems like it would be easier if there are bounds specified. Are there ways I could hack my function to direct one of these algorithms towards the (0, 1) region?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":265,"Q_Id":68293256,"Users Score":1,"Answer":"The function scipy.optimize.root_scalar has the bracket argument because when the function has a single parameter it is possible to use the bisection algorithm to find the root.\nIn higher dimensions there is no such bisection algorithm.\nNevertheless, in multiple dimensions it is possible to specify ranges in scipy.optimize.brute to limit the search space of the solution.\nTo find the root of f(x_1, ..., x_n), you can try using scipy.optimize.brute on f(x_1, ..., x_n)^2 since a root is a global minimum of the squared functions.","Q_Score":0,"Tags":"python,numpy,scipy,scipy-optimize,nonlinear-functions","A_Id":68293372,"CreationDate":"2021-07-07T21:41:00.000","Title":"Root finding for nonlinear vector functions in python: how can I place bounds on my variables?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working on an application using an IFM 3D camera to identify parts prior to a robot pickup. Currently I am able to find the centroid of these objects using contours from a depth image and from there calculate the center point of these objects in pixel space.\nMy next task is to then transform the 2D centroid coordinates to a 3D point in 'real' space. I am able to train the robot such that it's coordinate frame is either at the center of the image or at the traditional (0,0) point of an image (top left).\nThe 3D camera I am using provides both an intrinsic and extrinsic matrix. I know I need to use some combination of these matrices to project my centroid into three space but the following questions remain:\n\nMy current understanding from googling is the intrinsic matrix is used to fix lens distortion (barrel and pinhole warping, etc.) whereas the extrinsic matrix is used to project points into the real world. Is this simplified assumption correct?\n\nHow can a camera supply a single extrinsic matrix? I know traditionally these matrices are found using the checkerboard corners method but are these not dependent on the height of the camera?\n\nIs the solution as simple as taking the 3x4 extrinsic matrix and multiplying it by a 3x1 matrix [x, y, 1] and if so, will the returned values be relative to the camera center or the traditional (0,0) point of an image.\n\n\nThanks in advance for any insight! Also if it's any consolation I am doing everything in python and openCV.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":152,"Q_Id":68294560,"Users Score":0,"Answer":"No. I suggest you read the basics in Multiple View Geometry of Hartley and Zisserman, freely available in the web. Dependent on the camera model, the intrinsics contain different parameters. For the pinhole camera model, these are the focal length and the principal point.\n\nThe only reason why you maybe could directly transform your 2D centroid to 3D is that you use a 3D camera. Read the manual of the camera, it should be explained how the relation between 2D and 3D coordinates is given for your specific model.\nIf you have only image data, you can only compute a 3D point from at least two views.\n\nNo, of course not. Please don't be lazy and start reading the basics about camera projection instead of asking for others to explain the common basics that are written down everywhere in the web and literature.","Q_Score":0,"Tags":"python,matrix,graphics,computer-vision,camera-calibration","A_Id":68297657,"CreationDate":"2021-07-08T01:31:00.000","Title":"How to Transform Centroid from Pixel to Real World Coordinates","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"It exists a possibility to get a specific file from a specific node executed from a spark-submit?\nMy first approach was getting the list of every nodes in my cluster using spark-submit by a socket, that was the first part, now, I want to connect directly to a specific node to get a specific file, this file is not a HDFS file is a local file on that remote node.\nI cannot use a ftp because I do not have those credentials, they perform a direct connection.\ntextfile is not working, I would like to specify the node name and path of the file.\nEj.\n\ntextfile(remoteNodeConnectedToMyCluster:\/\/\/path\/file.txt)\n\nI hope been clear.\nThanks in advance.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":135,"Q_Id":68295324,"Users Score":0,"Answer":"There is no way to accomplish that, short of installing a server (e.g. FTP, HTTP) on the node to serve the file or running a script on the node to copy it to a distributed file system (e.g. HDFS).\nNote that a properly specified URL would have the form protocol:\/\/host\/path\/to\/file.txt.","Q_Score":0,"Tags":"python,scala,apache-spark,pyspark,spark-submit","A_Id":68301275,"CreationDate":"2021-07-08T03:40:00.000","Title":"Read a remote file from a specific node in my cluster using Spark Submit","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":1,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have prer-trained python model at local jupyter notebook and C# backend which is working on Visual Studio. I have input picture and I have to send Python model and evaluate after I have to take back for prediction result to C# backend. How can I do this communications on simplest way? I am thinking on service comminication between them, is there a possible solution for it?","AnswerCount":2,"Available Count":2,"Score":1.2,"is_accepted":true,"ViewCount":71,"Q_Id":68313050,"Users Score":0,"Answer":"Something that I did for a project that had a similar structure, was to run the python model in Django framework locally and make the C# backend to communicate with the model through a Django service. Django will run as a local web service.\nThis was a good pattern in my idea as it would isolate the python model and I was able to alter it separately from the C# backend. The python model could become available as a web service for other projects that need the same functionality.\nI've heard C# is able to run python code within the code, so you can use that too.","Q_Score":0,"Tags":"python,c#,keras,service","A_Id":68313168,"CreationDate":"2021-07-09T07:44:00.000","Title":"Communication between Python Keras CNN Model and C# Backend Project","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have prer-trained python model at local jupyter notebook and C# backend which is working on Visual Studio. I have input picture and I have to send Python model and evaluate after I have to take back for prediction result to C# backend. How can I do this communications on simplest way? I am thinking on service comminication between them, is there a possible solution for it?","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":71,"Q_Id":68313050,"Users Score":0,"Answer":"I use python script to evaluate input on pre-trained neural networks writing XML file that contain output values and save it on Google drive.\nLater, I download XML file to process it using Console application using C#.","Q_Score":0,"Tags":"python,c#,keras,service","A_Id":68313768,"CreationDate":"2021-07-09T07:44:00.000","Title":"Communication between Python Keras CNN Model and C# Backend Project","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"First of all, I'm not experienced in model training so please be gentle :)\nI need to make some time series predictions to handle an issue related to my product. If the value is too low my customer ask for a quick fix and they cannot know that until it happens. I have collected some data related to different customers but the same product.\nData_1\n\n\n\n\ntime\nvalue\n\n\n\n\n2020-09-20\n600\n\n\n2020-09-21\n450\n\n\n2020-09-22\n350\n\n\n2020-09-23\n300\n\n\n2020-09-24\n150\n\n\n2020-09-25\n50\n\n\n\n\nData_2\n\n\n\n\ntime\nvalue\n\n\n\n\n2020-09-20\n50\n\n\n2020-09-21\n600\n\n\n2020-09-22\n550\n\n\n2020-09-23\n400\n\n\n2020-09-24\n200\n\n\n2020-09-25\n50\n\n\n\n\nWhen the value hits 50, we change the product and it's value goes 600. I tried the prophet and kats from facebook and they predict on training data. What I want is train with data_1 & data_2 & data_3 ... and predict with data_4 that can start from 50-600 depending on customer. What would be your approach?\nTLDR\nSame product,different sources. Same dates,different values. Cut them from 50-600 points or combine them all? How to approach ML model?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":57,"Q_Id":68318799,"Users Score":0,"Answer":"\"Different Customers - Same Product\" data gives an insight to you . But each product data (in each customer) may have its own characteristics.\nYou have to check if data distribution same in each customer. If not, please get the data of the product for each customers and do the math.\nFor the Time-Series approach, i would say you can try many algorithms in kats and facebook prophet itself and check the results-Backtesting (MAPE is good for your problem). Look at the best one (minimum error) and implement it.","Q_Score":1,"Tags":"python,machine-learning,time-series,artificial-intelligence,facebook-prophet","A_Id":69467518,"CreationDate":"2021-07-09T14:52:00.000","Title":"Time Series Prediction with Different Sources","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"AttributeError Traceback (most recent call last)\n in \n14 sys.path.append(ROOT_DIR) # To find local version of the library\n15 from mrcnn import utils\n---> 16 import mrcnn.model as modellib\n17 from mrcnn import visualize\n18 # Import COCO config\n~\\ComputerVisionProject\\Mask_RCNN_CustomDataset\\Mask_RCNN-master\\Mask_RCNN-master\\mrcnn\\model.py in \n253\n254\n--> 255 class ProposalLayer(KE.Layer):\n256 \"\"\"Receives anchor scores and selects a subset to pass as proposals\n257 to the second stage. Filtering is done based on anchor scores and\nAttributeError: module 'keras.engine' has no attribute 'Layer'","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":267,"Q_Id":68325628,"Users Score":0,"Answer":"This isn\u2019t strictly a duplicate, but a similar question is found here: AttributeError: module 'keras.engine' has no attribute 'input_layer'\nIn essence, many of the import and attribute errors from keras come from the fact that keras changes its imports depending on whether you are using a CPU or using a GPU or ASIC. Some of the engine classes don\u2019t get imported in every case.\nInstead, use from keras.layers import Layer and use that layer class in place of the one from the engine.","Q_Score":0,"Tags":"python-3.x,keras,jupyter-notebook,computer-vision,data-science","A_Id":70634968,"CreationDate":"2021-07-10T07:23:00.000","Title":"I was working on Mask RCNN so while executing demo.ipynb on jupyter notebook i got an error can anyone please help me out","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"AttributeError Traceback (most recent call last)\n in \n14 sys.path.append(ROOT_DIR) # To find local version of the library\n15 from mrcnn import utils\n---> 16 import mrcnn.model as modellib\n17 from mrcnn import visualize\n18 # Import COCO config\n~\\ComputerVisionProject\\Mask_RCNN_CustomDataset\\Mask_RCNN-master\\Mask_RCNN-master\\mrcnn\\model.py in \n253\n254\n--> 255 class ProposalLayer(KE.Layer):\n256 \"\"\"Receives anchor scores and selects a subset to pass as proposals\n257 to the second stage. Filtering is done based on anchor scores and\nAttributeError: module 'keras.engine' has no attribute 'Layer'","AnswerCount":2,"Available Count":2,"Score":0.0,"is_accepted":false,"ViewCount":267,"Q_Id":68325628,"Users Score":0,"Answer":"!pip install tensorflow==1.15 keras==2.0.8\nInstall the above version then restart the run time it will work","Q_Score":0,"Tags":"python-3.x,keras,jupyter-notebook,computer-vision,data-science","A_Id":71201395,"CreationDate":"2021-07-10T07:23:00.000","Title":"I was working on Mask RCNN so while executing demo.ipynb on jupyter notebook i got an error can anyone please help me out","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to plot an interactive plot with pyCharm (from mne), and disabled \"Show plots in tool window\". When I run my code, I see that a new window is trying to open, but closes immediately, as if something is blocking it. I know it's not a problem with the plot itself, as it works when \"Show plots in tool window\" is enabled (but than it's not interactive).\nI have no idea what's blocking the new window, does someone have an idea?\nI'm working on Mac (Big Sur).\nThanks!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":118,"Q_Id":68326410,"Users Score":0,"Answer":"I had the same problem and could solve it by using plt.show(block=True) instead of plt.show(). This blocks the python script from finishing and closing the figure. Once you close the figure, the python script continues.","Q_Score":0,"Tags":"python,matplotlib,pycharm,mne-python","A_Id":68395279,"CreationDate":"2021-07-10T09:20:00.000","Title":"pyCharm doesn't open plot with \"Show plots in tool window\" disabled - probably due to blocking","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Use case is processing some array of clusters data created in labview in python. Need pythonic representation of the array of clusters . Ideally should be able to post back a modified array of clusters of the same type back to labview.","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":293,"Q_Id":68332595,"Users Score":2,"Answer":"I started with XML and found it lacking support for arrays natively. Next tried JSON format and it seems better because of native support for arrays. LabView flatten to JSON.vi (in LV pallete String \/Flatten Unflatten String) to create a JSON string (that can be saved to a file if needed) and Unflatten from JSON.vi ( in same LV palette String \/ Flatten Unflatten String) to read back the python modified string back into LabVIEW array of clusters . Note: \"Flatten to JSON.vi\" does not support ENUM in clusters but does support Text Ring so right click, replace, String & ENUM, Text Ring for all ENUM clusters in Ring for all ENUM controls in cluster.","Q_Score":1,"Tags":"python,json,xml,labview","A_Id":68332609,"CreationDate":"2021-07-11T01:19:00.000","Title":"what is a simple way to exchange array of clusters data between labview and python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"NameError: name 'pixels' is not defined\nfrom mtcnn.mtcnn import MTCNN\nimport cv2\nmodel = MTCNN()\ndetect face in the image\nfaces = model.detect_faces(pixels)\nextract details of the face\nx1, y1, width, height = faces[0]['box']","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":58,"Q_Id":68334007,"Users Score":0,"Answer":"following error is shown when above mentioned code is run","Q_Score":0,"Tags":"python,conv-neural-network,pixel","A_Id":68334008,"CreationDate":"2021-07-11T07:13:00.000","Title":"when i run the below mentioned code it gives me error that is pixels is not defined","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I've searched a lot on the internet but haven't found an exact method. If someone can point me to a library that can do this, that would be great.\nI want to find a 4-dimensional cubic spline function such that f(A, B) = C,D.\nThanks in advance!","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":41,"Q_Id":68340362,"Users Score":0,"Answer":"There is a function called CubicSpline in scipy.interpolate.","Q_Score":0,"Tags":"python,numpy,scipy,interpolation,cubic-spline","A_Id":68340456,"CreationDate":"2021-07-11T22:36:00.000","Title":"Can I use any library or Scipy in Python for 4 or n dimensional interpolation?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a VM that I've been running in VMWare Fusion on my MacBook. I use it to run a Python program that makes use of tensorflow. Everything works fine on my MacBook.\nI copied the same VM to a ThinkPad. Using VMWare Workstation, I'm able to power on the machine, and run other programs within the VM just fine, but when I run the program that uses tensorflow, I get the error: Illegal instruction (core dumped).\nAny ideas as to what may be going wrong? I'd assume a VM should work on any machine it's run on, so I'm not sure what could be causing the error.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":98,"Q_Id":68340481,"Users Score":0,"Answer":"I solved this by uninstalling and reinstalling tensorflow and tensorflow_text. Apparently tensorflow relies on the CPU instructions that are available at the time of its build. Because these instructions are passed from the VM to the host machine, it can break when running the VM on a different machine.","Q_Score":0,"Tags":"python,tensorflow,vmware,vmware-workstation,vmware-fusion","A_Id":68349592,"CreationDate":"2021-07-11T23:06:00.000","Title":"Using tensorflow in VMWare virtual machine works on one machine, not on other machine","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I was wondering if I could build a classification model that just works on simple data I for example stock market classification 1 if it goes up 0 of down. I ask because I never see models like this and tutorials only ever with image or text classification and I typically see regression models working with this form of data","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":71,"Q_Id":68341220,"Users Score":0,"Answer":"Yes, definitely!\nAfter all image is just a 2D array of numbers.\nWhen you build your classification network, or modify an existing one, you just want to design it so the input layer of the neural network will be a simple array of numbers.\nIf I have to estimate its performance, I would bet on higher performance relative to a conversational image classifier that does the same task, because every bit of input data is relevant and the data will most likely be smaller without losing any details.","Q_Score":0,"Tags":"python,numpy,tensorflow,deep-learning,artificial-intelligence","A_Id":68341260,"CreationDate":"2021-07-12T02:05:00.000","Title":"Can you build a classification model with a simple numpy array","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Given a set of data that looks like the following, each line are 10 characters in length. They are links of a network, comprised of combinations of 4 or 5 character node numbers. Below is an example of the situations I would face:\n|10637 4652|\n| 1038 1037|\n|7061219637|\n|82004 2082|\nAs the dataset doesn't care much about spacing, While lines 1, 2 and 4 can be read in Pandas easily with either sep=' ' or delim_whitespace=True, I'm afraid I can't do the same for line 3. There is very little I can do to the input data file as it's generated from a third party software\n(apart from doing some formatting in Excel, which seemed counterintuitive...) Please, is there something in Pandas allowing me to specify the number of characters (in my case, 5) as a delimiter?\nAdvice much appreciated.","AnswerCount":4,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":90,"Q_Id":68353026,"Users Score":0,"Answer":"I would just use df['my_col'].str[0:6] after reading it in as one column.\nIf your file is just this data then @ifly6's use of read_fwf is more appropriate. I just assumed that this is one column as part of a larger CSV in which case this is the approach I would use.","Q_Score":3,"Tags":"python,pandas,dataframe","A_Id":68353122,"CreationDate":"2021-07-12T19:34:00.000","Title":"Pandas read_csv on file without space?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have df1\n\n\n\n\nShip_Date\nPrice\n\n\n\n\n07\/15\/2014\n5\n\n\n08\/19\/2015\n9\n\n\n09\/20\/2016\n7\n\n\n\n\nI also have df2\n\n\n\n\nShip_Date\n\n\n\n\n08\/19\/2015\n\n\n07\/15\/2014\n\n\n09\/20\/2016\n\n\n07\/15\/2014\n\n\n\n\nI need the final output for df2 to be\n\n\n\n\nShip_Date\nPrice\n\n\n\n\n08\/19\/2015\n9\n\n\n07\/15\/2014\n5\n\n\n09\/20\/2016\n7\n\n\n07\/15\/2014\n5\n\n\n\n\nI also already added the 'Price' Column for df2. I need help setting the values in each cell for the 'Price' column to be the price corresponding to the date in df1","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":53,"Q_Id":68355484,"Users Score":0,"Answer":"You can use the map function for the pandas series:\nMap the df2['Ship_Date'] to the values of df1['Price'], and store the mapped series in your 'Price' column of the df2. The mapping argument has to be a pandas series with the index 'Ship_Date'.It can be done by setting the df1 index to the 'Ship_Date' and selecting the 'Price' column.\ndf2['Price'] = df2['Ship_Date'].map(df1.set_index('Ship_Date')['Price'])","Q_Score":0,"Tags":"python,pandas,dataframe","A_Id":68370517,"CreationDate":"2021-07-13T01:38:00.000","Title":"PANDAS: How do a copy a value in pandas from a dataframe to another dataframe based on different cells","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have one table in which I want to convert all the years column into row and one column's row should be converted into columns. Following is the sample table\n\n\n\n\nCity\nSales\n2016\n2017\n2018\n\n\n\n\nA\nX\n100\n120\n160\n\n\nA\nY\n90\n120\n130\n\n\nA\nZ\n130\n160\n190\n\n\nB\nX\n200\n220\n260\n\n\nB\nY\n290\n220\n230\n\n\nB\nZ\n230\n260\n290\n\n\nC\nX\n300\n320\n360\n\n\nC\nY\n390\n320\n330\n\n\nC\nZ\n330\n360\n390\n\n\n\n\nFinal table looks like:\n\n\n\n\nCity\nYear\nX\nY\nZ\n\n\n\n\nA\n2016\n100\n90\n130\n\n\nA\n2017\n120\n120\n160\n\n\nA\n2018\n160\n130\n190\n\n\nB\n2016\n200\n290\n230\n\n\nB\n2017\n220\n220\n260\n\n\nB\n2018\n260\n230\n290\n\n\nC\n2016\n300\n390\n330\n\n\nC\n2017\n320\n320\n360\n\n\nC\n2018\n360\n330\n390","AnswerCount":4,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":221,"Q_Id":68364359,"Users Score":0,"Answer":"This is exactly what I was looking for! However, it worked for some files, but not for others with same structure. Not sure why, probably too many to repeat and pivot. I found that if I sort the data frame by the key fields before pivot, it works for any file. So, in the example above, you would need to sort on at least the key 'City'; in my own work, I sort both fields like 'City' and 'Year' just in case. I thought of this because it's required for SAS proc transpose.","Q_Score":1,"Tags":"python,pandas,dataframe,numpy,backend","A_Id":71595420,"CreationDate":"2021-07-13T14:29:00.000","Title":"Convert some columns into row and one column's rows into columns in python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I knew 'image_dataset_from_directory' is available for tf-nightly, but I'm using GPU to train my data, so I installed tf-nightly-gpu, which seems doesn't support 'image_dataset_from_directory'?\nIs there any way to use 'image_dataset_from_directory' with a gpu version of TF?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":73,"Q_Id":68378811,"Users Score":0,"Answer":"I solved it.\ninstead of using \"from tensorflow.keras.preprocessing.image import image_dataset_from_directory\"\nuse \"from tensorflow.keras.preprocessing import image_dataset_from_directory\"","Q_Score":0,"Tags":"python,tensorflow,keras","A_Id":68379860,"CreationDate":"2021-07-14T13:13:00.000","Title":"ImportError: cannot import name 'image_dataset_from_directory' with TF-nightly-gpu","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I currently have the IVP solver working with an event, which looks like this:\nsol = solve_ivp(fun3, (0, tend), V, method='LSODA', events= event, args=(r_s,), t_eval=t) \nHowever I want the solver to check two event, not one. So I want something like this:\nsol = solve_ivp(fun3, (0, tend), V, method='LSODA', events= (event, event2), args=(r_s,), t_eval=t) \nHowever that doesn't work.\nDoes anybody know how to check for multiple events?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":137,"Q_Id":68381628,"Users Score":0,"Answer":"It works! PyCharm showed a warning, but it actually works","Q_Score":0,"Tags":"python,solver,differential-equations","A_Id":68474540,"CreationDate":"2021-07-14T16:12:00.000","Title":"Multiple events for solve_ivp","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have 2 poses to classify. For each pose i have 60 video samples. But the problem is that the total number of frames in each video are different.\nIn that case, the input to the LSTM will be uneven. Is there any way to solve this? or we need the videos with same number of frames?\nDetail: The inputs are the keypoints which are extracted for each frame. Suppose for each frame the keypoints are 100, then for video with 60 frames, the total keypoints will be 6000. On the other hand for video with 75 frames, the keypoints will be 7500.\nIn first case, (x, y, 6000), in second case (x, y, 7500). BUT the input_shape to the LSTM (or any other NN) should be set constant (say (x, y, 6000)).\nThis is just for two case. I have over 50 videos. How can I solve this problem?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":72,"Q_Id":68405220,"Users Score":0,"Answer":"Zero padding to complement the missing frames can be one of the\nsolution. This will allow the total number of frames per video to be\nuniform for all set of videos.\n\nAnother approach to make the uniform number of frames could be by making multiple\ncopies of the first and last frames and appending them.","Q_Score":0,"Tags":"python,lstm,video-processing,pose-estimation,mediapipe","A_Id":68660274,"CreationDate":"2021-07-16T07:35:00.000","Title":"How to set input to the LSTM ( pose recognition through videos), if my videos are with variable frames?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a CSV file having 100000 rows. COPY_FROM() successfully inserted all the rows into the database table within seconds. But the row order found in database table is not similar to the row order found in the CSV file. Some of the rows in between seems to be shuffled. Did not find any solutions. Please help me out.\nCSV file\n\nR1\nR2\nR3\nR4\n\nPG table\n\nR1\nR3\nR2\nR4","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":59,"Q_Id":68407946,"Users Score":3,"Answer":"That is normal and is to be expected. PostgreSQL inserts the rows wherever it finds room in the table, and when you query the table without ORDER BY, you won't necessarily always get the rows in the same order.\nIf you want your rows ordered, query them with an ORDER BY clause.","Q_Score":0,"Tags":"python,postgresql","A_Id":68408072,"CreationDate":"2021-07-16T11:03:00.000","Title":"Psycopg2 - COPY_FROM does not maintain row order","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using a cv2 rectangle for bounding box purposes and I want to rotate it about its axis by some angle. Since the warpAffine function is used to rotate images, I am unable to use it here.","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":400,"Q_Id":68423495,"Users Score":0,"Answer":"It's already some time I used it, but as far as I remember, all these ROI types are just plain x-y rectangles. No rotation is possible (you can also see from the constructors, there is no way how to define the rotation). So it is always wide along x-axis and high along y-axis.\nIf you want to just draw rectangle, I propose to just determine all four corner points and then by simple lines draw the bounding box. Eventually you can use polylines to do it in one command.","Q_Score":1,"Tags":"python,opencv,computer-vision","A_Id":68423586,"CreationDate":"2021-07-17T19:02:00.000","Title":"How do I change the angle of a cv2 rectangle?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a .pkl file that has looks something like this but has at least 300 rows:\n\n\n\n\nX\nY\nZ\nM\n\n\n\n\n-0.522\n3\n0.55\nYes\n\n\n0.44\n5\nNaN\nNo\n\n\nNaN\nNaN\n0.241\nMaybe\n\n\n0.325\n3\nNan\nYes\n\n\n\n\nI want to get a list of values for Y and M [3 = Yes, 5 = No, 3 = Yes ] but in some of the rows there are NaNs.\nCurrently I am able to get Y without the NaNs\nBut there are no NaNs in M. I need to remove the M values that do not have a Y value. (Y = NaN)\nThen print(Y_no_nans together with M_no_Y_nans)","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":25,"Q_Id":68447195,"Users Score":0,"Answer":"If I'm not mistaken about what you want, you can simply use print(df[[\"Y\",\"M\"]].dropna()).\nIf you wish to remove the NaN from the data altogether, pass an inplace=True argument in the dropna method (df.dropna(inplace=True)).","Q_Score":1,"Tags":"python,concatenation,pickle,nan","A_Id":68447782,"CreationDate":"2021-07-19T21:24:00.000","Title":"Need to write a function that joins two values from two separate columns together of different lengths","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using JupyterLab on a MacOS Big Sur and Chrome browser. Before today I could upload files to JupyterLab and simply \"copy path\" into e.g. pd.read_csv('') and it would be recognized. It will recognize the path to a file on my desktop but not a file uploaded to JupyterLab. I would appreciate any help","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":1687,"Q_Id":68447535,"Users Score":0,"Answer":"I use the exact same setup. Jupyter Lab opens in Chrome, but it uses files from your local directories. Therefore files aren't uploaded. If you copy path directly from Jupyter it will give you the relative path. If you need the absolute path you have to find the file in your local directory.","Q_Score":1,"Tags":"python,jupyter-lab","A_Id":68447652,"CreationDate":"2021-07-19T22:11:00.000","Title":"JupyterLab Error FileNotFoundError: [Errno 2] No such file or directory","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":1,"Web Development":0},{"Question":"I created a column out of the values of other two columns. However, the problems is that there are undesired white spaces at the end and beginning of many values of the column for example:\n\" Hernandez\"\n\"Martinez \"\n\"Gutierrez Romero\" (This one is actually a desired white-space case)\nI can not simply get rid of all the white spaces because there are some white spaces that need to be there like in the case of \"Gutierrez Romero\" I was wondering if anybody can help me to fix this problems thanks","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":51,"Q_Id":68450079,"Users Score":0,"Answer":"So I have actually found the answer, but thanks for the help!\ndata_frame_trimmed = dataset.apply(lambda x: x.str.strip() if x.dtype == \"object\" else x)","Q_Score":0,"Tags":"python,pandas,whitespace,data-cleaning,removing-whitespace","A_Id":68450567,"CreationDate":"2021-07-20T05:47:00.000","Title":"Getting rid of specific white spaces at the beginning and end of string","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"For re-training a model it is useful to know the hyperparameters of the elder model. It could give us a starting point. I have a .h5 keras model where I want to extract some hyperparameters like Batch_size and number of epochs. I have tried model.summary() but doesn't give the necessary information and also model.get_config().\nIs there any way to extract these hyperparameters of the Keras model?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":117,"Q_Id":68451364,"Users Score":0,"Answer":"If you want to get all hyperparameters of optimizer, please do:\nmodel.optimizer.get_config()\nIf you want to get all hyperparameters of layers, please do:\nmodel.get_config()","Q_Score":0,"Tags":"python,tensorflow,keras,hyperparameters","A_Id":70234556,"CreationDate":"2021-07-20T07:52:00.000","Title":"Extract hyperparameters from a trained Keras model","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"When we train an XGB model using AWS built-in models\ne.g. (container = sagemaker.image_uris.retrieve(\"xgboost\", region, \"1.2-1\")),\nBased on my understanding, The training job requires numerical vectors for the train and validation.\nMeaning that if you have a dataset with categorical values and strings, you need to convert them into a vector. the model only deals with float numbers,\n(Outside Sagemaker, I can use TFIDF to vectorize my features and construct a DMatrix), but this approach doesn't seem to be supported by Sagemaker.\n\nDoes anyone know how this data transformation is done in Sagemaker?\nIs this a bad idea to use BlazyngText unsupervised learning to generate the vectors?\nShould we have a preprocessing step and in that step we use TFIDF?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":91,"Q_Id":68470428,"Users Score":0,"Answer":"Ok, after pulling my hair for a while, we built a solution as below:\nOn the preprocessing step, we used TFIDF to vectorize categorical values and then stored the data into S3.\nOn the training step, we read that training input and fed it into the XGB estimator.","Q_Score":0,"Tags":"python,vectorization,xgboost,amazon-sagemaker","A_Id":69297892,"CreationDate":"2021-07-21T13:30:00.000","Title":"Vectorising categorical dataset for XGBoost in Sagemaker","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm using pandas to manage some data frames.\nIn every tutorial I've seen so far, they import both numpy and pandas when working with pandas so I imported both.\nI also recently installed flake8 linter, and its giving me the following message:\nnumpy as np imported but not used\nDo both packages need to run together or can I delete that Numpy?","AnswerCount":3,"Available Count":3,"Score":1.2,"is_accepted":true,"ViewCount":407,"Q_Id":68475687,"Users Score":4,"Answer":"No, you do not need to import numpy for pandas to function properly. Most tutorials use numpy for some computations which is why it is imported. Otherwise, pandas is self sufficient.","Q_Score":1,"Tags":"python,pandas,numpy,flake8,linter","A_Id":68475731,"CreationDate":"2021-07-21T19:51:00.000","Title":"Do I need to import Numpy to use Pandas?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm using pandas to manage some data frames.\nIn every tutorial I've seen so far, they import both numpy and pandas when working with pandas so I imported both.\nI also recently installed flake8 linter, and its giving me the following message:\nnumpy as np imported but not used\nDo both packages need to run together or can I delete that Numpy?","AnswerCount":3,"Available Count":3,"Score":0.1325487884,"is_accepted":false,"ViewCount":407,"Q_Id":68475687,"Users Score":2,"Answer":"The answer is NO, numpy and pandas are not strictly bound.\nSometimes you need the help of numpy to do some special works, like computations, that's why you may need to import and use.\nBut to work with pandas, numpy is not mandatory.","Q_Score":1,"Tags":"python,pandas,numpy,flake8,linter","A_Id":68475741,"CreationDate":"2021-07-21T19:51:00.000","Title":"Do I need to import Numpy to use Pandas?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm using pandas to manage some data frames.\nIn every tutorial I've seen so far, they import both numpy and pandas when working with pandas so I imported both.\nI also recently installed flake8 linter, and its giving me the following message:\nnumpy as np imported but not used\nDo both packages need to run together or can I delete that Numpy?","AnswerCount":3,"Available Count":3,"Score":0.1325487884,"is_accepted":false,"ViewCount":407,"Q_Id":68475687,"Users Score":2,"Answer":"You don't have to import numpy. Numpy and pandas are two different packages. They are both powerful libraries to edit data efficiently, and they are working together pretty good. This is why people use them together. But this does not mean you have to import both.\nStill, do not remove numpy, since pandas depends numpy for some internal operations.","Q_Score":1,"Tags":"python,pandas,numpy,flake8,linter","A_Id":68475751,"CreationDate":"2021-07-21T19:51:00.000","Title":"Do I need to import Numpy to use Pandas?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have elementary knowledge on package managers, so forgive me if my question is phrased badly.\nI am using miniconda as a package manager. I have python 3.8 installed, and I use jupyter lab to run ipython kernels.\nMy issue is that when import torch then the version 1.7.1 is loaded to the notebook, however, when I look at conda list I see that version 1.8.1 of torch is installed.\nWhen I try to update using conda update --all and conda update pytorch nothing is being installed.\nSo\n\nI don't know why pytorch is not updated to the new version of 1.9.\nI don't know why an older version 1.7.1 is loaded to my jupyter notebook.\n\nwould love to get some help!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":263,"Q_Id":68482586,"Users Score":0,"Answer":"I am not sure exactly what solved it, but:\nI updated homebrew which required me to install some command line tools of x-code, and then I managed to install pytorch again using\nconda install pytorch torchvision -c pytorch.\nNow the proper version is loaded when I use jupyter.","Q_Score":0,"Tags":"python,conda,jupyter-lab","A_Id":68483156,"CreationDate":"2021-07-22T09:39:00.000","Title":"jupyter runs an old pytorch version","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have to work on task of using hand keypoints as pointer (or touchless mouse).\nThe main problem here is that the (deep learning) hand keypoints are not perfect (sometime under varied of light, skin colors), therefore the chosen key point are scattering, not smoothly moving like the real mouse we use.\nHow can I smooth them online (in real-time). Not the solution given array of 2D points and then we smooth on this array. This is the case of new point get in one by one and we have to correct them immediately! to avoid user suffer the scattering mouse.\nI'm using opencv and python. Please be nice since I'm new to Computer Vision.\nThanks","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":174,"Q_Id":68496749,"Users Score":0,"Answer":"Since you want a physics like behavior, you can use a simple physics model. Note all arrays below describe properties of the current state of your dynamics and therefore have the same shape (1, 2).\n\ndefine forces\na:attraction = (k - p) * scaler\n\nvelocity\nv:velocity = v + a\n\npositions\np:current position = p + v\nk:new dl key point = whatever your dl outputs\n\n\nYou output p to the user. Note, If you want a more natural motion, you can play with the scaler or add additional forces (like a) to v.\nAlso, to get all points, concatenate p to ps where ps.shape = (n, 2).","Q_Score":1,"Tags":"python,opencv,computer-vision,object-detection","A_Id":68608241,"CreationDate":"2021-07-23T09:06:00.000","Title":"Smoothing 2D points (scattered) in real-time (online smoothing)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have been dealing with this much too long. I am using a MacBook Pro. This suddenly started happening when running Jupyter. I could not fix it. I completely uninstalled anaconda (which was using Python3.8) then completely uninstalled Python3.9. I installed Python3.96. Then went back to basics and reinstalled numpy, pandas, sklearn. Everything seems to be there in \/Library\/Frameworks\/Python.framework\/Versions\/3.9\/lib\/python3.9\/site-packages\nThis command fails in IDLE and gives the error in the title of my question.\nfrom sklearn.model_selection import train_test_split\nIt does not give the error in Mac's Terminal\nThe search path for IDLE looks correct.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":456,"Q_Id":68502755,"Users Score":0,"Answer":"So after a few weeks of simply using Googles Colab I did the following. Purchased App Cleaner and Uninstaller for Mac and got rid of all Python related apps that I do not need any more after moving to Colab and Kaggle's API. Removed and reinstalled Python. Ran the Idle program again and it worked! Yay!. The problem started while using Jupiter with Anaconda. Just randomly appeared. When I decided to work on it again yesterday I thought it might have been some malware on my Mac. The reason I thought it was malware is that the Idle message was giving me the message that sklearn was not a package and it could not find train_test split - even when I asked for another sklearn module - e.g. datasets. It always referred to train_test_split even when I did not request it. Hence the cleanup of my Mac (everything Python related and more). It's all good now.","Q_Score":0,"Tags":"python,scikit-learn","A_Id":68759944,"CreationDate":"2021-07-23T17:00:00.000","Title":"ModuleNotFoundError: No module named 'sklearn.model_selection'; 'sklearn' is not a package","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I used t-SNE to reduce the dimensionality of my data set from 18 to 2, then I used kmeans to cluster the 2D data points.\nUsing this, print(kmeans.cluster_centers_)\nI now have an array of the 2D centroids of the clusters, but I want to get the 18D original data points that these centroids corresponds.\nIs there a way to work t-SNE backwards? Thanks!","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":96,"Q_Id":68512127,"Users Score":0,"Answer":"Unfortunately the answer is no, there is not.\nt-SNE computes a nonlinear mapping of each point individually, based on probability theory. It does not provide a continuously defined function nor its inverse.\nYou could try to interpolate the 18D coordinates based on the cluster members.\nIn general you might revisit how much sense it really makes to run k-means on a t-SNE result.","Q_Score":0,"Tags":"python,k-means,tsne","A_Id":68512190,"CreationDate":"2021-07-24T17:03:00.000","Title":"How to use tSNE and kmeans centroids to find the original data points the centroids correspond to?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am studying data analyzing and data science recently.\nWhen I preprocess the money data(amount of money), I routinely use 'log' to lower the scale and normalize. However, there are some scalers in python like 'StandardScaler', 'Normalizer', 'MinScaler' and etc. I wonder when should I use log method and StandardScaler\/Normalizer to scale data.\nI have thought about this question and understand like below.\n\nlog scale lowers size and normalize data, but doesn't make the perfect Nomal distribution. Mostly used in monetary data.\n\nStandardScaler makes the data perfect Normal distribution\n\nI have to use Normalizer when I have different measure features together(like distance, dollars, weight etc). Use this to preprocess features in one scoop.\n\n\nAm I understanding it right?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":117,"Q_Id":68517986,"Users Score":0,"Answer":"Yes you are right\nNo, not necessarily it makes data normally distributed but it makes all data unit free and within same location and scale i.e. mean 0 and variance 1. Therefore, many algorithms that are based on distance measures do not get more affected by high variance variable like house price as opposed to low variance variable like interest rate in a National Revenue model.\nBy normalizer if you meant scaling then yes\n\nHowever, For tree based algorithms or any algorithm that do not use distances measures the scaling is not required","Q_Score":0,"Tags":"python,statistics,data-analysis,normalization,preprocessor","A_Id":68520541,"CreationDate":"2021-07-25T11:14:00.000","Title":"when should I use log scaling and standard scaling in python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"Is it possibile to import a path that is in .svg format into a plot in bokeh. If someone could give me a north that would be great, because so far my research did not encounter much information about the subject.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":52,"Q_Id":68522107,"Users Score":0,"Answer":"No such API exists as of Bokeh 2.3.3 and I'm not aware of any issue regarding it, either (AFAIK you are the first person to ask about it).","Q_Score":0,"Tags":"python,svg,plot,jupyter-notebook,bokeh","A_Id":68533372,"CreationDate":"2021-07-25T19:59:00.000","Title":"Add .svg into a plot in bokeh","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a Model class that has functions to train and predict using a machine learning model.\nBecause the data used for training is normalized, the predictions are also normalized and hence need to be inversely transformed.\nShould the function inverseTransform be part of the Model class as a staticmethod or should it be outside the class?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":23,"Q_Id":68524118,"Users Score":0,"Answer":"It worked for me to have it outside the model class","Q_Score":0,"Tags":"python","A_Id":68524174,"CreationDate":"2021-07-26T03:15:00.000","Title":"Should inverseTransform be a static method for a model making predictions","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"The question is very simple but don't know how to implement it in practice. I would like to train a tensorflow LSTM model with the dataset, which is incredible large (50 millions records). I am able to load the data file to a local machine but the machine crash during the pre-processing stage due to limited memory. I have tried to del un-used files and garbage collection to free the memory but it does not help.\nIs there any way, I can train a tensorflow model separately for example, the model will be train 5 times, each time only use 10 million records and then delete 10 million records after training to free the memory ram. The same procedure will be repeated for 5 times to train a tensorflow model.\nThanks","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":141,"Q_Id":68534132,"Users Score":2,"Answer":"There are some ways to avoid these problems:\n1- You can use google colab and high-RAM in runtime or any other Rent a VM in the cloud.\n2- The three basic software techniques for handling too much data: compression, chunking, and indexing.","Q_Score":0,"Tags":"python,tensorflow,machine-learning,data-science","A_Id":68643899,"CreationDate":"2021-07-26T17:25:00.000","Title":"How to train a model with BIG data size and limited memory ram?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"hi we operate a chiller (for air-conditioning) in a few buildings in our city, the way we operate is we turn the chiller on at 9am (the building opens at 10 am) for precooling and add another chiller after 15 minutes, and add another one if needed on the next 15 minutes, this practice has been done a for a very long time. we have all sorts of data from the chiller itself, the pump, cooling tower, the building temperature as well as the weather. I want to know if the 15 minutes is just right or it can be delayed lets say 20,25 or 30 minutes (as it will have effect on energy savings) using a python program or machine learning algorithm. thank you","AnswerCount":1,"Available Count":1,"Score":-0.1973753202,"is_accepted":false,"ViewCount":40,"Q_Id":68538260,"Users Score":-1,"Answer":"I guess you have to clarify what you is your priority.\nWould you like to keep the temperature at 21C since 9:50AM at the lowest cost?\nIt might depend of the morning temperature how much time you need to start in advance your chillers.\nOn the other hand you might need to keep the temperature below 25C at any time because of regulations.\nI guess the amount of chiller running will depend on the outside temperature and the amount of people in the building.\nMaybe your power price is variable during the day.\nSure you can have some AI algorithm to estimate the cheapest operation but you will have to put all the data in there and you could probably start with no prediction algorithm at all and using a temperature weather forecast and a projected occupancy.","Q_Score":0,"Tags":"python,machine-learning","A_Id":68538310,"CreationDate":"2021-07-27T02:31:00.000","Title":"Optimization of operation using python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I would like to see if someone can help me with a problem on optimising an emissions model, to essentially change the input conditions to match measured outputs.\nThe issue is the following. I have the following model data:\n\n\n\n\nTreatment group\n# of animals\nTreatment efficiency\nModel emissions\n\n\n\n\nControl\n110\n1\n110\n\n\nA\n88\n0.5\n44\n\n\nB\n22\n0.25\n5.5\n\n\n\n\nThe model predicts emissions from a barn with a set number of animals in it. In this case, there are 220 animals and the predicted TOTAL emissions are 159.5 units. Each animal emits 1 unit of emissions, unless the treatment applied reduces emissions by a set fraction, as indicated in the treatment efficiency for groups A and B.\nHowever, experimental measurements show TOTAL emissions to be 13.5 higher at 173.0\nFrom known information, we can confirm that the number of animals is definitely 220 and treatment efficiency is not in doubt. Therefore, the only variable that can explain this is that animals are not assigned to treatment groups as they are in the model. If more animals are part of the control group and less part of treatment groups A and B, then the emissions will go up and can approach the correct measured value.\nI am not very well versed in math, and too often I ran into things like this which ended up having more simple solutions. But my original model is in Excel and I don't think there is a way to do this with simple formulas. It feels like an optimisation problem to me. For example, if I add the 13.5 emissions to the control group, bringing total emissions to 123.5 for control and total emissions to the correct 173.0, then the number of animals in the control group has to become 123.5, to make sure emissions from the control group return to the max of 1 per animal. We can only get there by moving animals from groups A and B.\nI do this once under the constraint that animals have to be moved proportionally to treatment efficiency. This results in the following table after 1 iteration, moving 10.8 animal from group A and 2.7 (lets assume we can split up animals for the moment):\n\n\n\n\nTreatment group\n# of animals\nTreatment efficiency\nModel emissions\nEmission per animal\n\n\n\n\nControl\n123.5\n1\n123.5\n1\n\n\nA\n77.2\n0.5\n38.6\n0.56\n\n\nB\n19.3\n0.25\n3.825\n0.28\n\n\n\n\nNow, with the same number of animals, total emissions are 166.9. Closer to the observed value of 173.0. I can continue doing this and assume would approach to the right distribution of animals.\nNote that my real life problem is bigger than this, with up to 5 treatment groups and I have to repeat this for about 120 different setups of animals and treatment efficiencies. Hence I would like to automate this to find a way to optimise it towards the new correct distribution of animals. I think this can be done given we add the constraints:\n\nConstraint #1: Number of animals in treatment groups can only change proportionally.\n\nI assume without this constraint there is an infinite number of solutions.\n\nConstraint #2: If observed emissions are higher than modelled emissions, number of animals in the control group can't decrease.\n\nI think that is impossible for this to even happen with constraint #1 so this constraint may be superfluous, but in my real life problem this is the case so I added it anyway. There are no cases in my problem where observed emissions are lower than modelled emissions.\nI added R and python to this as those are the programming languages I know, though I haven't used it like this before for an optimisation problem so I would not really know where to start. Can anyone give any pointers?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":44,"Q_Id":68541263,"Users Score":0,"Answer":"Ok, I think this can be closed. Some more inspection revealed that this problem can be represented as a system of linear equations, which is then easy to solve using matrix notation. No need for any optimisation code as there is no nonlinear behaviour in this problem.","Q_Score":0,"Tags":"python,r,math,optimization,model","A_Id":68581326,"CreationDate":"2021-07-27T08:18:00.000","Title":"Possible solution to suspected optimisation problem in python or R for animal emissions","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Hi I am trying to upload a zip archive of required libraries to run my project on AWS Lambda. Since the size of the zipped PyTorch library exceeds the size limit of AWS Lambda, I am looking to decrease the number of files I upload from the library.\nI have a trained neural network and I need PyTorch just to carry out the inference on Lambda.\nIs there a list of files that I can delete from the package? Is there a way to identify these files?\nThanks in advance :)","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":71,"Q_Id":68547647,"Users Score":0,"Answer":"a walk around would be using Lambda support for EFS. You could prestage your dependencies to a folder structure in EFS and then point the lambda to run there. You should then be able to import the pytorch and any other packages you place as subdirectories under the working directory.","Q_Score":0,"Tags":"python,amazon-web-services,aws-lambda,neural-network,pytorch","A_Id":68547693,"CreationDate":"2021-07-27T15:24:00.000","Title":"Is there a way to delete unused files from PyTorch to run a light version of it?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm working on a really sparse multilabel classification problem, with 1000 labels to make predictions on, and on average very few labels would be active. Around 5 would be the median positive labels per image.\nI tried to use BCEWithLogitsLoss, but the results weren't great irrespective with different weights, however even with pos weight set as 10, 100, 300, 1000, 3000, the results were terrible, and the highest f1 score requires a high threshold, near 0.95, though while training the threshold is 0.5 post sigmoid activation. The highest f1 I was able to achieve is around 0.3, and the top 5 recall is around .22.\nI also tried to use pos_weight = (Number of negative examples)\/(Number of positive examples).\nHowever none of these seem to work.\nThe issue is that the loss converges with these parameters, when there is still room for improvement.\nI was wondering if there's more robust loss functions for such Imbalanced data. I was also looking at Focal Loss, NLL loss, Label Smoothing, but I don't know if they would work well for my problem. Any help would be much appreciated!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":185,"Q_Id":68560135,"Users Score":0,"Answer":"I solved it finally by taking the reciprocal of pos_weight instead of the one I mentioned in the question, like so:\npos_weight = (Number of positive examples)\/(Number of negative examples).\nAlso used a little trick (by setting weight to 10000), to scale up the loss function, so that it does not show up as 0 (It has a tendency to do this)\nTo be honest I have no clue why this worked, and might be specific to my usecase, but hey atleast it works.","Q_Score":0,"Tags":"python,tensorflow,pytorch,loss-function,multilabel-classification","A_Id":68939537,"CreationDate":"2021-07-28T12:08:00.000","Title":"What loss function should be used for sparse multilabel Image Classification pytorch","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working on a Pandas dataframe in Python. Whenever I want to calculate something, I need to type the entire dataframe name and the column name like dataframe_name.column_name. Previously I worked on R, where we can attach the dataframe using attach(dataframe_name). Is there anything like that we can do in Python Pandas library?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":45,"Q_Id":68575569,"Users Score":0,"Answer":"Just write dataframe_name['new_column_name']=... and new column will be added.","Q_Score":0,"Tags":"python,pandas","A_Id":68575641,"CreationDate":"2021-07-29T12:03:00.000","Title":"How to attach a dataframe in Python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a list including some names, as example:\ndata_set_names=['matrix_1','matrix_2','matrix_3'].\nInside a loop, I want to use each of these names for storing the output of some computations, which are as NumPy array. I highly appreciate if someone could tell me how to do that. As I looked it up online, exec() function can be used to convert a string to a variable name, but in my case, it is not useful.","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":204,"Q_Id":68589469,"Users Score":1,"Answer":"You can use the dictionary of str\/numpyArray","Q_Score":0,"Tags":"python,string,numpy-ndarray,data-conversion","A_Id":68589554,"CreationDate":"2021-07-30T10:30:00.000","Title":"Using a string as a name for a numpy array","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using Python 3.9 on Windows 10 which I downloaded directly from the Microsoft Store.\nI tried running a script in PowerShell: Bash *.sh\nThis script is supposed to tell my computer to execute a .py script which uses scipy.io and many other modules.\nThen I received this error:\n\nModuleNotFoundError: No module named 'scipy'\n\nMy strategy was to make sure pip was up to date, then use it to install the desired packages, then run some commands to see if the packages were installed.\nI ran this command to update pip:\npython3 -m pip install --upgrade pip\nI ran this command to get some modules:\npython -m pip install --user numpy scipy matplotlib ipython jupyter pandas sympy nose\nI also tried this command just in case:\npip install scipy\nand got the result:\n\nRequirement already satisfied ...\n\nI ran the command pip list to make sure scipy was in the list (and it was there).\nThen I ran the command python and my prompt changed to \">>>\" and entered import scipy and did not receive any errors.\nI am very confused as to how I have scipy installed yet have my script tell me it isn't there. Please help!","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":240,"Q_Id":68595731,"Users Score":0,"Answer":"I had the same issue. You might have multiple versions of python and you only installed scipy on the one you are not using\nOR\nyou are using an IDE which has the option to use packages you install that are not by default in python. Pycharm has that. When you make a new project, it has a tick option saying \"Inherit global site-packages\" which means it will use additional packages you have installed any.","Q_Score":0,"Tags":"python,powershell,pip,scipy","A_Id":68595879,"CreationDate":"2021-07-30T18:37:00.000","Title":"Why do I receive a \"no module named scipy\" error even after I have installed the module via pip?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to get the elements in an ndarray that are strings. That is, exclude the elements that are integers and floats.\nLets say I have this array:\nx = np.array([1,'hello',2,'world'])\nI want it to return:\narray(['hello','world'],dtype = object)\nI've tried doing np.where(x == np.str_) to get the indices where that condition is true, but it's not working.\nAny help is much appreciated.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":77,"Q_Id":68595929,"Users Score":0,"Answer":"When you run x = np.array([1,'hello',2,'world']), numpy converts everything to string type.\nIf it is one dimensional array, you can use:\ny = np.array([i for i in x if not i.replace(\".\",\"\",1).replace(\"e+\",\"\").replace(\"e-\",\"\").replace(\"-\",\"\").isnumeric()])\nto get all non-numeric values.\nIt can identify all floats with negative sign and and e+\/e- )\nlike, for input: x = np.array([1,'hello',+2e-50,'world', 2e+50,-2, 3\/4, 6.5 , \"!\"])\noutput will be : array(['hello', 'world', '!'], dtype=' \n\n\nActivate the environment\n\n\nsource \/bin\/activate\n\n\nInstall numpy and scipy\n\n\npip3 install numpy \npip3 install scipy","Q_Score":14,"Tags":"python,scikit-learn,scipy,apple-m1","A_Id":69783449,"CreationDate":"2021-08-02T11:37:00.000","Title":"Installing scipy and scikit-learn on apple m1","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have to calculate number of days when temperature was more than 32 degree C, in last 30 days.\nI am try use rolling average. The issue is that number of days in a month varies.\nweather_2['highTemp_days'] = weather_2.groupby(['date','station'])['over32'].apply(lambda x: x.rolling(len('month')).sum())\nweather_2 has 66 stations\ndate varies from 1950 to 2020\nover32 is boolean data. If temp on that date is > 32 then 1 otherwise zero.\nmonth is taken from the date data which is weather_2['month'] = weather_2['date'].dt.month","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":22,"Q_Id":68623643,"Users Score":0,"Answer":"I used this\nweather_2['highTemp_days'] = weather_2.groupby(['year','station'])['over32'].apply(lambda x: x.rolling(30).sum())\nThis issue was I was grouping by date. That is why the answer was wrong.","Q_Score":0,"Tags":"python,lambda,group-by,rolling-computation,temp","A_Id":68623856,"CreationDate":"2021-08-02T14:48:00.000","Title":"Calculating rolling on a mixed date using groupby","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I almost completed my project but need some help. Let me summarize what I have already done. I exported a CSV file from ESXI, and using Python, I make several calculations and created a pie chart of these values. Here I have one result for calculation and the pie chart. Currently, I want to write these results to CSV simultaneously. How can I do that? As you know, pandas only display pie charts on different windows. I want to save that chart on CSV.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":50,"Q_Id":68633037,"Users Score":1,"Answer":"A pie chart is just a type of data visualization. I guess you are already using a dataframe to display this using plt.show().if you want to save that chart,\nyou could combine data,labels,colors to dataframe and save it as a csv. In order to save as csv: df.to_csv(file_name, sep='\\t')","Q_Score":1,"Tags":"python","A_Id":68633512,"CreationDate":"2021-08-03T08:53:00.000","Title":"copy created pie chart and calculated values to csv file","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have one data frame in python. How can I calculate the 3sigma value for each column of my data frame using python? please help me with this.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":236,"Q_Id":68640003,"Users Score":1,"Answer":"The command you're looking for is df.std() * 3","Q_Score":0,"Tags":"python,statistics,analysis","A_Id":68640258,"CreationDate":"2021-08-03T16:54:00.000","Title":"Calculate the 3 sigma value using python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have some problems with clustering method, that is K-Means\nI want to cluster a new data with latitude and longitude coordinates. But before that, I have set the cluster center myself, with the existing data. Can anyone explain in python code how to input cluster center data into kmeans method without doing a fit to kmeans?\nbecause when the existing data is fit to kmeans, the center of the cluster will change, so the new data will be based on the new cluster center obtained from the fitting results.\nThanks for your attention","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":61,"Q_Id":68646702,"Users Score":0,"Answer":"It would be easier to just implement the kmeans prediction algorithm. Do you specifically need to use sklearn kmeans? After fitting you should be able to change the model.cluster_centers_ but you would not be able to control the labels.","Q_Score":0,"Tags":"python,cluster-computing,center,k-means,centroid","A_Id":68648364,"CreationDate":"2021-08-04T06:57:00.000","Title":"How to input or determine cluster center in k-means python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have built (model.compile()) a Neural Network model using Keras. Then I have fitted the model (model.fit()) using my train data. Finally, I am using the model to predict (model.predict()) the values of the test data.\nBased on my understanding, in the process of fitting the model, the weights of the neurons of the network are being updated in each batch. Is this still the case, when predicting? Do the weights of the neural network get updated for each batch when predicting? Is there a possibility to switch this option on and off? I am running two analyses and in the first one, I would like the weights not to update when predicting but in the other one I would like the weights to update for each batch.","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":54,"Q_Id":68649021,"Users Score":0,"Answer":"Weights do not update when predicting, only when training and hence only for Model.fit","Q_Score":0,"Tags":"python,tensorflow,machine-learning,keras,neural-network","A_Id":68649173,"CreationDate":"2021-08-04T09:43:00.000","Title":"Keras predicting and updating the neuron weights at the same time","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I used auto_arima function with seasonality to forecast covid19 and got ARIMA(0,1,1)(2,0,2)\nCan anyone explain me the reason for each parameter (p,d,q)(P,D,Q)?\n(Ex: why AR is 0 meanwhile SAR is 2)","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":49,"Q_Id":68662207,"Users Score":0,"Answer":"For Samira is decompose (p,d,q) and (P, D, Q) with the seasonal.\nAR(0) or p = 1.\nThe time serie does not depend on time spent.\nd = 1\ncov(Xt, Xt-1) = No Constant.\nThe serie is stationnary with one differentiable.\nYt = Xt - Xt-1\ncov(Xt, Yt) = Constant\nAM(1). The times serie depend a one random evenement.\nidem for seasonal.\nFor exemple (P,D,Q)12 months, you have for every year.\nP = 2\nThe time serie by Years(month) depend Year-1(month) and Year-2(month).\nWith july, you have July 2021 depend July 2020 and July 2019 but with AR(0) July 2021 not depend of June\nD = 0 The procesus is stationnary.\ncov(month 2021, month 2020) = constant for every months.\nQ = 2\nThe time serie depend a random event with mean equal 0 (Noise white), exemple :\nJuly 2021 depend event at July 2020 and July 2019, and for all month you have month 2021 depend event same month 2020 and same month 2019.\nBest regard,","Q_Score":0,"Tags":"python,arima,pmdarima","A_Id":68662734,"CreationDate":"2021-08-05T07:18:00.000","Title":"Can anyone explain the number for each parameter in SARIMA?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a 2d array of shape (512,512). I need to convert this to shape (512,512,3). All values of 2d dimension will be repeated on other two dims. How can I do this in python?","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":39,"Q_Id":68664341,"Users Score":1,"Answer":"I would use array[..., None].repeat(3, -1)","Q_Score":0,"Tags":"python,numpy","A_Id":68664632,"CreationDate":"2021-08-05T09:51:00.000","Title":"Converting 2D array into 3D by repeating same layer 3 times","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I would like to warp one fisheye image:\nLeft:\nInto this target image:\nThe target image is actually a part of the synthetic panorama:\nI know a method called mesh warping, like:\nBut how am I able to find or define a irregular mesh like this? Very grateful if someone can give me some suggestions. I would like to have this mesh, so that I can use this mesh for every frame of a video and warp every frame into this target image.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":224,"Q_Id":68669766,"Users Score":0,"Answer":"Is this a one-off project, or are you trying to write an automatic procedure?\nIf the former, you can just hand-tag corresponding points in the two images till you have enough coverage, particularly in the more \"curvy\" areas, then warp using (for example) a thin-plate spline defined by the point correspondences. This works iteratively: match some points, warp, figure out where the error is largest, add more point matches there. Doing all this in, say, Matlab or Python+OpenCv is quite easy.\nYou can then try to automate it using feature extraction and matching. The trouble is you'll need to use both point and line correspondences...","Q_Score":0,"Tags":"python,opencv,image-processing,graphics,warp","A_Id":68674621,"CreationDate":"2021-08-05T15:49:00.000","Title":"Image warping using mesh","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":1,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Is it necessary to convert tensors and models to CUDA with tensor.to in colab when I've chosen runtime type as GPU?\nI want use CUDA for training my model","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":118,"Q_Id":68670817,"Users Score":1,"Answer":"tensor.to(device) transfer data to the given device.\nYes, you need to transfer model, input, labels etc to whatever device you are intending to use","Q_Score":0,"Tags":"python,pytorch,google-colaboratory","A_Id":69101736,"CreationDate":"2021-08-05T17:06:00.000","Title":"Using CUDA in Colab","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"is the pdf of the normal distribution. To approximate the cdf:\n( \u2264 ) \u2248 [() + \u22ef + ( \u2212 2) + ( \u2212 ) + ()],\ne.g. \u03b1 = 0.01, a = -100 and k = 0, then the summation is\n( \u2264 0) \u2248 0.01[(\u2212100) + \u22ef + (\u22120.02) + (\u22120.01) + (0)]\nThe accuracy of the approximation increases with the decrease of the step range \u03b1. That means, the smaller the step width is, the more terms we can put between a and k, and the more accurate is the probability.\nDesign a python program to compute P(X \u2264 k). I am not very clear how the iteration works like what is after ()? What is in the ...","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":216,"Q_Id":68670842,"Users Score":0,"Answer":"It seems like a test question, so I don't want to write down the code here. However, let me give you some tips:\n-Generate a numpy array from a to k with step alpha (with np.arange or np.linspace).\n-Compute f(x) ofthis array\n-Add all the values (with np.sum) and multiply it by alpha.","Q_Score":0,"Tags":"python,math,normal-distribution,cdf","A_Id":68681900,"CreationDate":"2021-08-05T17:08:00.000","Title":"Approximute cumulative distribution function (CDF) by the weighted sum of the density function","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to use a model.h5 (witch I created on python3,tensorflow2) on a node on ROS kinetic (ubuntu 16.04) to predict the steering angle of a turtlebot3 (running on gazebo7) after receiving a frame\/image. The incompatibility of ROS with any other python versions takes me to a deadend since I tried everything I could think of. I tried installing a venv of python 3, but as soon as I change the python alternative or the script's python version ROS won't run and none of the other possible solutions that I found online worked for me.\nThanks in advance!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":117,"Q_Id":68691568,"Users Score":0,"Answer":"You won't be able to run a ros node with Python3 under Kinetic. As mentioned in a comment Noetic would be your best option if you need Python3, however, you cannot run Noetic on 16.04; it would need to be 20.04. If both python3 and Kinetic\/16.04 nodes are absolutely needed you'll have to use another way to communicate. The best way to do this is most likely abstracting out the ros parts from your python3 scripts and having it communicate via TCP\/UDP socket.","Q_Score":0,"Tags":"python,python-3.x,ubuntu-16.04,ros,tensorflow2","A_Id":68718323,"CreationDate":"2021-08-07T10:35:00.000","Title":"Trying to create a ROS Kinetic Node which depends on python 3.6 but Kinetic supports only python version 2","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"What is the equivalent of the options start_dim and end_dim of the flatten PyTorch layers, in Tensorflow?\nWith Tensorlfow we only have data_format and it is not customizable.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":155,"Q_Id":68691960,"Users Score":1,"Answer":"I don't think there is an identical implementation in tf. However, you can always use tf.reshape and add the shape yourself with a simple function which takes as arguments input, start_dim and end_dim and outputs the corresponding output shape that torch.flatten would give you.","Q_Score":2,"Tags":"python,tensorflow,pytorch,flatten","A_Id":68692261,"CreationDate":"2021-08-07T11:27:00.000","Title":"Convert Flatten layer from PyTorch to Tensorflow - Equivalent for start_dim and end_dim","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"(my environment is vs code using pylance)\nFor example, arrays returned from train_test_split() or LinearRegression.predict() are not recognized as an array and do not offer any autocomplete suggestions. In google colab and spyder after typing my_returned_array., I get a long list of available array functions, but in VS code with pylance I get nothing.\nIs there some additional configuration I need to do or is there some other extension I need to use?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":100,"Q_Id":68692778,"Users Score":0,"Answer":"Google Colab and Spyder maintain the state of all variables as parts of the program are run. VS Code does a similar thing with the Jupyter Notebooks extension while running in debug mode, allowing me to explore the states of variables, but pylance doesn't seem to pick up state information from the Jupyter notebook. While this would be a wonderful feature, it is not a necessary behavior.","Q_Score":0,"Tags":"python,visual-studio-code,pylance","A_Id":68713665,"CreationDate":"2021-08-07T13:25:00.000","Title":"Intellisense not recognizing variables returned by sklearn as array type","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm new to the computer vision world, I'm trying to create a script with the objective to gather data from a dataset of images.\nI'm interested in what kind of objects are in those images and getting a summary of them in a json file for every image.\nI've checked out some YOLO implementations but the ones I've seen are almost always based on COCO and have 80 classes or have a custom dataset.\nI've seen that there are algorithms like InceptionV3 etc. which are capable of classifying 1000 classes. But per my understanding object classification is different from object recognition.\nIs there a way to use those big dataset classification algos for object detection?\nOr any other suggestion?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":263,"Q_Id":68694379,"Users Score":0,"Answer":"First, to level set on terminology.\nImage Classification based neural networks, such as Inception and Resnet, classify an entire image based upon the classes the network was trained on. So if the image has a dog, then the classifier will most likely return the class dog with a higher confidence score as compared to the other classes the network was trained on. To train a network such as this, it's simple enough to group the same class images (all images with a dog) into folders as inputs. ImageNet and Pascal VOC are examples of public labeled datasets for Image Classification.\nObject Detection based neural networks on the other hand, such as SSD and Yolo, will return a set of coordinates that indicate a bounding box and confident score for each class (object) that is detected based upon what the network was trained with. To train a network such as this, each object in an image much as annotated with a set of coordinates that correspond to the bounding boxes of the class (object). The COCO dataset, for example, is an annotated dataset of 80 classes (objects) with coordinates corresponding to the bounding box around each object. Another popular dataset is Object365 that contains 365 classes.\nAnother important type of neural network that the COCO dataset provides annotations for is Instance Segmentation models, such as Mask RCNN. These models provide pixel-level classification and are extremely compute-intensive, but critical for use cases such as self-driving cars. If you search for Detectron2 tutorials, you will find several great learning examples of training a Mask RCNN network on the COCO dataset.\nSo, to answer your question, Yes, you can use the COCO dataset (amongst many other options available publicly on the web) for object detection, or, you can also create your own dataset with a little effort by annotating your own dataset with bounding boxes around the object classes you want to train. Try Googling - 'using coco to train ssd model' to get some easy-to-follow tutorials. SSD stands for single-shot detector and is an alternative neural network architecture to Yolo.","Q_Score":0,"Tags":"python,computer-vision,object-detection,object-recognition","A_Id":68703676,"CreationDate":"2021-08-07T16:47:00.000","Title":"General object recognition with biggest number of classes","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a question regarding the model.fit method and overfitting from the scikit learn library in Pandas\nDoes the generic sklearn method model.fit(x---, y--) returns the score after applying the model to the specified training data?\nAlso, it is overfitting when performance on the test data degrades as more training data is used to learn the model?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":107,"Q_Id":68697124,"Users Score":1,"Answer":"model.fit(X, y) doesn't explicitly give you the score, if you assign a variable to it, it stores all the artifacts, training parameters. You can get the score by using model.score(X, y).\nOverfitting in simple words is increasing the variance in your model by which your model fails to generalize. There are ways to reduce overfitting like feature engineering, normalization, regularization, ensemble methods etc.","Q_Score":0,"Tags":"python,python-3.x,machine-learning,scikit-learn","A_Id":68697861,"CreationDate":"2021-08-08T01:11:00.000","Title":"sklearn method model.fit(x---, y--)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am using the package plotnine to make ggplot's. In this context I wanted to use \"loess\". The package gives an error and says: \"For loess smoothing, install 'scikit-misc'\". I installed it but I still receive this error. It seems that the following statement does not work:\nfrom skmisc.loess import loess\nIt says then \"DLL load failed while importing _loess: Das angegebene Modul wurde nicht gefunden.\" So that the module is not found. From other answers it was suggested that I should install numpy and mkl. I did both, still without any success.\nCould you please help me what I can do to use \"loess\" method?\nThank v much!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":919,"Q_Id":68699084,"Users Score":0,"Answer":"in colab do this: !pip install scikit-misc (do not need ! in terminal. This works for me)","Q_Score":3,"Tags":"python,scikit-learn,loess","A_Id":72071629,"CreationDate":"2021-08-08T08:33:00.000","Title":"Not possible to load skmisc.loess in python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Sklearn used n_jobs parameter in multiple functions. We can pass how many cores we want to use. For example 1 for one core and -1 for all cores. My system has six cores and I want to use [0,1,3,4] cores only. Is this possible?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":54,"Q_Id":68700344,"Users Score":0,"Answer":"No, that is not possible: you can't specify specific cores, that is up to the system.","Q_Score":1,"Tags":"python,machine-learning,scikit-learn","A_Id":68700522,"CreationDate":"2021-08-08T11:32:00.000","Title":"Specify cores in n_jobs sklearn","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have two dataframes df_pp and df_epc containing 3 common columns, POSTCODE, HOUSE_NAME, HOUSE_NUMBER. I want to merge these two dataframes into one dataset using the following logic.\n(POSTCODE && (HOUSE_NAME || HOUSE_NUMBER))\nSo, I want to pick a row in the new merged dataset if the postcode matches and either of the house number or house names match. I tried the following code. But it is not what I expected.\nnew_df = pd.merge(left=df_epc, right=df_pp, on=['POSTCODE', 'HOUSE_NUMBER', 'HOUSE_NAME'], how='inner') #690","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":67,"Q_Id":68700779,"Users Score":0,"Answer":"If I understand your logic correctly you want to do a outer join on HOUSE_NAME and HOUSE_NUMBER (union).\nThen you want to do a inner join on POSTCODE (intersection).\nYou need to understand the difference between how you join and give some more information about what you except in the end.","Q_Score":0,"Tags":"python,pandas,dataframe","A_Id":68700889,"CreationDate":"2021-08-08T12:29:00.000","Title":"Merge \/ Join two data frames based on 3 columns in pandas","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am facing some issues concatenating 2 vaex data frames. When I concat both data frames, the column names are ignored.\nFirst I read a CSV file using vaex\n>>> import vaex as vx \n>>> df = vx.read_csv(\"fl_name\", header=None)\n>>> df.column_names \n ['0', '1', '2', '3', '4', '5', '6']\nThen I try to concat this data frame to an existing one\n>>> df_original \n ['A', 'B', 'C', 'D', 'E', 'F', 'G']\nTo enable that, I matched the new data frame column names to existing ones\n>>> df.column_names = df_original.column_names \n>>> df_original.concat(df) \nWhen I checked the resulting data frame columns, I got\n ['A', 'B', 'C', 'D', 'E', 'F', 'G', '0', '1', '2', '3', '4', '5', '6']\nIs there any way to solve this issue and make vaex respect the column names?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":293,"Q_Id":68701649,"Users Score":0,"Answer":"After searching for some possible solutions, I found one in pandas.\nThe easiest way would be to read the file using the desired columns names\n\u00b4\u00b4\u00b4df = vx.read_csv(\"fl_name\", header=None, names=['A', 'B', 'C', 'D', 'E', 'F', 'G'])\u00b4\u00b4\u00b4\nDoing that, the code will work properly.","Q_Score":0,"Tags":"python,dataframe,concatenation,vaex","A_Id":68704173,"CreationDate":"2021-08-08T14:21:00.000","Title":"concatenate 2 vaex dataframes causing columns issue","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"What is the difference between one_hot_encoder and pd.get_dummies? Because sometimes, the get_dummies function gives the same results as the one hot encoding thing, but people tend to use the one hot encoding df to fit in their model. So what is the difference? And will it affect my model?\nthanks","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":63,"Q_Id":68702705,"Users Score":2,"Answer":"In fact, they produce the same result while transforming the categorical variable into dummies. The difference is that one_hot_encoder stores the transformation in an object. Once you have the instance of OneHotEncoder(), you can save it to use it later in a preprocessing step for your prediction pipeline.\nIf you are just making some experiments, you can use any of them. But if you want your preprocessing process to be better organized, you better use OneHotEncoder.\nIf you plan to use it for categorical features treatment, you can also use LabelEncoder.","Q_Score":1,"Tags":"python,sklearn-pandas","A_Id":68702840,"CreationDate":"2021-08-08T16:30:00.000","Title":"One Hot Encoding vs pd.get_dummies","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to train a model. I only have around 8k labelled data and around 20k unlabelled data. What I was thinking is, is it OK to train and test a model using the 8k labelled data and use that model to predict the classes of the remaining 20k unlabelled data. Then, using all the data creating a new model. I am trying to do binary classification and the model works quite well on the initial labelled population.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":36,"Q_Id":68705681,"Users Score":1,"Answer":"Yes, you can do that and it's absolutely fine and this strategy is often used as well. There are just a couple of things that you need to take care of while doing so:\n\nCreate good stratified testing data from the labeled 18000 images. If possible use k-fold splits.\nNow predict the other unlabelled images and get the pseudo labels.\nTrain a model on the whole dataset.\nThis is the most important step. Here you will validate your model on the k-fold splits and then evaluate if the performance of your model increases or not in comparison to the k-fold results on just the labeled data.\n\nKeep iterating these steps till your score improves but always be careful that there is no data leak regarding the k-fold data.","Q_Score":0,"Tags":"python,machine-learning,scikit-learn,classification,data-science","A_Id":68707465,"CreationDate":"2021-08-09T00:23:00.000","Title":"Using the predictions of a model to train a new model","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a sagemaker endpoint that serves a Random Forest Classifier SKLearn model. This model predicts the kind of user someone is based on there interaction on a website. I have had two releases for this model.\nThe first model had 4 kinds of user: 'user-type-1', 'user-type-2', 'user-type-3', 'other'\nThe second release differed from the first in that there was more training data used and there were 10 types of user 'user-type-1', 'user-type-2', 'user-type-3', 'user-type-4', 'user-type-5', 'user-type-6', 'user-type-7', 'user-type-8', 'user-type-9','other'. To be more specific, in the first model many users got predicted as 'other' whereas in the second model many of these users were in one of the new categories.\nThe parameters for the random forest was the same in both models.\nQuestion: The second model uses a lot more memory than the first and I cannot figure out why. Both models are of similar size and the same number of calls to the endpoint are being made under the second release. Any ideas why I might need a larger instance with more memory in the second model than the first?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":41,"Q_Id":68709594,"Users Score":1,"Answer":"The values attribute of classification-type SkLearn tree models is essentially a data matrix (n_leaves, n_classes) (probability distributions associated with each leaf node).\nIn the first experiment this matrix has 4 columns, in the second experiment it has 10 columns - a 2.5X increase in size.","Q_Score":0,"Tags":"python,machine-learning,random-forest,amazon-sagemaker","A_Id":68710729,"CreationDate":"2021-08-09T09:15:00.000","Title":"Why does my sagemaker model need a larger instance for real-time inference","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":1},{"Question":"Opencv keeps crashing my computer. It seems like it only happens when it is computing very hard. It happens at random times and does not give a blue screen. Just reboots.\nCode works completely fine on my i7.\nPython 3.9.4\nopenCV 4.5.3\nwin 10\nAMD Ryzen 9 5900X\nAnyone else experienced this or have some insights?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":11,"Q_Id":68717299,"Users Score":0,"Answer":"Seems to be some issue with AMD core management. Just running the code on a specific core solved my issue.\nOn windows, you do that by:\nstart \/affinity X mysript.py\nX is the dec of the core combo. 1 will run on core 1, 2 will run on core 2, 3 will run on core 1+2, and so on.","Q_Score":0,"Tags":"opencv-python","A_Id":68894251,"CreationDate":"2021-08-09T19:02:00.000","Title":"Opencv reboots windows","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I want to retrieve the pickle off my trained model, which I know is in the run file inside my experiments in Databricks.\nIt seems that the mlflow.pyfunc.load_model can only do the predict method.\nThere is an option to directly access the pickle?\nI also tried to use the path in the run using the pickle.load(path) (example of path: dbfs:\/databricks\/mlflow-tracking\/20526156406\/92f3ec23bf614c9d934dd0195\/artifacts\/model\/model.pkl).","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":2115,"Q_Id":68718719,"Users Score":1,"Answer":"Use the frmwk's native load_model() method (e.g. sklearn.load_model()) or download_artifacts()","Q_Score":1,"Tags":"python,azure,databricks,datastore,mlflow","A_Id":68720467,"CreationDate":"2021-08-09T21:26:00.000","Title":"How can I retrive the model.pkl in the experiment in Databricks","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have used YOLOv4 to detect objects in an image now I want to blur those objects or superimpose black color inside the bounding box. How can I do that using OpenCV or some other library?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":415,"Q_Id":68721469,"Users Score":0,"Answer":"cv2.rectangle(frame, (x, y), (x + w, y + h), color, -1)\nI just changed the width of the bounding box and it worked.\nThank you @micka","Q_Score":0,"Tags":"python,opencv,computer-vision,yolo,yolov4","A_Id":68853090,"CreationDate":"2021-08-10T05:25:00.000","Title":"How to fill\/blur the inside of bounding box in YOLO object detection?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Apologies for wordy question but it's impossible to recreate a sanitised simple example without significant effort, but in short I have a function that does some maths on a row, and then adds the output of the calculations to several new columns, and when I use df[new_columns] = df.apply(function_name,axis=1) with df having only two rows, I get the right answer, however if df has 20 rows, it generates the wrong answer.\nFurthermore, I have added a print statement to the function, in both examples (2 rows and 20 rows) to tell me what the function is going to add into the new columns, and the answer is correct every single time according to the print statement, but then somehow when the answer is being added to the final df, it seems to be going wrong somewhere.\nI simply do not understand this issue - is it a memory thing with apply() or something?? Any help very much appreciated!!!!\nEdit: it's giving me this warning 'DeprecationWarning: The default dtype for empty Series will be 'object' instead of 'float64' in a future version. Specify a dtype explicitly to silence this warning.'","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":40,"Q_Id":68726546,"Users Score":0,"Answer":"Turns out the issue was having nans in the data. I got it down to the point where the function worked with 6 rows of data but not with 7, but then I added a more explicit nan check (I was using 'try except' before, changed to math.isnan() and that solved the problem.","Q_Score":0,"Tags":"python,dataframe,apply","A_Id":68809205,"CreationDate":"2021-08-10T12:07:00.000","Title":"When I apply a function to a DF to create multiple new columns, I get different results depending how many rows are in the DF I submit","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a 3D array representing a batch of images (batch_size x W x H)\nimages = np.random.rand(8,100,100)\nand a 2D array (batch_size x 2)\nindices = np.random.randint(0, 100, size=(8, 2))\nwhich contains x,y indices for accessing pixel values of the images. The following\nimages[:,indices[:,0],indices[:,1]\nreturns an array of shape (8,8) but I would like to get an array of shape (8,) that contains pixel values for each image at the respective x, y positions stored in indices.\nLooking for a way to index the array w\/o using a for loop.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":117,"Q_Id":68732097,"Users Score":0,"Answer":"Think I solved it. Just needed to get the diagonal of the output:\noutput = images[:,indices[:,0],indices[:,1]\nnp.diag(output) gives pixel values for each image at x,y positions (indices).","Q_Score":0,"Tags":"python,arrays,indexing","A_Id":68759483,"CreationDate":"2021-08-10T18:45:00.000","Title":"Indexing a batch of images (3D numpy array) using a 2D array to get pixel values for each image","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have an SAS file that is roughly 112 million rows. I do not actually have access to SAS software, so I need to get this data into, preferably, a pandas DataFrame or something very similar in the python family. I just don't know how to do this efficiently. ie, just doing df = pd.read_sas(filename.sas7bdat) takes a few hours. I can do chunk sizes but that doesn't really solve the underlying problem. Is there any faster way to get this into pandas, or do I just have to eat the multi-hour wait? Additionally, even when I have read in the file, I can barely do anything with it because iterating over the df takes forever as well. It usually just ends up crashing the Jupyter kernel. Thanks in advance for any advice in this regard!","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":219,"Q_Id":68735169,"Users Score":0,"Answer":"Maybe you don't need your entire file to work on it so you can take 10%. You can also change your variable types to reduce its memory.\n\nif you want to store a df and re use it instead of re importing the entire file each time you want to work on it you can save it as a pickle file (.pkl) and re open it by using pandas.read_pickle","Q_Score":1,"Tags":"python,pandas,sas","A_Id":68748056,"CreationDate":"2021-08-11T01:55:00.000","Title":"Efficient Way to Read SAS file with over 100 million rows into pandas","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a question regarding transfer learning. Let suppose there is a neural network model that takes an input of shape (250,7). I want to initialise the model with the weights of this pre-trained model and then train it on my dataset to update the weights according to my dataset. But my dataset is of shape (251,8). Is there way to initialise the weights using pre-trained model considering my input shape is different? If so how can I do that? Insights will be appreciated.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":173,"Q_Id":68738166,"Users Score":1,"Answer":"You could try adding another layer before the transfer learning model. Just like the last layer, this will update its weights on your dataset and should work fine.","Q_Score":0,"Tags":"python,keras,deep-learning","A_Id":68738794,"CreationDate":"2021-08-11T08:01:00.000","Title":"transfer learning in keras when input shape is different","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Context: I was using Python on Atom IDE and installing\/importing packages is working normally. Now I would like to work with Python on Rstudio through Reticulate package.\nProblem: I'm not able to import Pandas on Rstudio even though a can Import numpy and math. The error is \"ModuleNotFoundError: No module named 'pandas'\".\ni) Python 3.8.5 installed (32 bit)\nii) pip3 21.1.2 installed\niii) Reticulate 1.2.0 installed\niv) Pandas is already installed (~\\AppData\\Local\\Programs\\Python\\Python38-32\\Lib\\site-packages)","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":351,"Q_Id":68741751,"Users Score":0,"Answer":"You could have many Python environments.\nCheck reticulate::py_module_available(\"pandas\").\nAnd, if neccesary, reticulate::py_install(\"pandas\").","Q_Score":0,"Tags":"python,r,rstudio,reticulate","A_Id":68741989,"CreationDate":"2021-08-11T12:09:00.000","Title":"Importing Python package (pandas) from R with Reticulate","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am just curious to know whether it is possible to export some final graphs or pictures after the successful animation of any object. I have used \"Mathematica\" and I know that a video can be exported as a sequence of images. If it is possible in Manim, then what is the proper way to do it?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":520,"Q_Id":68743394,"Users Score":0,"Answer":"One possible way is to use ffmpeg. Using FFmpeg you can convert the video file into images. After downloading FFmpeg, navigate to the path where FFmpeg exe is available and from the command prompt, you can try the below command.\nffmpeg -i input file path output file path\nEx: ffmpeg -i input file path C:\\images\\img%04d.png\nThe above command will convert each frame of the video to a png image in the path specified. \"img%04d\" is for the output file name format. In the output file path, you will be able to observe files like img0001, img0002. Each png file will represent a particular frame in the video.\nI had tried with an mp4 file and it works fine.","Q_Score":0,"Tags":"python,manim","A_Id":68743765,"CreationDate":"2021-08-11T13:51:00.000","Title":"Is it possible to export the pictures in png format from a Manim animation video?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":1,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am building a multiple linear regression model using python. I found the correlation coefficients between all the independent variables and the dependent variable. They were all greater than 0.5. However, the equation given by the regression model has a few negative coefficients. Why is that?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":308,"Q_Id":68745222,"Users Score":1,"Answer":"The situation you describe is not impossible. The key is to analyse the correlation between your independent variables. If there is a strong correlation between two of them, it is possible that one of these two has a negative coefficient in your linear regression.\nFor instance, take the following example where you want to predict y using x1and x2 as independant variables :\n\nLet's say that y is deterministic and follows y = x1 + 2 * x2.\nLet's say that x2is also deterministic and that x2 = 0.1 * x1\n\nThen, your linear regression has an infinite number of possiblity, you could say that y = 1.2 * x1 + 0 * x2 as well as y = 0 * x1 + 12 * x2 or y = 2 * x1 - 8 * x2. In the latter case, although there is a positive correlation between yand x2, you have a negative coefficient in your linear regression. There is no error, nothing wrong.\nThat is why you should not jump to conclusions and say that because there is a positive slope in your linear regression model, that necessarily means that there is a positive correlation between the independent and the predicted variable. And of course, that you cannot infer any causation from your results.\nI hope that answers the question.","Q_Score":1,"Tags":"python,machine-learning,linear-regression,correlation,coefficients","A_Id":68745802,"CreationDate":"2021-08-11T15:49:00.000","Title":"Negative coefficients in regression for positive coefficient of correlation","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Hell all, so let try to describe my problem in the best light possible. I have experience with Python but have never used FME. I would like to delete a full row of data based on criteria in a particular column.\nI have an idea of how I would write this in Python but being new to FME not quiet sure where I start here with the transformations.. For example: the Column will have an A, B, or C. If the column for any row has a \"C\" I want to to delete this full row. While it seems simple enough Python I'm not quite sure where to start with FME. Any help or helpful tips to point me in the right direction that would be great.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":201,"Q_Id":68750681,"Users Score":0,"Answer":"You need a \"tester\" transformer, add you're conditions in the transformer. You'll have 2 output ports, the first one (passed) is the data matching the conditions, the second (failed) not matching, that it.\n(google translate from french)","Q_Score":0,"Tags":"python,fme,simpletransformers","A_Id":68757060,"CreationDate":"2021-08-12T01:48:00.000","Title":"FME issue, deleting row based cell value","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working with time series datasets where I have two different cases. One where my sequences are of same size and the other one where the sequences are of different lengths. When I have same length sequences I can merge all the datasets and then fit the model once.\nBut for different length sequences, I was wondering how differently should the keras model.fit will behave\n\nif the models are fitted with each different length sequences one by one with batch size=length of sequence\nif the models are fitted once with all the sequences merged together having a fixed batch size\n\nAnd based on the given scenario what should be the correct or better course of action?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":77,"Q_Id":68761970,"Users Score":0,"Answer":"In first scenario, the weights will be optimized first with first dataset and then will be changed(updated) for the second dataset and so on. In second scenario, you are simultaneously asking the model to learn patterns from all the datasets. This means the weights will be adjusted according to all the datasets all at once. I will prefer the second approach because NN have the tendency to forget\/break when trained on new datasets. They are more likely to focus on the data they have seen recently.","Q_Score":0,"Tags":"python,tensorflow,keras,time-series,recurrent-neural-network","A_Id":68765784,"CreationDate":"2021-08-12T17:36:00.000","Title":"How does keras model fit differ when called multiple times with different datasets each time and when called once with all datasets?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"For some reason, on my Ubuntu 20.04 machine when I use OpenCV in Python like:\ncv2.imwrite(\"myfile.webp\", cv2image)\nin my code, the file of 800x600 px has about 300 KiB while if I do:\ncv2.imwrite(\"myfile.jpg\", cv2image)\nthe output file of the same pixel size has about 100 KiB.\nWhy is that, if webp should have 25% less in size than jpg?\nOr do I have to set some options first?\nP.S. for png:\ncv2.imwrite(\"myfile.png\", cv2image)\nthe size is about 500 KiB.","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":672,"Q_Id":68767831,"Users Score":1,"Answer":"SOLVED! It should be like this to work:\ncv2.imwrite(\"myfile.webp\", cv2image, [int(cv2.IMWRITE_WEBP_QUALITY), 20])\nNow, the file has 4 kB ;D","Q_Score":0,"Tags":"python,file,opencv,jpeg,webp","A_Id":68768754,"CreationDate":"2021-08-13T06:38:00.000","Title":"Saved webp images are 3x bigger than jpg in OpenCV","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Is there a way to convert a panda.Dataframe composed by numpy.float64 and Nan values into a matrix that has some fixed values instead of nan values?\nIt is my first question and i'm starting to use python then sorry if it isn't an intelligent question","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":17,"Q_Id":68773875,"Users Score":0,"Answer":"You can use either df.fillna(value) or df.replace(np.nan, value)","Q_Score":0,"Tags":"python,dataframe,matrix,nan","A_Id":68774446,"CreationDate":"2021-08-13T14:18:00.000","Title":"DataFrame with Nan values into matrix (Python)","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am newbie in python, I have one scenario :\nI have two dataframes df_open & df_closed. df_open is having old values and needs to be updated using df_closed periodically.\nFor ex:\ndf_open\n\n\n\n\nPrimary_key\nName\n\n\n\n\n1\nA\n\n\n2\nB\n\n\n\n\ndf_closed\n\n\n\n\nPrimary_key\nName\n\n\n\n\n1\nA\n\n\n2\nX\n\n\n3\nC\n\n\n\n\nAnd my desired output is\ndf_open\n\n\n\n\nPrimary_key\nName\n\n\n\n\n1\nA\n\n\n2\nX\n\n\n3\nC\n\n\n\n\nThis is some kinda of upsert operation which needs to be implemented using python pandas.\nThanks :)","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":27,"Q_Id":68773983,"Users Score":0,"Answer":"I can't comment yet to verify first. For your example though, I think right join will do the job.\ndf_open.merge(df_closed, on=('Primary_key', 'Name'), how='right')","Q_Score":0,"Tags":"python,python-3.x,pandas,dataframe","A_Id":68776089,"CreationDate":"2021-08-13T14:25:00.000","Title":"How to show the values of a single dataframe from the merge between two dataframes?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to use both TA-lib version 0.4.21 and Tensorflow 2.6.0 in the same project. Both require different numpy versions:\nTF ~= 1.19.2\nTA-lib >= 1.19.4\nGiven those dependencies, numpy 1.19.4 or 1.19.5 should work just fine, but I get the following exception:\nnumpy.ndarray size changed, may indicate binary incompatibility. Expected 88 from C header, got 80 from PyObject\nI tried uninstalling and installing numpy 1.19.4 and 1.19.5 several times, on python 3.8 and 3.9 but the result is the same.\nRemoving TF and using latest version on numpy resolves the issue - but this isn't a solution for me.\nDidn't find anything online about this collision between the two libraries.\nWill be glad for help, thanks!","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":1704,"Q_Id":68776283,"Users Score":0,"Answer":"I also encountered the same problem as you. I reinstalled numpy after installing TA-Lib 0.4.21 and tensorflow 2.6.0. Commands used: pip install -U numpy & pip install numpy. Now my current version of numpy is still 1.21.2, but it seems that the version collision no longer exists.","Q_Score":5,"Tags":"python-3.x,numpy,tensorflow,ta-lib","A_Id":68996634,"CreationDate":"2021-08-13T17:32:00.000","Title":"Tensorflow 2.6.0 and TA-lib 0.4.21 numpy version collision","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"When i train a model from a csv dataframe, is the output from model.predict in the same order as the columns from the Y dataframe?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":44,"Q_Id":68784743,"Users Score":1,"Answer":"Yes. When you train a model, you are tweaking the weights to try to make the predictions match the labels in the training data by minimising the loss, and so the model is trained on the exact order you provide your labels in. Essentially your model is making predictions each time as part of the forward propagation phase of the training, and model.predict() simply performs a forward pass in exactly the same manner, so it's the same order.","Q_Score":0,"Tags":"python-3.x,pandas,numpy,keras,deep-learning","A_Id":68794184,"CreationDate":"2021-08-14T15:33:00.000","Title":"In what order are the classses in the output of model.predict (keras)?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to implement TFLite model for food detection and segmentation. This is the model i chose suitable for my food images dataset: [https:\/\/tfhub.dev\/s?deployment-format=lite&q=inception%20resnet%20v2].\nI searched over google to understand how the images are required to be annotated, but only end up in confusion. I understand the dataset is converted to TFRecords and then fed to the pretrained model. But for training the model with custom dataset, does not it require an annotation file? I dont see any info about this on TF hub either.\nPlease can anyone help me on this!","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":106,"Q_Id":68811676,"Users Score":1,"Answer":"The answer to your question is depends on what model do you plan to train.\nIn the case of a model for food detection and segmentation you do need annotations when training. If you do not provide the model with labeled training data as it is a supervised learning model it cannot learn from them.\nIf you were to train an autoencoder the data does not need to be annotated. Hope the keywords used in this answer help you out search for more information about the topic.","Q_Score":0,"Tags":"python-3.x,tensorflow-lite","A_Id":68827651,"CreationDate":"2021-08-17T04:27:00.000","Title":"Does training a tflite model require images annotated?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Trying to decide which method would be faster for this. It's a permanent reusable script.\nIf I have a million folders on a server and each folder is considered one \"unit\". All the files in that folder are part of it. One file contains the details of the unit. In that file is a timestamp. If that timestamp is less than x. It needs to be copied, otherwise we leave it.\nShould I feed the list of paths into a multi-process function where each process would read a file off the list, check the timestamp and if good start the copy in that same process... then join the task when done, log the folder name in a text\/pickle file as done and repeat til all are finished. Resuming would happen by eliminating that folder name from the new list generation on rerun. List is generated each run in the main thread.\nOR would it be quicker to kick off x amount of threads to process the files and read their data into a csv or set of csvs. I would handle the write-to csv's in batches in a proper queue. one column would be a True or False whether to copy that unit. Once the list is complete, read the valid paths from the CSV where copy was set to True and then kick off new threads to start copying that path and filling in a completed column next to that row when it's done.\nI've used the latter method with pandas several times and have had great success with it. I prefer it because it simultaneously builds the final status report while also letting me resume without having to regenerate the list. the first lets us resume as well but we have to regenerate the list and still have to check each file for those not processed yet.\nI feel like the CSV method allows for less chance of failure for whatever reason as it's just reading the file, doing the check, writing the result to a csv, moving on. It's not tying up the thread on a long copy, nor is it writing to the file its reading. Max rows I've dealt with per server was around 300k and the csv for that is quite small in file size. I think the largest I had was about 50-100mb and it read it completely into a list in less than a min. I haven't used Dask but maybe that can even speed things up more.\nBefore I commit to one way or another, I wanted to ask for some feedback.\nIs it better to have long running threads open doing longer tasks for longer time. Or better to break the job up into say two halves and have threads open to process quicker tasks on each side?\nthanks.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":38,"Q_Id":68812263,"Users Score":0,"Answer":"I feel the first approach could be faster. Although, it heavily depends on what sort of data you are dealing with.\nWhy do you call it a \"longer task\"? The time taken for a single unit would always be either equal to or lesser that your existing approach (due to the overhead of waiting for other threads to write to the CSV file in a queue).","Q_Score":0,"Tags":"python,multithreading,csv","A_Id":68812352,"CreationDate":"2021-08-17T05:48:00.000","Title":"need to read a million files for a timestamp and move the files in its folder based on the timestamp... which method is fastest?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Suppose I have a dataframe and I want to print it using a printer or get a hard copy of a dataframe. I have almost 30 columns and hundreds of rows in that dataframe. I just want to get a printed copy of it in any format.\nI tried making a PDF of it and then press Ctrl+P but the dataframe values were not readable. Same with HTML too. I just want the data to be readable. How can I do so?\nI am creating an application for those people who are not really familiar with using computers. So I hope for a simple and easy answer.\nI already understand that I could use to_excel and to_csv. However, then the user would have to open an Excel file and click on print. I would like it to be more simple and easy for use than that.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":62,"Q_Id":68815406,"Users Score":1,"Answer":"Converting it to Excel and printing would be an option.\npd.to_excel()","Q_Score":0,"Tags":"python,pandas","A_Id":68815483,"CreationDate":"2021-08-17T10:04:00.000","Title":"How to get a readable text copy of a dataframe using Python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I need to upsample my original data of 250Hz to 96000Hz.I did it in python using librosa.resample. But when I did it in matlab I am getting a fluctuated signal. I used resample command in Matlab. I tried with interp,upsample but didn't work. I need to get an exact replica of upsampled output that I got in python. Why I am getting a different output in matlab? What I have to do to get the exact output of python upsampling in MATLAB? Is there any function equivalent to librosa.resample in matlab?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":73,"Q_Id":68843213,"Users Score":0,"Answer":"You can try to import your signal to the systemIdentification toolbox, and use the resample function there. I have used that before and it works accurately.\nSimply write systemIdentification to the Matlab console. Hope it helps, if not you might need to post some code.","Q_Score":0,"Tags":"python,matlab,interpolation","A_Id":68849768,"CreationDate":"2021-08-19T06:49:00.000","Title":"Matlab equivalent function for python librosa. resample","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm trying to convert a dataset of dimensions (32, 32, 3, 10000) dimension dataset to a grayscale dataset, where I would have (32, 32, 1, 10000) dimensions, but I need to have that 1 channel because I will input this to a Neural Network. I tried using numpy.average, but the shape becomes (32, 32, 10000) which the TensorFlow unit is not taking as an input. I even tried to manually average it, but it had the same result. Could you guys help me with this?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":112,"Q_Id":68846382,"Users Score":0,"Answer":"Try (0.299 * Red) + (0.587 * Green) + (0.114 \u2219 Blue) instead of averaging.","Q_Score":1,"Tags":"python,numpy,keras,tensorflow2","A_Id":68846506,"CreationDate":"2021-08-19T10:45:00.000","Title":"Converting RGB Dataset to Grayscale Dataset by averaging color channels with Numpy","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Hello I am a machine learning newbie. I need some help with unsupervised clustering of high dimentional data. I have data with over 15 dimensions with around 50 - 80 thousand rows. The data looks something like this (15 participants with almost equal number of rows each and 15 features) -\n\n\n\n\nParticipant\ntime\nfeature 1\nfeature 2...\n\n\n\n\n1\n0.05\nval\nval\n\n\n1\n0.10\nval\nval\n\n\n2\n0.05\nval\nval\n\n\n2\n0.10\nval\nval\n\n\n2\n0.15\nval\nval\n\n\n\n\nThe data consists of many participants, each participant has multiple rows of data and they are time stamped with their features. My goal is to cluster this data according to participants and make inferences based on these clusters. The problem here is that there are many rows for each participant and I cannot represent each participant with a single point so clustering them seems like a difficult task.\nI would like help with:\n\nWhat would be the best way to cluster this data so that I can make inferences according to the participant ?\n\nWhich clustering technique should I use? I have tried sklearn's Kmeans, meanshift and other libraries but they take too long and crash my system.\n\n\nSorry If it's a bit difficult to understand I will try my best to answer your questions. Thank you in advance for the help. If this question is very similar to some other question please let me know (I was not able to find it).\nThank you :)","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":92,"Q_Id":68847401,"Users Score":0,"Answer":"Since you have trouble with the necessary amount of compute you have to make some sort of compromise here. Here's a few suggestions that will likely fix your problem, but they all come at a cost.\n\nDimension reduction i.e. PCA to reduce your number of columns to ~2 or so. You will lose some information, but you will be able to plot it and do inference via K-means.\n\nAverage the patients data. Not sure if this will be enough, this depends on you data. This will lose the over-time observation of your patients but likely drastically reduce your number of rows.\n\n\nMy suggestion is to do dimension reduction since losing the over time data on your patients might render your data useless. There is also other stuff beside PCA, for example auto encoders. For clustering the way your descibe I'd recommend you stick to K-means or soft K-means.","Q_Score":0,"Tags":"python,machine-learning,cluster-analysis,unsupervised-learning,feature-clustering","A_Id":68875023,"CreationDate":"2021-08-19T11:55:00.000","Title":"Unsupervised Clustering of large multi-dimentional data","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Say we have two dataframes, A with columns a,b,c and B with columns a,b,d and some values\nA =\n\n\n\n\na\nb\nc\n\n\n\n\n1\n2\n3\n\n\n4\n5\n6\n\n\n7\n8\n9\n\n\n\n\nand B =\n\n\n\n\na\nb\nd\n\n\n\n\n1\n2\n3\n\n\n4\n5\n6\n\n\n7\n8\n9\n\n\n\n\nIs there a pandas function with can combine the two so that\nC = f(A,B) =\n\n\n\n\na\nb\nc\nd\n\n\n\n\n1\n2\n3\nnan\n\n\n4\n5\n6\nnan\n\n\n7\n8\n9\nnan\n\n\n1\n2\nnan\n3\n\n\n4\n5\nnan\n6\n\n\n7\n8\nnan\n9\n\n\n\n\nIn other words, the columns that exist in one dataframe but not the other should be set to 'nan' in the other when adding the rows, but still add rows values on the columns common to both. I've tried join, concat and merge, but it seems that they don't work in this way, or I've used them wrong. Anyone have suggestions?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":34,"Q_Id":68861665,"Users Score":1,"Answer":"Use pd.concat([A, B], axis=0, ignore_index=True)","Q_Score":0,"Tags":"python,pandas,dataframe","A_Id":68861719,"CreationDate":"2021-08-20T11:42:00.000","Title":"Pandas add dataframe to another row-wise by columns setting columns not available in the other as \"nan\"","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm making an app that cleans-etc-search a CSV that is updated daily on a website. I was using an EC2 to download the file using python pandas.read_csv(url) to an EBS, but now I want to make the app serverless.\nI want to automate the download from 'https:\/\/sam.gov\/api\/prod\/fileextractservices\/v1\/api\/download\/Contract%20Opportunities\/datagov\/ContractOpportunitiesFullCSV.csv?privacy=Public' and upload it to S3 serverless. I'm not sure if is possible to do it serverless. Is there a better way to do it?\nThe file size is about 500 MB.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":241,"Q_Id":68877139,"Users Score":1,"Answer":"A lambda is exactly what you would want to use for this kind of scenario. Do the following:\n\nCreate the S3 bucket\nWrite the lambda function\nConfigure an IAM role to give lambda permission to write to the S3 bucket\nConfigure an EventBridge task to trigger the lambda function daily","Q_Score":0,"Tags":"python-3.x,amazon-web-services,amazon-s3,aws-lambda,aws-serverless","A_Id":68877185,"CreationDate":"2021-08-21T22:17:00.000","Title":"Is there a way to download a csv file from a website and upload it directly to Amazon S3 using Lambda?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":1,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":1},{"Question":"Dataset:\n\n\n\n\nTeam\nOpponent\nHome\/Away\nGround\nMatch Date\nMatch Year\nMatch Period\nMargin\nResult\n\n\n\n\nCountry A\nCountry B\nAway\nGround1\n20-09-2016\n2016\nSep-16\n5 wickets\nLost\n\n\nCountry C\nCountry D\nAway\nGround2\n08-07-2012\n2012\nJul-12\n66 runs\nWon\n\n\n\n\nThe target column for prediction is Result, which is a binary classification with values either Won or Lost\nAim is to predict whether the match result of a given team (team1), against an opponent (team2) at a given ground, is Won or Lost, so the input to the ML model from the user would be Team, Opponent, Ground.\nThe accuracy of the model is pretty low when only categorical columns are considered as input.\nAny help on methods to train the ML model with just categorical variables..\nThanks!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":55,"Q_Id":68879644,"Users Score":0,"Answer":"Convert the categorical variables to binary, so the ML models can understand it. I would split match column into two columns each one has one country, then convert every country to a unique binary or a value. The model can then understand your approach","Q_Score":0,"Tags":"python,machine-learning,classification,random-forest,decision-tree","A_Id":68879685,"CreationDate":"2021-08-22T08:30:00.000","Title":"Classification based on categorical features","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"So basically, I need a numpy function which will do this or something similar to this:\ncorrect_answers = np.array([scores[i][y[i]] for i in range(num_train)])\nbut using numpy, because Python list comprehension is too slow for me\nscores is a num_train X columns matrix and y is an array of length num_train and takes values from 0 to columns - 1 inclusive\nIs there a workaround using arange or something similar? Thanks.","AnswerCount":2,"Available Count":1,"Score":-0.0996679946,"is_accepted":false,"ViewCount":38,"Q_Id":68880891,"Users Score":-1,"Answer":"correct_answers = scores[np.arange(num_train), y[np.arange(num_train)]]\nThis does the thing I wanted to do, props to the other dude which gave me the idea","Q_Score":0,"Tags":"python,arrays,numpy,multidimensional-array","A_Id":68881039,"CreationDate":"2021-08-22T11:33:00.000","Title":"Is there a numpy function which takes from each line i of a matrix an element on the column y[i] and puts them all into an array?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a question regarding Google Vision product search.\nI know the Product Search index of products is updated approximately every 30 minutes. Does indexTime reset to default value \"1970-01-01T00:00:00Z\" on an unused ProductSet?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":62,"Q_Id":68891269,"Users Score":0,"Answer":"That means that it hasn't been indexed yet","Q_Score":0,"Tags":"python-3.x,google-cloud-platform,google-cloud-vision,google-product-search","A_Id":69913285,"CreationDate":"2021-08-23T10:48:00.000","Title":"Google Vision product search indexing","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"We are currently using Python2.7 with HDP3.1.5 (PySpark | Spark2.3) and RHEL 7.9.\nWe are planning to upgrade to Python3.x as Python2.7 support has ended.\nIf anyone could please help with determining the latest stable Python3.x? version that will best suit or compatible with HDP3.1.5 (Spark2.3) and RHEL 7.9?\nOR\nLet me know necessary steps I should follow to determine the best stable Python3.x? version for our HDP stack?\nThanks,\nPB","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":73,"Q_Id":68892984,"Users Score":0,"Answer":"The max Python version supported is 2.7.5, Python Version 3.x is not supported as it will create conflict with the versions shipped (HDP3.1.5 + Ambari2.7.5).\nPython3 support is not on the road map of HDP 3x and even for Ambari.\nThis is something which may be done in future to make Python3 as the default for the OS Cloudera supports.","Q_Score":0,"Tags":"python-3.x,hadoop,pyspark,rhel7,hdp","A_Id":68940562,"CreationDate":"2021-08-23T12:46:00.000","Title":"How to determine which Latest stable Python3.x suits best for HDP3.1.5 and RHEL7.9","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"In Python when write #\n\n\nimport sensitivity\n\n\ni found that error\n\nImportError Traceback (most recent call last)\n in \n----> 1 import sensitivity\n~\\anaconda3\\envs\\name_of_my_env\\lib\\site-packages\\sensitivity_init_.py in \n3 visualizations including gradient DataFrames and hex-bin plots\n4 \"\"\"\n----> 5 from sensitivity.main import SensitivityAnalyzer\n~\\anaconda3\\envs\\name_of_my_env\\lib\\site-packages\\sensitivity\\main.py in \n9 from IPython.display import display, HTML\n10\n---> 11 from sensitivity.df import sensitivity_df, _style_sensitivity_df, _two_variable_sensitivity_display_df\n12 from sensitivity.hexbin import _hex_figure_from_sensitivity_df\n13\n~\\anaconda3\\envs\\name_of_my_env\\lib\\site-packages\\sensitivity\\df.py in \n6\n7 import pandas as pd\n----> 8 import pd_utils\n9 from pandas.io.formats.style import Styler\n10 import numpy as np\n~\\anaconda3\\envs\\name_of_my_env\\lib\\site-packages\\pd_utils_init_.py in \n37 join_col_strings\n38 )\n---> 39 from pd_utils.plot import plot_multi_axis\n40\n41\n~\\anaconda3\\envs\\name_of_my_env\\lib\\site-packages\\pd_utils\\plot.py in \n2\n3 import pandas as pd\n----> 4 from pandas.plotting._matplotlib.style import _get_standard_colors\n5 import matplotlib.pyplot as plt\n6\nImportError: cannot import name '_get_standard_colors' from 'pandas.plotting._matplotlib.style' (C:\\Users\\DELL\\anaconda3\\envs\\name_of_my_env\\lib\\site-packages\\pandas\\plotting_matplotlib\\style.py)","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":175,"Q_Id":68906194,"Users Score":1,"Answer":"There is a mistake on the plot.py script of the sensitivity library. You need to change the import from from pandas.plotting._matplotlib.style import _get_standard_colors to from pandas.plotting._matplotlib.style import get_standard_colors\nTherefore just removing the underscore","Q_Score":1,"Tags":"python,pandas","A_Id":68906332,"CreationDate":"2021-08-24T10:49:00.000","Title":"I have python error when import sensitivity","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a problem that I'm not sure how to solve properly.\nSuppose we have to generate 1 <= n <= 40 numbers: X[1], X[2], ..., X[n].\nFor each number, we have some discrete space we can draw a number from. This space is not always a range and can be quite large (thousands\/millions of numbers).\nAnother constraint is that the resulting array of numbers should be sorted in ascending order: X[1] <= X[2] <= ... <= X[n].\nAs an example for three numbers:\nX[1] in {8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31}\nX[2] in {10, 20, 30, 50}\nX[3] in {1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003}\nExamples of valid outputs for this test: [9, 20, 2001], [18, 30, 1995]\nExample of invalid outputs for this test: [25, 10, 1998] (not increasing order)\nI already tried different methods but what I'm not satisfied with is that they all yield not uniformly distributed results, i.e. there is a strong bias in all my solutions and some samples are underrepresented.\nOne of the methods is to try to randomly generate numbers one by one and at each iteration reduce the space for the upcoming numbers to satisfy the increasing order condition. This is bad because this solution always biases the last numbers towards the higher end of their possible range.\nI already gave up on looking for an exact solution that could yield samples uniformly. I would really appreciate any reasonable solution (preferably, on Python, but anything will do, really).","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":73,"Q_Id":68920797,"Users Score":4,"Answer":"I won't code it for you but here's the logic to do the non brute force approach:\nLet's define N(i,x) the number of possible samples of X[1],...,X[i] where X[i]=x. And S(i) the possible values for X[i]. You have the recursion formula N(i,x) = Sum over y in S(i-1) with y<=x of N(i-1,y). This allows you to very quickly compute all N(i,x). It is then easy to build up your sample from the end:\nKnowing all N(n,x), you can draw X[n] from S(n) with probability N(n,X[n]) \/ (Sum over x in S(N) of N(n,x))\nAnd then you keep building down: given you have already drawn X[n],X[n-1],...,X[i+1] you draw X[i] from S(i) with X[i]<=X[i+1] with probability N(i,X[i]) \/ (Sum over x in S(i) with x<=X[i+1] of N(i,x))","Q_Score":0,"Tags":"python,random","A_Id":68921360,"CreationDate":"2021-08-25T10:03:00.000","Title":"Generating discrete random numbers under constraints","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a large (~26k) list of dicts; I call .sort(key=lambda x:x['score'], reverse=True) to sort the list by the score of each element. While it does do some amount of sorting, it's not hard to find examples of out-of-order items.\nSpecifically, I have a data set of the form {specimen:\"Specimen Name\", test_param:2.6, score:0.8649} (score is between -1 and 1, and is what I'm trying to sort on). About 26k of these entries are put into a single list (let's call it data). I call data.sort(key=lambda x:x['score'], reverse=True), and yet the resulting list contains items in the middle of the list that have a higher score than at the head; the items have no discernable (to me) pattern to their order, apart from being \"generally\" greatest-to-least.\nI've tried several approaches to make sure it wasn't some silly type error: casting to float in the lambda and supplying a default value with key=lambda x:float(x.get('score', -100)); reformatting the list of dicts into a list of tuples (score, dict) and sorting by x[0]. The (incorrect) order that it returns is very consistent, so I'm ruling out race condition oddities.\nI've resulted to hand-crafting a simple sort function, and that works fine (just slower). How is it that this seemingly simple case of sorting is exhibiting such odd behavior?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":28,"Q_Id":68925253,"Users Score":1,"Answer":"Someone recommended that I check for NaN values in score, and sure enough, there were some. Removing those now allows the sort to work properly.\nTL;DR - don't allow NaNs in your sort key. If you see weird sorting behavior, check for NaNs.","Q_Score":0,"Tags":"python,python-3.x,sorting","A_Id":68925783,"CreationDate":"2021-08-25T14:55:00.000","Title":"confused by python builtin sort() returning out-of-order items","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to import talos python module using import talos\nthis is the error I get:\n\nImportError: cannot import name 'SGD' from 'keras.optimizers'\n\nI have solved the same error message before when I used from keras.optimizers import Adam,Nadam, SGD changing the code to from tensorflow.keras.optimizers import Adam,Nadam, SGD. However, the error message I get now is within the internal talos import command. talos 0.4.8, keras 2.2.4, tensorflow 2.6.0\nThank you","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":1537,"Q_Id":68933859,"Users Score":1,"Answer":"Talos 0.4.8 supports Tensorflow 2.0.0\nInstall latest version of Talos==1.0, which supports Tensorflow 2.6.0.\nfrom tensorflow.keras.optimizers import Adam,Nadam, SGD and import talos works just fine with talos 1.0 and Tensorflow 2.6.0.","Q_Score":1,"Tags":"python,tensorflow,keras,talos","A_Id":69068604,"CreationDate":"2021-08-26T06:56:00.000","Title":"Cannot import name 'SGD' from 'keras.optimizers' when importing talos","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have comma separated text (string format) from as output from an API call, an small example shown below.\ncs_file = 'Reviewer Name,Account Reviewer Name,Account Manager Name\\r\\n\"Last, First\",\"Last, First\",\"Last, First\"'\nA new line is shown by '\\r\\n'. My thought would be to split the text at this first an then create a data frame by splitting at \",\". However, splitting at '\\r\\n' does not work, just get one list...\ncs_list = []\ncs_list = cs_file.split(r'\\r\\n')\nAny suggestions on a better approach? The goal would be to have this text saved as a csv.","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":499,"Q_Id":68939732,"Users Score":1,"Answer":"You should use cs_list = cs_file.split('\\r\\n').\nUsing a raw-string would have worked if you assigned cs_file with cs_file = 'Reviewer Name,Account Reviewer Name,Account Manager Name\\\\r\\\\n\"Last, First\",\"Last, First\",\"Last, First\"'.\nPython by default doesn't use raw-strings for assignment. I like to print strings to see how they visually look as all the escape characters can get confusing.","Q_Score":0,"Tags":"python,csv","A_Id":68939821,"CreationDate":"2021-08-26T13:45:00.000","Title":"Python Formatting comma separated text string to save as csv file","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a script in python that uses cv-bridge. But I keep getting this error:\nERROR: Could not find a version that satisfies the requirement cv-bridge==1.15.0 (from -r requirements.txt (line 5)) (from versions: none)\nERROR: No matching distribution found for cv-bridge==1.15.0 (from -r requirements.txt (line 5))\nTo reproduce the error:\npip install -r requirements.txt\nrequirements.txt:\ncv-bridge==1.15.0\nDoes anybody know how to solve it?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":281,"Q_Id":68942222,"Users Score":0,"Answer":"You have to actually install CV_Bridge and your script is failing because it cannot find a match for the exact version. As mentioned in the comment, this is almost certainly because of how old that version is. You should install the bridge via apt by doing sudo apt-get install ros-(DISTRO)-cv-bridge and sudo apt-get install ros-(DISTRO)-vision-opencv.","Q_Score":0,"Tags":"python,opencv,ros","A_Id":68944911,"CreationDate":"2021-08-26T16:27:00.000","Title":"No matching distribution found for cv-bridge python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working on a task of generating synthetic data to help the training of my model. This means that the training is performed on synthetic + real data, and tested on real data.\nI was told that batch normalization layers might be trying to find weights that are good for all while training, which is a problem since the distribution of my synthetic data is not exactly equal to the distribution of the real data. So, the idea would be to have different \u2018copies\u2019 of the weights of batch normalization layers. So that the neural network estimates different weights for synthetic and real data, and uses just the weights of real data for evaluation.\nCould someone suggest me good ways to actually implement that in pytorch? My idea was the following, after each epoch of training in a dataset I would go through all batchnorm layers and save their weights. Then at the beginning of the next epoch I would iterate again loading the right weights. Is this a good approach? Still, I am not sure how I should deal with the batch-norm weights at test time since batch-norm treats it differently.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":80,"Q_Id":68946833,"Users Score":0,"Answer":"It sounds like the problem you're worried about is that your neural network will learn weights that work well when the batch norm is computed for a batch of both real and synthetic data, and then later at test time it will compute a batch norm on just real data?\nRather than trying to track multiple batch norms, you probably just want to set track_running_stats to True for your batch norm layer, and then put it into eval mode when testing. This will cause it to compute a running mean and variance over multiple batches while training, and then it will use that mean and variance later at test time, rather than looking at the batch stats for the test batches.\n(This is often what you want anyway, because depending on your use case, you might be sending very small batches to the deployed model, and so you want to use a pre-computed mean and variance rather than relying on stats for those small batches.)\nIf you really want to be computing fresh means and variances at test time, what I would do is instead of passing a single batch with both real and synthetic data into your network, I'd pass in one batch of real data, then one batch of synthetic data, and average the two losses together before backprop. (Note that if you do this you should not rely on the running mean and variance later -- you'll have to either set track_running_stats to False, or reset it when you're done and run through a few dummy batches with only real data to compute reasonable values. This is because the running mean and variance stats are only useful if they're expected to be roughly the same for every batch, and you're instead polarizing the values by feeding in different types of data in different batches.)","Q_Score":1,"Tags":"python,pytorch,dataset,conv-neural-network,batch-normalization","A_Id":68960580,"CreationDate":"2021-08-27T00:51:00.000","Title":"How to deal with batch normalization for multiple datasets?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"i'm training EfficientDet-D7(head_only=True) in 2080TI * 1.\nAnd i'm using NVIDIA\/APEX:amp.\nWhen i use opt_level=O1, although the memory is definitely reduced compared to when apex is not used.\nBut, when I use opt_level=O2orO3, more memory is consumed.\nI am experimenting with the same 2080 Ti, each with a separate GPU by creating two containers with the same docker image. The learning code also copied the code using O1 as it is and changed it to O3, and the args required for learning are all the same. (The batch size and d7 are also the same.)\nWhy happen this... TT\nAdditionally, Can you recommend the book about this?(ex. deep learning Memory, gpu ... etc)\nThanks!","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":92,"Q_Id":68949428,"Users Score":1,"Answer":"You're optimizing for speed. Some speed optimizations will reduce memory usage. Other will increase them.\n\nAn example of when speed optimization reduces memory usage is when unnecessary variables and function calls are removed.\n\nAn example of the opposite is loop unrolling.\n\n\nThere's no reason to expect optimization to either reduce or increase memory usage. That's not the goal when optimizing for speed. Any increase or decrease is just a byproduct.\nIf you really want to find out why it happens in your particular case, you can study the documentation for your compiler and inspect the assembly code.","Q_Score":1,"Tags":"python,deep-learning,pytorch,gpu,apex","A_Id":68951451,"CreationDate":"2021-08-27T07:21:00.000","Title":"Why don't O3 less than O1 in gpu memory?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Need to merge a DataFrame with another DataFrame without affecting existing data\ndf1:\n\n\n\n\nName\nSubject\nmark\n\n\n\n\na\nTa\n52\n\n\nb\nEn\n\n\n\nc\nMa\n\n\n\nd\nSs\n60\n\n\n\n\ndf2:\n\n\n\n\nName\nmark\n\n\n\n\nb\n57\n\n\nc\n58\n\n\n\n\nExpected Output:\n\n\n\n\nName\nSubject\nmark\n\n\n\n\na\nTa\n52\n\n\nb\nEn\n57\n\n\nc\nMa\n58\n\n\nd\nSs\n60","AnswerCount":3,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":41,"Q_Id":68950000,"Users Score":0,"Answer":"One of the ways in which you can achieve this is by using the below steps:\n\nInner join the 2 tables using the pandas.merge()command.\nCreate a new column which basically checks if the marks column from df1 is not None, then take that value, else, take df2 column value.","Q_Score":1,"Tags":"python,pandas","A_Id":68950101,"CreationDate":"2021-08-27T08:04:00.000","Title":"Merge a dataframe to another dataframe without existing data","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"im downloading an xls file from the web using selenium.\nnow,i want to use the data in it with pandas, but 1 column includes numbers in scientific notation.\nis there a way to change them to numbers?\nim trying to use the data in the excel, and transfer some of it into google sheet for my team to use, but if i cant figure out how to send the numbers and not the scientific notations, it wont work.\nthanks,\nAvi","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":25,"Q_Id":68962190,"Users Score":0,"Answer":"What you can do is this:\n\nyour data is imported as string, so we need to split it at e to get our power of 10 out:\ndf = pd.DataFrame({'sci_num' :['6.2345e20'] })\ndf[['num','exp10']] = df['sci_num'].str.split('e', expand=True)\n\nThen you need to use these two columns to get your results:\ndf['sci_num_corrected'] = df['num'].astype(float) * (10 ** df['exp10'].astype(int))","Q_Score":0,"Tags":"python-3.x,pandas","A_Id":68966220,"CreationDate":"2021-08-28T07:22:00.000","Title":"Sceintific notation to number in xls file - python","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"i'm trying to train my neural network. it aims is to predict video quality. i am using VGG16+LSTM networks, but the VGG16 is not trainable. the total of trainable parameters are 700,000.\ni have three questions:\n\nis enough 700,000 trainable parameters for training the 68000 input frames?\nis it essential to train vgg16?\nhow many epochs needed for getting the best resaults?","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":99,"Q_Id":68962584,"Users Score":0,"Answer":"You start with one and see what impact it had.\nEven one epoch will take long and getting the error takes also a bit of time.","Q_Score":0,"Tags":"python,neural-network,conv-neural-network,lstm","A_Id":68967217,"CreationDate":"2021-08-28T08:21:00.000","Title":"how many epochs needed for 68000 input frames for CNN + LSTM acrhitecture?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"maybe this is a research-based question, but I am posting it here if I got any practical solution.\n(OPEN_WORLD_CLASSIFICATION)\nproblem is simple, let me explain with an example.\nI have DOG-CAT classification model. now if let's say I pass \"elephant\", it will predict as DOG which is wrong.\nhow to handle this problem, I want to know whenever \"unknown\" images come to the model.\nThe approach I tried-: I trained with three class[\"dog\", \"cat\", \"unknown\"]. in the \"unknown\" class folder I put random images.\nbut the problem with this approach is, it will reduce the overall accuracy of the model.\nis there any example for this kind of problem would be appreciated.\nThanks in advance.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":42,"Q_Id":68974182,"Users Score":0,"Answer":"In the DOG-CAT binary classification problem you define your input data space from a subset of the superset of animals. Thus, the input is meant to come from the DOG-CAT distribution or else it would be out of the scope of this classifier. It would be like you have a classifier to define an expensive or cheap house from an image and you use as input a car. So, you have to redefine what is the problem you want to solve, have a dog-cat, dog-cat-other or dog-cat-frog-etc. classifier. The reduced accuracy is something to be expected because there are probably way many more features that should me extracted in order to classify correctly on these 3 categories. For example, you can tell the difference of a dog from a cat just from the shape of the eyes, but how can you tell the difference of a cat and a small tiger? Using more data probably will lead to better results.","Q_Score":1,"Tags":"python,tensorflow,deep-learning","A_Id":68975432,"CreationDate":"2021-08-29T15:00:00.000","Title":"how to handle \"unknow class\" in deep learning model","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I tried to use pyinstaller to compile a .py I wrote. I used a bunch of libraries including sklearn, nltk, gensim but did not use tensorflow at all. However, when I compiled the program, there were many warnings about tensorflow modules not found, such as:\nWARNING: Hidden import \"tensorflow._api.v2.compat.v1.estimator\" not found!\nIs it because other libraries somehow used tensorflow in their functions? Is there a way to find what the usage is? Thanks!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":47,"Q_Id":69021547,"Users Score":0,"Answer":"Gensim uses tensorflow.\nYou can add --hidden-import=\"tensorflow._api.v2.compat.v1.estimator\" with your pyinstaller command and it will resolve this error.","Q_Score":1,"Tags":"python,tensorflow,pyinstaller","A_Id":69039550,"CreationDate":"2021-09-01T23:29:00.000","Title":"Pyinstaller hidden import not found for unused library","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I need to build a model that can expand multiple short sentences to multiple long sentences. I was thinking to use a pre-trained Transformer model to do this just like when we want to do a paragraph or text summarization except, in this case, I switched the output and input values. I tried this using t5-base, ran it on Google Colab, and using really minimum data like 10 rows of data, the idea was to see whether it works or not regardless of the output. But I always got errors like below:\n\nRuntimeError: CUDA out of memory. Tried to allocate 502.00 MiB (GPU 0;\n11.17 GiB total capacity; 10.29 GiB already allocated; 237.81 MiB free; 10.49 GiB reserved in total by PyTorch)\n\nI interpret this error as I did something wrong or my idea did not work. Is there anyone who can suggest how to do this?\nPlease advise","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":60,"Q_Id":69023072,"Users Score":0,"Answer":"I reduce the batch size and it solves the problem.","Q_Score":0,"Tags":"python,nlp,huggingface-transformers,pre-trained-model","A_Id":69024908,"CreationDate":"2021-09-02T01:36:00.000","Title":"Using Pre-trained Transformer Model to Expand Short Sentences to Long Sentences","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"For example, for a simple linear model y=wx+b where x and y are input and output respectively, w and b are training parameters, I am wondering, in every epoch, how can I update b first and then update w?","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":120,"Q_Id":69028986,"Users Score":1,"Answer":"Not really possible. TF's backprop calculate gradients across all variables based on the values of the other variables at the time of forward prop. If you want to alternate between training w and b, you would unfreeze w and freeze b (set it to trainable=False), forwardprop and backprop, then freeze w and unfreeze b, and forward prop and back prop. I don't think that'd run very fast since TF isn't really design to switch the trainable flag on every mini batch.","Q_Score":0,"Tags":"python,tensorflow,optimization,gradient-descent","A_Id":69042612,"CreationDate":"2021-09-02T11:02:00.000","Title":"How to implement coordinate descent using tensorflow?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a simple web app which uses sklearn transformed vectors (tfidf \/ count \/ normalizer) & other pytorch (transformer models). I usually dump these models via joblib. This app calls these models via fastapi based apis. Until now everything is fine.\n\nBut the above listed vectors and models are updated on daily basis, on runtime. By the part of same application which uses it. So, whenever new files are ready we starts using them.\nWhenever we get a call from api, we search for todays model and does:\njoblib.load then respond to api calls. In this process, whenever we are getting too many calls, we are doing many times joblib.load and finally we starts getting Too many files open OSError.\nIf we wouldn't be updating these models daily then I could have done loading once in global variables. But now I don't have a clear and best idea, to design it in such a way that, we can update models on daily basis & whenever the models are available for today, then start using them.\nAlso, one more constraint, until the models for today are not available, we use yesterdays model to serve requests.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":40,"Q_Id":69042371,"Users Score":1,"Answer":"It sounds like what you want to do is load the model once, use the model in memory, and then every so often check whether a new model is available on disk and reload it if an updated version is available.","Q_Score":0,"Tags":"python,design-patterns,scikit-learn,pytorch,data-science","A_Id":69047046,"CreationDate":"2021-09-03T09:10:00.000","Title":"How to update models \/ vectors on runtime, on daily basis?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Considering train is a Pandas dataframe,\nwhat is the difference between these two?\n\ntarget = train['claim']\u200d\ntarget = \u200dtrain['claim'].copy()\u200d\n\nSince both these code snippets are used to assign the value of the column to a target variable, how are they different?","AnswerCount":2,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":43,"Q_Id":69047023,"Users Score":3,"Answer":"target = train['claim'] means that target will point to the exact same object stored in train['claim']. Any modification done to this object via either target or train['claim'] will affect both.\ntarget = train['claim'].copy() means you're creating a copy of whatever's in train['claim'] and storing it to target. Subsequent modifications to the object in traint['claim'] won't affect target, and vice-versa.","Q_Score":2,"Tags":"python,pandas,dataframe,machine-learning","A_Id":69047088,"CreationDate":"2021-09-03T15:01:00.000","Title":"what is the difference between target = train['claim'] and target = train['claim'].copy()?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am doing a model training of CNN in Python and I have a question. I know that data normalization is important to scale the data in my dataframe between 0 and 1, but let's say I perform z-score normalization on my dataframe VERTICALLY (which means scale the data within the scope of each feature), but after I deployed the model and want to use it on real world scenarios, I only have one row of data in my dataframe (but with same amount of features), I am not able to perform normalization anymore because there is only one data for each feature. The standard deviation will be 0 and division of 0 in z-score is not applicable.\nI want to confirm that do I still need to perform data normalization on real world scenarios? If I do not need to, will the result differs because I did normalization during my model training?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":44,"Q_Id":69054028,"Users Score":2,"Answer":"If you are using a StandardScaler from scikit-learn. You need to save the scaler object and use it for transforming new data after deployment.","Q_Score":0,"Tags":"python,tensorflow,normalization,standardization","A_Id":69054064,"CreationDate":"2021-09-04T09:27:00.000","Title":"Data normalization in Python CNN model training","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"For a college course, I have to produce a coding project over the course of 1 year. My current idea is a neural network that detects an image, processes what that image is, then reads it aloud in 2 different languages. My idea is to make this a website or a mobile app, and to use Python. Is this too ambitious? Or not ambitious enough? Or should I look at something completely different?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":47,"Q_Id":69061542,"Users Score":0,"Answer":"There are many approaches for your project. I\u2018ve listed some of them here.\nFor your website\/app itself:\n\nEither use a Python Library like Flask, Django or web for the backend part.\nEven though plain HTML\/CSS\/JS would be enough for your frontend part of the project, you might use jQuery for simplifying the upload process of an image.\n\nImage Classification:\n\nTo classify an image, you can either use a library like Tensorflow or PyTorch or just use an API like imagga (saving you a lot of work).\nNow, turning the result to speech can be made possible by using Google\u2018s Text-To-Speech library \u201egtts\u201c.\n\nI hope I could help you,\nwish you luck for the project !","Q_Score":0,"Tags":"python,neural-network,artificial-intelligence","A_Id":69062294,"CreationDate":"2021-09-05T07:56:00.000","Title":"Trying a Neural Network in Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Please, I need clarification on something.\nLet's assume I have a dataset from two different website\n\nJaka website\nMaka website\n\nThe first website has a different dataset that contains different information.\nLet's assume the Jaka website has a dataset named blood dataset, hands-dataset, legs-dataset, and eyes dataset. Let's assume the Maka website also has some datasets called fingers-dataset, stomach-dataset, eyeball-dataset, toes-dataset, and kneel-datasets.\nLet's assume that the largest of these datasets is fingers-dataset from the Maka website.\nI used only this fingers-dataset to train LINEARSVC and saved the model.\nI am then using the same model to predict the outcome of all other datasets.\nThe model is performing differently on all Jaka website's datasets, but giving the same result on the Maka website's datasets. I am solving this using a regression method.\nThe problem here is that I am getting the same result for all the datasets on Maka's website. I am thinking maybe it is because I used one of the datasets on that website to train the model.\nPlease, am I missing something here?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":21,"Q_Id":69062210,"Users Score":0,"Answer":"Your train and test data should be from same I.I.D (Independent and\nIdentically Distributed). I.e. each data point (both test and train)\nshould be independent of one another and all the data point should be\nfrom same distribution.\nThere is a very high possibility that the underling datasets you are using (for train and test) are not from the same distribtu9ion.","Q_Score":0,"Tags":"python,regression,svm","A_Id":69062332,"CreationDate":"2021-09-05T09:40:00.000","Title":"LinearSVC output","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":1},{"Question":"I have a result of my pre-grouping of grouping columns like this\n\n\n\n\nLetters\nNumbers\n\n\n\n\nA\n1\n\n\nA\n2\n\n\nA\n3\n\n\nB\n1\n\n\nB\n2\n\n\nB\n3\n\n\nC\n1\n\n\nC\n1\n\n\nC\n1\n\n\n\n\nNow what I wanna do is, to define that C is a Significant factor for 1s as its 100% there but with A or B its only 33%. I wanna show that C significantly differs from A and B.\nI think there should be a solution with pandas and data frames, but I'm not really sure how to find that value. Which of the pandas Methods can I use to find that value?\nExpected Output:\nC significantly differs from A and B in its result spectrum. This is proven by this factor of significancy (this factor is what i search)\nThanks for the help in advance :).","AnswerCount":3,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":41,"Q_Id":69079825,"Users Score":0,"Answer":"I found the answer by playing more with my data.\nThe answer is to build a new dataframe with 6 columns\n\n\n\n\nA\nB\nC\n1\n2\n3\n\n\n\n\n1\n-\n-\n1\n-\n-\n\n\n1\n-\n-\n-\n1\n-\n\n\n1\n-\n-\n-\n-\n1\n\n\n-\n1\n-\n1\n-\n-\n\n\n-\n1\n-\n-\n1\n-\n\n\n-\n1\n-\n-\n-\n1\n\n\n-\n-\n1\n1\n-\n-\n\n\n-\n-\n1\n1\n-\n-\n\n\n-\n-\n1\n1\n-\n-\n\n\n\n\nThat way I can use the corr function of pandas and see how significant my \"C\" actually really is.","Q_Score":0,"Tags":"python,pandas,data-science","A_Id":69125258,"CreationDate":"2021-09-06T20:08:00.000","Title":"How to find significancy of grouped Data","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"In the examples I have found on PSM, the datasets are unbalanced. In other words, there is a small treatment group and a larger control group, from which the observations that are closest to treatment group are drawn. Through this process, we get a data set with the same number of observations for both treatment and control groups. But what if the observations in the treatment and control group are equal?\nI have a small data set with 600 observations; 300 treatment and 300 control. I want to extract observations which are not significantly different with regards to some variables across the two groups of treatment and control. How can I do that?\nIn other words, I have to restrictions:\n1 - I want my two groups to be statistically insignificant with regards to certain variables.\n2- I want to keep as many data points as possible without violating 1.\nI have worked with MatchIt in R but it does not seem to have such option.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":179,"Q_Id":69094829,"Users Score":0,"Answer":"MatchIt has several options to accomplish this. Here are a few:\n\nPair matching with a caliper (i.e., method = \"nearest\" or \"genetic\" and caliper specified). Only the closest units will be paired, leaving the unpaired units out of the final analysis. This reduces your sample size but restricts the sample to a region with a good overlap and often good resulting covariate balance but changes the estimand to one unspecified.\n\nPair matching with replacement (i.e., method = \"nearest\" or \"genetic\" and replace = TRUE). Each treated unit will be matched to a control unit, but control units can be reused, so it doesn't matter how many there are. Matching with replacement can also be used when there are more treated than control units. If no caliper is used, this method retains the ATT as the target estimand.\n\nFull matching (i.e., method = \"full\"). This forms subclasses of all units in an optimal way and then produces matching weights. No units are discarded, and it doesn't matter how many units of each treatment group there are. Any estimand can be validly targeted with this method.\n\n\nMake sure you read the MatchIt vignettes to understand these methods and how to estimate effects using them. They are all explained in detail.\nIf none of these methods are giving you balance, you might just have an inherently imbalanced sample. Weighting methods (available in the WeightIt package) might be a good alternative. You should try many methods of matching and weighting to find the one that yields the best balance while retaining precision and the target estimand (if desired).","Q_Score":0,"Tags":"python,r,propensity-score-matching","A_Id":69096995,"CreationDate":"2021-09-07T21:42:00.000","Title":"Propensity Score Matching for Balanced Datasets","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"For stanford NER 3 class model, Location, Person, Organization recognizers are available. Is it possible to add additional classes to this model. For example : Sports as one class to tag sports names.\nor if not, is there any model where i can add additional classes.\nNote: I didnt exactly mean to add \"sports\" as a class. I was wondering is there a possibility to add a custom class in that model. If not possible in stanford, is it possible with spacy..","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":39,"Q_Id":69098281,"Users Score":0,"Answer":"Sports doesn't really fall into the Entity category, as there are a limited number of them, and they are pretty fixed, unlike the names of people or locations, so you can list them all.\nI would simply set up a list of sports names, and use string matching to find them.","Q_Score":0,"Tags":"python-3.x,nlp,nltk,stanford-nlp","A_Id":69099205,"CreationDate":"2021-09-08T06:54:00.000","Title":"Adding additional classes in stanford NLP NER","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I received an excel file containing some JSON data which looks like this:-\n\n{\\currentPortfolioId\":null\/\"isNewRTQ\":true\/\"isNewInvestmentTenure\":true\/\"isNearTermVolatility\":false\/\"getPath\":true\/\"riskProfile\":\"Moderate\"\/\"initialInvestment\":200000\/\"cashflowDate\":\"01-01-2021\"\/\"currentWealth\":200000\/\"goalPriority\":\"Wish\"\/\"rebalancing\":\"yearly\"\/\"goalAmount\":2000000\/\"startDate\":\"16-06-2021\"\/\"endDate\":\"01-01-2031\"\/\"isNewGoalPriority\":true\/\"infusions\":[0\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/0]\/\"scenario_type\":\"regular\"\/\"infusion_type\":\"monthly\"\/\"xforwardForValue\":\"49.228.234.102:49907\/ 13.86.190.104:3072\/ 172.30.217.148:36243\"}\"\n\nA point to note here is that the above data is just one cell of the excel file, there is similar data located in many other cells of the excel file, the key pairs are similar in all the data as the one mentioned above.\nAs I extracted the data into python I converted it into a dictionary, as the data is mangled with lots of \"\/\" and \"\" I cleaned the data by removing these symbols and replacing \"\/\" with \",\" to make it like a dictionary.\nAfter cleaning I found out that the dictionary is mangled, as \"\" were missing in some places where it should be:-\n\n1L: '{currentPortfolioId:null,isNewRTQ:true,isNewInvestmentTenure:true,isNearTermVolatility:false,getPath:true,riskProfile:Moderate,initialInvestment:200000,cashflowDate:01-01-2021,currentWealth:200000,goalPriority:Wish,rebalancing:yearly,goalAmount:2000000,startDate:16-06-2021,endDate:01-01-2031,isNewGoalPriority:true,infusions:0,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,0,scenario_type:regular,infusion_type:monthly,xforwardForValue:49.228.234.102:49907, 13.86.190.104:3072, 172.30.217.148:36243}'\n\nAs it is visible the data appears like a long long string after cleaning rather than a proper dict. How can I use this dict to make a dataframe which can contain the columns like given in the data:- riskprofile, inititalinvestment, riskprofile, cashflowdate, infusions etc. so that the subsequent values of those key pairs inside that long string falls into subsequent rows, just like a dataframe.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":24,"Q_Id":69101530,"Users Score":0,"Answer":"I took the raw data the one you mentioned above and did some changes and considering the string to be\n'{\"\\currentPortfolioId\":null\/\"isNewRTQ\":true\/\"isNewInvestmentTenure\":true\/\"isNearTermVolatility\":false\/\"getPath\":true\/\"riskProfile\":\"Moderate\"\/\"initialInvestment\":200000\/\"cashflowDate\":\"01-01-2021\"\/\"currentWealth\":200000\/\"goalPriority\":\"Wish\"\/\"rebalancing\":\"yearly\"\/\"goalAmount\":2000000\/\"startDate\":\"16-06-2021\"\/\"endDate\":\"01-01-2031\"\/\"isNewGoalPriority\":true\/\"infusions\":[0\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/10000\/0]\/\"scenario_type\":\"regular\"\/\"infusion_type\":\"monthly\"\/\"xforwardForValue\":\"49.228.234.102:49907\/ 13.86.190.104:3072\/ 172.30.217.148:36243\"}'\nThen the next thing to be done was to replace \"\/\" with \",\" and \"\\\" to \"\" using str.replace() in python. The output I got was -\n'{\"currentPortfolioId\":null,\"isNewRTQ\":true,\"isNewInvestmentTenure\":true,\"isNearTermVolatility\":false,\"getPath\":true,\"riskProfile\":\"Moderate\",\"initialInvestment\":200000,\"cashflowDate\":\"01-01-2021\",\"currentWealth\":200000,\"goalPriority\":\"Wish\",\"rebalancing\":\"yearly\",\"goalAmount\":2000000,\"startDate\":\"16-06-2021\",\"endDate\":\"01-01-2031\",\"isNewGoalPriority\":true,\"infusions\":[0,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,0],\"scenario_type\":\"regular\",\"infusion_type\":\"monthly\",\"xforwardForValue\":\"49.228.234.102:49907, 13.86.190.104:3072, 172.30.217.148:36243\"}'\nThen I simply used json.loads() function and the data was converted into the dictionary. The output would be something like this -\n{'currentPortfolioId': None, 'isNewRTQ': True, 'isNewInvestmentTenure': True, 'isNearTermVolatility': False, 'getPath': True, 'riskProfile': 'Moderate', 'initialInvestment': 200000, 'cashflowDate': '01-01-2021', 'currentWealth': 200000, 'goalPriority': 'Wish', 'rebalancing': 'yearly', 'goalAmount': 2000000, 'startDate': '16-06-2021', 'endDate': '01-01-2031', 'isNewGoalPriority': True, 'infusions': [0, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 0], 'scenario_type': 'regular', 'infusion_type': 'monthly', 'xforwardForValue': '49.228.234.102:49907, 13.86.190.104:3072, 172.30.217.148:36243'} \u200b","Q_Score":0,"Tags":"python","A_Id":69101819,"CreationDate":"2021-09-08T10:38:00.000","Title":"How do I create a dataframe out of a long string which was supposed to be a dictionary?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a Convolutional Neural Network model made in tensorflow 2.6. I wish to deploy it in free, Heroku plan. But Heroku free plan, only allows a maximum slug size of 500MiB. Is there any way I can host the model in the Heroku free plan?\nMy end goal is to build an API, which when passed with an image in base64 format, returns a label.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":56,"Q_Id":69104320,"Users Score":0,"Answer":"I found a solution.\nUse tensorflow-cpu.\ntensorflow-cpu is much smaller than tensorflow and can fit into the maximum permissible size of Heroku for free, which is 500MiB.","Q_Score":0,"Tags":"python,tensorflow,heroku","A_Id":69123222,"CreationDate":"2021-09-08T13:48:00.000","Title":"How to deploy a tensorflow model in Heroku, within the free slug size available of 500MiB?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":1},{"Question":"Unet is a pretty popular network architecture, used in various computer vision tasks. Commonly, Unet encoder has downsampling layers that downsample by 2, which means the stride of the conv layer used will be 2 and filter sizes >3.\nFor a problem that I am trying, I want to perform downsampling 8 times ( by 2 each time). Instead of having 8 layers in the encoder, I thought I can have 4 layers that downsample by 4 each. For this, I dont think filter sizes like 3 or 5 make much sense- during the sliding, the filter will end up not covering certain pixels.\nI would like to get some pointers on how I need to alter the filter size as I alter stride and vice-versa. Additionally, would it also make sense to reduce the number of filters if I increase filter size?\nA pointer to the readers of this Q: I searched the internet for prior works that use stride 4, and found AlexNet. Its first conv layer has filters 11x11x96 and stride 4. So, I am encouraged to increase my filter size. :)","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":98,"Q_Id":69108774,"Users Score":0,"Answer":"I'm not sure if this fits your problem. But if you want to downsampling 8 times and avoid the problem of strides, you can set the padding to \"same\" in the Conv2D layers. It will apply the stride and padding with zeros evenly to the left\/right or up\/down of the input such that output has the same height\/width dimension as the input.","Q_Score":6,"Tags":"python,deep-learning,conv-neural-network,convolution","A_Id":69837125,"CreationDate":"2021-09-08T19:37:00.000","Title":"CNN: correlation between filter size and stride","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I use Visual Studio Code for all of my programming in Python, and rely heavily on the Interactive Window and Data Viewer. I usually work with large data sets, though this has only marginally affected run times in the past. For some reason recently, when clicking on a data frame in the Interactive Window, a Data Viewer tab will appear but not fully load the data frame. The blue line signaling that it is working just keeps scrolling across the top of the screen interminably. Everything else seems to work fine, and the programs are still able to run, however I can't really continue developing them.\nDoes anyone have any tips for how to make the Data Viewer work again? I have already uninstalled and re-installed Visual Studio Code, and have disabled extensions as well.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":653,"Q_Id":69110292,"Users Score":0,"Answer":"I have solved this by re-installing the Python extension. Thank you!","Q_Score":2,"Tags":"python,visual-studio-code,vscode-settings,delay,vscode-extensions","A_Id":69119644,"CreationDate":"2021-09-08T22:24:00.000","Title":"Visual Studio Code Data Viewer Issues","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to install the Dalle-pytorch, but at every try, the following error appears:\n\n[WinError 2] Le fichier sp\u00e9cifi\u00e9 est introuvable: 'c:\\python39\\Scripts\\sacremoses.exe' -> 'c:\\python39\\Scripts\\sacremoses.exe.deleteme'.\n\nCan anyone help me solve it?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":76,"Q_Id":69120103,"Users Score":0,"Answer":"Try to use pip install sacremoses","Q_Score":1,"Tags":"python","A_Id":69744186,"CreationDate":"2021-09-09T14:33:00.000","Title":"WinError 2 cannot find file: 'c:\\\\python39\\\\Scripts\\\\sacremoses.exe' -> 'c:\\\\python39\\\\Scripts\\\\sacremoses.exe.deleteme'","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"For every dataframe row I need to make a REST call and use response in order to create multiple columns in the dataframe.\nI see the following nasty solution:\n\nadd temporary column response which will contain the response\nbuild needed columns from response\nfinally remove response\n\nWhat is the proper way to solve my problem?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":146,"Q_Id":69121269,"Users Score":0,"Answer":"I solved the task with the help of rdd.mapPartitions. This seems to be the best solution.","Q_Score":0,"Tags":"python,apache-spark,pyspark","A_Id":69250869,"CreationDate":"2021-09-09T15:51:00.000","Title":"Add multiple columns to PySpark dataframe","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am reading an image using OpenCV. It looks like when I click on a pixel then I could display the pixel coordinates and info using the cv2.setMouseCallback() function. I want to display those info right under the mouse cursor.\nI searched Google and it looks like I need to use GUI libraries. Is there a similar function in OpenCV?","AnswerCount":2,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":214,"Q_Id":69127706,"Users Score":2,"Answer":"Well, it is not impossible, but you do not want to do it. OpenCV can display an image, so you would have to draw anything you need into the image and display the new image in the same window.","Q_Score":2,"Tags":"python,opencv","A_Id":69128256,"CreationDate":"2021-09-10T05:37:00.000","Title":"Displaying text under mouse cursor using OpenCV","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm pretty new to dask and have an issue I can't resolve myself.\nI've got a dask dataframe:\nDask DataFrame Structure:\nnpartitions=1622\n\n\n\n\nDate\nUserId\nAdNetwork\nRevenue\nPlatform\nInstallTime\n\n\n\n\ndatetime64[ns]\nobject\nobject\nfloat64\nobject\ndatetime64[ns]\n\n\n\n\nDask Name: assign, 28302 tasks\nI grouped this data by InstallTime and count unique users fro each day to count number of installs by date like this:\ninstalls = client.persist(total_revenue.groupby(['InstallTime', 'Platform'])['UserId'].nunique().reset_index())\nAnd got a new dask dataframe like this:\nDask DataFrame Structure:\nnpartitions=1\n\n\n\n\nindex\nInstallTime\nPlatform\nUserId\n\n\n\n\nint64\ndatetime64[ns]\nobject\nint64\n\n\n\n\nDask Name: reset_index, 1 tasks\nWhen I want to check what is in dataframe with head() or try any other functions I receive the next error:\nIndexError: Too many levels: Index has only 1 level, not 2\nWhen I'm trying to use compute() I receive the same error.\nI haven't find such a problem here or in google, so I'll appreciate any help.\nThanks!","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":429,"Q_Id":69130191,"Users Score":0,"Answer":"I've found a problem - you can group dask dataframes only by one column.\ninstalls = client.persist(total_revenue.groupby(['InstallTime'])['UserId'].nunique().reset_index())\nThis worked.","Q_Score":0,"Tags":"python,python-3.x,pandas,dataframe,dask","A_Id":69130657,"CreationDate":"2021-09-10T09:32:00.000","Title":"Why head() returns IndexError: Too many levels: Index has only 1 level, not 2 in dask dataframe?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I created a v.environment where I have Python version 3.6.5 and there I installed tensorflow-gpu.\nThe version of TensorFlow is 1.4.0 and of Keras is 2.6.0.\nWhen I write on the script import keras it appears the following Error:\n\nImportError: cannot import name 'tf2'\n\nHave you any idea?","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":8101,"Q_Id":69132718,"Users Score":1,"Answer":"From comments\n\nHere the problem caused by the TF is too old, and the keras is\ntoo new. Your choice is to downgrade keras to 2.2.1, or use newer\nversion of tf (paraphrased by Vinson Ciawandy & homomathematicus)","Q_Score":1,"Tags":"python,tensorflow,keras","A_Id":69283409,"CreationDate":"2021-09-10T13:08:00.000","Title":"Cannot import name 'tf2'","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a DataFrame I read from a CSV file and I want to store the individual values from the rows in the DataFrame in some variables. I want to use the values from the DataFrame in another step to perform another operation. Note that I do not want the result as series but values such as integers. I am still learning but I could not understand those resources I have consulted. Thank you in advance.\n\n\n\n\nX\nY\nZ\n\n\n\n\n1\n2\n3\n\n\n3\n2\n1\n\n\n4\n5\n6\n\n\n\n\nI want the values in a variable as x=1,3,4 and so on, as stated above.","AnswerCount":3,"Available Count":1,"Score":-0.0665680765,"is_accepted":false,"ViewCount":71,"Q_Id":69143210,"Users Score":-1,"Answer":"df.values is a numpy array of a dataframe. So you can manipulate df.values for subsequent processing.","Q_Score":2,"Tags":"python,pandas,dataframe","A_Id":69143234,"CreationDate":"2021-09-11T12:52:00.000","Title":"Store values from rows of a DataFrame and use them in another operation","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Has anyone been able to make tensorflow detect the GPU using python 3.7?\nHow did you do it? I've downloaded cuDNN 8.1, CUDA 11.2, then pip installed tensorflow using pip install tensorflow-gpu==2.5 I've added another environment variable for cuDNN's bin, however I am still getting this result Num GPUs Available 0. Does Tensorflow (CUDA 11.2) even work with the AMD Radeon Vega 8?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":304,"Q_Id":69145093,"Users Score":0,"Answer":"No it does not, because cuDNN is a product of NVIDIA and so is CUDA. NVIDIA designs their own GPUs and their product will look for those GPUs. In order for tensorflow to detect the GPU you will have to use one of NVIDIA's GPU.","Q_Score":0,"Tags":"tensorflow,gpu,python-3.7","A_Id":69426470,"CreationDate":"2021-09-11T17:04:00.000","Title":"Tensorflow (CUDA 11.2) not detecting GPU on a AMD Radeon Vega 8 (Envy Laptop) using Python 3.7","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I tried to import numpy but I received a ModuleNotFoundError: No module named 'numpy' error. Someone told me it could be because I didn't have numpy installed, but I already did.\nupon installing numpy I got Requirement already satisfied: numpy in .\/opt\/anaconda3\/lib\/python3.8\/site-packages.\nwhich python returns \/Users\/MacBook\/opt\/anaconda3\/bin\/python. I am new at this, but I'm guessing the reason I got that error was because the files aren't in the same place? If so, how do I move it to the right place?\nside note: I have a similar issue with matplotlib and this is running on VS code if that helps. Also I use spyder and I don't get the numpy nor the matplotlib error over there, but the error seems to be on VS code","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":670,"Q_Id":69148743,"Users Score":1,"Answer":"Try uninstalling numpy and re-installing. You also try re-install anaconda. I had this same issue and that fixed it.","Q_Score":0,"Tags":"python,numpy,path,anaconda","A_Id":69149228,"CreationDate":"2021-09-12T05:36:00.000","Title":"Python: No module named 'numpy'","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm handling some CSV files with sizes in the range 1Gb to 2Gb. It takes 20-30 minutes just to load the files into a pandas dataframe, and 20-30 minutes more for each operation I perform, e.g. filtering the dataframe by column names, printing dataframe.head(), etc. Sometimes it also lags my computer when I try to use another application while I wait. I'm on a 2019 Macbook Pro, but I imagine it'll be the same for other devices.\nI have tried using modin, but the data manipulations are still very slow.\nIs there any way for me to work more efficiently?\nThanks in advance for the responses.","AnswerCount":3,"Available Count":1,"Score":0.1325487884,"is_accepted":false,"ViewCount":1324,"Q_Id":69153017,"Users Score":2,"Answer":"This may or may not help you, but I found that storing data in HDF files has significantly improved IO speed. If you are ultimately the source of CSV files, I think you should try to store them as HDF instead. Otherwise what Michael has already said may be the way to go.","Q_Score":2,"Tags":"python,pandas,dataframe,csv","A_Id":69153412,"CreationDate":"2021-09-12T15:51:00.000","Title":"Is there a way to speed up handling large CSVs and dataframes in python?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have image with bunch of circles(intersecting and non intersecting circles) in it. I have to group each of them(non intersecting only) into group of three circles such that distance between circles must be minimum and have minimum standard deviation between them and return only one group with least distance and standard deviation between them for those circles.\nEach Circle have values such x,y,r where x,y is the center of circle and r is the radius.\nMy main intention is to find traffic light signal(red,yellow and green circle) in a given image.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":57,"Q_Id":69153442,"Users Score":0,"Answer":"I can think of the following algorithm:\n\nBuild a KD-tree for all circle centers.\nNow repeat the following:\n\ni) choose a random circle A and find its closest neigbhour B. If there is a circle collision or the radius deviates more then some threshold mark B for later use. Repeat until an acceptable neigbour B is found. If none is found mark A for later use. If B was found redo the process to find C close to A. If no C found try close to B. If both A,B,C found mark as a trafic light signal. (Validate by measuring distance between circles and centers lining up)\nii) Now unmark non-trafic light circles and repeat i) until no more A,B,C can be found.\nThe whole algorithm resembles some variation of agglomorative clustering with clusters of 3 produced.","Q_Score":0,"Tags":"python-3.x,numpy,opencv","A_Id":69153980,"CreationDate":"2021-09-12T16:44:00.000","Title":"Finding Standard deviation of circles - OpenCV related","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Is there a difference between saving the Keras model with the extension .h5 and extension .hdf5?\nIn other words, is there a difference between those two lines of code model.save('model.h5') and model.save('model.hdf5') assuming that I have a Keras model named model in my code?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":315,"Q_Id":69156551,"Users Score":0,"Answer":"An H5 file is a data file saved in the Hierarchical Data Format (HDF). Files saved in the HDF5 version are saved as an H5 or HDF5 file.\nThe extension is used so that people and applications can identify the file format from the name, so either can be used.\nIt is the same as there are multiple .jpeg, .jpg, etc. in jpeg format image files.","Q_Score":0,"Tags":"python,keras,tf.keras,hdf","A_Id":69318424,"CreationDate":"2021-09-13T02:12:00.000","Title":"What is the difference between saving Keras model with extension .h5 and extension .hdf5?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":1},{"Question":"My dataframe has these 2 columns: \"reach\" and \"height\". the column \"reach\" has a lot of missing value. But the column 'height' have all the value needed. What I see is that reach is often a function of height. Therefore, for the rows with NaN, I want to look at the height, then find another row with the same \"height\" and that has \"reach\" available, then copy this value to the 1 with missing value\n\n\n\n\nname\nSApM\nSLpM\nheight\nreach\nrecord\nstance\nstrAcc\nstrDef\nsubAvg\ntdAcc\ntdAvg\ntdDef\nweight\nborn_year\nwin\nlose\ndraw\nnc\n\n\n\n\nJustin Frazier\n6.11\n1.11\n6' 0\"\n75\n10-3-0\nSouthpaw\n0.66\n0.04\n0\n0\n0\n0\n265\n1989\n10\n3\n0\n\n\n\nGleidson Cutis\n8.28\n2.99\n5' 9\"\nnan\n7-4-0\nOrthodox\n0.52\n0.59\n0\n0\n0\n0\n155\n1989\n7\n4\n0\n\n\n\nXavier Foupa-Pokam\n2.5\n1.47\n6' 1\"\nnan\n32-22-0\nOpen Stance\n0.43\n0.49\n0\n0\n0\n0.16\n185\n1982\n32\n22\n0\n\n\n\nMirko Filipovic\n1.89\n2.11\n6' 2\"\n73\n35-11-2-(1 NC)\nSouthpaw\n0.5\n0.63\n0.3\n0.4\n0.19\n0.78\n230\n1974\n35\n11\n2\n1\n\n\nJordan Johnson\n2.64\n3.45\n6' 2\"\n79\n10-0-0\nOrthodox\n0.47\n0.53\n1.2\n0.42\n3.25\n1\n205\n1988\n10\n0\n0\n\n\n\nMartin Kampmann\n3.28\n3.22\n6' 0\"\n72\n20-7-0\nOrthodox\n0.42\n0.62\n2\n0.41\n1.86\n0.78\n170\n1982\n20\n7\n0\n\n\n\nDarren Elkins\n3.05\n3.46\n5' 10\"\n71\n27-9-0\nOrthodox\n0.38\n0.52\n1.1\n0.33\n2.67\n0.56\n145\n1984\n27\n9\n0\n\n\n\nAusten Lane\n6.32\n5.26\n6' 6\"\nnan\n2-1-0\nOrthodox\n0.35\n0.6\n0\n0\n0\n0\n245\n1987\n2\n1\n0\n\n\n\nRachael Ostovich\n3.97\n2.54\n5' 3\"\n62\n4-6-0\nOrthodox\n0.43\n0.57\n0.8\n0.83\n2.03\n0.66\n125\n1991\n4\n6\n0\n\n\n\nTravis Lutter\n2.42\n0.41\n5' 11\"\n75\n10-6-0\nOrthodox\n0.32\n0.42\n0.7\n0.24\n1.95\n0.3\n185\n1973\n10\n6\n0\n\n\n\nTom Murphy\n0.17\n2.5\n6' 2\"\nnan\n8-0-0\nSouthpaw\n0.71\n0.84\n2.5\n0.85\n7.51\n0\n227\n1974\n8\n0\n0\n\n\n\nDarrell Montague\n5.38\n1.92\n5' 6\"\n67\n13-5-0\nSouthpaw\n0.25\n0.52\n1.4\n0.25\n0.72\n0.33\n125\n1987\n13\n5\n0\n\n\n\nLauren Murphy\n4.25\n3.95\n5' 5\"\n67\n15-4-0\nOrthodox\n0.4\n0.61\n0.1\n0.34\n1.16\n0.7\n125\n1983\n15\n4\n0\n\n\n\nBill Mahood\n3.59\n1.54\n6' 3\"\nnan\n20-7-1-(1 NC)\nOrthodox\n0.85\n0.17\n3.9\n0\n0\n0\n200\n1967\n20\n7\n1\n1\n\n\nNate Marquardt\n2.32\n2.71\n6' 0\"\n74\n35-19-2\nOrthodox\n0.49\n0.55\n0.8\n0.51\n1.87\n0.7\n185\n1979\n35\n19\n2\n\n\n\nMike Polchlopek\n1.33\n2\n6' 4\"\nnan\n1-1-0\nOrthodox\n0.38\n0.57\n0\n0\n0\n0\n285\n1965\n1\n1\n0\n\n\n\nHarvey Park\n7.21\n3.77\n6' 0\"\n70\n12-3-0\nOrthodox\n0.5\n0.33\n0\n0\n0\n0\n155\n1986\n12\n3\n0\n\n\n\nJunyong Park\n3.17\n4.37\n5' 10\"\n73\n13-4-0\nOrthodox\n0.47\n0.58\n0.6\n0.57\n3.02\n0.46\n185\n1991\n13\n4\n0\n\n\n\nRicco Rodriguez\n1.15\n1.85\n6' 4\"\nnan\n53-25-0-(1 NC)\nOrthodox\n0.51\n0.61\n1\n0.39\n2.3\n0.4\n265\n1977\n53\n25\n0\n1\n\n\nAaron Riley\n3.78\n3.45\n5' 8\"\n69\n30-14-1\nSouthpaw\n0.34\n0.61\n0.1\n0.34\n1.18\n0.6\n155\n1980\n30\n14\n1","AnswerCount":2,"Available Count":1,"Score":0.0996679946,"is_accepted":false,"ViewCount":146,"Q_Id":69164852,"Users Score":1,"Answer":"I think that a method does not exist to do that in a simple step.\nIf i were in your shoes I would:\n\nCreate a support dataset made up of height|reach fully populated, in which I would store my best guess values\nJoin the support dataframe with the existing ones, using height as key\nCoalesce the values where NaN appears: df.reach = df.reach.fillna(df.from_support_dataset_height)","Q_Score":1,"Tags":"python,pandas","A_Id":69164998,"CreationDate":"2021-09-13T14:55:00.000","Title":"fill NaN with values of a similar row","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I get a file not found error while using the read_csv() function on a Jupyter notebook even when I have the exact path listed. Any pointers on why this happens? Googled it and one solution was to prefix the path with 'r' which worked. However why is this prefix required?","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":36,"Q_Id":69170070,"Users Score":0,"Answer":"This is raw strings event. It is necessary on Windows operating systems when the path contains backslashes. Otherwise the backslash is treated as an escape character. For example, \"hello\\nworld\" -- the \\n means a newline. r\"hello\\nworld\" literally means the characters \"hello\\nworld\" And in this way we can see in the screen\nhello world","Q_Score":0,"Tags":"python,jupyter","A_Id":69170118,"CreationDate":"2021-09-13T23:21:00.000","Title":"file not found error while using read_csv on a Jupyter notebook","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to improve my classification model, using statsmodel in LogisticRegression i note that some features that didn't pass in t test and don't have many influency when i use this model are very important when i change the model, for example i looked up to feature_importances of a RandomForestClassifier and the more important feature did not influence LogisticRegression.\nWith this in mind, i thought to use LogisticRegression without this feature and use the predict_proba to pick the probabilities, then i create another model using RandomForest but now using all features and including the logisticRegressor probabilities. Or i can pick all probabilities of many models and use them as features of another model.. Anything of This make sense? I dont know if i am inserting any bias doing this and why.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":29,"Q_Id":69170933,"Users Score":0,"Answer":"I found that what I was doing was stacking, but instead of using another model's response as a feature, I was using the probability of being 1 (predict_proba).","Q_Score":0,"Tags":"python,machine-learning,scikit-learn,prediction,method-combination","A_Id":69269138,"CreationDate":"2021-09-14T01:58:00.000","Title":"May i use the sklearn predict_proba of a model (LogisticRegression for example) as a feature of another model (RandomForestClassifier for example)?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am working on image detection where I am detecting and classifying an image into one of 14 different thoric diseases (multi-label classification problem).\nThe model is trained on NIH dataset with which I get 80% AUC. Now I want to improve the model by training on a second dataset. But the main problem is both dataset's classes are not matched.\nThe second dataset contains 10 classes that overlap with the first dataset with which I trained the model.\nQuestions:\n\nIs it possible to retrain a model on fewer classes.\n\nWill retraining my model on a new dataset impact the AUC of other non-similar classes?\n\nHow big is the chance that this will improve the model?\n\n\nThe model and code are based on fast.ai and PyTorch.","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":135,"Q_Id":69175045,"Users Score":2,"Answer":"Based on discussion in the comments:\n\nYes, if the classes overlap (with different data points from a different dataset) you can train the same classifier layer with two datasets. This would mean in one of the datasets, 4 out of 14 classes are simply not trained. What this means is that you are basically making your existing 14-class dataset more imbalanced by adding more samples for only 10 out of 14 classes.\nTraining on 10 out of 14 classes will introduce a forgetting effect on the 4 classes that are not trained additionally. You can counteract this somewhat by using the suggested alternate training, or by combining all the data into one big dataset, but this does not solve the fact that the new combined dataset is then probably more imbalanced than the original 14-class dataset. Unless the 4 classes not in the 10-class dataset are for some reason over represented in the 14-class dataset, but I assume you're not going to get that lucky.\nBecause both your dataset and your model will focus heavier on 10 out of the 14 classes, your accuracy may go up. However, this means that the 4 classes that do not overlap are simply being ignored in favor of higher accuracy on the remaining 10 classes. On paper, the numbers may look better, but in practice you're making your model less useful for a 14-class classification task.","Q_Score":3,"Tags":"python,pytorch,object-detection","A_Id":69204738,"CreationDate":"2021-09-14T09:12:00.000","Title":"Is it possible to retrain a trained model on fewer classes?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I was wondering if the learning rate is set to update the weights during the backpropagation on the layers of a neural network. How and where do the weights get updated?\nI can't see the connection between optimizer, learning rate, and the backpropagation function.","AnswerCount":2,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":45,"Q_Id":69178744,"Users Score":2,"Answer":"The gradient descent algorithm has the learning rate term in it. Since the gradient descent is backpropagated, the learning rate is taken into account during backpropagation.","Q_Score":0,"Tags":"python,optimization,pytorch","A_Id":69178888,"CreationDate":"2021-09-14T13:30:00.000","Title":"How does Learning Rate affect Gradients in Back Prop","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to find a way, either in R or Python, to use a dataframe as a table in an Oracle SQL statement.\nIt is impractical, for my objective, to:\n\nCreate a string out of a column and use that as a criteria (more than a 1k, which is the limit)\nCreate a new table in the database and use that (don't have access)\nDownload the entire contents of the table and merge in pandas (millions of records in the database and would bog down the db and my system)\n\nI have found packages that will allow you to \"register\" a dataframe and have it act as a \"table\/view\" to allow queries against it, but it will not allow them to be used in a query with a different connection string. Can anyone point me in the right direction? Either to allow two different connections in the same SQL statement (to Oracle and a package like DuckDB) to permit an inner join or direct link to the dataframe and allow that to be used as a table in a join?\nSAS does this so effortlessly and I don't want to go back to SAS because the other functionality is not as good as Python \/ R, but this is a dealbreaker if I can't do database extractions.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":116,"Q_Id":69181208,"Users Score":0,"Answer":"Answering my own question here -- after much research.\nIn short, this cannot be done. A series of criteria, outside of a list or concat, you cannot create a dataframe in python or R and pass it through a query into a SQL Server or Oracle database. It's unfortunate, but if you don't have permissions to write to temporary tables in the Oracle database, you're out of options.","Q_Score":0,"Tags":"python,r,pandas,oracle,join","A_Id":69894161,"CreationDate":"2021-09-14T16:12:00.000","Title":"Python or R -- create a SQL join using a dataframe","Data Science and Machine Learning":1,"Database and SQL":1,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am trying to come up with an experimental solution for a problem related to prediction (similar to stock price prediction).\nI've been reading a lot of documentation about using Machine Learning and about stock prices prediction using LSTM (keras and tensorflow). I understand the general theory of machine learning in itself and how a LSTM layer works behind the scenes.\nMy main concern is that every tutorial about stock price prediction I find, it comes up with a different amount of hidden LSTM layers and each one of them has a pre-defined number of units without much explanation. In the case of the classic \"Apple (AAPL) stock price prediction\" scenario, I see tutorials with 3 layers and 50 units, others with only 2 layers but 128 units.\nIn the case I have to code something by myself, how can I determine the amount of LSTM and the amount of units for the prediction to function properly? My main guess at the moment is trying to figure it out with trials and errors. I was wondering if there is some sort of relation between the problem, the data and the solution.\nAlso if someone can explain the effects of having more\/less LSTM layers and more\/less units other than doing more calculations, it would be awesome!","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":56,"Q_Id":69194730,"Users Score":1,"Answer":"A good method is to start with a small dataset, with a few features.\nCreate a very simple neural model and try to train it on this set.\nIf your net predicts the test-set correctly, it complicates the dataset and re-train.\nBut , if net does not work, it increases its size, by adding nodes or layer.\nWhen dataset is full of all features, you have a best network for this task","Q_Score":0,"Tags":"python,machine-learning,keras,lstm,prediction","A_Id":69196262,"CreationDate":"2021-09-15T14:07:00.000","Title":"How to determine the amount of layers and unit count in price prediction with Machine Learning and LSTM?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"target_positive_replace = np.where(positive_replace[...,0]>0 or positive_replace[...,1]>0 or positive_replace[...,2]>0),target_positive_replace[...,1]=255 ,0) \nI have a three-channel RGB image.\nWant to perform above operation.\nif one of the given values in a channel is greater than zero (channel value>0). I want to make that pixel green. (0,255,0).\n\nValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":42,"Q_Id":69208338,"Users Score":0,"Answer":"Your problem is that positive_replace[...,x] returns an array which cannot be checked with >0(wrong). So as the Error Message states you can either check each element of the returned array with a.all() or a.any() or you have to make sure to retreive the integer color value.\nEdit\nThe above is only partially true. As @Cris Luengo states in his comment or expects a single value, not an array. So either compare single values with a.all() and a.any() or compare the boolean array returned by positive_replace[...,x]>0 with |","Q_Score":0,"Tags":"python,numpy,image-processing","A_Id":69208482,"CreationDate":"2021-09-16T12:21:00.000","Title":"replacing pixel value of one channel based on values of other two channels","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"In a real system, some sensor data will be dumped into specific directory as csv files. Then some data pipeline will populate these data to some database. Another pipeline will send these data to predict service.\nI only have training and validation csv files as of now. I'm planning to simulate the flow to send data to predict service following way:\nDAG1 - Every 2 min, select some files randomly from a specific path and update the timestamp of those files. Later, I may chose to add a random delay after the start node.\nDAG2 - FileSensor pokes every 3 min. If it finds subset of files with modified timestamp, it should pass those to subsequent stages to eventually run the predict service.\nIt looks to me if I use FileSensor as-is, I can't achieve it. I'll have to derive from FileSensor class (say, MyDirSensor), check the timestamp of all the files - select the ones which are modified after the last successful poke and pass those forward.\nIs my understanding correct? If yes, for last successful poke timestamp, can I store in some variable of MyDirSensor? Can I push\/pull this data to\/from xcom? What will be task-id in that case? Also, how to pass these list of files to the next task?\nIs there any better approach (like different Sensor etc.) for this simulation? I'm running the whole flow on standalone machine currently. My airflow version is 1.10.15.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":182,"Q_Id":69217245,"Users Score":1,"Answer":"I am not sure if current Airflow approach is best for this use case actually. In the current incarnation Airflow is really all about working on \"data intervals\" - so basically each \"dag run\" is connected to some \"data interval\" and it should be processing data for that data interval. Classic Batch processing.\nIf I understand your case is more like a streaming (not entirely) but close. You get some (subset of) data which arrived since the last time and you process that data. This is not what (again current) version of Airflow - not even 2.1 is supposed to handle - because there is a complex manipulation of \"state\" which is not \"data interval\" related (and Airflow currently excels in the \"data interval\" case).\nYou can indeed do some custom operators to handle that. I think there is no ready-to-reuse pattern in Airflow for what you want to achieve, but Airflow is flexible enough that if you write your own operators you can certainly work around it and implement what you want. And writing operators in Airflow is super easy - it's a simple Python class with \"execute\" which can reuse existing Hooks to reach out to external services\/storages and use XCom for communication between tasks. It's surprisingly easy to add a new operator doing even complex logic (and again - reusing hooks to make it easier to communicate with external services). For that, I think it's still worth to use Airflow for what you want to do.\nHow I would approach it - rather than modifying the timestamps of the files, I'd create other files - markers - with the same names, different extensions and base my logic of processing on that (this way you can use the external storage as the \"state\"). I think there will be no ready \"operators\" or \"sensors\" to help with it, but again - writing custom one is easy and should work.\nHowever soon (several months) in Airflow 2.2 (and even more in 2.3) we are going to have some changes (mainly around flexible scheduling and decoupling dag runs from data intervals and finally to allow dynamic DAG with flaxible structure that can change per-run) that will provide some nice way of handling cases similar to yours.\nStay tuned - and for now rely on your own logic, but look out for simplifying that in the future when Airflow will be better suited for your case.\nAnd in the meantime - do upgrade to Airflow 2. It's well worth it and Airflow 1.10 reached end of life in June, so the sooner you do, the better - as there will not be any more fixes to Airflow 1.10 (even critical security fixes)","Q_Score":0,"Tags":"python-3.x,airflow","A_Id":69221007,"CreationDate":"2021-09-17T02:57:00.000","Title":"How to retrieve recently modified files using airflow FileSensor","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":1,"Web Development":0},{"Question":"I first installed Spyder and then afterwards Python on a server (with Windows Server 2019) all on the directory \"C:\\Users\\wi932\\ .spyder-py3\" and the Python folder \"C:\\Users\\wi932\\Python\\Python38\". Then I installed many packages (like tensorflow, matplotlib, scikitlearn) by using the command prompt of windows and pip from the directory \"C:\\Users\\wi932\\Python\\Python38\\Scripts\" and it was okay.\nHowever, when running Spyder I can't use the packages that I installed using pip. Whenever I run a Python programm with those modules I get an error message \"ModuleNotFoundError: No module named 'tensorflow'\". So the question is how can I build a \"connection\" between the pip and Spyder?\nDoes anyone have an idea? I'll appreciate every comment.","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":331,"Q_Id":69222344,"Users Score":1,"Answer":"Have you considered installing anaconda?\nSpyder comes as a part of this and is easy to install from the anaconda client. You can also create your base environment in the anaconda client and then switch to pip to install packages from there.","Q_Score":0,"Tags":"python,pip,spyder","A_Id":69222514,"CreationDate":"2021-09-17T11:03:00.000","Title":"Spyder can't find installed modules with pip","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have taken an input dataset and did some transformations on it, then wrote it into the output dataset.\nI have built this output dataset, and now I have to take the time taken to build the output dataset and compare that with a threshold time provided. If the build duration is greater than the threshold given, I have to throw a warning or alert\nFor example\nBuild time : 120 minutes\nThreshold : 100 min\nAs Build time is more than threshold it should throw a warning","AnswerCount":1,"Available Count":1,"Score":0.3799489623,"is_accepted":false,"ViewCount":76,"Q_Id":69254864,"Users Score":2,"Answer":"You can use a Data Health check to receive this kind of alert. From the dataset preview page click the Health tab. Under the Add Checks section click Time and then Job Duration. This will open a modal dialog where you can set the threshold time and create the check.\nOnce the check is created you will receive an email whenever a build on this dataset lasts longer than the specified threshold time.","Q_Score":1,"Tags":"pyspark,palantir-foundry,foundry-code-repositories,foundry-python-transform","A_Id":69257605,"CreationDate":"2021-09-20T12:59:00.000","Title":"How to throw a warning if threshold value exceeds in foundry code repositories","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have used Gensim library to find the similarity between a sentence against a collection of paragraphs, a dataset of texts. I have used Cosine similarity, Soft cosine similarity and Mover measures separately. Gensim returns a list of items including docid and similarity score. For Cosine similarity and Soft cosine similarity, I guess the similarity score is the cosine between the vectors. Am I right?\nIn Gensim documents, they wrote it is the semantic relatedness, and no extra explanation. I have search a lot, but did not find any answer. Any help please","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":29,"Q_Id":69258013,"Users Score":0,"Answer":"Usually by 'similarity', people are seeking to find a measure semantic relatedness - but whether the particular values calculated achieve that will depend on lots of other factors, such as the sufficiency of training data & choice of other appropriate parameters.\nWithin each code context, 'similarity' has no more and no less meaning than how it's calculated right there - usually, that's 'cosine similarity between vector representations'. (When there's no other hints it means something different, 'cosine similarity' is typically a safe starting assumption.)\nBut really: the meaning of 'similarity' at each use is no more and no less than whatever that one code path's docs\/source-code dictate.\n(I realize that may seem an indirect & unsatisfying answer. If there are specific uses in context in Gensim source\/docs\/example where the meaning is unclear, you could point those out & I might be able to clarify those more.)","Q_Score":0,"Tags":"python,text,gensim,sentence-similarity","A_Id":69258490,"CreationDate":"2021-09-20T16:37:00.000","Title":"What does Similarity Score mean in gensim?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I'm using GNU Radio for receive radio signal and write it to file (complex) with metadata.\nThen I parse file in python and I have variable with 1 sample (8 byte). I want to build FFT plot for just 1 specific sample or save it as image.\nIs that real? Can I do that with GRC, or maybe python have lib for that?\nThank you","AnswerCount":1,"Available Count":1,"Score":0.1973753202,"is_accepted":false,"ViewCount":143,"Q_Id":69260603,"Users Score":1,"Answer":"Your question makes no sense: the FFT of a single sample is just that sample. That's the definition of an FFT.\nThink of it that way: a spectrum tells you which frequencies are in a signal.\nWhat frequency components are in the signal \"0.23\" ? Only exactly one frequency component: a constant component of amplitude 0.23.","Q_Score":0,"Tags":"python,gnuradio,gnuradio-companion","A_Id":69260745,"CreationDate":"2021-09-20T20:44:00.000","Title":"Gnuradio: FFT plot for 1 sample","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Suppose we have 2 AVL trees (with methods insert(key) and delete(key)), but in one of them there exist corrupted nodes (the number of corrupted nodes is much less than the total number of nodes in that tree).\nWe want to merge 2 AVL trees into 1 single AVL tree such that the corrupted nodes are removed (we have the list of keys of corrupted nodes).\nThe \"naive\" algorithm is (assume tree 1 contains corrupted nodes): For each of the corrupted nodes, delete it from tree 1. Then insert all remaining nodes from tree 1 to tree 2, so the final AVL tree is the \"merged\" tree we want.\nNow the question is coming up with a more efficient way to merge 2 trees, better than the naive algorithm above.\nAnyone has any idea? Thanks for your help!","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":62,"Q_Id":69264141,"Users Score":0,"Answer":"A binary search tree can list its nodes in increasing order in linear time O(N). You can organize a merging process where you enumerate the nodes of both trees simultaneously, fetching the nodes in global order (and dropping the corrupt ones).\nIf you store the sorted elements in an array, it is possible to convert to a new balanced BST in linear time. You make it AVL by just setting all balance factors.\nI doubt that it is possible to construct the new tree without first merging to an intermediate array. (Which only needs to be an array of pointers.)","Q_Score":0,"Tags":"python,database,algorithm,avl-tree,lookup-tables","A_Id":69265180,"CreationDate":"2021-09-21T06:08:00.000","Title":"Merge 2 AVL trees with corrupted nodes in one of them","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a data set of ~150 samples where for each sample I have 11 inputs and 3 outputs. I tried to build a full regression model to take in 11 inputs to be trained to predict the 3 outputs The issue is with so few samples training a full model is almost impossible. For this reason I am experimenting with regression such as linear regression in pythons sklearn. From what I can find most regression models either support one input to predict one output (after regression is complete) or many inputs to predict one output.\nQuestion: Are there any types of regression that support many inputs to predict many outputs. Or perhaps any regression types at all that may be better suited for my needs.\nThank you for any help!","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":29,"Q_Id":69276241,"Users Score":0,"Answer":"Have you considered simply performing separate linear regressions for each dependent variable?\nAlso, you need to decide which inputs are theoretically significant (in terms of explaining the variation in the output) and then test for statistical significance to determine which ones should be retained in the model.\nAdditionally, test for multicollinearity to determine if you have variables which are statistically related and inadvertently influencing the output. Then, test in turn for serial correlation (if the data is a time series) and heteroscedasticity.\nThe approach you are describing of \"garbage in, garbage out\" risks overfitting - since you don't seem to be screening the inputs themselves for their relevance in predicting the output.","Q_Score":0,"Tags":"python,machine-learning,regression","A_Id":69276319,"CreationDate":"2021-09-21T22:29:00.000","Title":"Machine Learning Regression To Support Multi Variable Regression","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I am stuck on a problem about Olympics athletes.\nI need to find the number of different sports each country participates in from my data frame, I am unsure how to do this as the column 'country' obviously has duplicates as well as the column 'sport' and I cant figure out how to group them and return a value for each country\nAny help would be awesome :)","AnswerCount":2,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":53,"Q_Id":69278131,"Users Score":0,"Answer":"import pandas as pd\ndf = pd.DataFrame([{'Country': 'India', 'Sport': 'Badmintan'}, {'Country': 'China', 'Sport': 'Badmintan'},{'Country': 'India', 'Sport': 'Football'}])\nprint(df)\nprint(df.groupby(by=('Country')).count())\nAnswer:\nCountry\nChina 1\nIndia 2","Q_Score":0,"Tags":"python,pandas,dataframe","A_Id":69278482,"CreationDate":"2021-09-22T04:18:00.000","Title":"Finding number of times a sport comes up for each country python data frame","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":1,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a column of a dataframe which contains 6 unique values of:\n1, 2, 3, [1,2], [2,3], [1,2,3]\nI am trying use pandas.DataFrame.replace to replace [1,2] with 4 when i have tried the code below:\nx = df2['lockdown_level'].replace([1,2],4)\ni get an output:\n4, 4, 3, [1,2], [2,3], [1,2,3]\nwhereas i want the output of the unique values to be:\n1, 2, 3, 4, [2,3], [1,2,3]\nDoes anyone have any suggestions to replace a list with a single value?","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":46,"Q_Id":69281752,"Users Score":2,"Answer":"I would it do like this:\ndf2['lockdown_level'].apply(lambda x: 4 if x==[1, 2] else x)\nEleonora","Q_Score":0,"Tags":"python,pandas,list,dataframe","A_Id":69282038,"CreationDate":"2021-09-22T09:41:00.000","Title":"I am trying to use pandas.DataFrame.replace to replace cells that contain lists with a single values?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Can I find a value from Z column if I have two known values from X and Y?\n\n\n\n\nX;\nY;\nZ\n\n\n\n\nA;\n1;\nsyfgusj\n\n\nA;\n2;\nadaddsfd\n\n\nB;\n1;\nadsghfjgftrds\n\n\nB;\n2m;\nadergtw\n\n\nC;\n1;\nadergtw\n\n\nC;\n2;\naddfgftre\n\n\n\n\nValues in Y column are string type.\nI should find value in Z column by known values from columns X and Y.\nI converted CSV to list of lists, but can`t even imagine how to make next step.","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":40,"Q_Id":69283881,"Users Score":0,"Answer":"Considering values are unique, I would store the csv on a pandas dataframe, and then iterate over every row on the dataframe. If column 1 value and column 2 values are the ones you know, then return the z value from that exact row.\nThat should do it, tell me if u need further help!","Q_Score":0,"Tags":"python,list,csv","A_Id":69283941,"CreationDate":"2021-09-22T12:06:00.000","Title":"Python CSV get a value from a cell by value from previous columns","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"Is it necessary to normalize pixel values if there are only black and white ones (nothing in between\/no greys), before feeding into ResNet18 for classification?\nIOW, is this transform necessary?\ntransforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\nNote: I'm currently stacking each black and white image 3 times so it aligns with ResNet's RGB expectation.","AnswerCount":1,"Available Count":1,"Score":1.2,"is_accepted":true,"ViewCount":108,"Q_Id":69290712,"Users Score":1,"Answer":"the model is trained expecting values with 0 mean and some measured variance.\nThinking about your case, you would getting something like, eg,\nblue channel pixel with 1:\n(1-0.485)\/0.229 = 2.24\nand for pixel with 0:\n(0-0.485)\/0.229 = -2.11\nIf you are using pre trained weights i would guess that yes, it is necessary, otherwise, you can measure it in your training accuracy.\nAnyway, if you are not sure, test the result with and without it.","Q_Score":1,"Tags":"python,deep-learning,conv-neural-network,grayscale,resnet","A_Id":69290798,"CreationDate":"2021-09-22T20:12:00.000","Title":"Is it necessary to normalize pixel values if there are only black and white ones (no greys)?","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0},{"Question":"I have a large CSV file(300mb) with data about accidents based on pincodes\/zipcodes. The file has basically header and comma separated values. Key fields are Month, Date, Year, Pincode, Count.\nCount represents the accident count for that pincode, however each pincode can get several entries through the day say every few hours. So I want to be able to calculate the max accidents per pincode on a given date i.e I need to group by Month, Date, Year, Pincode and then sum over count after grouping?\nI have an idea of how to do this if I loaded the large-ish file into a database or a cloud service such as GCP BigQuery but I want to be able to do this with Python\/Pandas dataframes and then store the metrics I am calculating in a table. Is this approach possible with Pandas, if not then possibly PySpark is my last option but that involves the overhead of having to setup a Hadoop etc.\nI am open to any other ideas as I am a PyNovice :)\nThank you","AnswerCount":1,"Available Count":1,"Score":0.0,"is_accepted":false,"ViewCount":67,"Q_Id":69300550,"Users Score":0,"Answer":"You can signup for Databricks Community Edition (for free), in which you can easily have a Spark-ready environment, also easy enough to upload your CSV file.","Q_Score":0,"Tags":"python,pandas,dataframe,pyspark","A_Id":69302686,"CreationDate":"2021-09-23T13:00:00.000","Title":"How to read, groupby and calculate over a large CSV file in Python","Data Science and Machine Learning":1,"Database and SQL":0,"GUI and Desktop Applications":0,"Networking and APIs":0,"Other":0,"Python Basics and Environment":0,"System Administration and DevOps":0,"Web Development":0}]