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 | 28,419,293 | 0 | 0 | 0 | 1 | 1 | true | 0 | 2015-02-09T19:34:00.000 | 1 | 2 | 0 | How import dataset from S3 to cassandra? | 28,417,806 | 1.2 | python,cassandra,datastax-enterprise | The details depend on your file format and C* data model but it might look something like this:
Read the file from s3 into an RDD
val rdd = sc.textFile("s3n://mybucket/path/filename.txt.gz")
Manipulate the rdd
Write the rdd to a cassandra table:
rdd.saveToCassandra("test", "kv", SomeColumns("key", "value")) | i Launch cluster spark cassandra with datastax dse in aws cloud. So my dataset storage in S3. But i don't know how transfer data from S3 to my cluster cassandra. Please help me | 0 | 1 | 1,657 |
0 | 34,094,065 | 0 | 0 | 0 | 0 | 1 | true | 1 | 2015-02-09T20:34:00.000 | 0 | 1 | 0 | getting error with softmax and cross entropy in theano | 28,418,823 | 1.2 | python,theano,softmax | solved. I had to use T.nnet.categorical_crossentropy since my target variable is an integer vector. | I'm implementing a DNN with Theano. At the last layer of DNN, I'm using a softmax as a nonlinear function from theano.tensor.nnet.softmax
As a lost function i'm using cross entropy from T.nnet.binary_crossentropy
But I get a strange error:
"The following error happened while compiling the node', GpuDnnSoftmaxGrad{tensor_format='bc01' ..."
I'm a newbie with theano and can't figure out what's wrong with this model. Your help is appreciated
PS: my guess is it is somehow related to the fact that softmax takes a 2D tensor and returns a 2D tensor.
PS2:I'm using the bleeding edge Theano (just cloned) my CUDA version is old it is 4.2 BUT I'm almost sure that that's not the problem since I'm working without error with other DNN tools written based on Theano.
I'm using pylearn2 to accelerate and that's not the problem either since I already used it successfully with the current Theano and CUDA in another DNN.
The error happens at this line: train= theano.function([idx], train_loss, givens=givens, updates=updates)
The full error message is:
cmodule.py", line 293, in dlimport
rval = __import__(module_name, {}, {}, [module_name])
RuntimeError: ('The following error happened while compiling the node', GpuDnnSoftmaxGrad{tensor_format='bc01', mode='channel', algo='accurate'}(GpuContiguous.0, GpuContiguous.0), '\n', 'could not create cuDNN handle: The handle was not initialized(Is your driver recent enought?).', "[GpuDnnSoftmaxGrad{tensor_format='bc01', mode='channel', algo='accurate'}(<CudaNdarrayType(float32, (False, False, True, True))>, <CudaNdarrayType(float32, (False, False, True, True))>)]")
The Cross entropy funcion I'm using is defined as:
error = T.mean(T.nnet.binary_crossentropy(input, target_y)
where input is the output of the softmax layer and target_y is the labels. | 0 | 1 | 1,358 |
0 | 57,704,035 | 0 | 0 | 0 | 0 | 1 | false | 33 | 2015-02-09T21:37:00.000 | 52 | 3 | 0 | Check whether non-index column sorted in Pandas | 28,419,877 | 1 | python,pandas | Meanwhile, since 0.19.0, there is pandas.Series.is_monotonic_increasing, pandas.Series.is_monotonic_decreasing, and pandas.Series.is_monotonic. | Is there a way to test whether a dataframe is sorted by a given column that's not an index (i.e. is there an equivalent to is_monotonic() for non-index columns) without calling a sort all over again, and without converting a column into an index? | 0 | 1 | 17,253 |
0 | 64,579,432 | 0 | 0 | 0 | 0 | 1 | false | 7 | 2015-02-11T00:08:00.000 | 0 | 5 | 0 | numpy.loadtxt: how to ignore comma delimiters that appear inside quotes? | 28,444,272 | 0 | python,csv,numpy | While there is not such a parameter in numpy.loadtxt to ignore quoted or otherwise escaped commas, one alternative that has not been suggested yet would be the following...
Perform a find and replace using some text editor to replace commas with tabs
OR
save the file in Excel as tab delimited.
When you use numpy.loadtxt, you will simply specify delimiter='\t' instead of comma delimited.
Simple solution that could save you some code... | I have a csv file where a line of data might look like this:
10,"Apple, Banana",20,...
When I load the data in Python, the extra comma inside the quotes shifts all my column indices around, so my data is no longer a consistent structure. While I could probably write a complex algorithm that iterates through each row and fixes the issue, I was hoping there was an elegant way to just pass an extra parameter to loadtxt (or some other function) that will properly ignore commas inside quotes and treat the entire quote as one value.
Note, when I load the CSV file into Excel, Excel correctly recognizes the string as one value. | 0 | 1 | 5,651 |
0 | 28,488,596 | 0 | 0 | 0 | 0 | 1 | true | 8 | 2015-02-12T21:54:00.000 | 12 | 2 | 0 | Networkx duplicate edges | 28,488,559 | 1.2 | python,networkx | You can test it pretty quickly, but it only adds them once. Edges and nodes are represented as a dictionaries inside the graph structure, and they are only added if they don't actually exist.
For already existing edges, adding them again has no effect. | If the same edge is added twice to the networkx edge data structure, will it then have two edges between the nodes or still just one? For example, would a spring layout show the nodes converge more with edges [(a,b),(a,b),(a,b),(a,b)] than [(a,b),(a,b)]? If I want to weight the edge, how would I go about it? | 0 | 1 | 13,392 |
0 | 40,033,364 | 0 | 0 | 0 | 0 | 1 | false | 10 | 2015-02-12T22:04:00.000 | 4 | 2 | 0 | Retrieve string version of document by ID in Gensim | 28,488,714 | 0.379949 | python,gensim | Sadly, as far as I can tell, you have to start from the very beginning of the analysis knowing that you'll want to retrieve documents by the ids. This means you need to create your own mapping between ids and the original documents and make sure the ids gensim uses are preserved throughout the process. As is, I don't think gensim keeps such a mapping handy.
I could definitely be wrong, and in fact I'd love it if someone tells me there is an easier way, but I spent many hours trying to avoid re-running a gigantic LSI model on a wikipedia corpus to no avail. Eventually I had to carry along a list of ids and the associated documents so I could use gensim's output. | I am using Gensim for some topic modelling and I have gotten to the point where I am doing similarity queries using the LSI and tf-idf models. I get back the set of IDs and similarities, eg. (299501, 0.64505910873413086).
How do I get the text document that is related to the ID, in this case 299501?
I have looked at the docs for corpus, dictionary, index, and the model and cannot seem to find it. | 0 | 1 | 2,031 |
0 | 28,511,785 | 0 | 0 | 0 | 0 | 1 | true | 0 | 2015-02-13T22:48:00.000 | 1 | 1 | 0 | data exchange format ocaml to python numpy or pandas | 28,510,059 | 1.2 | python,numpy,ocaml,export-to-csv,hdf5 | First of all I would like to mention, that there're actually bindings for HDF-5 for OCaml. But, when I was faced with the same problem I didn't find one that suits my purposes and is mature enough. So I wouldn't suggest you to use it, but who knows, maybe today there is something more descent.
So, to my experience the best way to store numeric data in OCaml is Bigarrays. They are actually wrappers around the C-pointer, that can be allocated outside of OCaml runtime. They also can be a memory mapped regions. So, for me this is the most efficient way to share data between different processes (potentially written in different languages). You can share data using memory mapping with OCaml, Python, Matlab or whatever with very little pain, especially if you're not trying to modify it from different processes simultaneously.
Other approaches, is to use MPI, ZMQ or bare sockets. I would prefer the latter for the only reason that the former doesn't support bigarrays. Also, I would suggest you to look for capn'proto, it is also very efficient, and have bindings for OCaml and Python, and for your particular use case, can work very fine. | I'm generating time series data in ocaml which are basically long lists of floats, from a few kB to hundreds of MB. I would like to read, analyze and plot them using the python numpy and pandas libraries. Right now, i'm thinking of writing them to csv files.
A binary format would probably be more efficient? I'd use HDF5 in a heartbeat but Ocaml does not have a binding. Is there a good binary exchange format that is usable easily from both sides? Is writing a file the best option, or is there a better protocol for data exchange? Potentially even something that can be updated on-line? | 0 | 1 | 245 |
0 | 28,523,302 | 0 | 0 | 0 | 0 | 1 | true | 1 | 2015-02-15T05:19:00.000 | 8 | 1 | 0 | Sorting algorithm times using sorting methods | 28,523,247 | 1.2 | python,algorithm,sorting,time-complexity,computation-theory | The "similarity" (?!) that you see is completely illusory.
The elementary, O(N squared), approaches, repeat their workings over and over, without taking any advantage, for the "next step", of any work done on the "previous step". So the first step takes time proportional to N, the second one to N-1, and so on -- and the resulting sum of integers from 1 to N is proportional to N squared.
For example, in selection sort, you are looking each time for the smallest element in the I:N section, where I is at first 0, then 1, etc. This is (and must be) done by inspecting all those elements, because no care was previously taken to afford any lesser amount of work on subsequent passes by taking any advantage of previous ones. Once you've found that smallest element, you swap it with the I-th element, increment I, and continue. O(N squared) of course.
The advanced, O(N log N), approaches, are cleverly structured to take advantage in following steps of work done in previous steps. That difference, compared to the elementary approaches, is so pervasive and deep, that, if one cannot perceive it, that speaks chiefly about the acuity of one's perception, not about the approaches themselves:-).
For example, in merge sort, you logically split the array into two sections, 0 to half-length and half-length to length. Once each half is sorted (recursively by the same means, until the length gets short enough), the two halves are merged, which itself is a linear sub-step.
Since you're halving every time, you clearly need a number of steps proportional to log N, and, as each step is O(N), obviously you get the very desirable O(N log N) as a result.
Python's "timsort" is a "natural mergesort", i.e, a variant of mergesort tuned to take advantage of already-sorted (or reverse-sorted) parts of the array, which it recognizes rapidly and avoids spending any further work on. This doesn't change big-O because that's about worst-case time -- but expected time crashes much further down because in so many real-life cases some partial sortedness is present.
(Note that, going by the rigid definition of big-O, quicksort isn't quick at all -- it's worst-case proportional to N squared, when you just happen to pick a terrible pivot each and every time... expected-time wise it's fine, though nowhere as good as timsort, because in real life the situations where you repeatedly pick a disaster pivot are exceedingly rare... but, worst-case, they might happen!-).
timsort is so good as to blow away even very experienced programmers. I don't count because I'm a friend of the inventor, Tim Peters, and a Python fanatic, so my bias is obvious. But, consider...
...I remember a "tech talk" at Google where timsort was being presented. Sitting next to me in the front row was Josh Bloch, then also a Googler, and Java expert extraordinaire. Less than mid-way through the talk he couldn't resist any more - he opened his laptop and started hacking to see if it could possibly be as good as the excellent, sharp technical presentation seemed to show it would be.
As a result, timsort is now also the sorting algorithm in recent releases of the Java Virtual Machine (JVM), though only for user-defined objects (arrays of primitives are still sorted the old way, quickersort [*] I believe -- I don't know which Java peculiarities determined this "split" design choice, my Java-fu being rather weak:-).
[*] that's essentially quicksort plus some hacks for pivot choice to try and avoid the poison cases -- and it's also what Python used to use before Tim Peters gave this one immortal contribution out of the many important ones he's made over the decades.
The results are sometimes surprising to people with CS background (like Tim, I have the luck of having a far-ago academic background, not in CS, but in EE, which helps a lot:-). Say, for example, that you must maintain an ever-growing array that is always sorted at any point in time, as new incoming data points must get added to the array.
The classic approach would use bisection, O(log N), to find the proper insertion point for each new incoming data point -- but then, to put the new data in the right place, you need to shift what comes after it by one slot, that's O(N).
With timsort, you just append the new data point to the array, then sort the array -- that's O(N) for timsort in this case (as it's so awesome in exploiting the already-sorted nature of the first N-1 items!-).
You can think of timsort as pushing the "take advantage of work previously done" to a new extreme -- where not only work previously done by the algorithm itself, but also other influences by other aspects of real-life data processing (causing segments to be sorted in advance), are all exploited to the hilt.
Then we could move into bucket sort and radix sort, which change the plane of discourse -- which in traditional sorting limits one to being able to compare two items -- by exploiting the items' internal structure.
Or a similar example -- presented by Bentley in his immortal book "Programming Pearls" -- of needing to sort an array of several million unique positive integers, each constrained to be 24 bits long.
He solved it with an auxiliary array of 16M bits -- just 2M bytes after all -- initially all zeroes: one pass through the input array to set the corresponding bits in the auxiliary array, then one pass through the auxiliary array to form the required integers again where 1s are found -- and bang, O(N) [and very speedy:-)] sorting for this special but important case!-) | So I just learned about sorting algorithm s bubble, merge, insertion, sort etc. they all seem to be very similar in their methods of sorting with what seems to me minimal changes in their approach. So why do they produce such different sorting times ie O(n^2) vs O(nlogn) as an example | 0 | 1 | 297 |
0 | 28,546,908 | 0 | 0 | 0 | 0 | 1 | false | 0 | 2015-02-16T15:41:00.000 | 0 | 1 | 0 | How to cluster a series of right-skewed integers | 28,545,060 | 0 | python,cluster-analysis | On skewed data, it can help a lot to go into logspace.
You may first want to understand the distribution better, then split them.
Have you tried visualizing them, to identify appropriate splitting values?
One-dimensional data can be well visualized, and the results of a manual approach are often better than those of some blackbox clustering. | I have a series of integers. What I would like to do is split them into 5 discrete categories. I tried z-scores with bounds (-oo, -2), [-2, -1), [-1, +1], (+1, +2], (+2, +oo) but it doesn't seem to work probably because of the right-skewed data. So, I though that it might work with some sort of clustering. Any ideas? | 0 | 1 | 80 |
0 | 55,585,713 | 0 | 0 | 0 | 0 | 1 | false | 43 | 2015-02-18T07:33:00.000 | 2 | 3 | 0 | How to multiply two vector and get a matrix? | 28,578,302 | 0.132549 | python,numpy,matrix,vector,matrix-multiplication | If you are using numpy.
First, make sure you have two vectors. For example, vec1.shape = (10, ) and vec2.shape = (26, ); in numpy, row vector and column vector are the same thing.
Second, you do res_matrix = vec1.reshape(10, 1) @ vec2.reshape(1, 26) ;.
Finally, you should have: res_matrix.shape = (10, 26).
numpy documentation says it will deprecate np.matrix(), so better not use it. | In numpy operation, I have two vectors, let's say vector A is 4X1, vector B is 1X5, if I do AXB, it should result a matrix of size 4X5.
But I tried lot of times, doing many kinds of reshape and transpose, they all either raise error saying not aligned or return a single value.
How should I get the output product of matrix I want? | 0 | 1 | 49,959 |
0 | 28,608,797 | 0 | 0 | 0 | 0 | 1 | true | 1 | 2015-02-19T14:02:00.000 | 1 | 1 | 0 | How to get the content of a row of a Numpy array? | 28,608,320 | 1.2 | arrays,python-3.x,numpy | Use array indexing as below:
color[0] | How to get the content of a row of a Numpy array ? For example I have a Numpy array with 3 rows color=np.array([[255,0,0],[255,255,0],[0,255,0]]) and I want to retrieve the content of the first row [255,0,0]. | 0 | 1 | 41 |
0 | 35,262,231 | 0 | 1 | 0 | 0 | 1 | false | 0 | 2015-02-19T19:11:00.000 | 0 | 2 | 0 | unable to install scikit-earn on python 2.7.9 in Windows? | 28,614,874 | 0 | python-2.7,pip,scikit-learn | Changing the directory worked in my case.
Suppose your python 2.7.9 is in C drive so you set you directory as follows and write your command like this :
C:\python27\scripts> pip install -U scikit-learn | I have python 2.7.9 (which comes with pip already installed), I have numpy 1.8.2 and scipy 0.15.1 installed as well.
When I try to install scikit-learn, I get the following error
pip install -U scikit-learn
SyntaxError: invalid syntax
What am I doing wrong?
Or is there another way to install scikit- learn on windows, if I can't use pip ? | 0 | 1 | 771 |
0 | 58,636,713 | 1 | 0 | 0 | 0 | 1 | false | 35 | 2015-02-19T22:42:00.000 | 20 | 10 | 0 | Read a file line by line from S3 using boto? | 28,618,468 | 1 | python,amazon-web-services,amazon-s3,boto | I know it's a very old question.
But as for now, we can just use s3_conn.get_object(Bucket=bucket, Key=key)['Body'].iter_lines() | I have a csv file in S3 and I'm trying to read the header line to get the size (these files are created by our users so they could be almost any size). Is there a way to do this using boto? I thought maybe I could us a python BufferedReader, but I can't figure out how to open a stream from an S3 key. Any suggestions would be great. Thanks! | 0 | 1 | 83,468 |
0 | 28,618,872 | 0 | 0 | 0 | 0 | 1 | false | 12 | 2015-02-19T22:54:00.000 | 3 | 3 | 0 | numpy.fft() what is the return value amplitude + phase shift OR angle? | 28,618,591 | 0.197375 | python,numpy,fft | The magnitude, r, at a given frequency represents the amount of that frequency in the original signal. The complex argument represents the phase angle, theta.
x + i*y = r * exp(i*theta)
Where x and y are the numbers that that the numpy FFT returns. | The np.fft.fft() returns a complex array .... what is the meaning of the complex number ?
I suppose the real part is the amplitude !
The imaginary part is phase-shift ? phase-angle ? Or something else !
I figured out the position in the array represent the frequency. | 0 | 1 | 29,182 |
0 | 28,665,731 | 0 | 0 | 0 | 0 | 1 | true | 33 | 2015-02-22T03:53:00.000 | 9 | 3 | 0 | What is python's equivalent of R's NA? | 28,654,325 | 1.2 | python,numpy,pandas,scikit-learn,data-scrubbing | Scikit-learn doesn't handle missing values currently.
For most machine learning algorithms, it is unclear how to handle missing values, and so we rely on the user of handling them prior to giving them to the algorithm.
Numpy doesn't have a "missing" value. Pandas uses NaN, but inside numeric algorithms that might lead to confusion. It is possible to use masked arrays, but we don't do that in scikit-learn (yet). | What is python's equivalent of R's NA?
To be more specific:
R has NaN, NA, NULL, Inf and -Inf. NA is generally used when there is missing data. What is python's equivalent?
How libraries such as numpy and pandas handle missing values?
How does scikit-learn handle missing values?
Is it different for python 2.7 and python 3? | 0 | 1 | 54,508 |
0 | 37,332,201 | 0 | 1 | 0 | 0 | 2 | false | 558 | 2015-02-22T22:05:00.000 | 7 | 31 | 0 | How to count the occurrence of certain item in an ndarray? | 28,663,856 | 1 | python,numpy,multidimensional-array,count | y.tolist().count(val)
with val 0 or 1
Since a python list has a native function count, converting to list before using that function is a simple solution. | In Python, I have an ndarray y
that is printed as array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
I'm trying to count how many 0s and how many 1s are there in this array.
But when I type y.count(0) or y.count(1), it says
numpy.ndarray object has no attribute count
What should I do? | 0 | 1 | 883,665 |
0 | 59,595,030 | 0 | 1 | 0 | 0 | 2 | false | 558 | 2015-02-22T22:05:00.000 | 0 | 31 | 0 | How to count the occurrence of certain item in an ndarray? | 28,663,856 | 0 | python,numpy,multidimensional-array,count | here I have something, through which you can count the number of occurrence of a particular number:
according to your code
count_of_zero=list(y[y==0]).count(0)
print(count_of_zero)
// according to the match there will be boolean values and according to True value the number 0 will be return | In Python, I have an ndarray y
that is printed as array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
I'm trying to count how many 0s and how many 1s are there in this array.
But when I type y.count(0) or y.count(1), it says
numpy.ndarray object has no attribute count
What should I do? | 0 | 1 | 883,665 |
0 | 28,703,110 | 0 | 0 | 0 | 0 | 1 | false | 0 | 2015-02-24T06:45:00.000 | 0 | 1 | 0 | Normalizing constant of mixture of dirichlet distribution goes unbounded | 28,689,687 | 0 | python,machine-learning,statistics,probability,dirichlet | Some ideas. (1) To calculate the normalizing factor exactly, maybe you can rewrite the gamma function via gamma(a_i + 1) = a_i gamma(a_i) (a_i need not be an integer, let the base case be a_i < 1) and then you'll have sum(a_i, i, 1, n) terms in the numerator and denominator and you can reorder them so that you divide the largest term by the largest term and multiply those single ratios together instead of computing an enormous numerator and an enormous denominator and dividing those. (2) If you don't need to be exact, maybe you can apply Stirling's approximation. (3) Maybe you don't need the pdf at all. For some purposes, you just need a function which is proportional to the pdf. I believe Markov chain Monte Carlo is like that. So, what is the larger goal you are trying to achieve here? | I need to calculate PDFs of mixture of Dirichlet distribution in python. But for each mixture component there is the normalizing constant, which is the inverse beta function which has gamma function of sum of the hyper-parameters as the numerator. So even for a sum of hyper-parameters of size '60' it goes unbounded. Please suggest me a work around for this problem. What happens when I ignore the normalizing constant?
First its not the calculation of NC itself that is the problem. For a single dirichlet I have no problem . But what I have here is a mixture of product of dirichlets, so each mixture component is a product of many dirichlets each with its own NCs. So the product of these goes unbounded. Regarding my objective, I have a joint distribution of p(s,T,O), where 's' is discrete, 'T' and 'O' are the dirichlet variables i.e. a set of vectors of parameters which sum to '1'. Now since 's' is discrete and finite I have |S| set of mixture of product of dirichlet components for each 's'. Now my objective here is to find p(s|T,O). So I directly substitute a particular (T,O) and calculate the value of each p('s'|T,O). For this I need to calc the NCs. If there is only one mixture component then I can ignore the norm constant, calc. and renormalise finally, but since I have several mixture components each components will have different scaling and so I can't renormalise. This is my conundrum. | 0 | 1 | 492 |
0 | 28,753,451 | 0 | 0 | 0 | 0 | 1 | true | 0 | 2015-02-26T20:28:00.000 | 7 | 3 | 0 | Numpy fft.pack vs FFTW vs Implement DFT on your own | 28,752,126 | 1.2 | python,numpy,fft,fftw | If you are implementing the DFFT entirely within Python, your code will run orders of magnitude slower than either package you mentioned. Not just because those libraries are written in much lower-level languages, but also (FFTW in particular) they are written so heavily optimized, taking advantage of cache locality, vector units, and basically every trick in the book, that it would not surprise me if they ran at 10,000x the speed of a naive Python implementation. Even if you are using numpy in your implementation, it will still pale in comparison.
So yes; use numpy's fftpack. If that is not fast enough, you can try the python bindings for FFTW (PyFFTW), but the speedup from fftpack to fftw will not be nearly as dramatic. I really doubt there's a need to drop into C++ just for FFTs - they're sort of the ideal case for Python bindings. | I am currently need to run FFT on 1024 sample points signal. So far I have implementing my own DFT algorithm in python, but it is very slow. If I use the NUMPY fftpack, or even move to C++ and use FFTW, do you guys think it would be better? | 0 | 1 | 4,655 |
0 | 28,871,022 | 0 | 0 | 0 | 0 | 1 | true | 0 | 2015-03-01T04:17:00.000 | 0 | 1 | 0 | Obtain optimal number of boosting iterations in GradientBoostingClassifier using grid search | 28,790,032 | 1.2 | python,scikit-learn | Currently there is no way to directly get the optimum number of estimators from GradientBoostingClassifier. If you also pass n_estimators in the parameter grid to GridSearchCV it will only try the exact values you give it, and return one of these.
We are looking to improve this, by searching over the number of estimators automatically. | With GradientBoostingClassifier suppose I set n_estimators to 2000 and use GridSearchCV to search across learning_rate in [0.01, 0.05, 0.10] - how do I know the number of boosting iterations that produced the optimal result - is the model always going to fit 2000 trees for each value of learning_rate or is it going to use the optimal number of boosting iterations for each of these values? It wouldn't make sense to also include n_estimators in the grid search and search for all values in [1,2000]. | 0 | 1 | 1,119 |
0 | 28,948,827 | 0 | 0 | 0 | 0 | 1 | false | 0 | 2015-03-03T10:46:00.000 | -1 | 1 | 0 | Create splitting criterion for sklearn trees | 28,829,805 | -0.197375 | python,scikit-learn | As Andreas said above, splitting criteria are coded in cython. | I need other splitting criteria for a Desicion tree than the provided 'gini' and 'entropy. I want to use the wonderful sklearn package as base though. Is there a way to go around the C-implementation of the tree building process? As in implementing the criterion in Python and let the TreeBuilder work with it? | 0 | 1 | 601 |
0 | 28,862,593 | 0 | 0 | 0 | 1 | 1 | false | 1 | 2015-03-03T19:10:00.000 | 2 | 1 | 0 | How to do formmating with combination of pandas dataframe.to_excel and xlsxwriter? | 28,839,976 | 0.379949 | python,pandas,xlsxwriter | I found xlwings. It's intuitive and does all the things I want to do. Also, it does well with all pandas data types. | Is it possible to write nice-formatted excel files with dataframe.to_excel-xlsxwriter combo?
I am aware that it is possible to format cells when writing with pure xlsxwriter. But dataframe.to_excel takes so much less space.
I would like to adjust cell width and add some colors to column names.
What other alternatives would you suggest? | 0 | 1 | 100 |
0 | 28,854,271 | 0 | 0 | 0 | 0 | 1 | false | 0 | 2015-03-04T08:57:00.000 | 0 | 1 | 0 | opencv FaceRecognition during login | 28,850,205 | 0 | python,windows,visual-studio,opencv,login | You can store the snapshots in an array, run your recognition on each image and see if the user is recognized as one of the users you have trained your model on.
If not then prompt the user for their name, if the name matches one of the users you trained your model on, add these snapshots to their training set and re-train, so the model is more up to date, if it does not match any names, then you assume this is a new user and create a new label and folder for them, and retrain your recognizer.
Beware though that each time you add more snapshots the training time will increase, so perhaps limit each snapshot capture to 1 FPS or something. | maybe some of you can point me in the right direction.
I've been playing around with OpenCV FaceRecognition for some time with Eigenfaces to let it learn to recognize faces. Now I would like to let it run during windows logon.
Precisely, I want to make Snapshots of Faces when I log into a user so after the software has learned the faces after x logins and to which user it belongs, it will log me in automatically when it recognises me during typing.
As a prototype it would be enough to somehow get a textfield and get textinput working to "simulate" login in. Im using python.
I hope you understand what i want to achieve and can help me out.
Edit: Another Question/Idea: If i want to build an Application in Visual Studio, can I reuse my python Code or do I have to use c++? I could make a Windows Store app or something like that. | 0 | 1 | 211 |
0 | 28,858,326 | 0 | 0 | 0 | 0 | 1 | false | 1 | 2015-03-04T12:42:00.000 | 0 | 1 | 0 | converting dataframe from Hex to binary in using python | 28,854,821 | 0 | python,pandas,binary,hex | If I understood, in column 1 you have 00, column 2 : 55, ...
If I am right, you first need to concat three columns in a string value = str(col1)+str(col2)+str(col3) and then use the method to convert it in binary. | I am pretty new to Python and pandas library, i just learned how to read a csv file using pandas.
my data is actually raw packets i captured from sensor networks, to analyze corrupt packets.
what i have now is, thousands of rows and hundreds of columns, literally, and the values are all in Hex. i need to convert all the values to binary with trailing zeros.
i am at lost on how to accomplish that once i have read the CSV file successfully using pandas.
I'd appreciate every kind of help, even a simple direction.
here is my sample data:
00 FF FF 00 00 29 00 89 29 41 88 44 22 00 FF FF 01 00 3F 06 55 55 55
55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55
55 55 0A
00 FF FF 00 00 29 00 89 29 41 88 45 22 00 FF FF 01 00 3F 06 55 55 55
55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55
55 55 0A
00 FF FF 00 00 29 00 89 29 41 88 46 22 00 FF FF 01 00 3F 06 55 55 55
55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55
55 55 0A
00 FF FF 00 00 29 00 89 29 41 88 47 22 00 FF FF 01 00 3F 06 55 55 55
55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55
55 55 0A | 0 | 1 | 778 |
0 | 28,891,088 | 0 | 0 | 0 | 0 | 2 | false | 1 | 2015-03-05T19:13:00.000 | 1 | 2 | 0 | python-igraph pickling efficiency | 28,885,814 | 0.099668 | python-2.7,igraph | Pickle is a serializer from the standard library in Python. These guesses seem quite likely to me:
When igraph was started they did not want to create an own file format so they used pickle. Now the default behavior for saving graphs is not pickle but the own format.
When saving objects with igraph in graphml, the library knows what is important and what is not and will use minimal memory. Pickle, however, can serialize many Python objects to strings and will save every object in a list or dictionary in case it is reused or has cyclic references. | I am a beginner in igraph.
I have a graph data of 60000 nodes and 900K edges. I could successfully create the graph using python-igraph and write to disk. My machine has 3G memory.
When I wrote the graph to disk in graphml format, the memory usage was around 19%; with write_pickle, the usage went up to 50% and took significantly more time.
What is the reason behind this behavior of igraph? When should and when should I not use the pickle format?
Please shed light into this. | 0 | 1 | 650 |
0 | 28,895,245 | 0 | 0 | 0 | 0 | 2 | true | 1 | 2015-03-05T19:13:00.000 | 1 | 2 | 0 | python-igraph pickling efficiency | 28,885,814 | 1.2 | python-2.7,igraph | Pickling is a generic format to store arbitrary objects, which may reference other objects, which may in turn also reference other objects. Therefore, when Python is pickling an object, it must keep track of all the objects that it has "seen" and serialized previously to avoid getting stuck in an infinite loop. That's probably the reason why pickling is slower (and uses more memory).
The advantage of using pickling is that the pickled representation will preserve the exact Python type of every single graph, vertex or edge attribute (provided that you use types that support pickling). GraphML won't keep the exact types because there is no unambiguous mapping from Python types to GraphML types; for instance, all numeric attributes would be converted to doubles in the GraphML representation, irrespectively of whether the original attributes were Python ints, longs, or floating-point numbers. | I am a beginner in igraph.
I have a graph data of 60000 nodes and 900K edges. I could successfully create the graph using python-igraph and write to disk. My machine has 3G memory.
When I wrote the graph to disk in graphml format, the memory usage was around 19%; with write_pickle, the usage went up to 50% and took significantly more time.
What is the reason behind this behavior of igraph? When should and when should I not use the pickle format?
Please shed light into this. | 0 | 1 | 650 |
0 | 28,910,572 | 0 | 0 | 0 | 0 | 1 | true | 0 | 2015-03-06T22:04:00.000 | 1 | 1 | 0 | Identify Data Vectors with New Attributes and/or Values | 28,908,468 | 1.2 | python,scikit-learn | Not with anything built into scikit-learn, as removing rows is something that is not easily done in the current API.
It should be quite easy to write a custom function / class that does that based on the output of DictVectorizer. | I am setting up a classification system using scikit-learn. After training a classifier I would like to save it for reuse along with the necessary transforms such as the DictVectorizer.
I am looking for a way to filter the incoming stream of unclassified data that will feed into the feature transforms and classifier. Ideally, I would like to remove and flag vectors that contain new values for categorical attributes and/or altogether new attributes.
I have used the DictVectorizer.restrict() method to filter input data but this only results in the vectorizer filtering new attributes and zeroing new values, where I would also like to put aside inconsistent data. Is there an easy way to pull out rows with values and attribute that were not in the initial data set? | 0 | 1 | 34 |
0 | 28,933,536 | 0 | 0 | 0 | 0 | 1 | false | 1 | 2015-03-09T00:01:00.000 | 0 | 1 | 0 | How can I find the optimal buy and sell points for a stock if I have a transaction cost? | 28,933,388 | 0 | python,algorithm | It seems that optimal selling indices are those i such that
price[i-1] < price[i] and price[i+1] <= price[i] and for some j > i, price[i] - price[j] > 2. I don't know about names for an algorithm like that, but list comprehensions and the function any should be enough. | If I have a list of prices, say [4,2,5,6,9,3,1,2,5] and I have a transaction cost of $2 and I am able to buy and short sell then the optimal strategy is buy at 2 switch positions at 9 and and switch again at 1. So the optimal buy indices are [1,6] and the optimal sell indices are [4]. How can this be solved programmatically? Specifically I'm looking to be pointed in the right direction (i.e. This is a perfect case for A* ... or whatever) rather than a solution. | 0 | 1 | 717 |
0 | 28,940,905 | 0 | 0 | 0 | 0 | 1 | true | 1 | 2015-03-09T11:18:00.000 | 5 | 1 | 0 | Not losing the quality of pictures saved with cv2.imwrite() | 28,940,711 | 1.2 | python,opencv,colors,python-2.x | JPEG is a lossy format, you need to save your images as PNG as it is a lossless format. | I am wondering seriously about the effects of cv2.imwrite() function of OpenCV.
I noticed that when I read pictures with cv2.imread() and save them again with cv2.imwrite() function, their quality is not the same any more for the human eyes.
I ask you how can I keep the quality of the image the same as the original after saving it using cv2.imwrite() function.
I ask this question because I have really a serious issue in a larger program and when I checked the quality of the pictures saved by this function, I guesses that my problem comes certainly from this function.
For example, I draw using the mouse movements small red (Red=255) squares on picture . When I save the picture and count the number of pixels that have Red color equal to 255 I get very few of them only even if I draw a lot of them in pure red color. But when I check the image by my eyes, I notice the red pixels I drawed are not correctly saved in the correct red color I chosed (255).
Any one does know how to resolve this problem ? I mean to save the pictures using OpenCV without degrading its quality. | 0 | 1 | 2,752 |
0 | 49,022,627 | 0 | 0 | 0 | 0 | 1 | false | 4 | 2015-03-11T11:30:00.000 | 6 | 3 | 0 | Color a pixel in python opencv | 28,985,490 | 1 | python,opencv,image-processing | img[x,y]=[255, 255, 255] is wrong because opencv img[a,b] is a matrics then you need to change x,y then you must use img[y,x]
actualy mistake in the order of x,y
if you want to change color of point x,y use this >> img[y,x] = color | I need to color a pixel in an image. I use opencv and python.
I tried img[x,y]=[255 255 255] to color a pixel(x,y) but it wont work :(
Is there is any mistake in this?
Can you suggest any method?
Thanks in advance. | 0 | 1 | 24,622 |
0 | 28,997,147 | 0 | 0 | 0 | 0 | 1 | false | 4 | 2015-03-11T18:44:00.000 | 0 | 3 | 0 | Document Clustering in python using SciKit | 28,994,857 | 0 | python,machine-learning,scikit-learn,cluster-analysis,unsupervised-learning | For the large matrix after TF/IDF transformation, consider using sparse matrix.
You could try different k values. I am not an expert in unsupervised clustering algorithms, but I bet with such algorithms and different parameters, you could also end up with a varied number of clusters. | I recently started working on Document clustering using SciKit module in python. However I am having a hard time understanding the basics of document clustering.
What I know ?
Document clustering is typically done using TF/IDF. Which essentially
converts the words in the documents to vector space model which is
then input to the algorithm.
There are many algorithms like k-means, neural networks, hierarchical
clustering to accomplish this.
My Data :
I am experimenting with linkedin data, each document would be the
linkedin profile summary, I would like to see if similar job
documents get clustered together.
Current Challenges:
My data has huge summary descriptions, which end up becoming 10000's
of words when I apply TF/IDF. Is there any proper way to handle this
high dimensional data.
K - means and other algorithms requires I specify the no. of clusters
( centroids ), in my case I do not know the number of clusters
upfront. This I believe is a completely unsupervised learning. Are
there algorithms which can determine the no. of clusters themselves?
I've never worked with document clustering before, if you are aware
of tutorials , textbooks or articles which address this issue, please
feel free to suggest.
I went through the code on SciKit webpage, it consists of too many technical words which I donot understand, if you guys have any code with good explanation or comments please share. Thanks in advance. | 0 | 1 | 6,083 |
0 | 29,026,455 | 0 | 1 | 0 | 0 | 1 | true | 1 | 2015-03-12T19:40:00.000 | 1 | 1 | 0 | How to convert a sparse dict to scipy.sparse matrix in python? | 29,018,843 | 1.2 | python,numpy,matrix,scipy | With standard dict methods you can get a list of the keys, and another list of the values. Pass the 2nd to numpy.array and you should get a 100 x 7000 array. The keys list could also be made into array, but it might not be any more useful than the list. The values array could be turned into a sparse matrix. But its size isn't exceptional, and arrays have more methods.
Tomorrow I can add sample code if needed. | I have a very large dictionary of the following format {str: [0, 0, 1, 2.5, 0, 0, 0, ...], str: [0, 0, 0, 1.1, 0, 0, ...], ...}. The number of elements for each str key can be very big so I need an effective way to store and make calculations over this data.
For example right now my dict of str keys has 100 keys. Each key has one value which is a list of 7000 float elements. The length of str keys and values is constant. So, let's say str key is of length 5 and its value (which is a list) is 7000.
After some reading I found that scipy.sparse module has a nice collection of various matrices to store sparse data but scipy documentation is so sparse that I can barely understand what's going on.
Can you provide an example of how to convert the dictionary above to correct matrix type? | 0 | 1 | 1,646 |
0 | 29,050,296 | 0 | 0 | 0 | 0 | 1 | false | 1 | 2015-03-14T14:23:00.000 | 1 | 3 | 0 | Pandas Time-Series: Find previous value for each ID based on year and semester | 29,049,985 | 0.066568 | python,pandas,time-series | Use this function to create the new column...
DataFrame.shift(periods=1, freq=None, axis=0, **kwds)
Shift index by desired number of periods with an optional time freq | I realize this is a fairly basic question, but I couldn't find what I'm looking for through searching (partly because I'm not sure how to summarize what I want). In any case:
I have a dataframe that has the following columns:
* ID (each one represents a specific college course)
* Year
* Term (0 = fall semester, 1 = spring semester)
* Rating (from 0 to 5)
My goal is to create another column for Previous Rating. This column would be equal to the course's rating the last time the course was held, and would be NaN for the first offering of the course. The goal is to use the course's rating from the last time the course was offered in order to predict the current semester's enrollment. I am struggling to figure out how to find the last offering of each course for a given row.
I'd appreciate any help in performing this operation! I am working in Pandas but could move my data to R if that'd make it easier. Please let me know if I need to clarify my question. | 0 | 1 | 1,352 |
0 | 29,058,672 | 0 | 0 | 0 | 0 | 1 | true | 1 | 2015-03-15T01:35:00.000 | 0 | 1 | 0 | change the type of numpyndarray float element to string | 29,056,302 | 1.2 | python,numpy,casting | You can't change the type of parts of an ordinary ndarray. An ndarray requires all elements in the array to have the same numpy type (the dtype), so that mathematical operations can be done efficiently. The only way to do this is to change the dtype to object, which allows you to store arbitrary types in each element. However, this will drastically reduce the speed of most operations, and make some operations impossible or unreliable (such as adding two arrays). | I have an arff file as input. I read the arff file and put the element values in a numpy ndarray.Now my arff file contains some '?' as some of the elements. Basically these are property values of matrices calculated by anamod. Whichever values anamod cannot calculate it plugs in a '?' character for those. I want to do a Naive baiyes, Random Forest etc prediction for my data. So to handle the '?' I want to use an imputer which is like :
Imputer(missing_values='NaN', strategy='mean', axis=0)
The missing_values above is of type string of course. My question is that how to change the type of a few numpy ndarray elements to string from float. I used my_numpy_ndarray.astype('str') == 'NaN' to check for NaN values and I could do it successfully but I am not sure how to change the type of numpyndarray float element to string. | 0 | 1 | 117 |
0 | 29,061,597 | 0 | 0 | 0 | 0 | 1 | false | 9 | 2015-03-15T13:11:00.000 | 8 | 1 | 0 | a value too large for dtype('float64') | 29,060,962 | 1 | python,numpy,scikit-learn | Ok I got it. After i used Imputer(missing_values='NaN', strategy='median', axis=1) imp.fit(X2). I also had to write :
X2 = imp.fit_transform(X2). The reason being sklearn.preprocessing.Imputer.fit_transform returns a new array, it doesn't alter the argument array | I'm using numpy for reading an arff file and I'm getting the following error:
ValueError: Input contains NaN, infinity or a value too large for dtype('float64').
I used np.isnan(X2.any()) and np.isfinite(X2.all())to check if it's a nan or infinite case. But it's none of these. This means it's the third case, which is infinity or a value too large for dtype('float64').
I would appreciate if someone could tell me how to take care of this error.
Thanks. | 0 | 1 | 26,758 |
0 | 42,962,569 | 0 | 0 | 0 | 0 | 1 | false | 5 | 2015-03-16T01:12:00.000 | 0 | 5 | 0 | Is there a way to profile an OpenCL or a pyOpenCL program? | 29,068,229 | 0 | python,opencl,pyopencl | CodeXL from AMD works very well. | I am trying to optimize a pyOpenCL program. For this reason I was wondering if there is a way to profile the program and see where most of the time is needed for.
Do you have any idea how to approach this problem?
Thanks in advance
Andi
EDIT: For example nvidias nvprof for CUDA would do the trick for pyCuda, however, not for pyOpenCL. | 0 | 1 | 2,168 |
0 | 29,085,388 | 0 | 0 | 0 | 0 | 1 | true | 2 | 2015-03-16T19:24:00.000 | 0 | 3 | 0 | Shared file access between Python and Matlab | 29,085,298 | 1.2 | python,windows,matlab,file,shared | I am not sure about window's API for locking files
Heres a possible solution:
While matlab has the file open, you create an empty file called "data.lock" or something to that effect.
When python tries to read the file, it will check for the lock file, and if it is there, then it will sleep for a given interval.
When matlab is done with the file, it can delete the "data.lock" file.
Its a programmatic solution, but it is simpler than digging through the windows api and finding the right calls in matlab and python. | I have a Matlab application that writes in to a .csv file and a Python script that reads from it. These operations happen concurrently and at their own respective periods (not necessarily the same). All of this runs on Windows 7.
I wish to know :
Would the OS inherently provide some sort of locking mechanism so that only one of the two applications - Matlab or Python - have access to the shared file?
In the Python application, how do I check if the file is already "open"ed by Matlab application? What's the loop structure for this so that the Python application is blocked until it gets access to read the file? | 0 | 1 | 212 |
0 | 29,088,394 | 0 | 0 | 0 | 0 | 1 | false | 2 | 2015-03-16T22:27:00.000 | 0 | 1 | 0 | Logo recognition in OpenCV | 29,088,095 | 0 | python,opencv | You could probably use Haar cascades in openCv to do this. You will need to train haar detectors with both positive and negative samples of the logo but there is already utilities in openCv to help you with this. Just read up about haar in openCv documentation | I am currently making an application with OpenCV and a web server that finds certain car brands as part of an ongoing game in my family.
However, I don't know where to start. I googled it but all I found was a post on finding a yellow ball. I want to find a car logo from a picture (which could be angled or glaring) so I identify the car brand and add points to the score.
I know it seems like a tall order but could anybody help? | 0 | 1 | 1,164 |
0 | 60,111,168 | 0 | 0 | 0 | 0 | 3 | false | 3 | 2015-03-17T09:42:00.000 | 0 | 4 | 0 | Sklearn-GMM on large datasets | 29,095,769 | 0 | python,scikit-learn,bigdata,mixture-model | As Andreas Mueller mentioned, GMM doesn't have partial_fit yet which will allow you to train the model in an iterative fashion. But you can make use of warm_start by setting it's value to True when you create the GMM object. This allows you to iterate over batches of data and continue training the model from where you left it in the last iteration.
Hope this helps! | I have a large data-set (I can't fit entire data on memory). I want to fit a GMM on this data set.
Can I use GMM.fit() (sklearn.mixture.GMM) repeatedly on mini batch of data ?? | 0 | 1 | 3,292 |
0 | 36,488,496 | 0 | 0 | 0 | 0 | 3 | false | 3 | 2015-03-17T09:42:00.000 | 0 | 4 | 0 | Sklearn-GMM on large datasets | 29,095,769 | 0 | python,scikit-learn,bigdata,mixture-model | I think you can set the init_para to empty string '' when you create the GMM object, then you might be able to train the whole data set. | I have a large data-set (I can't fit entire data on memory). I want to fit a GMM on this data set.
Can I use GMM.fit() (sklearn.mixture.GMM) repeatedly on mini batch of data ?? | 0 | 1 | 3,292 |
0 | 29,109,730 | 0 | 0 | 0 | 0 | 3 | false | 3 | 2015-03-17T09:42:00.000 | 2 | 4 | 0 | Sklearn-GMM on large datasets | 29,095,769 | 0.099668 | python,scikit-learn,bigdata,mixture-model | fit will always forget previous data in scikit-learn. For incremental fitting, there is the partial_fit function. Unfortunately, GMM doesn't have a partial_fit (yet), so you can't do that. | I have a large data-set (I can't fit entire data on memory). I want to fit a GMM on this data set.
Can I use GMM.fit() (sklearn.mixture.GMM) repeatedly on mini batch of data ?? | 0 | 1 | 3,292 |
0 | 29,120,093 | 0 | 0 | 0 | 0 | 1 | false | 1 | 2015-03-18T10:43:00.000 | 0 | 3 | 0 | How to calculate inverse using cramer's rule in python? | 29,119,880 | 0 | python,numpy,matrix-inverse | linalg is right and you are wrong.
The matrix it gave you is indeed the inverse. However, if you are using np.array instead of np.matrix then the multiplication operator doesn't work as expected, since it calculates the component-wise product.
In that case you have to do mat.dot(inv(mat)).
In any case, what you will get will not be a perfect identity matrix due to rounding errors (when I tried it the off-diagonal matrix entries were in the order of 10 ** (-16)). | I'm trying to generate the inverse matrix using numpy package in python. Unfortunately , I'm not getting the answers I expected.
Original matrix:
([17 17 5]
[21 18 21]
[2 2 19])
Inverting the original matrix by Cramer's rule gives:
([4 9 15]
[15 17 6]
[24 0 17])
Apparently using numpy.linalg.inv() gives
-3.19488818e-01,3.80191693e-01,-6.38977636e-03,
3.33333333e-01, -3.33333333e-01, 2.26123699e-18,
-2.84345048e-01, 2.68370607e-01, 5.43130990e-02n
I expected that multiplying the original matrix and the inverse would have given an identity matrix but as you can see I give a matrix filled with floating points.
Where can be the issue? | 0 | 1 | 2,359 |
0 | 29,149,537 | 0 | 0 | 0 | 0 | 1 | true | 1 | 2015-03-19T15:32:00.000 | 1 | 1 | 0 | Generating high dimensional datasets with Scikit-Learn | 29,148,746 | 1.2 | python,scikit-learn,cluster-analysis,mean-shift | The standard deviation of the clusters isn't 1.
You have 8 dimensions, each of which has a stddev of 1, so you have a total standard deviation of sqrt(8) or something like that.
Kernel density estimation does not work well in high-dimensional data because of bandwidth problems. | I am working with the Mean Shift clustering algorithm, which is based on the kernel density estimate of a dataset. I would like to generate a large, high dimensional dataset and I thought the Scikit-Learn function make_blobs would be suitable. But when I try to generate a 1 million point, 8 dimensional dataset, I end up with almost every point being treated as a separate cluster.
I am generating the blobs with standard deviation 1, and then setting the bandwidth for the Mean Shift to the same value (I think this makes sense, right?). For two dimensional datasets this produced fine results, but for higher dimensions I think I'm running into the curse of dimensionality in that the distance between points becomes too big for meaningful clustering.
Does anyone have any tips/tricks on how to get a good high-dimensional dataset that is suitable for (something like) Mean Shift clustering? (or am I doing something wrong? (which is of course a good possibility)) | 0 | 1 | 681 |
0 | 29,256,366 | 0 | 0 | 0 | 0 | 1 | true | 2 | 2015-03-19T23:50:00.000 | 1 | 1 | 1 | MPI_Sendrecv with operation on recvbuf? | 29,157,039 | 1.2 | python,c,mpi,mpi4py | MPI_Recvreduce is what you're looking for. Unfortunately, it doesn't exist yet. It's something that the MPI Forum has been looking at adding to a future version of the standard, but hasn't yet been adopted and won't be in the upcoming MPI 3.1. | I use the MPI_Sendrecv MPI function to communicate arrays of data between processes. I do this in Python using mpi4py, but I'm pretty sure my question is independent of the language used.
What I really want is to add an array residing on another process to an existing local array. This should be done for all processes, so I use the MPI_Sendrecv function to send and receive the arrays in one go. I can then add the received array in the recvbuf to the local array and I'm done.
It would be nice however if I could save the step of having a separate recvbuf array, and simply receiving the data directly into the local array without overwriting the existing data, but rather updating it using some operation (addition in my case).
I guess what I'm looking for is a combined MPI_Sendrecv/MPI_Reduce function. Do some function like this exist in MPI? | 0 | 1 | 127 |
0 | 29,191,059 | 0 | 0 | 0 | 0 | 1 | false | 1 | 2015-03-21T13:18:00.000 | 1 | 1 | 0 | Classifying users by demographic using incomplete data | 29,183,178 | 0.197375 | python,statistics,scipy,scikit-learn,scikits | I think you can make use of a "naive Bayes" classifier here. In that case, the class (M or F) probability is a product of terms, one term for each available feature set, and you just ignore (exclude from the product) any feature set that is missing.
Here is the justification. Let's say the feature sets are X1, X2, X3. Each of these is a vector of features. The naive Bayes assumption is that feature sets are independent given the class, i.e., P(X1, X2, X3 | C) = P(X1 | C) P(X2 | C) P(X3 | C). (Remember that this is just a simplifying assumption -- it might or might not be true!) When all feature sets are present, the posterior class probability is just P(C | X1, X2, X3) = P(X1, X2, X3 | C) P(C) / Z = P(X1 | C) P(X2 | C) P(X3 | C) P(C) / Z, where Z is the normalizing constant that makes the probabilities of the 2 classes add up to 1. So to make use of this formulation, you need a density model for each of the feature sets; if this approach makes sense to you, we can talk about those density models.
Now what if a feature set (let's say X3) is missing? That means we need to calculate P(C | X1, X2) = P(X1, X2 | C) P(C) / Z. But note that P(X1, X2 | C) = integral P(X1, X2, X3 | C) dX3 = integral P(X1 | C) P(X2 | C) P(X3 | C) dX3 = P(X1 | C) P(X2 | C) integral P(X3 | C) dX3 by the naive Bayes assumption. Note that integral P(X3 | C) dX3 = 1, so P(X1, X2 | C) = P(X1 | C) P(X2 | C), i.e., the naive Bayes assumption still holds for just the observed feature sets, so you can go ahead and calculate P(C | X1, X2) = P(X1 | C) P(X2 | C) P(C) / Z, i.e., when some feature set is missing in a naive Bayes model, just ignore it. | I have some data containing usernames and their respective genders.
For example, an entry in my data list may look like:
{User: 'abc123', Gender: 'M'}
For each username, I am also given a bag of text, images, and locations attached to each of them, although it's not necessary that a user has at least one text, one image and one location attached to them.
For each data source, I can translate them into a vector of features, which I then feed into a classifier. I can then confirm if the classifier is effective via 10-fold cross-validation.
I want to combine some output from all the classifiers such that I can feed them into a meta-classifier to hopefully improve accuracy.
The problem is that since the data is incomplete, I can't simply combine all the vectors generated from each data source and feed them into one classifier. Some users may not have image data, or others may not have location data.
My current idea is to use each classifier to obtain some category probability set for each user, something like [Male: 0.75, Female: 0.25] from each data source's classifier, multiply all the categories' values, and use the highest value as the program's predicted category.
So if I have 1 classifier for each data source (text, image, location), then I have a total of 3 classifiers. Even if one or two of the data sources are missing for some users, I can still obtain a category probability set for those users.
Does scikit-learn have any algorithm that can output a probability weight that the user is of some gender instead of just classifying them?
Or is there some other algorithm that satisfies my needs?
Thanks for going through my wall of text! | 0 | 1 | 74 |
0 | 61,935,681 | 0 | 0 | 0 | 0 | 1 | false | 4 | 2015-03-23T08:07:00.000 | 0 | 2 | 0 | How to save a bokeh gridplot as single file | 29,205,574 | 0 | python,bokeh | First you save your grid in an object,
Let's say "a" the you confirms that "a" is a grid. Example
grid = bly.gridplot(graficas,ncols=3) # Here you save your grid
bpl.show(grid). # Here you show your grid
from bokeh.io import export_png # You need this library to export
Exportar grid
export_png(grid, filename="your path/name.png") | I am using bokeh (0.8.1) in combination with the ipython notebook to generate GridPlots. I would like to automatically store the generated GridPlots to a single png (hopefully pdf one day) on disk, but when using "Preview/Save" it cycles through all of the figures asking me to store them separately. Is there a more efficient way? | 0 | 1 | 1,852 |
0 | 29,212,482 | 0 | 0 | 0 | 0 | 1 | false | 1 | 2015-03-23T14:08:00.000 | 1 | 2 | 0 | Polyval(p,x) to evaluate polynomials | 29,212,385 | 0.099668 | python,numpy | Your p array is in the wrong order. You should start with the coefficient of the highest exponent.
Try with p=[1,0,2,1]. | I don't know much about Python and I'm trying to use it to do some simple polynomial interpolation, but there's something I'm not understanding about one of the built-in functions.
I'm trying to use polyval(p,x) to evaluate a polynomial p at x.
I made an example polynomial p(x) = 1 + 2x + x^3, I created an array p = [1,2,0,1] to define it and I want to know the values at x = 0,1,2 so I created another array x = [0,1,2].
Doing polyval(p,x) gave me an output of [1, 4, 17]. p(0) and p(1) are correct, but p(2) should be 13, not 17. Why is it giving me 17? | 0 | 1 | 5,765 |
0 | 29,240,968 | 0 | 0 | 0 | 0 | 2 | false | 0 | 2015-03-24T19:05:00.000 | 0 | 2 | 0 | Using OpenCV in Parse Cloud Code | 29,240,840 | 0 | android,python,opencv,parse-platform | No. JavaScript is the only language currently supported for writing CloudCode. | This will be my new post if I go wrong please don't judge me hard :)
I'm developing an OpenCV project with Python and also I'm developing its mobile interface in Android. My purpose is to compare plant pictures and decide their species.Researchers who use Android application will take plant photos and upload them (such as 'tree leaf photo'). I intent to execute comparison algorithms in the cloud. I use Parse as mobile database so I thought that I could use Cloud Code in Parse to run my Python codes. Can I do this ? | 0 | 1 | 89 |
0 | 29,246,105 | 0 | 0 | 0 | 0 | 2 | true | 0 | 2015-03-24T19:05:00.000 | 0 | 2 | 0 | Using OpenCV in Parse Cloud Code | 29,240,840 | 1.2 | android,python,opencv,parse-platform | You can have Parse Cloud Code call out to your Python code using HTTP if you want. Just as you can do the same from the Android app. This code can tell the web hook what images to download and process based on some condition (such as a researcher has uploaded a photo to be processed). Purely up to you how you trigger this. Your Cloud Code is JavaScript only though, same as your Android app is Java only (usually, unless you use Xamarin with C# or something else of course). | This will be my new post if I go wrong please don't judge me hard :)
I'm developing an OpenCV project with Python and also I'm developing its mobile interface in Android. My purpose is to compare plant pictures and decide their species.Researchers who use Android application will take plant photos and upload them (such as 'tree leaf photo'). I intent to execute comparison algorithms in the cloud. I use Parse as mobile database so I thought that I could use Cloud Code in Parse to run my Python codes. Can I do this ? | 0 | 1 | 89 |
0 | 29,287,544 | 0 | 0 | 0 | 0 | 1 | false | 347 | 2015-03-26T19:27:00.000 | 14 | 4 | 0 | Pandas read in table without headers | 29,287,224 | 1 | python,pandas | Make sure you specify pass header=None and add usecols=[3,6] for the 4th and 7th columns. | How can I read in a .csv file (with no headers) and when I only want a subset of the columns (say 4th and 7th out of a total of 20 columns), using pandas? I cannot seem to be able to do usecols | 0 | 1 | 539,397 |
0 | 60,968,639 | 0 | 0 | 0 | 0 | 1 | false | 1 | 2015-03-27T12:19:00.000 | -1 | 1 | 0 | matplotlib UserWarning When log axis is used in some cases | 29,300,510 | -0.197375 | python,matplotlib | not sure if this issue is still open, but I had a similar problem and updating seaborn fixed the issue for me. For you it might be matplotlib, depending which package you used for creating the graph. | Basically I am running some optimisation algorithms that I have created using Numpy and I want to plot the log of the error against the number of iterations. Having done this with linear regression and having had no issues, it is very strange that I seem to get issues when doing the exact same thing with logistic regression. I get the following "warning":
/usr/lib64/python2.6/site-packages/matplotlib/axis.py:1004:
UserWarning: Unable to find pixel distance along axis for interval
padding; assuming no interval padding needed. warnings.warn("Unable
to find pixel distance along axis for interval padding; assuming no
interval padding needed.")
However, when I don't use a log axis for the y axis, I don't get the error either. All the elements of the array that I am using are also positive, so it shouldn't have anything to do with taking the log of a non-positive number.
Has anyone ever encountered this before? Does anyone know what it may be referring to?
Thanks | 0 | 1 | 1,303 |
0 | 56,953,319 | 0 | 0 | 0 | 0 | 1 | false | 18 | 2015-03-27T23:56:00.000 | 1 | 3 | 0 | Is there a Python equivalent to the smooth.spline function in R | 29,312,005 | 0.066568 | python,r,smoothing,splines | From research on google, I concluded that
By contrast, the smooth.spline in R allows having knots at all the x values, without necessarily having a wiggly curve that hits all the points -- the penalty comes from the second derivative. | The smooth.spline function in R allows a tradeoff between roughness (as defined by the integrated square of the second derivative) and fitting the points (as defined by summing the squares of the residuals). This tradeoff is accomplished by the spar or df parameter. At one extreme you get the least squares line, and the other you get a very wiggly curve which intersects all of the data points (or the mean if you have duplicated x values with different y values)
I have looked at scipy.interpolate.UnivariateSpline and other spline variants in Python, however, they seem to only tradeoff by increasing the number of knots, and setting a threshold (called s) for the allowed SS residuals. By contrast, the smooth.spline in R allows having knots at all the x values, without necessarily having a wiggly curve that hits all the points -- the penalty comes from the second derivative.
Does Python have a spline fitting mechanism that behaves in this way? Allowing all knots but penalizing the second derivative? | 0 | 1 | 4,069 |
0 | 45,366,940 | 0 | 1 | 0 | 0 | 3 | false | 5 | 2015-03-28T02:26:00.000 | 1 | 6 | 0 | Cannot install ggplot with anaconda | 29,312,985 | 0.033321 | python,windows,anaconda,python-ggplot | I ran across the same issue when installing ggplot. None of the methods worked, eventually I reinstalled anaconda. Then everything works smoothly. | I want to be able to use geom_smooth in ggplot. However, when I typed conda install ggplot, I get the error no packages found in current win-32 channels matching ggplot. Anyone know what is going on? | 0 | 1 | 19,615 |
0 | 41,456,234 | 0 | 1 | 0 | 0 | 3 | false | 5 | 2015-03-28T02:26:00.000 | 0 | 6 | 0 | Cannot install ggplot with anaconda | 29,312,985 | 0 | python,windows,anaconda,python-ggplot | As of Jan 2016, ggplot now comes installed by default if you are using the Anaconda distribution so you can just use install ggplot. New to Python so this is still tripping me up. | I want to be able to use geom_smooth in ggplot. However, when I typed conda install ggplot, I get the error no packages found in current win-32 channels matching ggplot. Anyone know what is going on? | 0 | 1 | 19,615 |
0 | 29,313,575 | 0 | 1 | 0 | 0 | 3 | false | 5 | 2015-03-28T02:26:00.000 | 4 | 6 | 0 | Cannot install ggplot with anaconda | 29,312,985 | 0.132549 | python,windows,anaconda,python-ggplot | I think ggplot is simply not packaged for Anaconda as conda search ggplot doesn't find anything. How it can be easily installed via pip -- pip install ggplot. | I want to be able to use geom_smooth in ggplot. However, when I typed conda install ggplot, I get the error no packages found in current win-32 channels matching ggplot. Anyone know what is going on? | 0 | 1 | 19,615 |
0 | 54,869,627 | 0 | 1 | 0 | 0 | 1 | false | 29 | 2015-03-29T18:08:00.000 | 22 | 3 | 0 | What does NN VBD IN DT NNS RB means in NLTK? | 29,332,851 | 1 | python,nlp,nltk,text-parsing,pos-tagger | Even though the above links have all kinds. But hope this is still helpful for someone, added a few that are missed on other links.
CC: Coordinating conjunction
CD: Cardinal number
DT: Determiner
EX: Existential there
FW: Foreign word
IN: Preposition or subordinating conjunction
JJ: Adjective
VP: Verb Phrase
JJR: Adjective, comparative
JJS: Adjective, superlative
LS: List item marker
MD: Modal
NN: Noun, singular or mass
NNS: Noun, plural
PP: Preposition Phrase
NNP: Proper noun, singular Phrase
NNPS: Proper noun, plural
PDT: Pre determiner
POS: Possessive ending
PRP: Personal pronoun Phrase
PRP: Possessive pronoun Phrase
RB: Adverb
RBR: Adverb, comparative
RBS: Adverb, superlative
RP: Particle
S: Simple declarative clause
SBAR: Clause introduced by a (possibly empty) subordinating conjunction
SBARQ: Direct question introduced by a wh-word or a wh-phrase.
SINV: Inverted declarative sentence, i.e. one in which the subject follows the tensed verb or modal.
SQ: Inverted yes/no question, or main clause of a wh-question, following the wh-phrase in SBARQ.
SYM: Symbol
VBD: Verb, past tense
VBG: Verb, gerund or present participle
VBN: Verb, past participle
VBP: Verb, non-3rd person singular present
VBZ: Verb, 3rd person singular present
WDT: Wh-determiner
WP: Wh-pronoun
WP: Possessive wh-pronoun
WRB: Wh-adverb | when I chunk text, I get lots of codes in the output like
NN, VBD, IN, DT, NNS, RB.
Is there a list documented somewhere which tells me the meaning of these?
I have tried googling nltk chunk code nltk chunk grammar nltk chunk tokens.
But I am not able to find any documentation which explains what these codes mean. | 0 | 1 | 25,538 |
0 | 46,616,236 | 0 | 1 | 0 | 0 | 1 | false | 67 | 2015-03-30T21:05:00.000 | 50 | 5 | 0 | Plot inline or a separate window using Matplotlib in Spyder IDE | 29,356,269 | 1 | python,matplotlib,spyder | Go to
Tools >> Preferences >> IPython console >> Graphics >> Backend:Inline, change "Inline" to "Automatic", click "OK"
Reset the kernel at the console, and the plot will appear in a separate window | When I use Matplotlib to plot some graphs, it is usually fine for the default inline drawing. However, when I draw some 3D graphs, I'd like to have them in a separate window so that interactions like rotation can be enabled. Can I configure in Python code which figure to display inline and which one to display in a new window?
I know that in Spyder, click Tools, Preferences, Ipython Console, Graphics and under Graphics Backend select “automatic” instead of “inline”. However, this make all the figures to be in new windows. It can be messy when I have a lot of plots. So I want only those 3D plot to be in new windows, but all the other 2D plots remain inline. Is it possible at all?
Thanks! | 0 | 1 | 218,892 |
0 | 29,516,550 | 0 | 0 | 0 | 0 | 1 | false | 0 | 2015-03-31T00:14:00.000 | 0 | 1 | 0 | Get the count of each key in each Mapper or globally in Spark MapReduce model | 29,358,494 | 0 | java,python,hadoop,mapreduce,apache-spark | You can use pairRDD.countByKey() function for counting the rows according their keys. | We need to get the count of each key (the keys are not known before executing), and do some computation dynamically in each Mapper. The key count could be global or only in each Mapper. What is the best way to implement that? In Hadoop this is similar to an aggregator function.
The accumulator in Spark needs to be defined before the Mapper jobs run. But we do not know what and how many keys are there. | 0 | 1 | 110 |
0 | 29,385,747 | 0 | 0 | 0 | 0 | 2 | false | 0 | 2015-04-01T06:46:00.000 | 0 | 3 | 0 | The intersection between a trajectory and the circles in the same area | 29,384,494 | 0 | python,geometry,intersection | In general I would recommend to first make your algorithm work and then make it faster if you need to. You would be amazed by how fast Python in combination with a set of carefully selected libraries can be.
So for your problem, I would do the following:
1.) Install a set of libraries that makes your life easier:
- Matplotlib for 2D plotting of the rectangle, the circle and
the trajectory
2.) Numpy for general purpose array manipulation
3.) Optionally Scipy for its KDTree support (nearest neighbor search)
4.) Start implementing your problem
a.) Create a rectangle and visualize it using Matplotlib
b.) Create a set of circles and plot them within the rectangular area of 4a
c.) Create a trajectory and plot them within the rectangular area
Now the more difficult part starts. The way forward depends a little on how your trajectory is defined. For example, if your trajectory consists of line segments, you could calculate the intersection point between a circle and a line segment analytically. Three possible solutions exist, no intersection, 1 intersection (line touches circle) and 2 intersections. If your trajectory is more complex, you could discretize it by generating many points along it and than calculate if this point is on the edge of one of the circles. You have to be a little clever though about how the 3 possible solutions can be identified, because the points along the trajectory are finite.
Another option would be to also discretize the points on the edges of the circles. This would mean that the problem reduces for a large part to nearest neighbor search for which you can use the Scipy KDTree class. | I am new in coding. Now I have a question. I have an object who keep moving in an rectangle area. And I also have a lot of circle in this area too. I want to get all the intersection point between the trajectory and the all the circle. As the object is moving step by step, so was thinking that I can calculate the distance between the position of object and all the centre of each circle and compare the distance with radius of the circle. But I think that this will do a lot of computation as you need to calculate the distance at each step. Do you have any good idea or reference. By the way, I am woking on python. Thank you. As I do not have enough reputation , I can not add a picture about the problem | 0 | 1 | 1,435 |
0 | 29,388,615 | 0 | 0 | 0 | 0 | 2 | true | 0 | 2015-04-01T06:46:00.000 | 1 | 3 | 0 | The intersection between a trajectory and the circles in the same area | 29,384,494 | 1.2 | python,geometry,intersection | Let a be a number somewhere between the radius and diameter of the larger circles (if they have different radii).
Generate a grid of square tiles of side length a, so that grid(i,k) is the square from (i*a,k*a) to ((i+1)*a, (k+1)*a).
Each tile of the grid contains a list with pointers to circles or indices into the circle array.
For each circle, register it with each tile that it intersects with. Should be less than 4.
Now to test the point (x,y) of the trajectory for circle intersections resp. containment inside the corresponding disk, you only need to test it against the list of circles in tile ((int)(x/a), (int)(y/a). | I am new in coding. Now I have a question. I have an object who keep moving in an rectangle area. And I also have a lot of circle in this area too. I want to get all the intersection point between the trajectory and the all the circle. As the object is moving step by step, so was thinking that I can calculate the distance between the position of object and all the centre of each circle and compare the distance with radius of the circle. But I think that this will do a lot of computation as you need to calculate the distance at each step. Do you have any good idea or reference. By the way, I am woking on python. Thank you. As I do not have enough reputation , I can not add a picture about the problem | 0 | 1 | 1,435 |
0 | 45,776,219 | 0 | 0 | 0 | 0 | 1 | false | 1 | 2015-04-02T20:42:00.000 | 0 | 1 | 0 | Machine Learning -Issues with big dataset | 29,422,093 | 0 | python,machine-learning,scikit-learn,pca,logistic-regression | you can segment your data on few models which output will be input to the next model which will give you result.
Basically its RNN architecture.
Put such massive data in one network just not possible due to memory limitation. | I am trying to apply Machine Learning to a Kaggle.com dataset. The dimension of my dataset is 244768 x 34756. Now at this size none of the scikit algorithms work.
I thought i would apply PCA , but even that doesnt scale up to this dataset.
Is there anyway i can reduce redundant data from my training dataset? I can reduce dimension by applying PCA , but if i could apply PCA.
Since i am doing document classification , i resampled my dataset to 244768*5672 , by reducing the word vector size. PCA cant be applied to even this dataset.
Can i apply PCA by doing this method. Suppose my matrix is A -
X = A.T * A
pca(X) (X becomes 5672 x 5672 matrix)
Will this give me wrong answers?
Also when i apply Logistic regression , can i train the model incrementally , .ie
If A = 10000 x 500
Can i take 1000 x 500 , to logistic.fit(A) and then do the same for other rows? Is this kind of training wrong? | 0 | 1 | 110 |
0 | 29,477,966 | 0 | 0 | 0 | 0 | 1 | false | 2 | 2015-04-03T11:04:00.000 | 0 | 1 | 0 | Storing a large table on disk, with fast retrieval of a specified subset to np.ndarray | 29,430,979 | 0 | python,sqlite,python-3.x,numpy,hdf5 | You could create a region reference dataset where each element relates to one of the ~2000 identifiers.
Then the Python code to reference a particular identifier would look like this:
reg_ref - reg_ref_dset[identifier]
mysub = data_dset[reg_ref] | I need to store a table on disk, and be able to retrieve a subset of that table into a numpy.ndarray very fast. What's the best way to do that? I don't mind spending the time to preprocess this dataset before storing it on disk, since it won't be changed once it's created.
I'd prefer not to write any C code, and instead rely on existing python libraries. I am considering HDF5 (with either pytables or h5py), sqlite, numpy's memmap, or a custom binary file format.
For a custom file, I would sort the rows by the identifier, and add to the file a table of contents which, for every identifier, would specify the beginning and ending file offsets that encompass the data related to this identifier. This would probably be very fast in terms of I/O, but at a cost of using python rather than C code (since I don't think there's a library that does precisely that).
Details:
~100 million rows, ~5 columns of float and str data. One of the columns contains 100,000 different identifiers (so there are about 1000 rows per identifier). The subset to be retrieved is always specified by a set of identifiers (usually I need to retrieve ~2000 identifiers, so ~2% of the entire dataset).
Python 3.4, Linux, SSD drive (so random access is as fast as sequential). | 0 | 1 | 179 |
0 | 29,460,131 | 0 | 0 | 0 | 0 | 1 | true | 0 | 2015-04-04T11:38:00.000 | 1 | 1 | 0 | graph of multiple y axes in plotly | 29,445,943 | 1.2 | python,graph,plotly | Full disclosure, I work for Plotly.
Here's my shot at summarizing your problem in general, you've got 4 dimensions for each country (year, exports, gdp, standard of living).
You might be able to use either or both of these solutions:
visualize this in two dimensions using x-value, y-value, marker-size, and marker-line-size (a bubble chart in 2d)
visualize this in three dimensions using x-value, y-value, z-value, and marker-size
I'll leave a link to a notebook in the comments, but since it's not a very permanent link, I won't include it in the answer here. | I have 3 sets of comparison data(y axes) which needs to be plotted against a target source values. I'm comparing exports, gdp, standard of living values of different countries against a target countries values for different years. But values of each category are haphazard i.e exports in millions of dollars, gdp in percentage and standard of living scale of 1 to 10. Moreover I have years value for comparison as well.
What I want to see is over the years how different parameters for each country over different years vary against the target country parameters. All of this plotted in one graph in plotly.
I can plot multiple y axes in plotly, but the scale doesn't match.
Has anyone any suggestions how to fit all the comparison in one layout. Maybe this is more of a graphing suggestion needed rather than help in plotly? Any ideas how to squeeze all in one graph? | 0 | 1 | 925 |
0 | 29,469,527 | 0 | 1 | 0 | 0 | 1 | false | 0 | 2015-04-06T10:28:00.000 | 0 | 1 | 0 | random.random or random.choice for Monte Carlo simulation? | 29,469,458 | 0 | python,montecarlo | Do you want a uniform distribution of these 3 values? If so, random.choice will give you exactly that. | I want to apply a simple Monte Carlo simulation on a variable that has three distinct values. Should I use random.random and assign the float to a variable value, or use random.choice(["a", "b", "c"])? | 0 | 1 | 143 |
0 | 35,924,390 | 0 | 0 | 0 | 0 | 1 | false | 0 | 2015-04-07T00:15:00.000 | 0 | 1 | 0 | How to use DecisionTreeRegressor() for Categorical Segmentation? | 29,481,698 | 0 | python,decision-tree | For this kind of decision tree you need to use DecisionTreeClassifier(). It appears that DecisionTreeRegressor only works with numerical predictor data. DecisionTreeClassifier() only works with class predictor data. I really wanted one that does both, but it doesn't appear possible. | I have used the python's DecisionTreeRegressor() to segment data based on a Predictor that is continuous, and it works well.
In the present project I have been asked to use Categorical data as Predictor.
Predictor - Industry Domain, Response - Revenue.
On using DecisionTreeRegressor() it threw error
"Cannot change string to float : Industry Domain".
Can you suggest if there is any way to resolve this problem? | 0 | 1 | 385 |
0 | 29,547,417 | 0 | 1 | 0 | 0 | 1 | true | 5 | 2015-04-09T13:20:00.000 | 0 | 3 | 0 | Is there a pre-existing implementation of the General Number Field Sieve (GNFS) in Python? | 29,539,678 | 1.2 | python | the pearl wrapper for GGNFS (c implementation) was rewritten into python by Brian Gladman.
Look for factmsieve.py | Is there any inbuilt or online Implementation of GNFS factoring in Python? I need a version that can easily be used to factor integers in other programs so I would need to import and preferably is comparable with or only needs minimal change to work with Python 3. I need this to factor (multiple) numbers of over 90 digits in length and elliptic curve factorization is too slow for the purpose.
I have checked online and could only find Perl and C++ implementations.
If not is there any online resource that could guide me step by step to my own implementation of this algorithm? | 0 | 1 | 2,960 |
0 | 29,991,069 | 0 | 0 | 0 | 0 | 1 | false | 2 | 2015-04-10T03:30:00.000 | 3 | 1 | 1 | Which will give the best performance Hive or Pig or Python Mapreduce with text file and oracle table as source? | 29,552,853 | 0.53705 | python,hadoop,mapreduce,hive,apache-pig | Python Map Reduce or anything using Hadoop Streaming interface will most likely be slower. That is due to the overhead of passing data through stdin and stdout and the implementation of the streaming API consumer (in your case python). Python UDF's in Hive and Pig do the same thing.
You might not want to compress data flow into ORC on the Python side. You'll be subjected to using Python's ORC libraries, which I am not sure if they are available. It would be easier if you let Python return your serialized object and the Hadoop reduce steps to compress and store as ORC (Python as a UDF for computation)
Yes. Pig and Python have some what of a nice programmatic interface where in you can write python scripts to dynamically generate Pig Logic and submit it in parallel. look up Embedding Pig Latin in Python. It's robust enough to define Python UDFS and let Pig do the overall abstraction and job optimization. Pig does a lazy evaluation so in cases of multiple joins or multiple transformations it can demonstrate pretty good performance in the optimizing the complete pipe line.
You say HDP 2.1. Have you had a look at Spark ? If performance is important to you and looking at the datasets size which dont look huge you ll expect many time faster overall pipeline execution than Hadoop s native MR engine | I have the below requirements and confused about which one to choose for high performance. I am not java developer. I am comfort with Hive, Pig and Python.
I am using HDP2.1 with tez engine. Data sources are text files(80 GB) and Oracle table(15GB). Both are structured data. I heard Hive will suite for structure data and Python map reduce streaming concept too will have high performance than hive & Pig. Please clarify.
I am using Hive and the reasons are:
need to join those two sources based on one column.
using ORC format table to store the join results since the data size is huge
text file name will be used to generate one output column and that has been performed with virtual column concept input__file__name field.
After join need to do some arithmetic operations on each row and doing that via python UDF
Now the complete execution time from data copy into HDFS to final result taken 2.30 hrs with 4 node cluster using Hive and Python UDF.
My questions are:
1) I heard Java Mapreduce always faster. Will that be true with Python Map reduce streaming concept too?
2) Can I achieve all the above functions in Python like join, retrieval of text file name, compressed data flow like ORC since the volume is high?
3) Will Pig join would be better than Hive? If yes can we get input text file name in Pig to generate output column?
Thanks in advance. | 0 | 1 | 2,382 |
0 | 29,593,497 | 0 | 0 | 0 | 0 | 1 | true | 1 | 2015-04-11T06:52:00.000 | 1 | 1 | 0 | Is there a Python wrapper for Stanford Neural Net based dependency parser? | 29,575,034 | 1.2 | python,parsing,nlp,neural-network,stanford-nlp | I don't know of any such wrapper at the moment, and there are no plans at Stanford to build one. (Maybe the NLTK developers would be up for the challenge?) | I know about the Python wrappers for Stanford CoreNLP package but this package does not seem to contain neural net based dependency parser model. Rather it is present in Stanford-parser-full-****-- package for which I can't find any Python wrapper. My Question: Is there a Python wrapper that would parse using Stanford Neural Net based dependency parser? Any suggestions or directions would be helpful. Thanks! | 0 | 1 | 207 |
0 | 29,637,968 | 0 | 0 | 0 | 0 | 1 | false | 1 | 2015-04-13T06:05:00.000 | 0 | 1 | 0 | Moving Window Average Convolution with different Radii - Python | 29,598,769 | 0 | python,arrays,numpy | Since you are attempting a rather customized moving window average convolution, it is unlikely that you will find it in an existing library.
Instead you can implement this in a straightforward way with loops. Then use Cython, f2py or numba, etc to speed this up to a level comparable with a native C/Fortran implementation, while still using numpy to access and store data in memory. | I would like to perform a basic moving average convolution of an array where each pixel is replaced by the average of its surrounding pixels.
But my problem scenario goes like this :
I have two arrays valueArray and radiiArray. Both the arrays have the same shape.
I need to apply the moving average to the valueArray but instead of having a constant radius to get my neighboring pixels, I want each pixel's average be calculated with a different radii - values of which are stored in the radiiArray
I could implement it using for loops but that would be time consuming since the arrays are too large. Is this possible using the numpy library? | 0 | 1 | 267 |
0 | 29,605,232 | 0 | 0 | 0 | 0 | 1 | false | 0 | 2015-04-13T06:12:00.000 | 1 | 2 | 0 | How to convert RGB to Intensity in Python 2.7 using Opencv | 29,598,848 | 0.099668 | python,opencv | Try to use BGR2GRAY(and so on - BGR2HSL etc) instead of RGB2GRAY - OpenCV usually use BGR channel order, not RGB. | Here i have one RGB image where i need want extract plane of intensity.
I have tried HSL, in this i took L Luminosity but its not similar with Intensity, and tried RGB2GRAY but this also little bit similar but not actual.
so is there any special code to get intensity of the image? or is there any calculation of Intensity? | 0 | 1 | 954 |
0 | 68,004,057 | 0 | 0 | 0 | 1 | 1 | false | 25 | 2015-04-13T14:01:00.000 | 0 | 2 | 0 | Update existing row in database from pandas df | 29,607,222 | 0 | python,postgresql,pandas | For sql alchemy case of read table as df, change df, then update table values based on df, I found the df.to_sql to work with name=<table_name> index=False if_exists='replace'
This should replace the old values in the table with the ones you changed in the df | I have a PostgreSQL db. Pandas has a 'to_sql' function to write the records of a dataframe into a database. But I haven't found any documentation on how to update an existing database row using pandas when im finished with the dataframe.
Currently I am able to read a database table into a dataframe using pandas read_sql_table. I then work with the data as necessary. However I haven't been able to figure out how to write that dataframe back into the database to update the original rows.
I dont want to have to overwrite the whole table. I just need to update the rows that were originally selected. | 0 | 1 | 11,070 |
0 | 29,663,998 | 0 | 1 | 0 | 0 | 1 | false | 0 | 2015-04-16T01:30:00.000 | 0 | 2 | 0 | Python (instantiate) locks to multiple outputs | 29,663,838 | 0 | python,multithreading,locking,queue | It sounds like you will have potentially more than one thread writing to a single output file, so you want to make the writes thread-safe, while allowing another output file to be created and written to if a subject is added.
I would recommend having each thread simply lock the output file during the write. This would not prevent another output file from being created; you would simply ensure that that file gets locked during a write as well. Then, whether you have 16 or 32 threads or something in between, it doesn't matter how many output files you have -- simply ensure they are locked during the write, so any other thread that tries to write there will need to wait. | I am working on Python multi-threading application.
The scenario is:
The source data(thousands of small files per hour) contains data about many subjects(range 1-100). Each row starts with "subject1|col1|col2|...|coln|".
Right now users are interested in only 10(example) subjects. But in future they can add(or remove) more subjects as they prefer.
For this I wrote a program, which created a Queue and adds all source files in the directory to it. Configurable # of threads start and get a file from the queue and start parsing the data. I want to generate one large file per subject. so since user currently wants 10 subject parsed, I will generate 10 output files.
Since there can be 16-32 threads parsing the source data and writing to 10 output files, I don't want to create 10 locks, one for each output files (hard code the subject_lock per output file) since I want to provide flexibility for the program to dynamically start parsing new subject.
I am not able to think of any way to dynamically control the thread locks to the target output files (other than old school way of creating a empty file touch file(with subject_timestamp for debugging) which is generated based on the subject list, which is read from configuration file every few seconds).
Any recommendations or suggestions are appreciated.
Thanks,
Venkat | 0 | 1 | 184 |
0 | 29,692,821 | 0 | 1 | 0 | 0 | 1 | false | 0 | 2015-04-17T07:11:00.000 | 4 | 2 | 0 | How to convert string like 1.424304064E9 to datetime in pandas dataframe? | 29,692,575 | 0.379949 | python,pandas | use datetime.datetime.fromtimestamp(float("1.424304064E9")) | My data is in this format - "1.424304064E9"
I have tried pandas.to_datetime(df['ts']) but no success.
What am I missing? | 0 | 1 | 298 |
0 | 29,699,268 | 0 | 1 | 0 | 0 | 1 | false | 0 | 2015-04-17T12:13:00.000 | 0 | 3 | 0 | Dijkstra's algorithm on adjacency matrix in python | 29,698,896 | 0 | python,algorithm | When I had to implement Dijkstra's algorithm in php to find the shorter way between 2 tables of a database, I constructed the matrix with 3 values : 0 if the 2 points are the same, 1 if they are linked by an edge, -1 otherwise.
After that the algorithm just worked as intended. | How can I use Dijkstra's algorithm on an adjacency matrix with no costs for edges in Python? It has 1 if there is an edge between 2 vertices and 0 otherwise. The explanations that I've found on the internet are all for graphs with costs. | 0 | 1 | 2,624 |
0 | 30,233,155 | 0 | 1 | 0 | 0 | 1 | true | 2 | 2015-04-19T20:57:00.000 | 0 | 2 | 0 | RandomForestClassifier import | 29,735,766 | 1.2 | python,scikit-learn,random-forest | The problem was that I had the 64bit version of Anaconda and the 32bit sklearn. | I've installed Anaconda Python distribution with scikit-learn.
While importing RandomForestClassifier:
from sklearn.ensemble import RandomForestClassifier
I have the following error:
File "C:\Anaconda\lib\site-packages\sklearn\tree\tree.py", line 36, in <module>
from . import _tree
ImportError: cannot import name _tree
What the problem can be there? | 0 | 1 | 10,431 |
0 | 29,762,672 | 0 | 0 | 0 | 0 | 1 | false | 1 | 2015-04-20T23:18:00.000 | 1 | 1 | 0 | FreqDist().plot() as an histogram | 29,760,119 | 0.197375 | python,python-2.7,nltk | It seems NTLK has a tabulate() method, which gives you the numeric data. From there on you could use pylab to generate the hist() function (or bar() for a bar plot). | I am using NLTK and FreqDist().plot() . But for curiosity, it's there a way to transform the line graph into an histogram? and how I can put labels in both cases?
I've searched in the documentation, but sadly it isn't detailed for it.
Thanks in advance | 0 | 1 | 1,774 |
0 | 29,786,975 | 0 | 0 | 0 | 0 | 1 | false | 1 | 2015-04-21T06:23:00.000 | 0 | 1 | 0 | spark 1.3.1: Dataframe breaking MLib API | 29,764,424 | 0 | python,apache-spark,apache-spark-sql | I think community is going to patch this. But for now, we can use Dataframe.rdd in ALS.train (or any other place where we see only RDDs are allowed) | I am trying to use Spark SQL and MLib together to create a recommendation program (extending movie recommendation program) in python. It was working fine with 1.2.0.
However, in 1.3.1, by default spark create Dataframe objects instead of SchemaRDD objects as output of a SQL. hence, mlib.ALS.train method is failing with an assertion error:
assert(ratings,RDD)
(of course ratings is not RDD anymore :) )
Anyone facing this issue? Any workaround (I am thinking to use a map just to convert DF to RDD, but thats stupid :) ) | 0 | 1 | 208 |
0 | 29,785,304 | 0 | 1 | 0 | 0 | 1 | false | 0 | 2015-04-21T23:43:00.000 | 0 | 3 | 0 | get next value in list Pandas | 29,785,134 | 0 | python,list,pandas | It appears that printing the list wouldn't work, and you haven't provided us with any code to work with, or an example print of what your date time looks like. My best suggestion is to use the sort function.
dataframe.sort()
If I wanted a specific date to print, I would have to say to print it by index number once you have it sorted. Without knowing what your computers ability is to handle print statements of this size, I suggest copying this sorted file to a out txt file to ensure that you are getting the proper response. | I have a list of unique dates in chronological order.
I have a dataframe with dates in it. I want to use the list of dates in the dataframe to get the NEXT date in the list (find the date in dataframe in the list, return the date to the right of it ( next chronological date).
Any ideas? | 0 | 1 | 366 |
0 | 56,717,998 | 0 | 1 | 0 | 0 | 3 | false | 7 | 2015-04-22T12:40:00.000 | 0 | 4 | 0 | Cannot import cv2 in PyCharm | 29,797,893 | 0 | python,opencv,pycharm | Do the following steps:
Download and install the OpenCV executable.
Add OpenCV in the system path(%OPENCV_DIR% = /path/of/opencv/directory)
Go to C:\opencv\build\python\2.7\x86 folder and copy cv2.pyd file.
Go to C:\Python27\DLLs directory and paste the cv2.pyd file.
Go to C:\Python27\Lib\site-packages directory and paste the cv2.pyd file.
Go to PyCharm IDE and go to DefaultSettings > PythonInterpreter.
Select the Python which you have installed.
Install the packages numpy, matplotlib and pip in pycharm.
Restart your PyCharm. | I am working on a project that requires OpenCV and I am doing it in PyCharm on a Mac. I have managed to successfully install OpenCV using Homebrew, and I am able to import cv2 when I run Python (version 2.7.6) in Terminal and I get no errors. The issue arises when I try importing it in PyCharm. I get a red underline with:
no module named cv2
I assume that PyCharm is unable to locate my cv2.so file but I have the latest PyCharm version (4.0.6) and none of the forums I've looked at are helpful for this version. How do I get PyCharm to recognise my cv2 file? I went in Project Interpreter but there is no option for importing OpenCV from my own machine. Furthermore in Edit Configurations I defined an environment variable
PYTHONPATH
and set it to
/usr/local/lib/python2.7/site-packages:$PYTHONPATH
but this didn't help either.
Any ideas?
EDIT: I set up a virtualenv to no avail and figured out how to add a path to the current framework on the new PyCharm version and it turns out the path to cv2.so has already been given yet it is still complaining. | 0 | 1 | 8,253 |
0 | 44,804,084 | 0 | 1 | 0 | 0 | 3 | false | 7 | 2015-04-22T12:40:00.000 | 0 | 4 | 0 | Cannot import cv2 in PyCharm | 29,797,893 | 0 | python,opencv,pycharm | Have you selected the right version of python ?
or rather, when you have installed opencv with brew, this last probably has installed a new version of python that you can find in Cellar's Directory. You can see this immediately; from the main window of PyCharm select:
Configure -> Preferences -> Project Interpreter
click on Project Interpreter Combobox and be careful if there is a instance of python in Cellar's Directory, if yes, select it and you can see the cv2 in the list below. | I am working on a project that requires OpenCV and I am doing it in PyCharm on a Mac. I have managed to successfully install OpenCV using Homebrew, and I am able to import cv2 when I run Python (version 2.7.6) in Terminal and I get no errors. The issue arises when I try importing it in PyCharm. I get a red underline with:
no module named cv2
I assume that PyCharm is unable to locate my cv2.so file but I have the latest PyCharm version (4.0.6) and none of the forums I've looked at are helpful for this version. How do I get PyCharm to recognise my cv2 file? I went in Project Interpreter but there is no option for importing OpenCV from my own machine. Furthermore in Edit Configurations I defined an environment variable
PYTHONPATH
and set it to
/usr/local/lib/python2.7/site-packages:$PYTHONPATH
but this didn't help either.
Any ideas?
EDIT: I set up a virtualenv to no avail and figured out how to add a path to the current framework on the new PyCharm version and it turns out the path to cv2.so has already been given yet it is still complaining. | 0 | 1 | 8,253 |
0 | 39,482,840 | 0 | 1 | 0 | 0 | 3 | false | 7 | 2015-04-22T12:40:00.000 | 0 | 4 | 0 | Cannot import cv2 in PyCharm | 29,797,893 | 0 | python,opencv,pycharm | I got the same situation under win7x64 with pycharm version 2016.1.1, after a quick glimpse into the stack frame, I think it is a bug!
Pycharm ipython patches import action for loading QT, matplotlib, ..., and finally sys.path lost its way!
anyway, there is a workaround, copy Lib/site-packages/cv2.pyd or cv2.so to $PYTHONROOT, problem solved! | I am working on a project that requires OpenCV and I am doing it in PyCharm on a Mac. I have managed to successfully install OpenCV using Homebrew, and I am able to import cv2 when I run Python (version 2.7.6) in Terminal and I get no errors. The issue arises when I try importing it in PyCharm. I get a red underline with:
no module named cv2
I assume that PyCharm is unable to locate my cv2.so file but I have the latest PyCharm version (4.0.6) and none of the forums I've looked at are helpful for this version. How do I get PyCharm to recognise my cv2 file? I went in Project Interpreter but there is no option for importing OpenCV from my own machine. Furthermore in Edit Configurations I defined an environment variable
PYTHONPATH
and set it to
/usr/local/lib/python2.7/site-packages:$PYTHONPATH
but this didn't help either.
Any ideas?
EDIT: I set up a virtualenv to no avail and figured out how to add a path to the current framework on the new PyCharm version and it turns out the path to cv2.so has already been given yet it is still complaining. | 0 | 1 | 8,253 |
0 | 38,987,705 | 0 | 1 | 0 | 0 | 1 | false | 0 | 2015-04-23T00:28:00.000 | 0 | 2 | 0 | OpenCV with standalone python executable (py2exe/pyinstaller) | 29,811,423 | 0 | python,opencv,py2exe,pyinstaller | I guess I will go ahead and post an answer for this, but solution was provided by @otterb in the comments to the question. I am pasting the text here:
"py2exe is not perfect so will often miss some libraries or dll, pyd etc needed. Most likely you are missing opencv_highgui249.dll and opencv_ffmpeg249.dll etc. I would use py2exe with no single executable option enabled. And, start manually copying files that might be needed for your app. After identifying them, modify setup.py for py2exe to include them automatically."
I will note however that I use pyinstaller rather than py2exe, since I get fewer problems while building. I still have to manually copy the opencv dll files though.On Windows 7 they are located here: "C:\Python27\DLLs" and they need to be copied into the distribution folder so that they are on the same path as the other dll files that go with the distribution. | I have a python program that uses OpenCV to get frames from a video file for processing. I then create a standalone executable using py2exe (also tried pyinstaller and got same error). My computer and the target computer are both Windows 7, but the target computer does not have python installed. I use OpenCV to read the frame rate and individual images from a video file.
Problem: When I run the executable on the target computer the frame rate is returned as 0.0 and I cannot read frames.
If python is installed on the target machine then the executable runs as expected, otherwise it produces this error. So it seems that something is missing in the executable, but I get no errors when creating the executable to indicate what might be missing.
Others who have reported similar issues usually have not included the numpy dependency (and get an error indicating this), but I have included numpy. I have also tried including the entire PyQt4 module since this is listed as a dependency on the python xy site for OpenCV (I already have parts of PyQt4 for other parts of the code) and this does not solve the problem either. | 0 | 1 | 6,352 |
0 | 29,826,612 | 0 | 0 | 0 | 0 | 1 | false | 6 | 2015-04-23T14:30:00.000 | 2 | 2 | 0 | Python float precision float | 29,826,523 | 0.197375 | python,floating-point,double,precision | You could try the c_float type from the ctypes standard library. Alternatively, if you are capable of installing additional packages you might try the numpy package. It includes the float32 type. | I need to implement a Dynamic Programming algorithm to solve the Traveling Salesman problem in time that beats Brute Force Search for computing distances between points. For this I need to index subproblems by size and the value of each subproblem will be a float (the length of the tour). However holding the array in memory will take about 6GB RAM if I use python floats (which actually have double precision) and so to try and halve that amount (I only have 4GB RAM) I will need to use single precision floats. However I do not know how I can get single precision floats in Python (I am using Python 3). Could someone please tell me where I can find them (I was not able to find much on this on the internet). Thanks.
EDIT: I notice that numpy also has a float16 type which will allow for even more memory savings. The distances between points are around 10000 and there are 25 unique points and my answer needs to be to the nearest integer. Will float16 provide enought accuracy or do I need to use float32? | 0 | 1 | 4,158 |
0 | 32,484,856 | 0 | 0 | 0 | 0 | 1 | true | 7 | 2015-04-23T16:08:00.000 | 4 | 2 | 0 | Ripley's K Function (Second order intensity function) Python | 29,828,922 | 1.2 | python,spatial | Solved my problem, this is for others looking to do same analysis.
Definitely recommend using R for spatial analysis. A transfer from python is simple because all you need is coordinates of your point pattern.
Write a csv of x,y and z coordinates of your points using python
R has good functionality of reading csv using command
read.csv("filename"). Make sure the directory is set properly using setwd command.
Convert the csv you just read to a ppp(point
pattern which R understands) using as.ppp command.
Continue to use
Kest, Gest etc for required spatial analysis.
Cheers. | I am looking for Ripley's k function implementation in Python. But so far haven't been able to find any spatial modules implementing this in scipy or elsewhere.
I have created Voronoi tessellation of a fibre composite and need to perform analysis using Ripley's K and pair distribution functions compared to a Poisson distribution.
Cannot upload images-not enough rep. | 0 | 1 | 2,325 |
0 | 29,892,429 | 0 | 0 | 0 | 0 | 1 | false | 1 | 2015-04-24T01:27:00.000 | 0 | 2 | 0 | Python Pandas Large Row Processing | 29,837,153 | 0 | python,pandas | Row by row. Pandas is not the ideal tool for this.
I would suggest you look into Map/Reduce. It is designed for exactly this. Streaming is the key to row by row processing. | I have a lot of time series data. Almost 3 GB of csv files. The dimensions are 50k columns with 6000 rows. Now I need to process them row by row. They are time ordered and its important that for each row, I look at each column.
Would importing this in to pandas as a pivot table and iterating them over row by row efficient? Any suggestions? | 0 | 1 | 662 |
0 | 29,841,705 | 0 | 0 | 0 | 0 | 1 | false | 0 | 2015-04-24T06:15:00.000 | 0 | 1 | 0 | Is it better to store temp data in arrays or save it to file for access later? | 29,840,006 | 0 | python,performance,numpy,save | Try to make the data obsolete as fast as possible by further processing/accumulating e.g. plotting immediately.
You did not give details about the memory/storage needed. for sparse matrices there are efficient representations. if your matrices are not sparse there are roughly 500k entries per matrix and therefore 5G entries altogether. without knowing your data type this could be typically 40GB of memory.
I strongly suggest to review your algorithms for achieving a smaller memory footprint. | This is a broad question. I am running a very long simulation (in Python) that generates a sizeable amount of data (about 10,000 729*729 matrices). I only need the data to plot a couple of graphs and then I'm done with it. At the moment I save the data in (numpy) arrays. When the simulation is complete I plot the data.
One alternative would be to write the data to a file, and then access the file after simulation to plot graphs etc.
In general is there consensus on the best (i.e. quickest) way to manage large temporary data sets. Is either of these "best practice"? | 0 | 1 | 626 |
0 | 29,870,156 | 0 | 0 | 0 | 0 | 1 | false | 1 | 2015-04-25T19:56:00.000 | 0 | 1 | 0 | Ball-Line Segment Collision on End-Point of Line | 29,870,031 | 0 | python,math,vector,line,collision | Possible Solutions:
Instead of using a single 1D 'line', you could construct a 2D rectangle (that is as this as you want/need it to be) --- composed of 4 separate 'lines'. I.e. you can have collisions with any of the 4 faces of the rectangle object. Would that work?
Do some sort of corner collision -- if the ball is 'hits' the start or end of a line, have it bounce off appropriately. I think the way this would be done is as follows:
i. Collision occurs if the corner falls within the radius of the ball.
ii. Define a line between the corner and the center of the ball.
iii. Reverse the component of the ball's velocity along this line. | So I have a program where a ball subject to gravity bounces off of lines created by a user with mouse clicks. These lines are normally sloped. My collision bounces work perfectly EXCEPT in the case where ball does approximately this:
->O ------
My code works by finding the normal vector of the line such that the scalar product of the incident velocity vec of the ball and the normal of the line is negative (this means the vector have opposite directions).
Then I decompose the velocity into terms parallel and perpendicular to the normal,
and the reverse the direction of the parallel component.
During the edge case described above ball moves basically along the line. How can I account for this? Any advice?> | 0 | 1 | 157 |
0 | 29,883,739 | 0 | 0 | 0 | 0 | 1 | false | 14 | 2015-04-25T22:57:00.000 | 6 | 3 | 0 | Python multi dimensional sparse array | 29,871,669 | 1 | python,scipy | scipy.sparse has a number of formats, though only a couple have an efficient set of numeric operations. Unfortunately, those are the harder ones to extend.
dok uses a tuple of the indices as dictionary keys. So that would be easy to generalize from 2d to 3d or more. coo has row, col, data attribute arrays. Conceptually then, adding a third depth(?) is easy. lil probably would require lists within lists, which could get messy.
But csr and csc store the array in indices, indptr and data arrays. This format was worked out years ago by mathematicians working with linear algebra problems, along with efficient math operations (esp matrix multiplication). (The relevant paper is cited in the source code).
So representing 3d sparse arrays is not a problem, but implementing efficient vector operations could require some fundamental mathematical research.
Do you really need the 3d layout to do the vector operations? Could you, for example, reshape 2 of the dimensions into 1, at least temporarily?
Element by element operations (*,+,-) work just as well with the data of a flattened array as with the 2 or 3d version. np.tensordot handles nD matrix multiplication by reshaping the inputs into 2D arrays, and applying np.dot. Even when np.einsum is used on 3d arrays, the product summation is normally over just one pair of dimensions (e.g. 'ijk,jl->ikl')
3D representation can be conceptually convenient, but I can't think of a mathematical operation that requires it (instead of 2 or 1d).
Overall I think you'll get more speed from reshaping your arrays than from trying to find/implement genuine 3d sparse operations. | I am working on a project where I need to deal with 3 dimensional large array. I was using numpy 3d array but most of my entries are going to be zero, so it's lots of wastage of memory. Scipy sparse seems to allow only 2D matrix. Is there any other way I can store 3D sparse array? | 0 | 1 | 9,257 |
0 | 41,026,037 | 0 | 0 | 0 | 0 | 1 | false | 3 | 2015-04-26T18:40:00.000 | 0 | 2 | 0 | Arrow pointing to a point on a curve | 29,881,872 | 0 | python,matplotlib,plot | The inverted arrowhead is due to a negative sign of the head_length variable. Probably you are scaling it using a negative value. Using head_length= abs(value)*somethingelse should take care of your problem. | I am trying to plot arrows pointing at a point on a curve in python using matplotlib.
On this line i need to point vertical arrows at specific points.
This is for indicating forces acting on a beam, so their direction is very important. Where the curve is the beam and the arrow is the force.
I know the coordinate of said point, exactly, but it is of cause changing with the input.
This input should also dictate whether the arrow points upwards or downwards from the line. (negative and positive forces applied).
I have tried endlessly with plt.arrow, but because the scale changes drastically and so does the quadrant in which the arrow has to be. So it might have to start at y < 0 and end in a point where y > 0.
The problem is that the arrowhead length then points the wrong way like this --<. instead of -->.
So before I go bald because of this, I would like to know if there is an easy way to apply a vertical arrow (could be infinite in the opposite direction for all i care) pointing to a point on a curve, of which I can control whether it point upwards to the curve, or downwards to the curve. | 0 | 1 | 1,773 |
0 | 39,548,461 | 0 | 1 | 0 | 0 | 1 | false | 11 | 2015-04-26T21:20:00.000 | 1 | 5 | 0 | Trouble installing scipy via pyCharm windows 8 - no lapack / blas resources found | 29,883,690 | 0.039979 | python,pycharm,lapack,blas | I had the same issue, and downloading Anaconda, and switching the project interpreter in PyCharm to \Anaconda3\python.exe helped solve this.
Good luck! | I'm currently having trouble installing scipy via PyCharm's package manager. I have installed numpy successfully and do have the Microsoft Visual Studio C/C++ compiler in the System Variables.
However, when it's time to install scipy in PyCharm, the following error occurs:
Executed Command: pip install scipy
Error occured: numpy.distutils.system_info.NotFoundError: no lapack/blas resources found
I have seen other resources on installing blas / lapack on windows, but I'm unsure if it will work with PyCharm's installations.
If anybody has the solution / resources to redirect me to, please let me know. | 0 | 1 | 16,017 |
0 | 29,889,993 | 0 | 0 | 0 | 0 | 1 | false | 29 | 2015-04-27T05:58:00.000 | 1 | 9 | 0 | How to visualize a neural network | 29,888,233 | 0.022219 | python,image,neural-network | Draw the network with nodes as circles connected with lines. The line widths must be proportional to the weights. Very small weights can be displayed even without a line. | I want to draw a dynamic picture for a neural network to watch the weights changed and the activation of neurons during learning. How could I simulate the process in Python?
More precisely, if the network shape is: [1000, 300, 50],
then I wish to draw a three layer NN which contains 1000, 300 and 50 neurons respectively.
Further, I hope the picture could reflect the saturation of neurons on each layer during each epoch.
I've no idea about how to do it. Can someone shed some light on me? | 0 | 1 | 35,856 |
1 | 29,999,330 | 0 | 0 | 0 | 0 | 1 | false | 1 | 2015-04-28T09:02:00.000 | 0 | 1 | 0 | pyQT4 native file dialog remembering last directory | 29,914,909 | 0 | windows,python-3.x,pyqt4 | The QFileDialog.saveState() and QFileDialog.restoreState() methods can save and restore the current directory of the dialog box. | I have a pyQT4 application where the user is asked for a savefile (QFileDialog and all that...)
One annoyance is it does not remember the last directory so multiple call always defaults to the working directory of the application (or whatever I set the 3rd argument to)
If I set the option to not use the native file browser it remembers but "it is not native to windows" (note this doesn't bug me as I am a linux user, but others are not...)
One option I was considering was saving the last working directory and populating the 3rd argument with that for every call but this seems quite brutal, especially as it seems matplotlib appears to be remembering the last directory (so it is possible)
Any ideas?
filename = QtGui.QFileDialog.getSaveFileName(self, "Save Plot to CSV", '', "CSV Data (*.csv)") | 0 | 1 | 305 |
0 | 29,927,508 | 0 | 0 | 0 | 0 | 1 | false | 0 | 2015-04-28T16:12:00.000 | 0 | 2 | 0 | Scipy - Multiplying large sparse matrix causes segmentation fault? | 29,924,590 | 0 | python,numpy,segmentation-fault,scipy,sparse-matrix | Resolved the issue, turns out this is a memory problem. I ran the operation on another machine and received a MemoryIssue (whereas my machine gives a segfault), and when given more memory it turns into a "negative dimensions not allowed error" a long way into it, which I presume is an integer overflow in the calculation. | I have a CSR sparse matrix in scipy of size 444075 x 444075. I wish to multiply it by its transpose. However, when I do m * m.T it causes a segmentation fault 11 error. Is this a memory issue, and if so, is there a way to allocate more memory to the program? Is there a clever workaround/hack using subroutines other routines from scipy to multiply a different way? | 0 | 1 | 850 |
0 | 29,929,834 | 0 | 0 | 0 | 0 | 1 | false | 0 | 2015-04-28T18:05:00.000 | 0 | 1 | 0 | putting headers into an array, python | 29,926,772 | 0 | python,csv,numpy | Assuming I have understood what you mean by headers (it would be easier to tell with a few complete lines, even if you had to scale it down from your actual file)...
I would first read the irregular lines with normal python then, on the regular lines, use genfromtxt with skip_header and usecols (make a tuple like (i for i in range(2,102)) | I have a set of data that is below some metadata. I'm looking to put the headers into a numpy array to be used later. However the first header needs to be ignored as that is the x data header, then the other columns are the y headers. How do i read this? | 0 | 1 | 118 |
0 | 29,930,257 | 0 | 0 | 0 | 0 | 1 | false | 2 | 2015-04-28T21:21:00.000 | 0 | 3 | 0 | Performing Decomposition on Sparse Matrices in Python | 29,930,160 | 0 | python,scipy,scikit-learn,sparse-matrix,pca | Even the input matrix is sparse the output will not be a sparse matrix. If the system does not support a dense matrix neither the results will not be supported | I'm trying to decomposing signals in components (matrix factorization) in a large sparse matrix in Python using the sklearn library.
I made use of scipy's scipy.sparse.csc_matrix to construct my matrix of data. However I'm unable to perform any analysis such as factor analysis or independent component analysis. The only thing I'm able to do is use truncatedSVD or scipy's scipy.sparse.linalg.svds and perform PCA.
Does anyone know any work-arounds to doing ICA or FA on a sparse matrix in python? Any help would be much appreciated! Thanks. | 0 | 1 | 1,097 |
0 | 30,708,149 | 0 | 0 | 0 | 0 | 1 | true | 1 | 2015-04-29T11:44:00.000 | 0 | 1 | 0 | Python: flood filling of multidimensional image | 29,942,739 | 1.2 | python,image-processing,flood-fill | Hell yeah! scipy.ndimage.measurements module helps! | I have a binary multidimensional image. And I want to get some implementation of flood fill that will give me the next:
List of connected regions (with adjacent pixels with value True).
For each region I want to get its bounding box and list of pixel coordinates of all pixels from the interconnected region.
Is something like that implemented? | 0 | 1 | 897 |
0 | 40,606,389 | 0 | 1 | 0 | 0 | 1 | false | 63 | 2015-05-04T12:51:00.000 | 9 | 5 | 0 | In python, what is the difference between random.uniform() and random.random()? | 30,030,659 | 1 | python,random,uniform | In random.random() the output lies between 0 & 1 , and it takes no input parameters
Whereas random.uniform() takes parameters , wherein you can submit the range of the random number.
e.g.
import random as ra
print ra.random()
print ra.uniform(5,10)
OUTPUT:-
0.672485369423
7.9237539416 | In python for the random module, what is the difference between random.uniform() and random.random()? They both generate pseudo random numbers, random.uniform() generates numbers from a uniform distribution and random.random() generates the next random number. What is the difference? | 0 | 1 | 131,400 |
0 | 30,125,166 | 0 | 0 | 0 | 0 | 1 | false | 0 | 2015-05-04T16:31:00.000 | 0 | 1 | 0 | Plot 2d line diagram in mayavi | 30,035,123 | 0 | python,matplotlib,mayavi | Mayavi is not really good at plotting 2d-diagramms, you can cheat a little by setting your camera position parallel to an 2d image. If you want to plot 2d-diagramms try using matplotlib. | I have a dataset of a tennis game. This dataset contains the ball positions in each rally and the current score. I already 3d-visualized the game and ball positions in mayavi.
Now I want to plot 2d line diagrams in mayavi that visualizes the score developement after specific events (such as after: a break, a set-win, set-loss,...).
I came up with some ideas, but none of them are satisfying:
I could use imshow and "draw" the diagram
I could use points3d to plot the diagram
Maybe I can somehow use pyplot to plot the diagram, then make a screenshot und then plot this screenshot in mayavi... Any idea if this is possible?
Do you have any other idea how I could plot a 2d line diagram in mayavi? | 0 | 1 | 783 |
0 | 30,048,240 | 0 | 0 | 0 | 0 | 1 | false | 0 | 2015-05-05T08:03:00.000 | 1 | 1 | 0 | TfidfVectorizer does not use the whole set of words in all documents? | 30,047,341 | 0.197375 | python,nlp,tf-idf | Did you check the stop_words and max_features? If you provide values in either of these two, it will exclude some words. | I am trying to build a TFIDF model with TfidfVectorizer. The feature name list namely the number of column of sparse matrix is shorter than the length of word set of documents even though I set min_df as 1. What happened? | 0 | 1 | 525 |
0 | 30,059,056 | 0 | 0 | 0 | 0 | 1 | false | 0 | 2015-05-05T09:25:00.000 | 0 | 1 | 0 | Python: np.sort VS array.argsort() | 30,049,051 | 0 | python,arrays,sorting | I figure out why it didn't work with np.sort().
I misused the structured array function.
With the following dtype, I have created my array with the following line:
Data = np.zeros((78000,11),dtype=dtype2)
I though that I had to create 1 row for each structured data. WRONG ! The right line is: Data = np.zeros((78000,1),dtype=dtype2) | I'm facing something strange, the function sort and the attribut argsort don't give me the same results.
I have a Data array (CFD results) with the following structure:
dtype([('nodenumber', '<f8'), (' x-coordinate', '<f8'), (' y-coordinate', '<f8'), (' z-coordinate', '<f8'), (' pressure', '<f8'), (' total-pressure', '<f8'), (' x-velocity', '<f8'), (' y-velocity', '<f8'), (' z-velocity', '<f8'), (' temperature', '<f8'), ('total-temperature\n', '<f8')])
So, each column contains one measured parameters at one point. I would like to sort the array by increasing 'z-coordinate' AND of course move line by line during the sorting (1line <=> 1 point and coresponding values).
I tried this function:
Data_sorted = np.sort(Data,axis=0,kind='mergesort',order=' z-coordinate')
It returns me a sorted array but the lines are completely messed up. For example, the previous point 1 has now a completely different z-coordinate. I don't want that.
Then I used this function (The 3rd column is the z-coordinate) :
order = Data[:, 3].argsort(kind='mergesort')
Data_sorted = np.take(Data, order, axis=0)
And... it works ! The array has been sorted by increasing z-coordinate and the points are still coherent (it seems, at least).
Do you have an idea why these both similar function provide different results ?
Because in a 2nd step, I will need to do something like that:
Data_sorted = np.sort(Data,axis=0,kind='mergesort',order=(' z-coordinate',' y-coordinate'))\= | 0 | 1 | 906 |
Subsets and Splits