GUI and Desktop Applications
int64 0
1
| A_Id
int64 5.3k
72.5M
| Networking and APIs
int64 0
1
| Python Basics and Environment
int64 0
1
| Other
int64 0
1
| Database and SQL
int64 0
1
| Available Count
int64 1
13
| is_accepted
bool 2
classes | Q_Score
int64 0
1.72k
| CreationDate
stringlengths 23
23
| Users Score
int64 -11
327
| AnswerCount
int64 1
31
| System Administration and DevOps
int64 0
1
| Title
stringlengths 15
149
| Q_Id
int64 5.14k
60M
| Score
float64 -1
1.2
| Tags
stringlengths 6
90
| Answer
stringlengths 18
5.54k
| Question
stringlengths 49
9.42k
| Web Development
int64 0
1
| Data Science and Machine Learning
int64 1
1
| ViewCount
int64 7
3.27M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 19,621,115 | 0 | 0 | 0 | 0 | 1 | false | 1 | 2013-10-27T14:37:00.000 | 0 | 2 | 0 | cannot install scipy on openshift | 19,619,253 | 0 | python,scipy,openshift | You will probably find more info sshing into your app ad typing tail_all. | I want to install scikit-learn but this library needs scipy and numpy too.
I tried to add them on the setup.py but I had an error with numpy. I handle to install scikit-learn and numpy from virtenv, but I cannot install scipy.
I tried pip install scipy. The procedure finished without any problem but there isn't any scipy folder on site-packages.
Also, I tried to add only scipy on setup.py. The same as above. The procedure finished without an error but scipy isn't there.
Any help? | 0 | 1 | 651 |
0 | 19,662,546 | 0 | 1 | 0 | 0 | 1 | false | 10 | 2013-10-29T13:40:00.000 | 0 | 3 | 0 | iPython nbconvert and latex: use .eps instead of .png for plots | 19,659,864 | 0 | ipython | NBconvert does not run your code. So if you haven't plotted with SVG matplotlib backend it is not possible.
If you did so, then you need to write a nbconvert preprocessor that does svg-> eps and extend the relevant template to know how to embed EPS. | I have an iPython notebook that contains an inline plot (i.e. it contains the command plot(x,y)). When I issue the command ipython nbconvert --to latex --post PDF --SphinxTransformer.author='Myself' MyNotebook.ipynb the resulting .PDF file contains the figure, but it has been exported to .PNG, so it doesn't look very good (pixelated). How can I tell nbconvert to export all plots/figures to .EPS instead?
Thank you | 0 | 1 | 5,738 |
0 | 19,696,243 | 0 | 0 | 0 | 0 | 1 | false | 0 | 2013-10-30T03:27:00.000 | 0 | 1 | 0 | UserWarning: X scores are null at iteration | 19,673,279 | 0 | python,classification,scikit-learn | CCA doesn't support sparse matrices. By default, you should assume scikit-learn estimators do not grok sparse matrices and check their docstrings to find out if by chance you found one that does.
(I admit the warning could have been friendlier.) | I am trying to run CCA for a multi label/text classification problem but keep getting following warning and an error which I think are related
warnings.warn('Maximum number of iterations reached')
/Library/Python/2.7/site-packages/sklearn/cross_decomposition/pls_.py:290:
UserWarning: X scores are null at iteration 0 warnings.warn('X
scores are null at iteration %s' % k)
warnings.warn('Maximum number of iterations reached')
/Library/Python/2.7/site-packages/sklearn/cross_decomposition/pls_.py:290:
UserWarning: X scores are null at iteration 1
warnings.warn('X scores are null at iteration %s' % k)
...
for all the 400 iterations and then following error at the end which I think is a side effect of above warning:
Traceback (most recent call last): File "scikit_fb3.py", line 477,
in
getCCA(shorttestfilepathPreProcessed) File "scikit_fb3.py", line 318, in getCCA
X_CCA = cca.fit(x_array, Y_indicator).transform(X) File "/Library/Python/2.7/site-packages/sklearn/cross_decomposition/pls_.py",
line 368, in transform
Xc = (np.asarray(X) - self.x_mean_) / self.x_std_ File "/usr/local/bin/src/scipy/scipy/sparse/compressed.py", line 389, in
sub
raise NotImplementedError('adding a nonzero scalar to a ' NotImplementedError: adding a nonzero scalar to a sparse matrix is not
supported
What could possibly be wrong? | 0 | 1 | 877 |
0 | 19,676,762 | 0 | 1 | 0 | 0 | 2 | true | 127 | 2013-10-30T07:44:00.000 | 155 | 3 | 0 | Numpy array assignment with copy | 19,676,538 | 1.2 | python,arrays,numpy | All three versions do different things:
B = A
This binds a new name B to the existing object already named A. Afterwards they refer to the same object, so if you modify one in place, you'll see the change through the other one too.
B[:] = A (same as B[:]=A[:]?)
This copies the values from A into an existing array B. The two arrays must have the same shape for this to work. B[:] = A[:] does the same thing (but B = A[:] would do something more like 1).
numpy.copy(B, A)
This is not legal syntax. You probably meant B = numpy.copy(A). This is almost the same as 2, but it creates a new array, rather than reusing the B array. If there were no other references to the previous B value, the end result would be the same as 2, but it will use more memory temporarily during the copy.
Or maybe you meant numpy.copyto(B, A), which is legal, and is equivalent to 2? | For example, if we have a numpy array A, and we want a numpy array B with the same elements.
What is the difference between the following (see below) methods? When is additional memory allocated, and when is it not?
B = A
B[:] = A (same as B[:]=A[:]?)
numpy.copy(B, A) | 0 | 1 | 76,805 |
0 | 19,676,652 | 0 | 1 | 0 | 0 | 2 | false | 127 | 2013-10-30T07:44:00.000 | 33 | 3 | 0 | Numpy array assignment with copy | 19,676,538 | 1 | python,arrays,numpy | B=A creates a reference
B[:]=A makes a copy
numpy.copy(B,A) makes a copy
the last two need additional memory.
To make a deep copy you need to use B = copy.deepcopy(A) | For example, if we have a numpy array A, and we want a numpy array B with the same elements.
What is the difference between the following (see below) methods? When is additional memory allocated, and when is it not?
B = A
B[:] = A (same as B[:]=A[:]?)
numpy.copy(B, A) | 0 | 1 | 76,805 |
0 | 19,724,359 | 0 | 0 | 0 | 0 | 2 | false | 12 | 2013-10-31T18:33:00.000 | 0 | 5 | 0 | Supervised Dimensionality Reduction for Text Data in scikit-learn | 19,714,108 | 0 | python,machine-learning,scikit-learn,dimensionality-reduction | Use a multi-layer neural net for classification. If you want to see what the representation of the input is in the reduced dimension, look at the activations of the hidden layer. The role of the hidden layer is by definition optimised to distinguish between the classes, since that's what's directly optimised when the weights are set.
You should remember to use a softmax activation on the output layer, and something non-linear on the hidden layer (tanh or sigmoid). | I'm trying to use scikit-learn to do some machine learning on natural language data. I've got my corpus transformed into bag-of-words vectors (which take the form of a sparse CSR matrix) and I'm wondering if there's a supervised dimensionality reduction algorithm in sklearn capable of taking high-dimensional, supervised data and projecting it into a lower dimensional space which preserves the variance between these classes.
The high-level problem description is that I have a collection of documents, each of which can have multiple labels on it, and I want to predict which of those labels will get slapped on a new document based on the content of the document.
At it's core, this is a supervised, multi-label, multi-class problem using a sparse representation of BoW vectors. Is there a dimensionality reduction technique in sklearn that can handle that sort of data? Are there other sorts of techniques people have used in working with supervised, BoW data in scikit-learn?
Thanks! | 0 | 1 | 4,068 |
0 | 19,714,792 | 0 | 0 | 0 | 0 | 2 | false | 12 | 2013-10-31T18:33:00.000 | 0 | 5 | 0 | Supervised Dimensionality Reduction for Text Data in scikit-learn | 19,714,108 | 0 | python,machine-learning,scikit-learn,dimensionality-reduction | Try ISOMAP. There's a super simple built-in function for it in scikits.learn. Even if it doesn't have some of the preservation properties you're looking for, it's worth a try. | I'm trying to use scikit-learn to do some machine learning on natural language data. I've got my corpus transformed into bag-of-words vectors (which take the form of a sparse CSR matrix) and I'm wondering if there's a supervised dimensionality reduction algorithm in sklearn capable of taking high-dimensional, supervised data and projecting it into a lower dimensional space which preserves the variance between these classes.
The high-level problem description is that I have a collection of documents, each of which can have multiple labels on it, and I want to predict which of those labels will get slapped on a new document based on the content of the document.
At it's core, this is a supervised, multi-label, multi-class problem using a sparse representation of BoW vectors. Is there a dimensionality reduction technique in sklearn that can handle that sort of data? Are there other sorts of techniques people have used in working with supervised, BoW data in scikit-learn?
Thanks! | 0 | 1 | 4,068 |
0 | 19,719,936 | 0 | 0 | 0 | 0 | 1 | true | 8 | 2013-11-01T02:07:00.000 | 3 | 3 | 0 | How can one efficiently remove a range of rows from a large numpy array? | 19,719,746 | 1.2 | python,numpy | Because of the strided data structure that defines a numpy array, what you want will not be possible without using a masked array. Your best option might be to use a masked array (or perhaps your own boolean array) to mask the deleted the rows, and then do a single real delete operation of all the rows to be deleted before passing it downstream. | Given a large 2d numpy array, I would like to remove a range of rows, say rows 10000:10010 efficiently. I have to do this multiple times with different ranges, so I would like to also make it parallelizable.
Using something like numpy.delete() is not efficient, since it needs to copy the array, taking too much time and memory. Ideally I would want to do something like create a view, but I am not sure how I could do this in this case. A masked array is also not an option since the downstream operations are not supported on masked arrays.
Any ideas? | 0 | 1 | 2,948 |
0 | 19,732,333 | 0 | 0 | 0 | 0 | 1 | true | 0 | 2013-11-01T17:34:00.000 | 0 | 1 | 0 | Conversion of 2D cvMat to 1D | 19,732,097 | 1.2 | python,opencv,numpy | Use matrix.reshape((-1, 1)) to turn the n-element 1D matrix into an n-by-1 2D one before converting it. | How can I convert 2D cvMat to 1D? I have tried converting 2D cvMat to Numpy array then used ravel() (I want that kind of resultant matrix).When I tried converting it back to
cvMat using cv.fromarray() it gives an error that the matrix must be 2D or 3D. | 0 | 1 | 606 |
0 | 38,743,037 | 0 | 0 | 0 | 0 | 1 | false | 5 | 2013-11-02T15:32:00.000 | 0 | 2 | 0 | Is there a way to prevent numpy.linalg.svd running out of memory? | 19,743,525 | 0 | python,numpy,matrix,linear-algebra,svd | Try to use scipy.linalg.svd instead of numpy's func. | I have 1 million 3d points I am passing to numpy.linalg.svd but it runs out of memory very quickly. Is there a way to break down this operation into smaller chunks?
I don't know what it's doing but am I only supposed to pass arrays that represent a 3x3, 4x4 matrix? Because I have seen uses of it online where they were passing arrays with arbitrary number of elements. | 0 | 1 | 4,417 |
0 | 37,336,872 | 0 | 0 | 0 | 0 | 1 | false | 624 | 2013-11-05T20:20:00.000 | 12 | 11 | 0 | Difference between map, applymap and apply methods in Pandas | 19,798,153 | 1 | python,pandas,dataframe,vectorization | Probably simplest explanation the difference between apply and applymap:
apply takes the whole column as a parameter and then assign the result to this column
applymap takes the separate cell value as a parameter and assign the result back to this cell.
NB If apply returns the single value you will have this value instead of the column after assigning and eventually will have just a row instead of matrix. | Can you tell me when to use these vectorization methods with basic examples?
I see that map is a Series method whereas the rest are DataFrame methods. I got confused about apply and applymap methods though. Why do we have two methods for applying a function to a DataFrame? Again, simple examples which illustrate the usage would be great! | 0 | 1 | 436,006 |
0 | 19,800,482 | 0 | 0 | 0 | 0 | 1 | false | 1 | 2013-11-05T21:59:00.000 | 0 | 1 | 0 | Using Pandas to get the closest value to a timestamp | 19,799,893 | 0 | python,pandas | I suppose you could create another column that is the Hour and subtract the time in question and get the absolute (unsigned) value that you could then do the min function on.. It is not code but I think the logic is right (or at least close.. after you find the mins,, then you can select them and then do your resample.. | I'm using pandas to get hourly data from a dataset with fifteen minute sampling intervals. My problem using the resample('H', how='ohlc') method is that it provides values within that hour and I want the value closest to the hour. For instance, I would like to take a value sampled at 2:55 instead of one from 3:10, but can't figure out how to find the value that is closest if it occurs prior to the timestamp being evaluated against.
Any help would be greatly appreciated. | 0 | 1 | 630 |
0 | 70,856,990 | 0 | 0 | 0 | 0 | 1 | false | 48 | 2013-11-06T19:50:00.000 | 0 | 5 | 0 | How to filter numpy array by list of indices? | 19,821,425 | 0 | python,numpy,scipy,nearest-neighbor | The fastest way to do this is X[tuple(index.T)], where X is the ndarray with the elements and index is the ndarray of indices wished to be retrieved. | I have a numpy array, filtered__rows, comprised of LAS data [x, y, z, intensity, classification]. I have created a cKDTree of points and have found nearest neighbors, query_ball_point, which is a list of indices for the point and its neighbors.
Is there a way to filter filtered__rows to create an array of only points whose index is in the list returned by query_ball_point? | 0 | 1 | 89,890 |
0 | 19,867,945 | 0 | 0 | 0 | 0 | 1 | true | 1 | 2013-11-08T17:44:00.000 | 3 | 1 | 0 | Converting x,y coordinates into a format for getAffineTransform? | 19,865,347 | 1.2 | python,opencv | No I think there is something else that is the problem. Docs say: cv2.getAffineTransform Calculates an affine transform from three pairs of the corresponding points.
The problem is you are giving it 125 pairs of points. It only wants 3 pairs of point correspondences. This is of course the number of correspondences needed to solve the linear system of equations. If you are looking to estimate an affine transformation from noisy correspondences then you will need to use something like weighted least squares or RANSAC. To estimate affine transform from noisy data with a prepackaged algorithm it looks like cv2.estimateRigidTransform might work setting fullAffine = True | I'm trying to use the cv2.getAffineTransform(src,dst) function in openCV, but it crashes because my inputs are arrays containing 125 pairs of x,y coordinates and getAffineTransform wants its input to have three columns. Can I just concat a row full of zeros onto my array or is there a special transformation I should do? | 0 | 1 | 935 |
0 | 50,679,155 | 0 | 1 | 0 | 0 | 1 | false | 129 | 2013-11-11T06:32:00.000 | 2 | 10 | 0 | How to determine whether a column/variable is numeric or not in Pandas/NumPy? | 19,900,202 | 0.039979 | python,pandas,numpy | Just to add to all other answers, one can also use df.info() to get whats the data type of each column. | Is there a better way to determine whether a variable in Pandas and/or NumPy is numeric or not ?
I have a self defined dictionary with dtypes as keys and numeric / not as values. | 0 | 1 | 132,614 |
0 | 19,960,199 | 0 | 0 | 1 | 0 | 1 | false | 3 | 2013-11-11T18:38:00.000 | 0 | 1 | 0 | Using MCMC from PyMC as an efficient sampler for frequentist analysis? | 19,913,421 | 0 | python,pymc | You can create custom StepMethods to perform any kind of sampling you like. See the docs for how to create your own. | Is there an easy way to use PyMC's MCMC algorithms to efficiently sample a parameter space for a frequentists analysis? I'm not interested in the point density (for Bayesian analysis), but rather want a fast and efficient way to sample a multidimensional parameter space, so I would like to trace all tested points (i.e. in particular also the rejected points), while recurring points need to be saved only once in the trace.
I would be grateful for any helpful comments.
Btw, thanks for developing PyMC, it is a great package! | 0 | 1 | 155 |
0 | 24,098,425 | 0 | 0 | 0 | 0 | 1 | false | 5 | 2013-11-13T04:30:00.000 | 2 | 1 | 0 | Adding new words to text vectorizer in scikit-learn | 19,945,334 | 0.379949 | python,numpy,scipy,scikit-learn,scikits | No, this is not possible at present. It's also not "doable", and here's why.
CountVectorizer and TfidfVectorizer are designed to turn text documents into vectors. These vectors need to all have an equal number of elements, which in turn is equal to the size of the vocabulary, because that conventions is ingrained in all scikit-learn code. If the vocabulary is allowed to grow, then the vectors produced at various times have different lengths. This affects e.g. the number of parameters in a linear (or other parametric) classifiers trained on such vectors, which then also needs to be able to grow. It affects k-means and dimensionality reduction classes. It even affects something as simple as matrix multiplications, which can no longer be handled with a simple call to NumPy's dot routine, requiring custom code instead. In other words, allowing this flexibility in the vectorizers makes little sense unless you adapt all of scikit-learn to handle the result.
While this would be possible, I (as a core scikit-learn developer) would strongly oppose the change because it makes the code very complicated, probably slower, and even if it would work, it would make it impossible to distinguish between a "growing vocabulary" and the much more common situation of a user passing data in the wrong way, so that the number of dimensions comes out wrong.
If you want to feed data in in batches, then either using a HashingVectorizer (no vocabulary) or do two passes over the data to collect the vocabulary up front. | Scikit-learn CountVectorizer for bag-of-words approach currently gives two sub-options: (a) use a custom vocabulary (b) if custom vocabulary is unavailable, then it makes a vocabulary based on all the words present in the corpus.
My question: Can we specify a custom vocabulary to begin with, but ensure that it gets updated when new words are seen while processing the corpus. I am assuming this is doable since the matrix is stored via a sparse representation.
Usefulness: It will help in cases when one has to add additional documents to the training data, and one should not have to start from the beginning. | 0 | 1 | 2,027 |
0 | 20,009,112 | 0 | 0 | 0 | 0 | 1 | false | 0 | 2013-11-15T19:14:00.000 | 1 | 1 | 0 | OpenCV estimateAffine3D in Python: shapes of input matrix? | 20,008,825 | 0.197375 | python,opencv | As I can understand from source code, they have to be Point3D, i.e. non-homogenous. | I'm trying to find a transformation matrix that relates 2 3D point clouds. According to the documentation, cv2.estimateAffine3D(src, dst) --> retval, out, inliers.
src is the first 3D point set, dst is the second 3D point set.
I'm assuming that retval is a boolean.
Out is the 3x4 affine transformation matrix, and inliers is a vector.
My question is, what are the shapes of the input point sets? Do the points have to be homogeneous, i.e. 4xN? | 0 | 1 | 515 |
0 | 20,099,740 | 0 | 0 | 0 | 0 | 3 | true | 11 | 2013-11-18T10:30:00.000 | 3 | 5 | 0 | How to store wide tables in pytables / hdf5 | 20,045,535 | 1.2 | python,numpy,hdf5,pytables | This might not, in fact, be possible to do in a naive way. HDF5 allocates 64 kb of space for meta-data for every data set. This meta data includes the types of the columns. So while the number of columns is a soft limit, somewhere in the 2-3 thousand range you typically run out of space to store the meta data (depending on the length of the column names, etc).
Furthermore, doesn't numpy limit the number of columns to 32? How are you representing the data with numpy now? Anything that you can get into a numpy array should correspond to a pytables Array class. | I have data coming from a csv which has a few thousand columns and ten thousand (or so) rows. Within each column the data is of the same type, but different columns have data of different type*. Previously I have been pickling the data from numpy and storing on disk, but it's quite slow, especially because usually I want to load some subset of the columns rather than all of them.
I want to put the data into hdf5 using pytables, and my first approach was to put the data in a single table, with one hdf5 column per csv column. Unfortunately this didn't work, I assume because of the 512 (soft) column limit.
What is a sensible way to store this data?
* I mean, the type of the data after it has been converted from text. | 0 | 1 | 2,271 |
0 | 20,155,746 | 0 | 0 | 0 | 0 | 3 | false | 11 | 2013-11-18T10:30:00.000 | 1 | 5 | 0 | How to store wide tables in pytables / hdf5 | 20,045,535 | 0.039979 | python,numpy,hdf5,pytables | you should be able to use pandas dataframe
it can be saved to disk without converting to csv | I have data coming from a csv which has a few thousand columns and ten thousand (or so) rows. Within each column the data is of the same type, but different columns have data of different type*. Previously I have been pickling the data from numpy and storing on disk, but it's quite slow, especially because usually I want to load some subset of the columns rather than all of them.
I want to put the data into hdf5 using pytables, and my first approach was to put the data in a single table, with one hdf5 column per csv column. Unfortunately this didn't work, I assume because of the 512 (soft) column limit.
What is a sensible way to store this data?
* I mean, the type of the data after it has been converted from text. | 0 | 1 | 2,271 |
0 | 20,240,079 | 0 | 0 | 0 | 0 | 3 | false | 11 | 2013-11-18T10:30:00.000 | 1 | 5 | 0 | How to store wide tables in pytables / hdf5 | 20,045,535 | 0.039979 | python,numpy,hdf5,pytables | IMHO it depends on what do you want to do with the data afterwards and how much of it do you need at one time. I had to build a program for statistical validation a while ago and we had two approaches:
Split the columns in separate tables (e.g. using a FK). The overhead of loading them is not too high
Transpose the table, resulting in something like a key-value store, where the key is a tuple of (column, row)
For both we used postgres. | I have data coming from a csv which has a few thousand columns and ten thousand (or so) rows. Within each column the data is of the same type, but different columns have data of different type*. Previously I have been pickling the data from numpy and storing on disk, but it's quite slow, especially because usually I want to load some subset of the columns rather than all of them.
I want to put the data into hdf5 using pytables, and my first approach was to put the data in a single table, with one hdf5 column per csv column. Unfortunately this didn't work, I assume because of the 512 (soft) column limit.
What is a sensible way to store this data?
* I mean, the type of the data after it has been converted from text. | 0 | 1 | 2,271 |
0 | 20,058,784 | 0 | 0 | 1 | 0 | 1 | false | 0 | 2013-11-18T19:05:00.000 | 0 | 1 | 0 | Boost.Python: Converters unavailable from standalone python script | 20,055,758 | 0 | python,boost,converters | I found the problem... The prototype of my C++ function was taking cv::Mat& as argument and the converter was registered for cv::Mat without reference.
That was silly. | The title may not be as explicit as I wish it would be but here is what I am trying to achieve:
Using Boost.Python, I expose a set of class/functions to Python in the typical BOOST_PYTHON_MODULE(MyPythonModule) macro from C++ that produces MyPythonModule.pyd after compilation. I can now invoke a python script from C++ and play around with MyPythonModule without any issue (eg. create objects, call methods and use my registered converters). FYI: the converter I'm refering to is a numpy.ndarray to cv::Mat converter.
This works fine, but when I try to write a standalone Python script that uses MyPythonModule, my converters are not available. I tried to expose the C++ method that performs the converter registration to Python without any luck.
If my explanation isn't clear enough, don't hesitate to ask questions in the comments.
Thanks a lot for your help / suggestions. | 0 | 1 | 84 |
0 | 20,076,370 | 0 | 0 | 0 | 0 | 1 | false | 0 | 2013-11-19T03:21:00.000 | 1 | 2 | 0 | mayavi mlab get current axes | 20,062,512 | 0.099668 | python,mayavi | What you are expecting to be able to do from your matplotlib experience is not how mayavi axes work. In matplotlib the visualization is a child of the axes and the axes determines its coordinates. In mayavi or vtk, visualization sources consist of points in space. Axes are objects that surround a source and provide tick markings of the coordinate extent of those objects, that are not necessary for the visualizations, and where they exist they are children of sources. | Is there a way of a procedure similar to plt.gca() to get a handle to the current axes. I first do a=mlab.surf(x, y, u2,warp_scale='auto')
and then
b=mlab.plot3d(yy, yy, (yy-40)**2 ,tube_radius=20.0)
but the origin of a and b are different and the plot looks incorrect. So I want to put b into the axes of a
In short, what would be the best way in mayavi to draw a surface and a line on same axes? | 0 | 1 | 501 |
0 | 20,085,854 | 0 | 0 | 0 | 0 | 1 | true | 1 | 2013-11-19T20:55:00.000 | 1 | 1 | 0 | Getting all available frame size from capture device with OpenCV | 20,081,818 | 1.2 | c++,python,opencv,video-capture,image-capture | When you retrieve a frame from a camera, it is the maximum size that that camera can give. If you want a smaller image, you have to specify it when you get the image, and opencv will resize it for you.
A normal camera has one sensor of one size, and it sends one kind of image to the computer. What opencv does with it thereafter is up to you to specify. | I'm using Open CV 2.4.6 with C++ (with Python sometimes too but it is irrelevant). I would like to know if there is a simple way to get all the available frame sizes from a capture device?
For example, my webcam can provide 640x480, 320x240 and 160x120. Suppose that I don't know about these frame sizes a priori... Is it possible to get a vector or an iterator, or something like this that could give me these values?
In other words, I don't want to get the current frame size (which is easy to obtain) but the sizes I could set the device to.
Thanks! | 0 | 1 | 1,874 |
0 | 42,714,576 | 0 | 0 | 0 | 0 | 1 | false | 51 | 2013-11-19T23:26:00.000 | 7 | 2 | 0 | Find unique values in a Pandas dataframe, irrespective of row or column location | 20,084,382 | 1 | python,pandas,dataframe | Or you can use:
df.stack().unique()
Then you don't need to worry if you have NaN values, as they are excluded when doing the stacking. | I have a Pandas dataframe and I want to find all the unique values in that dataframe...irrespective of row/columns. If I have a 10 x 10 dataframe, and suppose they have 84 unique values, I need to find them - Not the count.
I can create a set and add the values of each rows by iterating over the rows of the dataframe. But, I feel that it may be inefficient (cannot justify that). Is there an efficient way to find it? Is there a predefined function? | 0 | 1 | 90,919 |
0 | 20,200,810 | 0 | 0 | 0 | 0 | 1 | false | 0 | 2013-11-24T18:35:00.000 | 1 | 1 | 0 | Train a feed forward neural network indirectly | 20,179,255 | 0.197375 | python,algorithm,neural-network,pybrain | Your idea with additional layer is good, although the problem is, that your weights in this layer have to be fixed. So in practise, you have to compute the partial derivatives of your R^2->R mapping, which can be used as the error to propagate through your network during training. Unfortunately, this may lead to the well known "vanishing gradient problem" which stopped the development of NN for many years.
In short - you can either manually compute the partial derivatives, and given expected output in R, simply feed the computed "backpropagated" errors to the network looking for R^2->R^2 mapping or as you said - create additional layer, and train it normally, but you will have to make the upper weights constant (which will require some changes in the implementation). | I am faced with this problem:
I have to build an FFNN that has to approximate an unknown function f:R^2 -> R^2. The data in my possession to check the net is a one-dimensional R vector. I know the function g:R^2->R that will map the output of the net into the space of my data. So I would use the neural network as a filter against bias in the data. But I am faced with two problems:
Firstly, how can I train my network in this way?
Secondly, I am thinking about adding an extra hidden layer that maps R^2->R and lets the net train itself to find the correct maps and then remove the extra layer. Would this algorithm be correct? Namely, would the output be the same that I was looking for? | 0 | 1 | 203 |
0 | 20,180,148 | 0 | 0 | 0 | 0 | 1 | true | 4 | 2013-11-24T18:36:00.000 | 4 | 1 | 0 | using RandomForestClassifier.predict_proba vs RandomForestRegressor.predict | 20,179,267 | 1.2 | python,scikit-learn | There is a major conceptual diffrence between those, based on different tasks being addressed:
Regression: continuous (real-valued) target variable.
Classification: discrete target variable (classes).
For a general classification method, term probability of observation being class X may be not defined, as some classification methods, knn for example, do not deal with probabilities.
However for Random Forest (and some other classification methods), classification is reduced to regression of classes probabilities destibution. Predicted class is taked then as argmax of computed "probabilities". In your case, you feed the same input, you get the same result. And yes, it is ok to treat values returned by RandomForestRegressor as probabilities. | I have a data set comprising a vector of features, and a target - either 1.0 or 0.0 (representing two classes). If I fit a RandomForestRegressor and call its predict function, is it equivalent to using RandomForestClassifier.predict_proba()?
In other words if the target is 1.0 or 0.0 does RandomForestRegressor output probabilities?
I think so, and the results I a m getting suggest so, but I would like to get a second opinion...
Thanks
Weasel | 0 | 1 | 4,377 |
0 | 30,234,937 | 0 | 0 | 0 | 0 | 1 | false | 8 | 2013-11-25T04:53:00.000 | 5 | 3 | 0 | ipython notebook nbconvert - how to remove red 'out[N]' text in top left hand corner of cell output? | 20,184,994 | 0.321513 | ipython,ipython-notebook | %%HTML
<style>
div.prompt {display:none}
</style>
This will hide both In and Out prompts
Note that this is only in your browser, the notebook itself isn't modified of course, and nbconvert will work just the same as before.
In case you want this in the nbconverted code as well, just put the <style>div.prompt {display:none}</style> in a Raw NBConvert cell. | I am using nbconvert to produce something as close as possible to a polished journal article.
I have successfully hidden input code using a custom nbconvert template. The doc is now looking very nice.
But I don't know how to suppress the bright red 'out[x]' statement in the top left corner of the output cells. Anyone know of any settings or hacks that are able to remove this also ?
Thanks,
John | 0 | 1 | 5,150 |
0 | 20,208,600 | 0 | 0 | 0 | 0 | 1 | false | 1 | 2013-11-25T20:04:00.000 | 2 | 1 | 0 | Can co-occurance of word be calculated using R/ python/ Map reducer? | 20,202,179 | 0.379949 | python,r | Counts of pairs are just products of counts of singletons.
This takes 5 seconds on my year old MacBook Pro using R:
Generate a matrix of 200000 rows and 180 columns whose elements are digits:
mat <- matrix(sample(0:9,180*200000,repl=T),nc=180)
Now table digits in each row:
tab <- sapply( 0:9, function(x) rowSums( mat==x ))
Now find the pair counts in each row:
cp <- combn( 0:9, 2, function(x) tab[,1+x[1] ] * tab[,1+x[2] ])
Sum the rows:
colSums(cp)
Verify the result for the first row:
tab2 <- table( matrix(mat[1,], nr=180, nc=180), matrix(mat[1,], nr=180, nc=180, byrow=TRUE))
all( tab2[ lower.tri(tab2)] == cp[1,] ) | I have a huge database of 180 columns and 200,000 rows. To illustrate in a better way, I have a matrix of 180 x 200000. Each matrix is a single digit number. I need to find their co-occurrence count.
For example I have a data of 5 columns having values 1,2,3,4,5. I need to find the number of times (1,2),(1,3),(1,4),(1,5),(2,3),(2,4),(2,5),(3,4),(3,5),(4,5) have occurred in the database. Can you please suggest me an approach to this problem?
I have an exposure to R and python. So any suggestion using those will really help.
Can this also be done using AWS map reducer? Any help or pointers on those lines would also be helpful. | 0 | 1 | 188 |
0 | 20,255,287 | 0 | 0 | 0 | 0 | 1 | false | 6 | 2013-11-26T16:32:00.000 | 4 | 2 | 0 | Method to set scipy optimization minimization step size | 20,222,657 | 0.379949 | python,optimization,scipy | I believe cobyla is the only technique that supports this in scipy.optimize.minimize. You can essentially control how big it's steps are with the rhobeg parameter. (It's not really the step size since it's a sequential linear method, but it has the same effect). | Is there a way to make the scipy optimization modules use a smaller step size?
I am optimizing a problem with a large set of variables (approximately 40) that I believe are near the optimal value, however when I run the scipy minimization modules (so far I have tried L-BFGS and CG) they do not converge because the initial step size is too large. | 0 | 1 | 5,636 |
0 | 20,238,109 | 0 | 0 | 0 | 0 | 1 | true | 1 | 2013-11-27T02:38:00.000 | 2 | 1 | 0 | Is it possible to access OpenCV OCL (OpenCL) methods from python (cv2)? | 20,232,889 | 1.2 | python,opencv,opencl | unfortunately, - no way.
opencv uses special Mat types for this, ocl::Mat or cuda::Mat ,
and those are not exposed to the wrappers (so, same problem for java and matlab) | From what I can tell, there's no way to access OpenCV's OpenCL (OCL) module from the python cv2 bindings. Does anyone know of a straightforward way to do this? | 0 | 1 | 1,033 |
0 | 20,557,736 | 0 | 0 | 0 | 0 | 4 | true | 6 | 2013-11-27T20:27:00.000 | 2 | 4 | 0 | Can sklearn Random Forest classifier adjust sample size by tree, to handle class imbalance? | 20,252,484 | 1.2 | python,r,scikit-learn,classification,random-forest | After reading over the documentation, I think that the answer is definitely no. Kudos to anyone who adds the functionality though. As mentioned above the R package randomForest contains this functionality. | Perhaps this is too long-winded. Simple question about sklearn's random forest:
For a true/false classification problem, is there a way in sklearn's random forest to specify the sample size used to train each tree, along with the ratio of true to false observations?
More details are below:
In the R implementation of random forest, called randomForest, there's an option sampsize(). This allows you to balance the sample used to train each tree based on the outcome.
For example, if you're trying to predict whether an outcome is true or false and 90% of the outcomes in the training set are false, you can set sampsize(500, 500). This means that each tree will be trained on a random sample (with replacement) from the training set with 500 true and 500 false observations. In these situations, I've found models perform much better predicting true outcomes when using a 50% cut-off, yielding much higher kappas.
It doesn't seem like there is an option for this in the sklearn implementation.
Is there any way to mimic this functionality in sklearn?
Would simply optimizing the cut-off based on the Kappa statistic achieve a similar result or is something lost in this approach? | 0 | 1 | 2,604 |
0 | 28,440,842 | 0 | 0 | 0 | 0 | 4 | false | 6 | 2013-11-27T20:27:00.000 | 0 | 4 | 0 | Can sklearn Random Forest classifier adjust sample size by tree, to handle class imbalance? | 20,252,484 | 0 | python,r,scikit-learn,classification,random-forest | As far as I am aware, the scikit-learn forest employ bootstrapping i.e. the sample set sizes each tree is trained with are always of the same size and drawn from the original training set by random sampling with replacement.
Assuming you have a large enough set of training samples, why not balancing this itself out to hold 50/50 positive/negative samples and you will achieve the desired effect. scikit-learn provides functionality for this. | Perhaps this is too long-winded. Simple question about sklearn's random forest:
For a true/false classification problem, is there a way in sklearn's random forest to specify the sample size used to train each tree, along with the ratio of true to false observations?
More details are below:
In the R implementation of random forest, called randomForest, there's an option sampsize(). This allows you to balance the sample used to train each tree based on the outcome.
For example, if you're trying to predict whether an outcome is true or false and 90% of the outcomes in the training set are false, you can set sampsize(500, 500). This means that each tree will be trained on a random sample (with replacement) from the training set with 500 true and 500 false observations. In these situations, I've found models perform much better predicting true outcomes when using a 50% cut-off, yielding much higher kappas.
It doesn't seem like there is an option for this in the sklearn implementation.
Is there any way to mimic this functionality in sklearn?
Would simply optimizing the cut-off based on the Kappa statistic achieve a similar result or is something lost in this approach? | 0 | 1 | 2,604 |
0 | 28,648,499 | 0 | 0 | 0 | 0 | 4 | false | 6 | 2013-11-27T20:27:00.000 | 3 | 4 | 0 | Can sklearn Random Forest classifier adjust sample size by tree, to handle class imbalance? | 20,252,484 | 0.148885 | python,r,scikit-learn,classification,random-forest | In version 0.16-dev, you can now use class_weight="auto" to have something close to what you want to do. This will still use all samples, but it will reweight them so that classes become balanced. | Perhaps this is too long-winded. Simple question about sklearn's random forest:
For a true/false classification problem, is there a way in sklearn's random forest to specify the sample size used to train each tree, along with the ratio of true to false observations?
More details are below:
In the R implementation of random forest, called randomForest, there's an option sampsize(). This allows you to balance the sample used to train each tree based on the outcome.
For example, if you're trying to predict whether an outcome is true or false and 90% of the outcomes in the training set are false, you can set sampsize(500, 500). This means that each tree will be trained on a random sample (with replacement) from the training set with 500 true and 500 false observations. In these situations, I've found models perform much better predicting true outcomes when using a 50% cut-off, yielding much higher kappas.
It doesn't seem like there is an option for this in the sklearn implementation.
Is there any way to mimic this functionality in sklearn?
Would simply optimizing the cut-off based on the Kappa statistic achieve a similar result or is something lost in this approach? | 0 | 1 | 2,604 |
0 | 30,005,356 | 0 | 0 | 0 | 0 | 4 | false | 6 | 2013-11-27T20:27:00.000 | 0 | 4 | 0 | Can sklearn Random Forest classifier adjust sample size by tree, to handle class imbalance? | 20,252,484 | 0 | python,r,scikit-learn,classification,random-forest | Workaround in R only, for classification one can simply use all cores of the machine with 100% CPU utilization.
This matches the time and speed of Sklearn RandomForest classifier.
Also for regression there is a package RandomforestParallel on GitHub, which is much faster than Python Sklearn Regressor.
Classification: I have tested and works well. | Perhaps this is too long-winded. Simple question about sklearn's random forest:
For a true/false classification problem, is there a way in sklearn's random forest to specify the sample size used to train each tree, along with the ratio of true to false observations?
More details are below:
In the R implementation of random forest, called randomForest, there's an option sampsize(). This allows you to balance the sample used to train each tree based on the outcome.
For example, if you're trying to predict whether an outcome is true or false and 90% of the outcomes in the training set are false, you can set sampsize(500, 500). This means that each tree will be trained on a random sample (with replacement) from the training set with 500 true and 500 false observations. In these situations, I've found models perform much better predicting true outcomes when using a 50% cut-off, yielding much higher kappas.
It doesn't seem like there is an option for this in the sklearn implementation.
Is there any way to mimic this functionality in sklearn?
Would simply optimizing the cut-off based on the Kappa statistic achieve a similar result or is something lost in this approach? | 0 | 1 | 2,604 |
0 | 20,295,628 | 0 | 0 | 0 | 0 | 1 | true | 10 | 2013-11-29T23:58:00.000 | 13 | 1 | 0 | Repeated Gaussian Blur in Image Processing | 20,294,916 | 1.2 | python,image,matlab,image-processing,gaussian | Successively applying multiple gaussian blurs to an image has the same effect as applying a single, larger gaussian blur, whose radius is the square root of the sum of the squares of the blur radii that were actually applied. In your case, s2 = sqrt(n*s1^2), and the blur radii is approximated as 3*si where i = 1, 2, which means pixels at a distance of more than 3si are small enough to be considered effectively zero during the blurring process. | I have two questions relating to repeated Gaussian blur.
What happens when we repeatedly apply gaussian blur to an image keeping the sigma and the radius same ?
And is it possible that after n iterations of repeatedly applying gaussian blur (sigma = s1) the image becomes the same as it would be on applying gaussian blur ( of sigma = s2; s1 < s2 ) 1 time on the original image. And if so what is the general formula for deriving that n number of times we have to apply gaussian blur with s1, given s1 and s2 (s1 < s2). | 0 | 1 | 2,451 |
0 | 20,295,483 | 0 | 0 | 0 | 0 | 1 | false | 0 | 2013-11-30T01:18:00.000 | 0 | 6 | 0 | Custom sorting in for loop | 20,295,446 | 0 | python,c,arrays,algorithm,sorting | Maybe use a nested for loop with the outside one looking at the ith point. then inside loop and calculate all the distances. After calculation use a native python sort for that row and then add it to the main 2d array. | Let's say I am given an array of n points(pair of coordinates). I want to generate a 2D array of points, where ith row has all elements sorted according to their distance from the ith point. There may be better and more efficient algorithms to get the final result, but for some reasons I want to do it by naive algorithm, i.e., brute-force. Also I don't want to write my own sorting function.
In C language, one can use the qsort function, but it's compare function only takes two parameters whereas I will be needing to pass three parameters: the reference point and two other points to be compared.
In Python too, one can use sorted function, but again, it's key function only takes one parameter, whereas in this case, I will need to pass two parameters.
So how do I do it? | 0 | 1 | 202 |
0 | 20,295,997 | 0 | 0 | 0 | 0 | 1 | false | 2 | 2013-11-30T02:52:00.000 | 1 | 2 | 0 | Indexing subsets of size k | 20,295,961 | 0.099668 | python,algorithm,indexing,subset | I think you could do this by recursively narrowing down ranges, right? You know that all subsets beginning with a given integer will be adjacent, and that for a given first element d there will be (n - d) choose (k-1) of them. You can skip ahead as far as necessary in the virtual list of subsets until you're in the range of subsets beginning with the first element of the target sorted subset, then recurse to narrow it down precisely.
EG, suppose n=20, k=6. If your target subset is {5, 8, 12, 14, 19}, none of the subsets beginning with 1-4 are valid choices. You know that the index first subset beginning with 5 will be ((19 choose 5) + (18 choose 5) + (17 choose 5) + (16 choose 5)). Call that index i0. Now you have (15 choose 5) subsets that all begin with 5 to index into, and none of the ones beginning with 5, 1-7... are interesting. (14 choose 4) of them start with 1, (13 choose 4) start with 2, etc. So the index of the first set beginning with 5, 8 will be i0 + (14 choose 4) + (13 choose 4) + (12 choose 4) + (11 choose 4) + (10 choose 4) + (9 choose 4) + (8 choose 4). Etc.
Writing the algorithm out is kind of painful, but I think it should work nicely with a computer keeping track of the fiddly details. | There are n choose k subsets of {1,2,...,n} of size k. These can be naturally ordered by sorting the elements and using the lexigraphical order.
Is there a fast way to determine the index of a given subset, i.e. its index in the sorted list of all subsets of size k? One method would be to create a dictionary from subsets to indices by enumerating all subsets of size k, but this requires n choose k space and time. For my application n and k are infeasibly large, but I only need to determine the indices of comparatively few subsets.
I'm coding in Python, but I'm more interested in a general algorithm than any specific implementation. Of course, if there's an especially fast way to do this in Python that would be great.
Motivation: The subsets of {1,2,...,n} of size k correspond bijectively to basis vectors of the kth exterior power of a vector space with dimension n. I'm performing computations in the exterior algebra of a vector space and trying to convert the resulting lists of vectors into sparse matrices to do linear algebra, and to do that I need to index the vectors by integers rather than by lists. | 0 | 1 | 397 |
1 | 31,173,939 | 0 | 0 | 0 | 0 | 2 | false | 0 | 2013-12-01T04:17:00.000 | 0 | 2 | 0 | ImportError: No module named _csv . Qpython for android logs | 20,308,674 | 0 | importerror,qpython | To install _csv or any other module, follow these steps. Here's what I did to install websocket (and all of its dependencies):
To install websocket on the phone:
Start QPython
Click the big button
Select “run local script”
Select “pip_console.py”
Type “pip install websocket” | I put goog_appengine inside android located at /mnt/sdcard
I also put wsgiref folder at same location.
from Qpython I manage to "send control key" + "d"
I got sh $
I put command like the ff:
"$python /mnt/sdcard/google_appengine/appcfg.py"
But Igot ImportError: no module _csv
I feel putting these is not same architecture " /usr/lib/python2.7/lib-dynload/_csv.x86_64-linux-gnu.so"
That come from ubuntu 13.04.
What to do next, Where I can find _csv module for Qpython+android_version.
Is it possible to upload my code through android? | 1 | 1 | 840 |
1 | 21,482,814 | 0 | 0 | 0 | 0 | 2 | false | 0 | 2013-12-01T04:17:00.000 | 0 | 2 | 0 | ImportError: No module named _csv . Qpython for android logs | 20,308,674 | 0 | importerror,qpython | You can install _csv from QPython's system. ( You can find system icon in qpython's new version 0.9.6.2 ) | I put goog_appengine inside android located at /mnt/sdcard
I also put wsgiref folder at same location.
from Qpython I manage to "send control key" + "d"
I got sh $
I put command like the ff:
"$python /mnt/sdcard/google_appengine/appcfg.py"
But Igot ImportError: no module _csv
I feel putting these is not same architecture " /usr/lib/python2.7/lib-dynload/_csv.x86_64-linux-gnu.so"
That come from ubuntu 13.04.
What to do next, Where I can find _csv module for Qpython+android_version.
Is it possible to upload my code through android? | 1 | 1 | 840 |
0 | 20,351,305 | 0 | 1 | 0 | 0 | 1 | false | 0 | 2013-12-03T12:17:00.000 | 0 | 2 | 0 | How to store high precision floats in a binary file, Python 2.7? | 20,350,989 | 0 | python,python-2.7,floating-point,floating-point-precision | The struct module can handle 64 bit floats. Decimals are another matter - the binary representation is a string of digits. Probably not what you want. You could covert it to BCD to halve the amount of storage. | In Python 2.7,I need to record high precision floats (such as np.float64 from numpy or Decimal from decimal module) to a binary file and later read it back. How could I do it? I would like to store only bit image of a high precision float, without any overhead.
Thanks in advance! | 0 | 1 | 239 |
0 | 20,375,614 | 0 | 0 | 0 | 0 | 2 | false | 18 | 2013-12-04T10:38:00.000 | 16 | 4 | 0 | How do I convert a numpy matrix into a boolean matrix? | 20,373,039 | 1 | python,numpy | You should use array.astype(bool) (or array.astype(dtype=bool)). Works with matrices too. | I have a n x n matrix in numpy which has 0 and non-0 values. Is there a way to easily convert it to a boolean matrix?
Thanks. | 0 | 1 | 34,445 |
0 | 20,373,327 | 0 | 0 | 0 | 0 | 2 | false | 18 | 2013-12-04T10:38:00.000 | 4 | 4 | 0 | How do I convert a numpy matrix into a boolean matrix? | 20,373,039 | 0.197375 | python,numpy | Simply use equality check:
Suppose a is your numpy matrix, use b = (a == 0) or b = (a != 0) to get the boolean value matrix.
In some case, since the value maybe sufficiently small but non-zero, you may use abs(a) < TH, where TH is the numerical threshold you set. | I have a n x n matrix in numpy which has 0 and non-0 values. Is there a way to easily convert it to a boolean matrix?
Thanks. | 0 | 1 | 34,445 |
0 | 49,957,628 | 0 | 0 | 0 | 0 | 1 | false | 8 | 2013-12-04T17:56:00.000 | 0 | 4 | 0 | Periodic Data with Machine Learning (Like Degree Angles -> 179 is 2 different from -179) | 20,382,484 | 0 | python,machine-learning,scipy,scikit-learn,angle | Another simpler way could be to use time as angle measurements than degree measurements (not DMS though). Since many analytics software features time as a datatype, you can use its periodicity to do your job.
But remember, you need to scale 360 degrees to 24 hours. | I'm using Python for kernel density estimations and gaussian mixture models to rank likelihood of samples of multidimensional data.
Every piece of data is an angle, and I'm not sure how to handle the periodicity of angular data for machine learning.
First I removed all negative angles by adding 360 to them, so all angles that were negative became positive, -179 becoming 181. I believe this elegantly handles the case of -179 an similar being not significantly different than 179 and similar, but it does not handle instances like 359 being not dissimilar from 1.
One way I've thought of approaching the issue is keeping both negative and negative+360 values and using the minimum of the two, but this would require modification of the machine learning algorithms.
Is there a good preprocessing-only solution to this problem? Anything built into scipy or scikit?
Thanks! | 0 | 1 | 3,296 |
0 | 20,389,326 | 0 | 0 | 0 | 0 | 2 | false | 0 | 2013-12-05T00:51:00.000 | 1 | 3 | 0 | load dataset into memory for future computation in python | 20,389,291 | 0.066568 | python | You could write a very quick CLI which would load the data, and then ask for a python filename, which it would then eval() on the data... | I have a large dataset that I perform experiments on. It takes 30 mins to load the dataset from file into memory using a python program. Then I perform variations of an algorithm on the dataset. Each time I have to vary the algorithm, I have to load the dataset into memory again, which eats up 30 minutes.
Is there any way to load the dataset into memory once and for always. And then each time to run a variation of an algorithm, just use that pre loaded dataset?
I know the question is a bit abstract, suggestions to improve the framing of the question are welcome. Thanks.
EDITS:
Its a text file, contains graph data, around 6 GB. If I only load a portion of the dataset, it doesn't make for a very good graph. I do not do computation while loading the dataset. | 0 | 1 | 233 |
0 | 68,645,793 | 0 | 0 | 0 | 0 | 2 | false | 0 | 2013-12-05T00:51:00.000 | 0 | 3 | 0 | load dataset into memory for future computation in python | 20,389,291 | 0 | python | One possible solution is to use Jupyter to load it once and keep the Jupyter session running. Then you modify your algorithm in a cell and always rerun that cell alone. You can operate on the loaded dataset in RAM as much as you want until you terminate the Jupyter session. | I have a large dataset that I perform experiments on. It takes 30 mins to load the dataset from file into memory using a python program. Then I perform variations of an algorithm on the dataset. Each time I have to vary the algorithm, I have to load the dataset into memory again, which eats up 30 minutes.
Is there any way to load the dataset into memory once and for always. And then each time to run a variation of an algorithm, just use that pre loaded dataset?
I know the question is a bit abstract, suggestions to improve the framing of the question are welcome. Thanks.
EDITS:
Its a text file, contains graph data, around 6 GB. If I only load a portion of the dataset, it doesn't make for a very good graph. I do not do computation while loading the dataset. | 0 | 1 | 233 |
0 | 20,390,085 | 0 | 0 | 0 | 1 | 1 | false | 0 | 2013-12-05T02:00:00.000 | 0 | 2 | 0 | Intersecting 2 big datasets | 20,389,982 | 0 | c#,python,database,bigdata | If you are only doing this once, your approach should be sufficient. The only improvement I would make is to read the big file in chunks instead of line by line. That way you don't have to hit the file system as much. You'd want to make the chunks as big as possible while still fitting in memory.
If you will need to do this more than once, consider pushing the data into some database. You could insert all the data from the big file and then "update" that data using the second, smaller file to get a complete database with one large table with all the data. If you use a NoSQL database like Cassandra this should be fairly efficient since Cassandra is pretty good and handling writes efficiently. | I have a giant (100Gb) csv file with several columns and a smaller (4Gb) csv also with several columns. The first column in both datasets have the same category. I want to create a third csv with the records of the big file which happen to have a matching first column in the small csv. In database terms it would be a simple join on the first column.
I am trying to find the best approach to go about this in terms of efficiency. As the smaller dataset fits in memory, I was thinking of loading it in a sort of set structure and then read the big file line to line and querying the in memory set, and write to file on positive.
Just to frame the question in SO terms, is there an optimal way to achieve this?
EDIT: This is a one time operation.
Note: the language is not relevant, open to suggestions on column, row oriented databases, python, etc... | 0 | 1 | 154 |
0 | 20,415,698 | 0 | 0 | 0 | 0 | 1 | false | 4 | 2013-12-06T03:29:00.000 | 5 | 5 | 0 | python pandas 3 smallest & 3 largest values | 20,415,414 | 0.197375 | python,pandas,dataframe | What have you tried? You could sort with s.sort() and then call s.head(3).index and s.tail(3).index. | How can I find the index of the 3 smallest and 3 largest values in a column in my pandas dataframe? I saw ways to find max and min, but none to get the 3. | 0 | 1 | 7,247 |
0 | 20,436,137 | 0 | 1 | 0 | 0 | 1 | true | 0 | 2013-12-06T14:43:00.000 | 0 | 2 | 0 | pyfits not working for windows 64 bit | 20,426,690 | 1.2 | python,numpy,windows64,pyfits | This is a problem importing numpy, not pyfits. You can tell because the traceback ended upon trying to import the numpy multiarray module.
This error suggests that the numpy you have installed was not built for the same architecture as your Python installation. | I am using windows 7 home basic 64 bit. I wanted to work with FITS file in python 3.3 so downloaded pyfits and numpy for 64 bit. When I import pyfits I get the following error:
Traceback (most recent call last): File "", line 1, in
import pyfits as py File
"C:\Python33\lib\site-packages\pyfits__init__.py", line 26, in
import pyfits.core File
"C:\Python33\lib\site-packages\pyfits\core.py", line 38, in
import pyfits.py3compat File
"C:\Python33\lib\site-packages\pyfits\py3compat.py", line 12, in
import pyfits.util File
"C:\Python33\lib\site-packages\pyfits\util.py", line 29, in
import numpy as np File
"C:\Python33\lib\site-packages\numpy__init__.py", line 168, in
from . import add_newdocs File
"C:\Python33\lib\site-packages\numpy\add_newdocs.py", line 13, in
from numpy.lib import add_newdoc File
"C:\Python33\lib\site-packages\numpy\lib__init__.py", line 8, in
from .type_check import * File
"C:\Python33\lib\site-packages\numpy\lib\type_check.py", line 11, in
import numpy.core.numeric as _nx File
"C:\Python33\lib\site-packages\numpy\core__init__.py", line 6, in
from . import multiarray ImportError: DLL load failed: %1
is not a valid Win32 application. | 0 | 1 | 718 |
0 | 20,483,571 | 0 | 0 | 0 | 0 | 1 | true | 1 | 2013-12-09T12:56:00.000 | 2 | 2 | 0 | Programmatic equivalent of Gimp's Contiguous selection tool | 20,471,228 | 1.2 | python,image-processing,gimp | pdb.gimp_image_select_contiguous_color is the programatic way - in a Python plug-in - of doing the magic wand. The drawback is that you have to issue suitable starting coordinates for it to work well.
Maye repeating the process in 3 distant points of the image, and if the selection does not diverge by much in two of those, assume that to be the one you want.
The procedure does not return the selection drawable, so you have to get it by issuing
pdb.gimp_image_get_selection afterwards. You will also need to set the threshold by calling pdb.gimp_context_set_sample_threshold before calling it.
(My suggestion: copy it to another, new image, resize that to an 8x8pixel image, from which you can get the pixel values and compare directly against other selections made); | I need to automate the analyses of many similar images which are basic lots of small blackish blobs on a somewhat homogeneous brown background.
I have tried the find_blobs method from simpleCV but it is not accurate enough. However with gimps contiguous selection tool, also known as Magic wand, I was able to achieve much better results, in separating the background from my blobs.
My problem is that I need to automate this process, so I can't have a person clicking on each image. Any suggestion of a Python friendly library in which I can find this functionality? Is using Gimp in batch mode the only way? | 0 | 1 | 1,258 |
0 | 61,375,377 | 0 | 0 | 0 | 0 | 1 | false | 13 | 2013-12-09T19:25:00.000 | 3 | 4 | 0 | How to force larger steps on scipy.optimize functions? | 20,478,949 | 0.148885 | python,optimization,numpy,scipy,gaussian | I realize this is an old question but I haven't been able to find many discussion of similar topics. I am facing a similar issue with scipy.optimize.least_squares. I found that xtol did not do me much good. It did not seem to change the step size at all. What made a big difference was diff_step. This sets the step size taken when numerically estimating the Jacobian according to the formula step_size = x_i*diff_step, where x_i is each independent variable. You are using fmin so you aren't calculating Jacobians, but if you used another scipy function like minimize for the same problem, this might help you. | I have a function compare_images(k, a, b) that compares two 2d-arrays a and b
Inside the funcion, I apply a gaussian_filter with sigma=k to a My idea is to estimate how much I must to smooth image a in order for it to be similar to image b
The problem is my function compare_images will only return different values if k variation is over 0.5, and if I do fmin(compare_images, init_guess, (a, b) it usually get stuck to the init_guess value.
I believe the problem is fmin (and minimize) tends to start with very small steps, which in my case will reproduce the exact same return value for compare_images, and so the method thinks it already found a minimum. It will only try a couple times.
Is there a way to force fmin or any other minimizing function from scipy to take larger steps? Or is there any method better suited for my need?
EDIT:
I found a temporary solution.
First, as recommended, I used xtol=0.5 and higher as an argument to fmin.
Even then, I still had some problems, and a few times fmin would return init_guess.
I then created a simple loop so that if fmin == init_guess, I would generate another, random init_guess and try it again.
It's pretty slow, of course, but now I got it to run. It will take 20h or so to run it for all my data, but I won't need to do it again.
Anyway, to better explain the problem for those still interested in finding a better solution:
I have 2 images, A and B, containing some scientific data.
A looks like a few dots with variable value (it's a matrix of in which each valued point represents where a event occurred and it's intensity)
B looks like a smoothed heatmap (it is the observed density of occurrences)
B looks just like if you applied a gaussian filter to A with a bit of semi-random noise.
We are approximating B by applying a gaussian filter with constant sigma to A. This sigma was chosen visually, but only works for a certain class of images.
I'm trying to obtain an optimal sigma for each image, so later I could find some relations of sigma and the class of event showed in each image.
Anyway, thanks for the help! | 0 | 1 | 4,444 |
0 | 20,499,162 | 0 | 0 | 0 | 0 | 1 | false | 2 | 2013-12-10T15:42:00.000 | 0 | 3 | 0 | How scipy.optimize.leastsq knows the order of parameters passed to it? | 20,498,752 | 0 | python,optimization,parameters,scipy | The order in which function parameters are passed is only ever not known when the function is defined with **kwargs (unnamed keyword arguments -- the function then has a dict called kwargs that contains them, obviously unordered).
When the function is defined with named parameters, though, the f(a=b, c=d) syntax does not create a dict -- it simply assigns the values to the corresponding named parameters within the function. | I want to model a data with gaussian with parameters (mu=1, sig=2, height=1) and pass initial parameters x0 = (0.8, 0.8, 0.9).
I am wondering how does the optimizer knows the order of parameters. I could have taken the parameters as (mu,height,sig) or in any other order.
Edit:
Gaussian model (mu=1,sig=1.5,height=0.8)
Initial parameters passed x0=(0.8,0.8,0.8)
How can I be sure that the optimizer understands it as (mu,sig,height) and not as (sig,mu,height)? | 0 | 1 | 160 |
0 | 20,500,867 | 0 | 0 | 0 | 0 | 1 | false | 1 | 2013-12-10T17:03:00.000 | 2 | 1 | 1 | MPI distributed, unordered work | 20,500,675 | 0.379949 | c++,python,c,mpi,distributed-computing | You can use MPI_ANY_SOURCE and MPI_ANY_TAG for receiving from anywhere. After receiving you can read the Information (source and tag) out of the MPI_Status structure that has to passed to the MPI_Recv call.
If you use this you do not neccessary need any asynchronous communication, since the master 'listens' to everybody asking for new jobs and returning results; and each slave does his task and then sends the result to the master asks for new work and waits for the answer from the master.
You should not have to work with scatter/gather at all since those are ment for use on an array of data and your problem seems to have more or less independant tasks. | I would like to write a MPI program where the master thread continuously submits new job to the workers (i.e. not just at the start, like in the MapReduce pattern).
Initially, lets say, I submit 100 jobs onto 100 workers.
Then, I would like to be notified when a worker is finished with a job. I would send the next job off, whose parameters depend on all the results received so far. The order of results does not have to be preserved, I would just need them as they finish.
I can work with C/C++/Python.
From the documentation, it seems like I can broadcast N jobs, and gather the results. But this is not what I need, as I don't have all of them available, and gather would block. I am looking for a asynchronous, any-worker recv call, essentially. | 0 | 1 | 182 |
0 | 20,509,223 | 0 | 0 | 0 | 0 | 1 | false | 1 | 2013-12-11T01:54:00.000 | 1 | 2 | 0 | how to randomise the image shown in a sketchpad | 20,509,103 | 0.099668 | python,random | To generate retrieve the path of a random image in a folder img_folder, it's not too difficult. You can use img_path_array = os.listdir('.../img_folder'). Randomly generate an integer between 0 and len(img_path_array) using random_index = randrange(len(img_path_array)) (import random to use this function), and gain access to the random file url by calling img_path_array[random_index]. | I really appreciate any responses. I am thoroughly confused and never knew this experiment design/builder software was so complicated!
I am a fast learner, but still a newbie so please be patient.
Yes I have googled the answers for my question but no answers to similar questions seem to work.
I have an experiment, there are 8 conditions,
each condition needs to show 1 image, chosen at random from a folder of similar images.
Each trial needs to be different (so each participant sits a differently ordered set of conditions) AND each condition's selected image will be different.
So;
Condition- Image
A - 1 to 140
B - 1 to 80
etc..
Recording data is not a problem as this can be done by hand, but I just need the images to be randomly selected from a pre-defined group.
I have tried using code to randomise and shuffle the order, but have got nowhere.
Please help,
Tom | 0 | 1 | 65 |
0 | 41,922,008 | 0 | 0 | 0 | 0 | 1 | false | 129 | 2013-12-11T19:33:00.000 | 9 | 9 | 0 | Numpy `logical_or` for more than two arguments | 20,528,328 | 1 | python,arrays,numpy | Building on abarnert's answer for n-dimensional case:
TL;DR: np.logical_or.reduce(np.array(list)) | Numpy's logical_or function takes no more than two arrays to compare. How can I find the union of more than two arrays? (The same question could be asked with regard to Numpy's logical_and and obtaining the intersection of more than two arrays.) | 0 | 1 | 64,891 |
1 | 25,369,835 | 0 | 0 | 0 | 0 | 1 | true | 0 | 2013-12-11T19:41:00.000 | 0 | 1 | 0 | vtk Filters causing point doubling and mangling normal values | 20,528,456 | 1.2 | c++,python,opengl,blender,vtk | This was solved by requesting that Blender perform a triangulization of the mesh prior to the export operation.
The mangling was due to Blender performing implicit triangulization of quads, resulting in faces which were stored as 4 non-coplanar points. By forcing explicit triangulation in advance, I was able to successfully perform the export and maintain model integrity/manifold-ness. The holes that were being experienced were due to the implicit triangulation not being copied by the exporter and thus causing loss of data. | Using VTK version 5.1, I'm having some issues with some models not displaying correctly in OpenGL.
The process for getting the models into VTK is a bit roundabout, but gets there and is fairly simple. Each model is a manifold mesh comprised of only quads and tris.
Blender models->custom export format containing points, point normals, and polygons
Custom export format->Custom C++ parser->vtkPolyData
vtkPolydata->vtkTriangleFilter->vtkStripper->vtkPolyDataNormals->final product
As our final product was showing irregular and missing normals when it was rendered, I had VTK write the object to a plaintext file, which I then parsed back into Blender using python.
Initial results were that the mesh was correct and matched the original model, however, when I used the Blender "select non-manifold" option, about 15% of the model showed to be nonmanifold. A bit of reading around online suggested the "remove doubles" as a solution, which did in fact solve the issue of making the mesh closed, but the normals were still irregular.
So, I guess I'm hoping there are some additional options/functions/filters I can use to ensure the models are properly read and/or processed through the filters. | 0 | 1 | 175 |
0 | 45,561,466 | 0 | 1 | 0 | 0 | 3 | false | 5 | 2013-12-12T00:14:00.000 | 0 | 4 | 0 | Pandas import error when debugging using PVTS | 20,532,621 | 0 | python,python-2.7,visual-studio-2012,pandas,ptvs | I faced the same issue, but just hitting 'Continue' will cause it to be ignored and the code execution will proceed in the usual way.
Or you could uncheck the "Break when this exception type is user-handled" option that comes up in the dialog box displaying the error. | I am dealing with a very silly error, and wondering if any of you have the same problem. When I try to import pandas using import pandas as pd I get an error in copy.py. I debugged into the pamdas imports, and I found that the copy error is thrown when pandas tries to import this: from pandas.io.html import read_html
The exception that is throwns is:
un(shallow)copyable object of type <type 'Element'>
I do not get this error if I try to straight up run the code and not use the PVTS debugger. I am using the python 2.7 interpreter, pandas version 0.12 which came with the python xy 2.7.5.1 distro and MS Visual Studio 2012.
Any help would be appreciated. Thanks! | 0 | 1 | 3,689 |
0 | 37,602,619 | 0 | 1 | 0 | 0 | 3 | false | 5 | 2013-12-12T00:14:00.000 | 0 | 4 | 0 | Pandas import error when debugging using PVTS | 20,532,621 | 0 | python,python-2.7,visual-studio-2012,pandas,ptvs | I had a system crash while developing a PTVS app and then ran into this problem, re-running the Intellisense 'refresh DB' cleared it. | I am dealing with a very silly error, and wondering if any of you have the same problem. When I try to import pandas using import pandas as pd I get an error in copy.py. I debugged into the pamdas imports, and I found that the copy error is thrown when pandas tries to import this: from pandas.io.html import read_html
The exception that is throwns is:
un(shallow)copyable object of type <type 'Element'>
I do not get this error if I try to straight up run the code and not use the PVTS debugger. I am using the python 2.7 interpreter, pandas version 0.12 which came with the python xy 2.7.5.1 distro and MS Visual Studio 2012.
Any help would be appreciated. Thanks! | 0 | 1 | 3,689 |
0 | 36,753,326 | 0 | 1 | 0 | 0 | 3 | false | 5 | 2013-12-12T00:14:00.000 | 0 | 4 | 0 | Pandas import error when debugging using PVTS | 20,532,621 | 0 | python,python-2.7,visual-studio-2012,pandas,ptvs | I had the same problem for a while, disabling "Debug standard library" didn't help, then I downloaded the latest version of Python (3.4), pip installed the libs (for example NLTK), and it worked! | I am dealing with a very silly error, and wondering if any of you have the same problem. When I try to import pandas using import pandas as pd I get an error in copy.py. I debugged into the pamdas imports, and I found that the copy error is thrown when pandas tries to import this: from pandas.io.html import read_html
The exception that is throwns is:
un(shallow)copyable object of type <type 'Element'>
I do not get this error if I try to straight up run the code and not use the PVTS debugger. I am using the python 2.7 interpreter, pandas version 0.12 which came with the python xy 2.7.5.1 distro and MS Visual Studio 2012.
Any help would be appreciated. Thanks! | 0 | 1 | 3,689 |
0 | 20,573,996 | 0 | 0 | 0 | 0 | 1 | false | 5 | 2013-12-13T17:41:00.000 | 7 | 1 | 0 | Mathematical background of statsmodels wls_prediction_std | 20,572,706 | 1 | python,statsmodels | There should be a variation on this in any textbook, without the weights.
For OLS, Greene (5th edition, which I used) has
se = s^2 (1 + x (X'X)^{-1} x')
where s^2 is the estimate of the residual variance, x is vector or explanatory variables for which we want to predict and X are the explanatory variables used in the estimation.
This is the standard error for an observation, the second part alone is the standard error for the predicted mean y_predicted = x beta_estimated.
wls_prediction_std uses the variance of the parameter estimate directly.
Assuming x is fixed, then y_predicted is just a linear transformation of the random variable beta_estimated, so the variance of y_predicted is just
x Cov(beta_estimated) x'
To this we still need to add the estimate of the error variance.
As far as I remember, there are estimates that have better small sample properties.
I added the weights, but never managed to verify them, so the function has remained in the sandbox for years. (Stata doesn't return prediction errors with weights.)
Aside:
Using the covariance of the parameter estimate should also be correct if we use a sandwich robust covariance estimator, while Greene's formula above is only correct if we don't have any misspecified heteroscedasticity.
What wls_prediction_std doesn't take into account is that, if we have a model for the heteroscedasticity, then the error variance could also depend on the explanatory variables, i.e. on x. | wls_prediction_std returns standard deviation and confidence interval of my fitted model data. I would need to know the way the confidence intervals are calculated from the covariance matrix. (I already tried to figure it out by looking at the source code but wasn't able to) I was hoping some of you guys could help me out by writing out the mathematical expression behind wls_prediction_std. | 0 | 1 | 2,096 |
0 | 20,579,228 | 0 | 0 | 0 | 0 | 1 | false | 3 | 2013-12-14T02:55:00.000 | 0 | 1 | 0 | Normalization in the artificial neural network | 20,579,179 | 0 | python,neural-network,normalization | One way to do this is to bit-encode your input; have one neuron per bit of the maximal length input string; and feed 0 as -1, and 1 as 1. If you desire a bit-string as output, then interpret positive outputs as 1 and negative outputs as 0. | I am having problem to understand normalization concept in artificial neural networks. If you could explain how it works. For example if I want input basketball score 58-72 or if I want input word “cat” (as a natural language word). How it works if the range is [-1,1]. Be aware that I am very new with ANN and normalization concept. | 0 | 1 | 756 |
0 | 20,617,702 | 0 | 0 | 0 | 0 | 1 | false | 1 | 2013-12-16T17:58:00.000 | 8 | 1 | 0 | Will random numbers still be random if I systematically delete every nth one? | 20,617,587 | 1 | python,random,numpy | If they were indistinguishable from to true random begin with, they will be indistinguishable from true random afterwards.
The reason is that any correlation or bias that exists among the remaining numbers would also constitute a correlation or bias among the complete set. Therefore if the complete set is good then the subset is good.
Of course, this would not necessarily be the case if you deleted the numbers selectively based on their value, rather than based solely on their position in the sequence.
Also, if the numbers are not good to begin with then they might conceivably be worse afterwards than before. For an extreme example, consider a sequence that consists of 9 zeros followed by the result of a coin toss, 9 zeros and another coin toss, etc. This data source has some entropy (1 bit per 10 values), but if you remove every 10th element then it has none (the remaining output is known in advance). | I am currently using numpy.random.random_sample to compute a large set of random numbers. If I delete, say, every 10th of these numbers, is the result still going to be as random as before? Or would I introduce some sort of skew by doing this?
EDIT: As pointed out this boils down to how good my RNG is. How can I find out if I can trust a RNG, or how would I spot a potential skew? | 0 | 1 | 101 |
0 | 29,225,626 | 0 | 0 | 0 | 1 | 1 | false | 12 | 2013-12-16T18:50:00.000 | 0 | 2 | 0 | Reading a large table with millions of rows from Oracle and writing to HDF5 | 20,618,523 | 0 | python,pandas,hdf5,pytables | Okay, so I don't have much experience with oracle databases, but here's some thoughts:
Your access time for any particular records from oracle are slow, because of a lack of indexing, and the fact you want data in timestamp order.
Firstly, you can't enable indexing for the database?
If you can't manipulate the database, you can presumably request a found set that only includes the ordered unique ids for each row?
You could potentially store this data as a single array of unique ids, and you should be able to fit into memory. If you allow 4k for every unique key (conservative estimate, includes overhead etc), and you don't keep the timestamps, so it's just an array of integers, it might use up about 1.1GB of RAM for 3 million records. That's not a whole heap, and presumably you only want a small window of active data, or perhaps you are processing row by row?
Make a generator function to do all of this. That way, once you complete iteration it should free up the memory, without having to del anything, and it also makes your code easier to follow and avoids bloating the actual important logic of your calculation loop.
If you can't store it all in memory, or for some other reason this doesn't work, then the best thing you can do, is work out how much you can store in memory. You can potentially split the job into multiple requests, and use multithreading to send a request once the last one has finished, while you process the data into your new file. It shouldn't use up memory, until you ask for the data to be returned. Try and work out if the delay is the request being fulfilled, or the data being downloaded.
From the sounds of it, you might be abstracting the database, and letting pandas make the requests. It might be worth looking at how it's limiting the results. You should be able to make the request for all the data, but only load the results one row at a time from the database server. | I am working with an Oracle database with millions of rows and 100+ columns. I am attempting to store this data in an HDF5 file using pytables with certain columns indexed. I will be reading subsets of these data in a pandas DataFrame and performing computations.
I have attempted the following:
Download the the table, using a utility into a csv file, read the csv file chunk by chunk using pandas and append to HDF5 table using pandas.HDFStore. I created a dtype definition and provided the maximum string sizes.
However, now when I am trying to download data directly from Oracle DB and post it to HDF5 file via pandas.HDFStore, I run into some problems.
pandas.io.sql.read_frame does not support chunked reading. I don't have enough RAM to be able to download the entire data to memory first.
If I try to use cursor.fecthmany() with a fixed number of records, the read operation takes ages at the DB table is not indexed and I have to read records falling under a date range. I am using DataFrame(cursor.fetchmany(), columns = ['a','b','c'], dtype=my_dtype)
however, the created DataFrame always infers the dtype rather than enforce the dtype I have provided (unlike read_csv which adheres to the dtype I provide). Hence, when I append this DataFrame to an already existing HDFDatastore, there is a type mismatch for e.g. a float64 will maybe interpreted as int64 in one chunk.
Appreciate if you guys could offer your thoughts and point me in the right direction. | 0 | 1 | 5,171 |
0 | 20,623,886 | 0 | 1 | 0 | 0 | 1 | false | 2 | 2013-12-17T00:43:00.000 | 0 | 4 | 0 | Python, find the index of 1D array that is filled with arrays of tuple | 20,623,847 | 0 | python,arrays,multidimensional-array,indexing,tuples | If you have a 1 dimensional array, that is simply an array of values like you mentioned where the array could equal [2013, 12, 16, 1, 10]. You access individual items in the array by using array[index]. However, there are actually 3 parameters used for getting array values:
array[start:end:step]
array[0, 1] is invalid, as the syntax is using colons not commas. 0,1 evaluates to a tuple of 2 values, (0, 1). If you want to get the value of 12, you need to say array[1] | I have a 1D array. each element holds a unique value IE [2013 12 16 1 10] so array[0,0] would be [2013] array[0,1] would be [12]. array[0,0:2] would be [2013 12].
When I try array.index(array[0,0:5]). It creates error and says that list indicies must be integers, not tuple. find the index of a specific element if the element is [2013 12 16 1 10] a tuple...? | 0 | 1 | 979 |
0 | 55,944,660 | 0 | 0 | 0 | 0 | 1 | false | 121 | 2013-12-17T14:59:00.000 | -2 | 6 | 0 | Skip rows during csv import pandas | 20,637,439 | -0.066568 | python,pandas,csv,readfile | skip[1] will skip second line, not the first one. | I'm trying to import a .csv file using pandas.read_csv(), however, I don't want to import the 2nd row of the data file (the row with index = 1 for 0-indexing).
I can't see how not to import it because the arguments used with the command seem ambiguous:
From the pandas website:
skiprows : list-like or integer
Row numbers to skip (0-indexed) or number of rows to skip (int) at the
start of the file."
If I put skiprows=1 in the arguments, how does it know whether to skip the first row or skip the row with index 1? | 0 | 1 | 269,629 |
0 | 20,661,301 | 0 | 0 | 0 | 0 | 1 | false | 10 | 2013-12-18T14:44:00.000 | 7 | 1 | 0 | What's the difference between kmeans and kmeans2 in scipy? | 20,661,142 | 1 | python,machine-learning,scipy,k-means | Based on the documentation, it seems kmeans2 is the standard k-means algorithm and runs until converging to a local optimum - and allows you to change the seed initialization.
The kmeans function will terminate early based on a lack of change, so it may not even reach a local optimum. Further, the goal of it is to generate a codebook to map feature vectors to. The codebook itself is not necessarily generated from the stoping point, but will use the iteration that had the lowest "distortion" to generate the codebook. This method will also run kmeans multiple times. The documentation goes into more specifics.
If you just want to run k-means as an algorithm, pick kmeans2. If you just want a codebook, pick kmeans. | I am new to machine learning and wondering the difference between kmeans and kmeans2 in scipy. According to the doc both of them are using the 'k-means' algorithm, but how to choose them? | 0 | 1 | 3,357 |
0 | 20,714,204 | 0 | 1 | 0 | 0 | 1 | true | 3 | 2013-12-20T21:06:00.000 | 1 | 1 | 0 | Can I statically type a h5file array in Cython? | 20,711,941 | 1.2 | python,cython,hdf5,pytables | If you use the h5py package, you can use numpy.asarray() on the datasets it gives you, then you have a more familiar NumPy array that you already know how to deal with.
Please note that h5py had a bug related to this until a couple years ago which caused disastrously slow performance when doing asarray() but this was solved so please don't use a very old version if you're going to try this. | I develop a library that uses Cython at a low level to solve flow problems across 2D arrays. If these arrays are numpy arrays I can statically type them thus avoiding the Python interpreter overhead of random access into those arrays. To handle arrays of sizes so big they don't fit in memory, I plan to use hd5file Arrays from pytables in place of numpy, but I can't figure out if it's possible to statically type a CArray.
Is it possible to statically type hd5file CArrays in Cython to avoid Python interpreter overhead when randomly accessing those arrays? | 0 | 1 | 100 |
0 | 20,729,020 | 0 | 0 | 0 | 0 | 1 | true | 1 | 2013-12-22T11:34:00.000 | 1 | 1 | 0 | highlight regions of no data in a Python imshow plot | 20,728,942 | 1.2 | python,imshow | try setting those values to np.nan ( or float('nan')); you may also want to pass interpolation='nearest' to imshow as an argument. | I am producing an imshow plot in Python.
In the final plot, I have strips/columns of data, between which there is no data at all - kind of like a barcode.
At the moment, where I have no data, I have just set all values to zero. The color of these regions of no data is therefore whatever colour represents zero in my colorbar - green in my case.
What I really want is for these columns/strips just to be white, and to make to really clear that these are regions of NO data.
I realise that I could change the colorbar so that the zero is white, but I really want to distinguish the regions of no data from any zeros that might be in the data.
Thank you. | 0 | 1 | 622 |
0 | 20,780,564 | 0 | 0 | 0 | 0 | 1 | false | 4 | 2013-12-26T03:38:00.000 | 0 | 1 | 0 | compare NumPy vs. NumPy+MKL performance | 20,778,806 | 0 | python,numpy,ubuntu-12.04,scientific-computing,intel-mkl | As far as I know the only way is to compile NumPy again without MKL, preferably in a virtualenv.... | So, I compiled NumPy from source, linking to MKL. Now I want to compare NumPy's performance with and without MKL. Is there any way I can "tell" NumPy not to use MKL, so I can produce the benchmarks? For instance, with numExpr we can do numexpr.use_vml = False. Is there anything similar for NumPy? I really don't wanna have to compile NumPy without MKL just for this.
(Ubuntu 12.04, Python 2.7.3, NumPy 1.8, Intel Composer XE 2013 SP1) | 0 | 1 | 1,214 |
0 | 70,174,450 | 0 | 0 | 0 | 0 | 1 | false | 0 | 2013-12-27T06:31:00.000 | 1 | 2 | 0 | Python . Select transparent colour or no colour for lines / points etc | 20,795,990 | 0.099668 | python | Try color = '#FF000000' its the Hex code. | How do I plot a line of transparent colour or no colour ?
For example :
plot(x,y,color='transparent')
or
plot(x,y,color='None')
BTW , color='white' is not what I'm looking for .
Thanks in advance invisible computer people . | 0 | 1 | 18,046 |
0 | 33,393,680 | 0 | 1 | 0 | 0 | 2 | false | 13 | 2013-12-28T19:02:00.000 | 2 | 3 | 0 | what's the difference between spatial and temporal characterization in terms of image processing? | 20,818,230 | 0.132549 | java,python,image,matlab,image-processing | Spatial = Space
Example, Image consist of pixel values which needs memory space to store. Spatial information = Pixel values stored into Memory
Temporal = Time
Example, Video consists of image frame sequence. With respect to time the frames are changed in video. This is called Temporal Information. | I am a beginner in learning image processing and I am a bit confused with the concept of spatial and temporal characterization. So, for Spatial characterization, is it like a 2D map which contains some statistical information about the map? And in terms of the temporal characterization, is the value with respect to time? What does it mean and why do we care? Thanks! | 0 | 1 | 72,641 |
0 | 70,253,700 | 0 | 1 | 0 | 0 | 2 | false | 13 | 2013-12-28T19:02:00.000 | 0 | 3 | 0 | what's the difference between spatial and temporal characterization in terms of image processing? | 20,818,230 | 0 | java,python,image,matlab,image-processing | Example of Spatial analysis application: Inspecting an image e.g. pose estimation on an image.
Example of Temporal analysis application: Inspecting a video e.g. vehicle monitoring or pedestrian path prediction | I am a beginner in learning image processing and I am a bit confused with the concept of spatial and temporal characterization. So, for Spatial characterization, is it like a 2D map which contains some statistical information about the map? And in terms of the temporal characterization, is the value with respect to time? What does it mean and why do we care? Thanks! | 0 | 1 | 72,641 |
0 | 20,914,427 | 0 | 0 | 0 | 0 | 1 | true | 3 | 2014-01-03T05:28:00.000 | 1 | 1 | 0 | How to draw and fill a polygon on a grid array using pure Numpy functions? | 20,897,140 | 1.2 | python,image,numpy,fill,polygons | In this case the point to achieve speed is more the used algorithms than the language of choice. Drawing and filling poligons rasterized over a grid of pixel falls into the domain of image processing algorithms and for sure AggDraw is using algorithms from that field.
The idea is that if you evaluate for each points a function that considers the vectorial nature of the polygon you need to do a number of operations that is at least O(2*p*A) where:
A = image area
p = average number of points in the perimeter of the polygons.
Conversely if you use image processing algorithms for each point you can consider to have a fixed and low number of operations. For example if you consider the FloodFill algorithm it is O(A) and I can say it is less than 30*A (about 30 operations per pixel).
So basically since the GADM polygons has many vertex is better to eliminate the vectorial nature of the problem as soon as possible and go with something like this:
construct the pixel map of the boundary
find one internal pixel
use the Floodfill algorithm that will work without any need to know about polygons as vectorial entities
The same algorithms can for sure be implemented in Numpy but before going for a Numpy graphical lib I would suggest to do the following:
measure the time spent in your code for the various steps:
Numpy array to AggDraw lists/sequences conversion
time taken by AggDraw
try to decimate the vertex of the polygons removing the ones that stay in the same pixel based on the current Zoom level and see if an how the times will be reduced | Here goes a difficult one for the expert Numpyer!
Does someone know or can come up with a way to use pure Numpy arrays and functions to draw as well as fill colored polygons on top of a numpy array grid?
This I think would take two steps:
The ability to fill the grid array with color values so that the
polygon filling could be written in one color, and the outline in
another one. What would be ideal and fastest for such a system, eg
tuples of rgb values, color name strings, etc?
The ability to draw and fill the inside of a polygon based on an
array of its pixel coordinates. Drawing the outline of it I think
should be pretty easy by just using the coordinates as indexes to
the grid array and setting them to the outline color values. More
difficult would be to fill the polygon. One way would be to iterate
through all pixel cell coordinates (or better yet only for the
neighboring cells of each polygon coordinate point) and test if its
coordinates are within the polygon pixel coordinates. I know there
are some simple inside-outside/biggerthan-smallerthan algorithms to
test for point in poly using regular Python, but for my purpose this
would be too slow and I am wondering if someone has the numpy skills
to set up such an advanced linked code using only the speed of the
numpy builtin functions to return True if a numpy pixel coordinate
is inside a polygon.
Lastly, if someone would know how to draw a line between two
pixel/grid/array coordinates by filling in all the cells in between
two pixels with a True or color value?
I know this is a tall order, but I was just curious to see if anyone would know. If so, then this could make for a pretty powerful and fast Numpy-based drawing library. In the end I would like to save the grid array as an image which is easy by passing it to PIL.
I am aware that PIL and Aggdraw can do the polygon drawings and that this has been suggested in many similar posts, but they are not very effective when receiving a numpy array of xy polygon/line coordinates. The assumption here is that my polygon coordinates are already in a numpy array format and I want to avoid the overhead of having to copy them into lists for every drawing (when we're talking about thousands of polygons frequently). So the difference in this post is about how to fill a polygon using pure Numpy. | 0 | 1 | 2,144 |
0 | 20,901,191 | 0 | 0 | 0 | 0 | 1 | false | 0 | 2014-01-03T10:03:00.000 | 0 | 1 | 0 | Common longest and shortest path in graphs | 20,901,030 | 0 | python,graph | If you have graphs with the same set of nodes (V1,...,VN) (if some nodes are unique that it does not matter, you simply ignore them as they cannot be the part of any common path) and want to find a shortest/longest path you can proceed as follows:
Generate the intersection of all the graphs, that is: a graph, that has nodes (V1,...,VN) and node Vi is connected to Vj iff in all your graphs Vi is connected to Vj. If you have adjacency matrices of each graph, it is just an element-wise multiplication of this matrices
Find the shortest/longest path in the resulting graph, it has a guarantee to be the shortest (between some two vertices I suppose?) /longest (common) among all of them. | I need a hint were to look algo ( maybe even in python )
So I have huge amount of graphs some, and I need to find common shortest and longest path for this graphs. or common parts ( shortest or longest )
Upd for more clear describing:
Before analysis graphs already have connections between nodes ? so they are already like a path.
And as result it's needed to have common possible path for all graphs depending on connections between nodes | 0 | 1 | 798 |
0 | 20,911,192 | 0 | 0 | 0 | 0 | 1 | false | 11 | 2014-01-03T19:20:00.000 | 1 | 5 | 0 | Choose random seed and save it | 20,911,147 | 0.039979 | python,numpy | When people need a random seed that can be recorded, people usually use the system time as a random seed. This means your program will act differently each time it is run, but can be saved and captured. Why don't you try that out?
If you don't want to do that for some reason, use the null version, numpy.random.seed(seed=None), then get a random number from it, then set the seed to that new random number. | I would like to choose a random seed for numpy.random and save it to a variable. I can set the seed using numpy.random.seed(seed=None) but how do you get numpy to choose a random seed and tell you what it is?
Number seems to use /dev/urandom on linux by default. | 0 | 1 | 6,170 |
0 | 33,822,675 | 0 | 0 | 0 | 0 | 1 | false | 2 | 2014-01-07T11:59:00.000 | 0 | 3 | 0 | Named-entity recognition: How to tag the training set and chose the algorithm? | 20,971,073 | 0 | python,nlp,nltk,named-entity-recognition,pos-tagger | Named Entity Recognition(Stanford) is enough for your problem.
Using POS tagging will not help your problem.
A sufficient amount of training data for generating the NER model would give you good results.
If you use the Stanford NER then it uses the CRF classifier and algorithm. | For text that contains company names I want to train a model that automatically tags contractors (company executing the task) and principals (company hiring the contractor).
An example sentence would be:
Blossom Inc. hires the consultants of Big Think to develop an outsourcing strategy.
with Blossom Inc as the principal and Big Think as the contractor.
My first question: Is it enough to tag only the principals and contractors in my training set or is it better to additionally use POS-tagging?
In other words, either
Blossom/PRINCIPAL Inc./PRINCIPAL hires/NN the/NN consultants/NN of/NN Big/CONTRACTOR Think/CONTRACTOR to/NN develop/NN an/NN outsourcing/NN strategy/NN ./.
or
Blossom/PRINCIPAL Inc./PRINCIPAL hires/VBZ the/DT consultants/NNS of/IN Big/CONTRACTOR Think/CONTRACTOR to/TO develop/VB an/DT outsourcing/NN strategy/NN ./.
Second question: Once I have my training set, which algorithm(s) of the nltk-package is/are most promising? N-Gram Tagger, Brill Tagger, TnT Tagger, Maxent Classifier, Naive Bayes, ...? Or am I completely on the wrong track here?
I am new to NLP and I just wanted to ask for advice before I invest a lot of time in tagging my training set. And my text is in German, which might add some difficulties... Thanks for any advice! | 0 | 1 | 2,772 |
0 | 20,984,538 | 0 | 0 | 0 | 0 | 1 | false | 0 | 2014-01-07T23:39:00.000 | 2 | 1 | 0 | Dispersing Random Sampling in CSV through Python | 20,984,266 | 0.379949 | python,python-2.7,csv,random,pandas | There are many ways to implement this, but the abstract algorithm should be something like this.
First, to create a new CSV that meets your second critera about each state being drawn with equal probability, draw each row as follows.
1) From the set of states, draw a state (each state is drawn with probability 1 / # of states). Let that state be s.
2) From the large CSV, draw a row from the set of rows where STATE = s.
As you draw rows, keep a record of the number of rows drawn from a given state/city pair. You could do this with a dictionary. Then, each time you draw a successive row, if there are any state/city pairs equal to the cap set by the user, exclude those state/city pairs from your conditional draw in step 2 above. This will satisfy your first requirement.
Does that make sense? If you get started with a bit of code that attempts to implement this, I'll happily tidy it up for you if it has any problems.
If you wanted to do the "somewhat trickier" algorithm in which the probability of selecting a city decreases with each selection, you could do that without much trouble. Basically, condition on the cities within state s after you draw s, then weight according to the number of times each city in that state has been drawn (you have this information because you've been storing it to implement the first requirement). You'll have to come up with the form of the weighting function, as it isn't implied by your description.
Again, if you try to code this up, I'm happy to take a look at any code you post and make suggestions. | I have a (large) directory CSV with columns [0:3] = Phone Number, Name, City, State.
I created a random sample of 20,000 entries, but it was, of course, weighted drastically to more populated states and cities.
How would I write a python code (using CSV or Pandas - I don't have linecache available) that would equally prioritize/weight each unique city and each state (individually, not as a pair), and also limit each unique city to 3 picks?
TRICKIER idea: How would I write a python code such that for each random line that gets picked, it checks whether that city has been picked before. If that city has been picked before, it ignores it and picks a random line again, reducing the number of considered previous picks for that city by one. So, say that it randomly picks San Antonio, which has been picked twice before. The script ignores this pick, places it back into the list, reduces the number of currently considered previous San Antonio picks, then randomly chooses a line again. IF it picks a line from San Antonio again, then it repeats the previous process, now reducing considered San Antonio picks to 0. So it would have to pick San Antonio three times in a row to add another line from San Antonio. For future picks, it would have to pick San Antonio four times in a row, plus one for each additional pick.
I don't know how well the second option would work to "scatter" my random picks - it's just an idea, and it looks like a fun way to learn more pythonese. Any other ideas along the same line of thought would be greatly appreciated. Insights into statistical sampling and sample scattering would also be welcome. | 0 | 1 | 114 |
0 | 21,009,215 | 0 | 0 | 0 | 0 | 1 | false | 5 | 2014-01-08T00:39:00.000 | 3 | 2 | 0 | How to obtain GridSearchCV partly finished results? | 20,984,918 | 0.291313 | python,scikit-learn,scikits | You can set the verbose option to a value >0. That will at least give you the results on stdout. | I have started a grid search for SVM parameters in a rather wide range.
The most of the search space have been calculated and now I got one last process, which goes already for 100 hours.
I'd like to see the results, that already have been calculated.
Is there any way to do it?
Thanks in advance! | 0 | 1 | 849 |
0 | 21,025,867 | 0 | 0 | 0 | 0 | 1 | true | 1 | 2014-01-09T16:27:00.000 | 1 | 1 | 0 | Python numpy: column arrays (2d) or lists (1d) | 21,025,774 | 1.2 | python,numpy | Depends on the use case. Both possibilities exist for a reason: if Z can be a matrix but just happens to have one column, make it a column vector. If Z is always a single vector, make it 1-d unless some operation (or library) requires the other format; 1-d is usually a bit easier to work with. | In numpy, is it recommended to create column arrays (2d arrays) rather than 1d arrays? For example, whereas Z = np.zeros((12,)) defines a 1-dimensional list, it might also be preferable to form Z = np.zeros((12,1)). | 0 | 1 | 133 |
0 | 21,063,050 | 0 | 1 | 0 | 0 | 2 | true | 3 | 2014-01-09T16:57:00.000 | 5 | 2 | 0 | Text with multiple colors in PsychoPy | 21,026,487 | 1.2 | python,text,colors,psychopy | No, that isn't possible right now. There's an experimental new stimulus class called TextBox that will allow it, but you'd have to write code to use that (not available yet from the Builder interface). Or just create some tif images of your stimuli and use those? | I am messing around in PsychoPy now, trying to modify the Sternberg demo for a class project. I want the stimulus text—the number set—to display in a variety of colors: say, one digit is red, the next blue, the next brown, etc. A variety within the same stimulus.
I can only find how to change the color of the entire set. I was wondering if I could add another variable to the spreadsheet accompanying the experiment and have the values in the cells be comma separated (red,blue,brown…). Is this possible? | 0 | 1 | 1,012 |
0 | 23,425,589 | 0 | 1 | 0 | 0 | 2 | false | 3 | 2014-01-09T16:57:00.000 | 2 | 2 | 0 | Text with multiple colors in PsychoPy | 21,026,487 | 0.197375 | python,text,colors,psychopy | The current way to implement this is to have a separate text stimulus for each digit, each with the desired colour.
If the text representation of the number is contained in a variable called, say, stimulusText then in the Text field for the first text component put "$stimulusText[0]" so that it contains just the first digit. In the next text component , use "$stimulusText[1]", and so on.
The colour of each text component can be either fixed or vary according to separate column variables specified in a conditions file. | I am messing around in PsychoPy now, trying to modify the Sternberg demo for a class project. I want the stimulus text—the number set—to display in a variety of colors: say, one digit is red, the next blue, the next brown, etc. A variety within the same stimulus.
I can only find how to change the color of the entire set. I was wondering if I could add another variable to the spreadsheet accompanying the experiment and have the values in the cells be comma separated (red,blue,brown…). Is this possible? | 0 | 1 | 1,012 |
0 | 21,050,187 | 0 | 0 | 0 | 0 | 1 | false | 3 | 2014-01-10T14:10:00.000 | 5 | 1 | 0 | Bootstrapping using Quantlib Python | 21,046,422 | 0.761594 | python,c++,bootstrapping,quantlib | PiecewiseYieldCurve is a class template, so it can't be exported to Python as such. By default, we're exporting to Python a particular instantiation of it; it's exported as PiecewiseFlatForward and it correspond to PiecewiseYieldCurve<ForwardRate,BackwardFlat>.
If you need another instantiation, you can edit QuantLib-SWIG/SWIG/piecewiseyieldcurve.i, add it (it you look at the end of the file, you'll find a few examples of how to do it) and regenerate and recompile the Python wrappers.
Finally, an example of bootstrap is available in QuantLib-SWIG/Python/examples/swap.py. | I want to bootstrap a yield curve in Python using QuantLib library.
I know that when doing bootstrapping using C++, there is a function for bootstrapping called PiecewiseYieldCurve in QuantLiab, but when I am using Python, there is no such function in Python QuantLib.
I wonder that if in Python QuantLib there is an alias of PiecewiseYieldCurve, so I have to call the alias function name in order to use PiecewiseYieldCurve function
Should I creating my own function to bootstrap the yield curve?
Thanks! | 0 | 1 | 1,387 |
0 | 24,621,287 | 0 | 0 | 0 | 0 | 1 | false | 2 | 2014-01-10T22:57:00.000 | 1 | 1 | 0 | Issue importing matplotlib.pyplot | 21,056,015 | 0.197375 | macos,python-2.7,matplotlib,enthought,canopy | Check your DYLD_LIBRARY_PATH and LD_LIBRARY_PATH. Make sure that you have your library paths in the right order. I changed mine recently due to a matlab install and it took ages before I made the connection that it was my LD_LIBRARY_PATH that was stuffed. Programs go searching for the libraries in the order specified by those paths. If you have another libpng (as I did) in a library path before the canopy one, then it will use that. Fine if the version is recent, otherwise you get these errors.
First unset them both and then run python and your plot. Hopefully that works. Then go about fixing your DYLD_LIBRARY_PATH and LD_LIBRARY_PATH.
I put these at the front of both /opt/local/lib:/Users/xxxxx/Library/Enthought/Canopy_64bit/User/lib
My error was ...
/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/matplotlib/_png.so
Reason: Incompatible library version: _png.so requires version 41.0.0 or later, but libpng12.dylib provides version 40.0.0 | I am pretty new to Python, having just taken a course and now trying to apply what I learned to convert matlab code to python. I have to plot some things, so I tried to import matplotlib.pyplot but keep getting
Incompatible library version: _png.so requires version 42.0.0 or later, but libpng12.0.dylib provides version 41.0.0
I don't really understand how to either update my libpng12.0.dylib (since I am not really a programmer, just someone who wants to learn python, so please be easy on me if this is a super easy question!), or tell my _png.so to look somewhere else, if that is appropriate. I have done a lot of digging in to this, and I know that there are a number of issues with installing matplotlib on osX, but I haven't seen anything about how to resolve this one.
I am running Enthought Canopy, using python 2.7, and I am running OS X 10.8
I really appreciate any help | 0 | 1 | 295 |
0 | 60,296,334 | 0 | 0 | 0 | 0 | 1 | false | 26 | 2014-01-12T05:40:00.000 | -1 | 3 | 0 | Why does from scipy import spatial work, while scipy.spatial doesn't work after import scipy? | 21,071,715 | -0.066568 | python,scipy | Use scipy version 1.2.1 to solve this issue...... | I would like to use scipy.spatial.distance.cosine in my code. I can import the spatial submodule if I do something like import scipy.spatial or from scipy import spatial, but if I simply import scipy calling scipy.spatial.distance.cosine(...) results in the following error: AttributeError: 'module' object has no attribute 'spatial'.
What is wrong with the second approach? | 0 | 1 | 26,860 |
0 | 21,118,718 | 0 | 0 | 0 | 0 | 1 | true | 1 | 2014-01-13T07:48:00.000 | 0 | 1 | 0 | Scikit Learn - Diagnosing when parallel jobs get stuck | 21,086,215 | 1.2 | python,parallel-processing,scikit-learn | I was unable to definitively find the cause of this problem, but it stopped happening when I increased the amount of memory available. So it seems reasonable to conclude that one of the children processes encountered a MemoryError and just died. | What is the proper way to diagnose what is happening when parallel jobs get stuck in Scikit-Learn?
Specifically, I have had several jobs that appear to finish (htop shows no CPU activity), but python stops responding. Pressing Ctrl+c doesn't exit (though it does register a KeyboardInterrupt, it doesn't kill the python process), and the process must be killed from shell. Total memory usage approaches the capacity of the machine, but I get no explicit errors that there was a MemoryError.
This has occurred with RandomForestRegressor, and also with cross_validation.cross_val_score, under both 0.14 and master on Ubuntu/Debian.
I suspect this is a memory issue, since the jobs seem to complete without a problem on machines with more memory. | 0 | 1 | 935 |
0 | 21,128,497 | 0 | 1 | 0 | 0 | 1 | true | 6 | 2014-01-14T23:33:00.000 | 3 | 2 | 0 | How do you create a compressed dataset in pytables that can store a Unicode string? | 21,126,295 | 1.2 | python,string,unicode,compression,pytables | PyTables does not natively support unicode - yet. To store unicode. First convert the string to bytes and then store a VLArray of length-1 strings or uint8. To get compression simply instantiate your array with a Filters instance that has a non-zero complevel.
All of the examples I know of storing JSON data like this do so using the HDF5 C-API. | I'm using PyTables to store a data array, which works fine; along with it I need to store a moderately large (50K-100K) Unicode string containing JSON data, and I'd like to compress it.
How can I do this in PyTables? It's been a long time since I've worked with HDF5, and I can't remember the right way to store character arrays so they can be compressed. (And I can't seem to find a similar example of doing this on the PyTables website.) | 0 | 1 | 3,616 |
0 | 21,169,703 | 0 | 1 | 0 | 0 | 1 | true | 51 | 2014-01-16T15:58:00.000 | 56 | 1 | 0 | When to use imshow over pcolormesh? | 21,166,679 | 1.2 | python,matplotlib | Fundamentally, imshow assumes that all data elements in your array are to be rendered at the same size, whereas pcolormesh/pcolor associates elements of the data array with rectangular elements whose size may vary over the rectangular grid.
If your mesh elements are uniform, then imshow with interpolation set to "nearest" will look very similar to the default pcolormesh display (without the optional X and Y args). The obvious differences are that the imshow y-axis will be inverted (w.r.t. pcolormesh) and the aspect ratio is maintained, although those characteristics can be altered to look like the pcolormesh output as well.
From a practical point of view, pcolormesh is more convenient if you want to visualize the data array as cells, particularly when the rectangular mesh is non-uniform or when you want to plot the boundaries/edges of the cells. Otherwise, imshow is more convenient if you have a fixed cell size, want to maintain aspect ratio, want control over pixel interpolation, or want to specify RGB values directly. | I often find myself needing to create heatmap-style visualizations in Python with matplotlib. Matplotlib provides several functions which apparently do the same thing. pcolormesh is recommended instead of pcolor but what is the difference (from a practical point of view as a data plotter) between imshow and pcolormesh? What are the pros/cons of using one over the other? In what scenarios would one or the other be a clear winner? | 0 | 1 | 24,635 |
0 | 21,172,252 | 0 | 0 | 0 | 0 | 2 | false | 2 | 2014-01-16T19:30:00.000 | 0 | 2 | 0 | Scipy.opimize.fmin_powell direc argument syntax | 21,171,095 | 0 | python,numpy,scipy,data-fitting | Apparently with wants vector sets, so direc=([1,0,0],[0,0.1,0],[0,0,1]) will do the job. However, still unclear on how this is arranged and functions, so not sure what would happen if some of those zeros were changed. | There is no information on how the direc argument of fmin-powell is supposed to be entered. All the scipy documentation for fmin_powell says is
direc : ndarray, optional
Initial direction set.
I thought that by giving direc=(0.1,0.1,1), I was telling it to start with step sizes of 0.1 for the first two fitting parameters and 1 for the third, which are needed in my case since the 3rd parameter is not sensitive to step sizes of 0.1. However, with this code it starts with 0.1 for all of the fitting parameters. If I try direc=(1,0.1,1), it uses an initial step of 1 for all parameters which destroys the fit, as the second parameter has a range of (0,1) and results in a division by zero if it ever goes negative. How are you supposed to set this argument? | 0 | 1 | 385 |
0 | 21,224,406 | 0 | 0 | 0 | 0 | 2 | false | 2 | 2014-01-16T19:30:00.000 | 1 | 2 | 0 | Scipy.opimize.fmin_powell direc argument syntax | 21,171,095 | 0.099668 | python,numpy,scipy,data-fitting | For Powell minimization, the initial set of direction vectors don't need to be aligned with the axes (although normally they are). As the algorithm runs, it updates the direction vectors to be whatever direction is best in order to step downhill quickly.
But, imagine a case where the surface defined by your function is almost all flat near the starting point. Except, in one particular direction (not aligned with any axis) there is a narrow gulley that descends downward rapidly to the function minimum. In this case, using the direction of the gulley as one of the initial direction vectors might be helpful. Otherwise, conceivably, it might take a while for the algorithm to find a good direction to start moving in. | There is no information on how the direc argument of fmin-powell is supposed to be entered. All the scipy documentation for fmin_powell says is
direc : ndarray, optional
Initial direction set.
I thought that by giving direc=(0.1,0.1,1), I was telling it to start with step sizes of 0.1 for the first two fitting parameters and 1 for the third, which are needed in my case since the 3rd parameter is not sensitive to step sizes of 0.1. However, with this code it starts with 0.1 for all of the fitting parameters. If I try direc=(1,0.1,1), it uses an initial step of 1 for all parameters which destroys the fit, as the second parameter has a range of (0,1) and results in a division by zero if it ever goes negative. How are you supposed to set this argument? | 0 | 1 | 385 |
0 | 21,197,452 | 0 | 0 | 0 | 0 | 1 | false | 0 | 2014-01-17T22:41:00.000 | 0 | 1 | 0 | Aggregation of data from CSV file using Pandas python | 21,197,311 | 0 | csv,python-3.x,io,pandas,pandastream | I've done a little bit of this in C#. First you open up the file and start reading lines of text. The first line in a .csv should be the header column, so handle that separately. The next lines should be your data.
Now once you have your line of text insert it into a string and then split using commas. That will give you a string array. Then make an int array by converting the strings to text. This should not be a problem as long as all data in the column are integers. If not, test for non-integer values and convert them to strings that are valid intergers. E.G. if array[0] == "no data" array[0] = "0", or array[0] = null. Then create column 3 by adding the integer values for the first and second columns together. | I need to process data from csv file in such a way that output should print three columns e.g.
c1,c2 and c3 where c1 and c2 must use group by clause like in mysql and c3 is sum of two other columns.
I am new to python, Ideas will really help me. | 0 | 1 | 128 |
0 | 49,123,783 | 0 | 0 | 0 | 0 | 1 | false | 22 | 2014-01-18T08:00:00.000 | 11 | 4 | 0 | pandas.merge: match the nearest time stamp >= the series of timestamps | 21,201,618 | 1 | python,pandas | Pandas now has the function merge_asof, doing exactly what was described in the accepted answer. | I have two dataframes, both of which contain an irregularly spaced, millisecond resolution timestamp column. My goal here is to match up the rows so that for each matched row, 1) the first time stamp is always smaller or equal to the second timestamp, and 2) the matched timestamps are the closest for all pairs of timestamps satisfying 1).
Is there any way to do this with pandas.merge? | 0 | 1 | 16,509 |
0 | 21,223,365 | 0 | 1 | 0 | 0 | 1 | false | 1 | 2014-01-18T14:45:00.000 | 2 | 2 | 0 | Passing Arrays from Python to Fortran (and back) | 21,205,596 | 0.197375 | python,arrays,fortran,f2py | I love the Python+Fortran stack. :)
When needing close communication between your Python front-end and Fortran engine, a good option is to use the subprocess module in Python. Instead of saving the arrays to a text file, you'll keep them as arrays. Then you'll execute the Fortran engine as a subprocess within the Python script. You'll pipe the Python arrays into the Fortran engine and then pipe the results out to display.
This solution will require changing the file I/O in both the Python and Fortran codes to writing and reading to/from a pipe (on the Python side) and from/to standard input and output (on the Fortran side), but in practice this isn't too much work.
Good luck! | Background:
My program currently assembles arrays in Python. These arrays are connected to a front-end UI and as such have interactive elements (i.e. user specified values in array elements). These arrays are then saved to .txt files (depending on their later use). The user must then leave the Python program and run a separate Fortran script which simulates a system based on the Python output files. While this only takes a couple of minutes at most, I would ideally like to automate the process without having to leave my Python UI.
Assemble Arrays (Python) -> Edit Arrays (Python) -> Export to File (Python)
-> Import File (Fortran) -> Run Simulation (Fortran) -> Export Results to File (Fortran)
-> Import File to UI, Display Graph (Python)
Question:
Is this possible? What are my options for automating this process? Can I completely remove the repeated export/import of files altogether?
Edit:
I should also mention that the fortran script uses Lapack, I don't know if that makes a difference. | 0 | 1 | 2,760 |
0 | 21,222,072 | 0 | 0 | 0 | 0 | 1 | true | 0 | 2014-01-19T18:31:00.000 | 5 | 1 | 0 | Numpy test() finished with errors | 21,220,842 | 1.2 | python-2.7,ubuntu,numpy | Notes for the future me, when trying to redo the stuff:
there are some prerequisites for working with numpy/scipy: g++ gfortran blas atlas lapack.
it seems to be better -- and time consuming -- to compile the numpy/scipy sources. pip install does this.
The commands were:
sudo apt-get install g++ gfortran liblapack-dev libopenblas-dev python-dev python-pip
sudo pip install nose
sudo pip install numpy
python -c "import numpy; numpy.test()"
For the scipy library the following worked:
sudo pip install scipy
python -c "import scipy; scipy.test()" | on ubuntu 12.04 x32 I have installed python 2.7.3, numpy 1.6.1 via sudo apt-get install python-numpy. I run the test() from numpy via numpy.test() and I get:
FAIL: test_pareto (test_random.TestRandomDist)
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/numpy/random/tests/test_random.py", line 313, in test_pareto
np.testing.assert_array_almost_equal(actual, desired, decimal=15)
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 800, in assert_array_almost_equal
header=('Arrays are not almost equal to %d decimals' % decimal))
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 636, in assert_array_compare
raise AssertionError(msg)
AssertionError:
Arrays are not almost equal to 15 decimals
(mismatch 16.6666666667%)
x: array([[ 2.46852460e+03, 1.41286881e+03],
[ 5.28287797e+07, 6.57720981e+07],
[ 1.40840323e+02, 1.98390255e+05]])
y: array([[ 2.46852460e+03, 1.41286881e+03],
[ 5.28287797e+07, 6.57720981e+07],
[ 1.40840323e+02, 1.98390255e+05]])
Ran 3169 tests in 17.483s
FAILED (KNOWNFAIL=3, SKIP=4, failures=1)
What should I do? did I miss a dependency or so?
Thanks. | 0 | 1 | 2,909 |
0 | 21,235,208 | 0 | 0 | 0 | 0 | 1 | false | 2 | 2014-01-20T13:02:00.000 | -1 | 3 | 0 | Store data locally long term | 21,234,887 | -0.066568 | python,numpy,storage,similarity | It is hard to answer you question. Because i don't know about ur data volume and type.
But i can tell you now.
If u are thinking about file for that, it may have scale out issue, if u scale out python server to # of box. So u may need a shared storage. In that case u have to think about shared storage file system like glusterFS or Hadoop. (glusterFS is more eaisier). But the access time will be very poor.
The other option is u can think about Redis. It is memory based key & value store. It also supports file persistance. (because of that it's characteristics is little different from memcahed.)
Final option is u can think about NoSQL which can support scalability and performance. But it is always depends on your requirement. | I am working on a reccommender algorithm for songs. I have a matrix of values that I get the cosine similiarity of in python ( numPy). The problem is that every time i run the program i need to recompute the similarity of every vector to every other vector. I want to store the results of computations locally so i don't have to compute it every time.
The first thing that comes to my mind is storing them in a text file, or in the database itself. Surely theres a better way though? | 0 | 1 | 846 |
0 | 21,278,176 | 0 | 0 | 0 | 0 | 1 | false | 0 | 2014-01-22T05:31:00.000 | 0 | 2 | 0 | Draw a curve joining a set of points in opencv python | 21,274,959 | 0 | python,opencv,math,geometry | If your question is related to the points being extracted in random order, the tool you need is probably the so called 2D alpha-shape. It is a generalization of the convex hull and will let you trace the "outline" of your set of points, and from there perform interpolation. | I have a set of points extracted from an image. I need to join these points to from a smooth curve. After drawing the curve on the image, I need to find the tangent to the curve and represent it on the image. I looked at cv2.approxPolyDP but it already requires a curve?? | 0 | 1 | 2,929 |
0 | 21,287,882 | 0 | 0 | 0 | 0 | 1 | false | 1 | 2014-01-22T15:53:00.000 | 0 | 3 | 0 | Plotting in Python | 21,287,667 | 0 | python,histogram,data-analysis | what format is your data in?
Python offers modules to read data from a variety of data formats (CSV, JSON, XML, ...)
CSV is a very common one that suffices for many cases (the csv module is part of the standard library)
Typically you write a small routine that casts the different fields as expected (string to floating point numbers, or dates, integers,...) and cast your data in a numpy matrix (np.array) where each row corresponds to a sample and each column to an observation
for the plots check matplotlib. It is really easy to generate graphs, especially if you have some previous experience with Matlab | I'm new to python and was curious as to how, given a large set of data consisting of census information, I could plot a histogram or graph of some sort. My main question is how to access the file, not exactly how the graph should be coded. Do I import the file directly? How do I extract the data from the file? How is this done?
Thanks | 0 | 1 | 498 |
0 | 21,363,163 | 0 | 0 | 0 | 0 | 1 | false | 0 | 2014-01-24T03:29:00.000 | 0 | 1 | 0 | opencv2 capture using retrieve() does not work but read() works | 21,323,878 | 0 | python,opencv,python-2.7,ubuntu,arduino | After reading the docs and performing many tests, I realized the I had not grabbed a frame before calling retrieve(). My thought was that the USB driver would automatically tick in the web cameras image into a buffer. Then, at any time, I could read that video frame's memory with having to wait. | I am using opencv2. I am able to capture frames from my web cam using cap.read() but not with cap.retrieve(). I like retrieve() because it does not block so my frame speed is faster. My retrieve() used to work but it stopped and now returns a black screen. both functions return true in the return status. I must have installed something like a different usb driver. I am using Ubuntu linux on a pcduino2. | 0 | 1 | 117 |
0 | 21,333,741 | 0 | 1 | 0 | 0 | 1 | false | 1 | 2014-01-24T12:45:00.000 | 1 | 1 | 0 | pandas: how to extract a set of dates from a DataFrame with datetime index? | 21,333,102 | 0.197375 | python,pandas | Take the intersection of their indices.
In [1]: import pandas as pd
In [2]: index1 = pd.DatetimeIndex(start='2000-1-1', freq='1T', periods=1000000)
In [3]: index2 = pd.DatetimeIndex(start='2000-1-1', freq='1D', periods=1000)
In [4]: index1
Out[4]:
[2000-01-01 00:00:00, ..., 2001-11-25 10:39:00]
Length: 1000000, Freq: T, Timezone: None
In [5]: index2
Out[5]:
[2000-01-01 00:00:00, ..., 2002-09-26 00:00:00]
Length: 1000, Freq: D, Timezone: None
In [6]: index1 & index2
Out[6]:
[2000-01-01 00:00:00, ..., 2001-11-25 00:00:00]
Length: 695, Freq: D, Timezone: None
In your case, do the following:
index1 = df1.index
index2 = df2.index
Then take the intersection of these as defined before.
Later you may wish to do something like the following to get the df at intersection index.
df1_intersection =df1.ix[index1 & index2] | I have two DataFrames with TimesSeriesIndex, df1, df2.
df2's index is a subset of df1.index.
How can I extract the index dates from df1 which also contained by df2, so I can run analysis on these dates. | 0 | 1 | 1,685 |
0 | 21,483,417 | 0 | 0 | 0 | 0 | 1 | true | 1 | 2014-01-31T15:06:00.000 | 2 | 1 | 0 | Python Matplotlib remove xlabels but not grid | 21,483,236 | 1.2 | python,matplotlib,label,axes | Try this: axes.xaxis.set_tick_params(label1On=False) | Is there a way to remove the labels of the x axis, but not the grid lines?
Both solutions to remove the labels also removed my grid lines.
I tried: axes.get_xaxis().set_visible(False) and axes.get_xaxis().set_ticks([]) | 0 | 1 | 90 |
0 | 21,486,017 | 0 | 1 | 0 | 0 | 1 | true | 6 | 2014-01-31T17:00:00.000 | 11 | 1 | 0 | How to label axes in Matplotlib using LaTeX brackets? | 21,485,769 | 1.2 | python,matplotlib,latex | Try ax.set_ylabel(r'$\langle B_{\mathrm{e}} \rangle$') for labeling Y-Axis or ax.set_title(r'$\langle B_{\mathrm{e}} \rangle$') for the title of the axes. | How to label axes in Matplotlib using LaTeX expression $\langle B_{\mathrm{e}} \rangle$?
I need to label my axis with nice looking "<" and ">" LaTeX brackets. | 0 | 1 | 7,377 |
Subsets and Splits