prompt
stringlengths
105
4.73k
reference_code
stringlengths
11
774
code_context
stringlengths
746
120k
problem_id
int64
0
999
library_problem_id
int64
0
290
library
class label
7 classes
test_case_cnt
int64
0
5
perturbation_type
class label
4 classes
perturbation_origin_id
int64
0
289
Problem: I'm using tensorflow 2.10.0. I've come across a case in which the averaging includes padded values. Given a tensor X of some shape (batch_size, ..., features), there could be zero padded features to get the same shape. How can I average the second to last dimension of X (the features) but only the non-zero ent...
non_zero = tf.cast(x != 0, tf.float32) y = tf.reduce_sum(x, axis=-2) / tf.reduce_sum(non_zero, axis=-2) result = y return result
import tensorflow as tf import copy def generate_test_case(test_case_id): def generate_ans(data): x = data non_zero = tf.cast(x != 0, tf.float32) y = tf.reduce_sum(x, axis=-2) / tf.reduce_sum(non_zero, axis=-2) return y def define_test_input(test_case_id): if test_case...
700
34
6Tensorflow
2
3Surface
32
Problem: How would you convert this Tensorflow 1.5 code to Tensorflow 2.3.0? import tensorflow as tf try: Session = tf.Session except AttributeError: Session = tf.compat.v1.Session tf.random.set_seed(10) A = tf.random.normal([100,100]) B = tf.random.normal([100,100]) with Session() as sess: result = sess.r...
tf.random.set_seed(10) def get_values(): A = tf.random.normal([100,100]) B = tf.random.normal([100,100]) return A,B @tf.function def compute(): A,B = get_values() return tf.reduce_sum(tf.matmul(A,B)) result = compute()
import tensorflow as tf import copy def generate_test_case(test_case_id): def generate_ans(data): FLAG = data return -805.02057 def define_test_input(test_case_id): if test_case_id == 1: FLAG = 114514 return FLAG test_input = define_test_input(test_case_id) ...
701
35
6Tensorflow
1
1Origin
35
Problem: I'm using tensorflow 2.10.0. So I'm creating a tensorflow model and for the forward pass, I'm applying my forward pass method to get the scores tensor which contains the prediction scores for each class. The shape of this tensor is [100, 10]. Now, I want to get the accuracy by comparing it to y which contains ...
def g(a): return tf.argmax(a,axis=1) result = g(a.__copy__())
import tensorflow as tf import copy def generate_test_case(test_case_id): def generate_ans(data): a = data return tf.argmax(a, axis=1) def define_test_input(test_case_id): if test_case_id == 1: a = tf.constant( [ [0.3232, -0.2321, 0.2332...
702
36
6Tensorflow
2
1Origin
36
Problem: I'm using tensorflow 2.10.0. So I'm creating a tensorflow model and for the forward pass, I'm applying my forward pass method to get the scores tensor which contains the prediction scores for each class. The shape of this tensor is [100, 10]. Now, I want to get the accuracy by comparing it to y which contains ...
def g(a): return tf.argmax(a,axis=0) result = g(a.__copy__())
import tensorflow as tf import copy def generate_test_case(test_case_id): def generate_ans(data): a = data return tf.argmax(a, axis=0) def define_test_input(test_case_id): if test_case_id == 1: a = tf.constant( [ [0.3232, -0.2321, 0.2332...
703
37
6Tensorflow
2
2Semantic
36
Problem: I'm using tensorflow 2.10.0. So I'm creating a tensorflow model and for the forward pass, I'm applying my forward pass method to get the scores tensor which contains the prediction scores for each class. The shape of this tensor is [100, 10]. Now, I want to get the accuracy by comparing it to y which contains ...
result = tf.argmax(a,axis=1) return result
import tensorflow as tf import copy def generate_test_case(test_case_id): def generate_ans(data): a = data return tf.argmax(a, axis=1) def define_test_input(test_case_id): if test_case_id == 1: a = tf.constant( [ [0.3232, -0.2321, 0.2332...
704
38
6Tensorflow
2
3Surface
36
Problem: I'm using tensorflow 2.10.0. The problem is that I need to convert the scores tensor so that each row simply contains the index of the lowest value in each column. For example if the tensor looked like this, tf.Tensor( [[0.3232, -0.2321, 0.2332, -0.1231, 0.2435, 0.6728], [0.2323, -0.1231, -0.5321, -0.1...
def g(a): return tf.argmin(a,axis=0) result = g(a.__copy__())
import tensorflow as tf import copy def generate_test_case(test_case_id): def generate_ans(data): a = data return tf.argmin(a, axis=0) def define_test_input(test_case_id): if test_case_id == 1: a = tf.constant( [ [0.3232, -0.2321, 0.2332...
705
39
6Tensorflow
2
0Difficult-Rewrite
36
Problem: I'm using tensorflow 2.10.0. I am trying to save my ANN model using SavedModel format. The command that I used was: model.save("my_model") It supposed to give me a folder namely "my_model" that contains all saved_model.pb, variables and asset, instead it gives me an HDF file namely my_model. I am using keras ...
tms_model = tf.saved_model.save(model,"export/1")
import copy import tokenize, io def generate_test_case(test_case_id): def generate_ans(data): FLAG = data return 1 def define_test_input(test_case_id): if test_case_id == 1: FLAG = 114514 return FLAG test_input = define_test_input(test_case_id) expected_re...
706
40
6Tensorflow
1
1Origin
40
Problem: I'm using tensorflow 2.10.0. I would like to generate 10 random integers as a tensor in TensorFlow but I don't which command I should use. In particular, I would like to generate from a uniform random variable which takes values in {1, 2, 3, 4}. I have tried to look among the distributions included in tensorfl...
def g(seed_x): tf.random.set_seed(seed_x) return tf.random.uniform(shape=(10,), minval=1, maxval=5, dtype=tf.int32) result = g(seed_x)
import tensorflow as tf import copy def generate_test_case(test_case_id): def generate_ans(data): seed_x = data tf.random.set_seed(seed_x) return tf.random.uniform(shape=(10,), minval=1, maxval=5, dtype=tf.int32) def define_test_input(test_case_id): if test_case_id == 1: ...
707
41
6Tensorflow
1
1Origin
41
Problem: I'm using tensorflow 2.10.0. I would like to generate 114 random integers as a tensor in TensorFlow but I don't which command I should use. In particular, I would like to generate from a uniform random variable which takes values in {2, 3, 4, 5}. I have tried to look among the distributions included in tensorf...
def g(seed_x): tf.random.set_seed(seed_x) return tf.random.uniform(shape=(114,), minval=2, maxval=6, dtype=tf.int32) result = g(seed_x)
import tensorflow as tf import copy def generate_test_case(test_case_id): def generate_ans(data): seed_x = data tf.random.set_seed(seed_x) return tf.random.uniform(shape=(114,), minval=2, maxval=6, dtype=tf.int32) def define_test_input(test_case_id): if test_case_id == 1: ...
708
42
6Tensorflow
1
2Semantic
41
Problem: I'm using tensorflow 2.10.0. I would like to generate 10 random integers as a tensor in TensorFlow but I don't which command I should use. In particular, I would like to generate from a uniform random variable which takes values in {1, 2, 3, 4}. I have tried to look among the distributions included in tensorfl...
tf.random.set_seed(seed_x) result = tf.random.uniform(shape=(10,), minval=1, maxval=5, dtype=tf.int32) return result
import tensorflow as tf import copy def generate_test_case(test_case_id): def generate_ans(data): seed_x = data tf.random.set_seed(seed_x) return tf.random.uniform(shape=(10,), minval=1, maxval=5, dtype=tf.int32) def define_test_input(test_case_id): if test_case_id == 1: ...
709
43
6Tensorflow
1
3Surface
41
Problem: I'm using tensorflow 2.10.0. I need to find which version of TensorFlow I have installed. I'm using Ubuntu 16.04 Long Term Support. A: <code> import tensorflow as tf ### output the version of tensorflow into variable 'result' </code> result = ... # put solution in this variable BEGIN SOLUTION <code>
result = tf.version.VERSION
import tensorflow as tf import copy def generate_test_case(test_case_id): def generate_ans(data): FLAG = data return tf.version.VERSION def define_test_input(test_case_id): if test_case_id == 1: FLAG = 114514 return FLAG test_input = define_test_input(test_cas...
710
44
6Tensorflow
1
1Origin
44
Problem: I have a set of data and I want to compare which line describes it best (polynomials of different orders, exponential or logarithmic). I use Python and Numpy and for polynomial fitting there is a function polyfit(). How do I fit y = Alogx + B using polyfit()? The result should be an np.array of [A, B] A: <cod...
result = np.polyfit(np.log(x), y, 1)
import numpy as np import copy def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: x = np.array([1, 7, 20, 50, 79]) y = np.array([10, 19, 30, 35, 51]) return x, y def generate_ans(data): _a = data x, y = _a ...
711
0
4Scipy
1
1Origin
0
Problem: I have a set of data and I want to compare which line describes it best (polynomials of different orders, exponential or logarithmic). I use Python and Numpy and for polynomial fitting there is a function polyfit(). How do I fit y = A + Blogx using polyfit()? The result should be an np.array of [A, B] A: <cod...
result = np.polyfit(np.log(x), y, 1)[::-1]
import numpy as np import copy def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: x = np.array([1, 7, 20, 50, 79]) y = np.array([10, 19, 30, 35, 51]) return x, y def generate_ans(data): _a = data x, y = _a ...
712
1
4Scipy
1
2Semantic
0
Problem: I have a set of data and I want to compare which line describes it best (polynomials of different orders, exponential or logarithmic). I use Python and Numpy and for polynomial fitting there is a function polyfit(). But I found no such functions for exponential and logarithmic fitting. How do I fit y = A*exp(B...
result = scipy.optimize.curve_fit(lambda t,a,b, c: a*np.exp(b*t) + c, x, y, p0=p0)[0]
import numpy as np import copy import scipy.optimize def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: y = np.array([1, 7, 20, 50, 79]) x = np.array([10, 19, 30, 35, 51]) p0 = (4, 0.1, 1) return x, y, p0 def g...
713
2
4Scipy
1
0Difficult-Rewrite
0
Problem: I can't figure out how to do a Two-sample KS test in Scipy. After reading the documentation scipy kstest I can see how to test where a distribution is identical to standard normal distribution from scipy.stats import kstest import numpy as np x = np.random.normal(0,1,1000) test_stat = kstest(x, 'norm') #>>> te...
statistic, p_value = stats.ks_2samp(x, y)
import numpy as np import copy from scipy import stats def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: np.random.seed(42) x = np.random.normal(0, 1, 1000) y = np.random.normal(0, 1, 1000) elif test_case_id == 2: ...
714
3
4Scipy
2
1Origin
3
Problem: I can't figure out how to do a Two-sample KS test in Scipy. After reading the documentation scipy kstest I can see how to test where a distribution is identical to standard normal distribution from scipy.stats import kstest import numpy as np x = np.random.normal(0,1,1000) test_stat = kstest(x, 'norm') #>>> te...
s, p = stats.ks_2samp(x, y) result = (p <= alpha)
import numpy as np import copy from scipy import stats def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: np.random.seed(42) x = np.random.normal(0, 1, 1000) y = np.random.normal(0, 1, 1000) elif test_case_id == 2: ...
715
4
4Scipy
2
0Difficult-Rewrite
3
Problem: According to the SciPy documentation it is possible to minimize functions with multiple variables, yet it doesn't tell how to optimize on such functions. from scipy.optimize import minimize from math import sqrt, sin, pi, cos def f(c): return sqrt((sin(pi/2) + sin(0) + sin(c) - 2)**2 + (cos(pi/2) + cos(0) + ...
def g(params): import numpy as np a, b, c = params return ((a+b-c)-2)**2 + ((3*a-b-c))**2 + np.sin(b) + np.cos(b) + 4 res = optimize.minimize(g, initial_guess) result = res.x
import numpy as np import copy from scipy import optimize def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: a = [-1, 0, -3] return a def generate_ans(data): _a = data initial_guess = _a def g(params): ...
716
5
4Scipy
1
1Origin
5
Problem: How does one convert a list of Z-scores from the Z-distribution (standard normal distribution, Gaussian distribution) to left-tailed p-values? I have yet to find the magical function in Scipy's stats module to do this, but one must be there. A: <code> import numpy as np import scipy.stats z_scores = np.array([...
temp = np.array(z_scores) p_values = scipy.stats.norm.cdf(temp)
import numpy as np import copy import scipy.stats def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: a = np.array([-3, -2, 0, 2, 2.5]) return a def generate_ans(data): _a = data z_scores = _a temp = np.array(z_...
717
6
4Scipy
1
1Origin
6
Problem: How does one convert a list of Z-scores from the Z-distribution (standard normal distribution, Gaussian distribution) to left-tailed p-values? Original data is sampled from X ~ N(mu, sigma). I have yet to find the magical function in Scipy's stats module to do this, but one must be there. A: <code> import scip...
temp = np.array(z_scores) p_values = scipy.stats.norm.cdf(temp)
import numpy as np import pandas as pd import scipy from scipy import sparse import scipy.stats import copy import io from scipy import integrate def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: z_scores = [-3, -2, 0, 2, 2.5] mu = 3 ...
718
7
4Scipy
1
0Difficult-Rewrite
6
Problem: How does one convert a left-tailed p-value to a z_score from the Z-distribution (standard normal distribution, Gaussian distribution)? I have yet to find the magical function in Scipy's stats module to do this, but one must be there. A: <code> import numpy as np import scipy.stats p_values = [0.1, 0.225, 0.5, ...
z_scores = scipy.stats.norm.ppf(p_values)
import numpy as np import copy import scipy.stats def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: a = [0.1, 0.225, 0.5, 0.75, 0.925, 0.95] return a def generate_ans(data): _a = data p_values = _a z_scores = ...
719
8
4Scipy
1
0Difficult-Rewrite
6
Problem: I have been trying to get the result of a lognormal distribution using Scipy. I already have the Mu and Sigma, so I don't need to do any other prep work. If I need to be more specific (and I am trying to be with my limited knowledge of stats), I would say that I am looking for the cumulative function (cdf unde...
result = stats.lognorm(s=stddev, scale=np.exp(mu)).cdf(x)
import numpy as np import copy from scipy import stats def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: stddev = 2.0785 mu = 1.744 x = 25 elif test_case_id == 2: stddev = 2 mu = 1 ...
720
9
4Scipy
2
1Origin
9
Problem: I have been trying to get the arithmetic result of a lognormal distribution using Scipy. I already have the Mu and Sigma, so I don't need to do any other prep work. If I need to be more specific (and I am trying to be with my limited knowledge of stats), I would say that I am looking for the expected value and...
expected_value = np.exp(mu + stddev ** 2 / 2) median = np.exp(mu)
import numpy as np import copy def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: stddev = 2.0785 mu = 1.744 return mu, stddev def generate_ans(data): _a = data mu, stddev = _a expected_value = np.ex...
721
10
4Scipy
1
0Difficult-Rewrite
9
Problem: I have this example of matrix by matrix multiplication using numpy arrays: import numpy as np m = np.array([[1,2,3],[4,5,6],[7,8,9]]) c = np.array([0,1,2]) m * c array([[ 0, 2, 6], [ 0, 5, 12], [ 0, 8, 18]]) How can i do the same thing if m is scipy sparse CSR matrix? The result should be csr...
result = sa.multiply(sb)
import numpy as np import copy from scipy import sparse def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: sa = sparse.csr_matrix(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) sb = sparse.csr_matrix(np.array([0, 1, 2])) elif test...
722
11
4Scipy
2
1Origin
11
Problem: I have this example of matrix by matrix multiplication using numpy arrays: import numpy as np m = np.array([[1,2,3],[4,5,6],[7,8,9]]) c = np.array([0,1,2]) m * c array([[ 0, 2, 6], [ 0, 5, 12], [ 0, 8, 18]]) How can i do the same thing if m is scipy sparse CSR matrix? The result should be csr...
result = sA.multiply(sB) return result
import numpy as np import copy from scipy import sparse def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: sa = sparse.csr_matrix(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) sb = sparse.csr_matrix(np.array([0, 1, 2])) elif test...
723
12
4Scipy
2
3Surface
11
Problem: I have some data that comes in the form (x, y, z, V) where x,y,z are distances, and V is the moisture. I read a lot on StackOverflow about interpolation by python like this and this valuable posts, but all of them were about regular grids of x, y, z. i.e. every value of x contributes equally with every point o...
result = scipy.interpolate.griddata(points, V, request)
import numpy as np import copy import scipy.interpolate def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: points = np.array( [ [27.827, 18.53, -30.417], [24.002, 17.759, -24.782], ...
724
13
4Scipy
1
1Origin
13
Problem: I have some data that comes in the form (x, y, z, V) where x,y,z are distances, and V is the moisture. I read a lot on StackOverflow about interpolation by python like this and this valuable posts, but all of them were about regular grids of x, y, z. i.e. every value of x contributes equally with every point o...
result = scipy.interpolate.griddata(points, V, request).tolist()
import numpy as np import copy import scipy.interpolate def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: points = np.array( [ [27.827, 18.53, -30.417], [24.002, 17.759, -24.782], ...
725
14
4Scipy
1
2Semantic
13
Problem: I have a numpy array for an image that I read in from a FITS file. I rotated it by N degrees using scipy.ndimage.interpolation.rotate. Then I want to figure out where some point (x,y) in the original non-rotated frame ends up in the rotated image -- i.e., what are the rotated frame coordinates (x',y')? This sh...
def rot_ans(image, xy, angle): im_rot = rotate(image,angle) org_center = (np.array(image.shape[:2][::-1])-1)/2. rot_center = (np.array(im_rot.shape[:2][::-1])-1)/2. org = xy-org_center a = np.deg2rad(angle) new = np.array([org[0]*np.cos(a) + org[1]*np.sin(a), -org[0]*np.sin(a) + org...
import numpy as np import copy from scipy import misc from scipy.ndimage import rotate def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: data_orig = misc.face() x0, y0 = 580, 300 # left eye; (xrot,yrot) should point there ...
726
15
4Scipy
1
1Origin
15
Problem: How can I extract the main diagonal(1-d array) of a sparse matrix? The matrix is created in scipy.sparse. I want equivalent of np.diagonal(), but for sparse matrix. A: <code> import numpy as np from scipy.sparse import csr_matrix arr = np.random.rand(4, 4) M = csr_matrix(arr) </code> result = ... # put solut...
result = M.A.diagonal(0)
import numpy as np import copy from scipy.sparse import csr_matrix def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: arr = np.array( [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] ) elif test_ca...
727
16
4Scipy
2
1Origin
16
Problem: I simulate times in the range 0 to T according to a Poisson process. The inter-event times are exponential and we know that the distribution of the times should be uniform in the range 0 to T. def poisson_simul(rate, T): time = random.expovariate(rate) times = [0] while (times[-1] < T): tim...
result = stats.kstest(times, stats.uniform(loc=0, scale=T).cdf)
import numpy as np import random import copy from scipy import stats def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: def poisson_simul(rate, T): time = random.expovariate(rate) times = [0] while t...
728
17
4Scipy
1
1Origin
17
Problem: I simulate times in the range 0 to T according to a Poisson process. The inter-event times are exponential and we know that the distribution of the times should be uniform in the range 0 to T. def poisson_simul(rate, T): time = random.expovariate(rate) times = [0] while (times[-1] < T): tim...
result = stats.kstest(times, stats.uniform(loc=0, scale=T).cdf) return result
import numpy as np import random import copy from scipy import stats def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: def poisson_simul(rate, T): time = random.expovariate(rate) times = [0] while t...
729
18
4Scipy
1
3Surface
17
Problem: I simulate times in the range 0 to T according to a Poisson process. The inter-event times are exponential and we know that the distribution of the times should be uniform in the range 0 to T. def poisson_simul(rate, T): time = random.expovariate(rate) times = [0] while (times[-1] < T): tim...
res= stats.kstest(times, stats.uniform(loc=0, scale=T).cdf) if res[1] < 0.05: result = False else: result = True
import numpy as np import random import copy from scipy import stats def generate_test_case(test_case_id): def define_test_input(test_case_id): def poisson_simul(rate, T): time = random.expovariate(rate) times = [0] while times[-1] < T: times.append(time...
730
19
4Scipy
2
0Difficult-Rewrite
17
Problem: I have two csr_matrix, c1, c2. I want a new matrix Feature = [c1, c2]. But if I directly concatenate them horizontally this way, there's an error that says the matrix Feature is a list. How can I achieve the matrix concatenation and still get the same type of matrix, i.e. a csr_matrix? And it doesn't work if...
Feature = sparse.hstack((c1, c2)).tocsr()
import copy from scipy import sparse def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: c1 = sparse.csr_matrix([[0, 0, 1, 0], [2, 0, 0, 0], [0, 0, 0, 0]]) c2 = sparse.csr_matrix([[0, 3, 4, 0], [0, 0, 0, 5], [6, 7, 0, 8]]) return...
731
20
4Scipy
1
1Origin
20
Problem: I have two csr_matrix, c1 and c2. I want a new sparse matrix Feature = [c1, c2], that is, to stack c1 and c2 horizontally to get a new sparse matrix. To make use of sparse matrix's memory efficiency, I don't want results as dense arrays. But if I directly concatenate them this way, there's an error that say...
Feature = sparse.hstack((c1, c2)).tocsr()
import copy from scipy import sparse def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: c1 = sparse.csr_matrix([[0, 0, 1, 0], [2, 0, 0, 0], [0, 0, 0, 0]]) c2 = sparse.csr_matrix([[0, 3, 4, 0], [0, 0, 0, 5], [6, 7, 0, 8]]) return...
732
21
4Scipy
1
3Surface
20
Problem: I have two csr_matrix, c1 and c2. I want a new matrix Feature = [c1 c2]. That is, I want to concatenate c1 and c2 in vertical direction. But I don't know how to represent the concatenation or how to form the format. How can I achieve the matrix concatenation and still get t...
Feature = sparse.vstack((c1, c2))
import copy from scipy import sparse def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: c1 = sparse.csr_matrix([[0, 0, 1, 0], [2, 0, 0, 0], [0, 0, 0, 0]]) c2 = sparse.csr_matrix([[0, 3, 4, 0], [0, 0, 0, 5], [6, 7, 0, 8]]) return...
733
22
4Scipy
1
2Semantic
20
Problem: Given two sets of points in n-dimensional space, how can one map points from one set to the other, such that each point is only used once and the total euclidean distance between the pairs of points is minimized? For example, import matplotlib.pyplot as plt import numpy as np # create six points in 2d space; t...
C = scipy.spatial.distance.cdist(points1, points2) _, result = scipy.optimize.linear_sum_assignment(C)
import numpy as np import copy import scipy.spatial import scipy.optimize def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: np.random.seed(100) points1 = np.array( [(x, y) for x in np.linspace(-1, 1, 7) for y in np.lins...
734
23
4Scipy
1
1Origin
23
Problem: Given two sets of points in n-dimensional space, how can one map points from one set to the other, such that each point is only used once and the total Manhattan distance between the pairs of points is minimized? For example, import matplotlib.pyplot as plt import numpy as np # create six points in 2d space; t...
C = scipy.spatial.distance.cdist(points1, points2, metric='minkowski', p=1) _, result = scipy.optimize.linear_sum_assignment(C)
import numpy as np import copy import scipy.spatial import scipy.optimize def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: np.random.seed(100) points1 = np.array( [(x, y) for x in np.linspace(-1, 1, 7) for y in np.lins...
735
24
4Scipy
1
2Semantic
23
Problem: I want to remove diagonal elements from a sparse matrix. Since the matrix is sparse, these elements shouldn't be stored once removed. Scipy provides a method to set diagonal elements values: setdiag If I try it using lil_matrix, it works: >>> a = np.ones((2,2)) >>> c = lil_matrix(a) >>> c.setdiag(0) >>> c <2x2...
b = sparse.csr_matrix(a) b.setdiag(0) b.eliminate_zeros()
import numpy as np import copy import tokenize, io from scipy import sparse def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: a = np.ones((2, 2)) b = sparse.csr_matrix(a) elif test_case_id == 2: a = [] b...
736
25
4Scipy
2
1Origin
25
Problem: I am working with a 2D numpy array made of 512x512=262144 values. Such values are of float type and range from 0.0 to 1.0. The array has an X,Y coordinate system which originates in the top left corner: thus, position (0,0) is in the top left corner, while position (512,512) is in the bottom right corner. This...
blobs = img > threshold labels, result = ndimage.label(blobs)
import numpy as np import copy from scipy import ndimage def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: np.random.seed(10) gen = np.random.RandomState(0) img = gen.poisson(2, size=(512, 512)) img = ndimage.ga...
737
26
4Scipy
1
1Origin
26
Problem: I am working with a 2D numpy array made of 512x512=262144 values. Such values are of float type and range from 0.0 to 1.0. The array has an X,Y coordinate system which originates in the top left corner: thus, position (0,0) is in the top left corner, while position (512,512) is in the bottom right corner. This...
blobs = img < threshold labels, result = ndimage.label(blobs)
import numpy as np import copy from scipy import ndimage def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: np.random.seed(10) gen = np.random.RandomState(0) img = gen.poisson(2, size=(512, 512)) img = ndimage.ga...
738
27
4Scipy
1
2Semantic
26
Problem: I am working with a 2D numpy array made of 512x512=262144 values. Such values are of float type and range from 0.0 to 1.0. The array has an X,Y coordinate system which originates in the top left corner: thus, position (0,0) is in the top left corner, while position (512,512) is in the bottom right corner. This...
blobs = img > threshold labels, result = ndimage.label(blobs) return result
import numpy as np import copy from scipy import ndimage def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: np.random.seed(10) gen = np.random.RandomState(0) img = gen.poisson(2, size=(512, 512)) img = ndimage.ga...
739
28
4Scipy
1
3Surface
26
Problem: I am working with a 2D numpy array made of 512x512=262144 values. Such values are of float type and range from 0.0 to 1.0. The array has an X,Y coordinate system which originates in the top left corner: thus, position (0,0) is in the top left corner, while position (512,512) is in the bottom right corner. This...
blobs = img > threshold labels, nlabels = ndimage.label(blobs) r, c = np.vstack(ndimage.center_of_mass(img, labels, np.arange(nlabels) + 1)).T # find their distances from the top-left corner d = np.sqrt(r * r + c * c) result = sorted(d)
import numpy as np import copy from scipy import ndimage def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: np.random.seed(10) gen = np.random.RandomState(0) img = gen.poisson(2, size=(512, 512)) img = ndimage.ga...
740
29
4Scipy
1
0Difficult-Rewrite
26
Problem: Is there a simple and efficient way to make a sparse scipy matrix (e.g. lil_matrix, or csr_matrix) symmetric? Currently I have a lil sparse matrix, and not both of sA[i,j] and sA[j,i] have element for any i,j. When populating a large sparse co-occurrence matrix it would be highly inefficient to fill in [row, ...
rows, cols = M.nonzero() M[cols, rows] = M[rows, cols]
import copy import tokenize, io from scipy import sparse def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: sA = sparse.random(10, 10, density=0.1, format="lil", random_state=42) return sA def generate_ans(data): _a = data ...
741
30
4Scipy
1
1Origin
30
Problem: Is there a simple and efficient way to make a sparse scipy matrix (e.g. lil_matrix, or csr_matrix) symmetric? Currently I have a lil sparse matrix, and not both of sA[i,j] and sA[j,i] have element for any i,j. When populating a large sparse co-occurrence matrix it would be highly inefficient to fill in [row, ...
rows, cols = sA.nonzero() sA[cols, rows] = sA[rows, cols] return sA
import copy import tokenize, io from scipy import sparse def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: sA = sparse.random(10, 10, density=0.1, format="lil", random_state=42) return sA def generate_ans(data): _a = data ...
742
31
4Scipy
1
3Surface
30
Problem: I'm trying to reduce noise in a binary python array by removing all completely isolated single cells, i.e. setting "1" value cells to 0 if they are completely surrounded by other "0"s like this: 0 0 0 0 1 0 0 0 0 I have been able to get a working solution by removing blobs with sizes equal to 1 using a loop,...
def filter_isolated_cells(array, struct): filtered_array = np.copy(array) id_regions, num_ids = scipy.ndimage.label(filtered_array, structure=struct) id_sizes = np.array(scipy.ndimage.sum(array, id_regions, range(num_ids + 1))) area_mask = (id_sizes == 1) filtered_array[area_mask[id_regions]] = 0 ...
import numpy as np import copy import tokenize, io import scipy.ndimage def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: square = np.zeros((32, 32)) square[10:-10, 10:-10] = 1 np.random.seed(12) x, y = (32 * np...
743
32
4Scipy
1
1Origin
32
Problem: I'm trying to reduce noise in a python image array by removing all completely isolated single cells, i.e. setting nonzero value cells to 0 if they are completely surrounded by other "0"s like this: 0 0 0 0 8 0 0 0 0 I have been able to get a working solution by removing blobs with sizes equal to 1 using a lo...
def filter_isolated_cells(array, struct): filtered_array = np.copy(array) id_regions, num_ids = scipy.ndimage.label(filtered_array, structure=struct) id_sizes = np.array(scipy.ndimage.sum(array, id_regions, range(num_ids + 1))) area_mask = (id_sizes == 1) filtered_array[area_mask[id_regions]] = 0 ...
import numpy as np import copy import tokenize, io import scipy.ndimage def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: np.random.seed(42) square = np.zeros((32, 32)) square[10:-10, 10:-10] = np.random.randint(1, 255, siz...
744
33
4Scipy
1
2Semantic
32
Problem: I have a sparse 988x1 vector (stored in col, a column in a csr_matrix) created through scipy.sparse. Is there a way to gets its mean and standard deviation without having to convert the sparse matrix to a dense one? numpy.mean seems to only work for dense vectors. A: <code> import numpy as np from scipy.spars...
mean = col.mean() N = col.shape[0] sqr = col.copy() # take a copy of the col sqr.data **= 2 # square the data, i.e. just the non-zero data standard_deviation = np.sqrt(sqr.sum() / N - col.mean() ** 2)
import numpy as np import copy import tokenize, io from scipy.sparse import csr_matrix def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: np.random.seed(10) arr = np.random.randint(4, size=(988, 988)) A = csr_matrix(arr) ...
745
34
4Scipy
4
1Origin
34
Problem: I have a sparse 988x1 vector (stored in col, a column in a csr_matrix) created through scipy.sparse. Is there a way to gets its max and min value without having to convert the sparse matrix to a dense one? numpy.max seems to only work for dense vectors. A: <code> import numpy as np from scipy.sparse import cs...
Max, Min = col.max(), col.min()
import numpy as np import copy import tokenize, io from scipy.sparse import csr_matrix def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: np.random.seed(10) arr = np.random.randint(4, size=(988, 988)) A = csr_matrix(arr) ...
746
35
4Scipy
4
2Semantic
34
Problem: I have a sparse 988x1 vector (stored in col, a column in a csr_matrix) created through scipy.sparse. Is there a way to gets its median and mode value without having to convert the sparse matrix to a dense one? numpy.median seems to only work for dense vectors. A: <code> import numpy as np from scipy.sparse im...
n = col.shape[0] val = col.data for i in range(n-len(val)): val = np.append(val,0) Median, Mode = np.median(val), np.argmax(np.bincount(val))
import numpy as np import copy import tokenize, io from scipy.sparse import csr_matrix def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: np.random.seed(10) arr = np.random.randint(4, size=(988, 988)) A = csr_matrix(arr) ...
747
36
4Scipy
4
0Difficult-Rewrite
34
Problem: I'd like to achieve a fourier series development for a x-y-dataset using numpy and scipy. At first I want to fit my data with the first 8 cosines and plot additionally only the first harmonic. So I wrote the following two function defintions: # fourier series defintions tau = 0.045 def fourier8(x, a1, a2, a3, ...
def fourier(x, *a): ret = a[0] * np.cos(np.pi / tau * x) for deg in range(1, len(a)): ret += a[deg] * np.cos((deg+1) * np.pi / tau * x) return ret popt, pcov = curve_fit(fourier, z, Ua, [1.0] * degree)
import numpy as np import copy from scipy.optimize import curve_fit def generate_test_case(test_case_id): def define_test_input(test_case_id): s = """1.000000000000000021e-03,2.794682735905079767e+02 2.000000000000000042e-03,2.792294526290349950e+02 2.999999999999999629e-03,2.7797947706902...
748
37
4Scipy
2
1Origin
37
Problem: I have a raster with a set of unique ID patches/regions which I've converted into a two-dimensional Python numpy array. I would like to calculate pairwise Euclidean distances between all regions to obtain the minimum distance separating the nearest edges of each raster patch. As the array was originally a rast...
import itertools n = example_array.max()+1 indexes = [] for k in range(1, n): tmp = np.nonzero(example_array == k) tmp = np.asarray(tmp).T indexes.append(tmp) result = np.zeros((n-1, n-1)) for i, j in itertools.combinations(range(n-1), 2): d2 = scipy.spatial.distance.cdist(indexes[i], indexes[j], met...
import numpy as np import itertools import copy import scipy.spatial.distance def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: example_array = np.array( [ [0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0], ...
749
38
4Scipy
1
1Origin
38
Problem: I have a raster with a set of unique ID patches/regions which I've converted into a two-dimensional Python numpy array. I would like to calculate pairwise Manhattan distances between all regions to obtain the minimum distance separating the nearest edges of each raster patch. I've experimented with the cdist f...
import itertools n = example_array.max()+1 indexes = [] for k in range(1, n): tmp = np.nonzero(example_array == k) tmp = np.asarray(tmp).T indexes.append(tmp) result = np.zeros((n-1, n-1), dtype=float) for i, j in itertools.combinations(range(n-1), 2): d2 = scipy.spatial.distance.cdist(indexes[i], in...
import numpy as np import itertools import copy import scipy.spatial.distance def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: example_array = np.array( [ [0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0], ...
750
39
4Scipy
1
2Semantic
38
Problem: I have a raster with a set of unique ID patches/regions which I've converted into a two-dimensional Python numpy array. I would like to calculate pairwise Euclidean distances between all regions to obtain the minimum distance separating the nearest edges of each raster patch. As the array was originally a rast...
import itertools n = example_array.max()+1 indexes = [] for k in range(1, n): tmp = np.nonzero(example_array == k) tmp = np.asarray(tmp).T indexes.append(tmp) result = np.zeros((n-1, n-1)) for i, j in itertools.combinations(range(n-1), 2): d2 = scipy.spatial.di...
import numpy as np import itertools import copy import scipy.spatial.distance def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: example_array = np.array( [ [0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0], ...
751
40
4Scipy
1
3Surface
38
Problem: I am able to interpolate the data points (dotted lines), and am looking to extrapolate them in both direction. How can I extrapolate these curves in Python with NumPy/SciPy? The code I used for the interpolation is given below, import numpy as np import matplotlib.pyplot as plt from scipy import interpolate x ...
result = np.zeros((5, 100)) for i in range(5): extrapolator = interpolate.UnivariateSpline(x[:, i], y[:, i], k = 2, s = 4) y_int = extrapolator(x_val) result[i, :] = y_int
import numpy as np import copy from scipy import interpolate def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: x = np.array( [ [0.12, 0.11, 0.1, 0.09, 0.08], [0.13, 0.12, 0.11, 0.1, 0.09], ...
752
41
4Scipy
1
1Origin
41
Problem: How do we pass four datasets in scipy.stats.anderson_ksamp? The anderson function asks only for one parameter and that should be 1-d array. So I am wondering how to pass four different arrays to be compared in it? Thanks A: <code> import numpy as np import scipy.stats as ss x1=[38.7, 41.5, 43.8, 44.5, 45....
statistic, critical_values, significance_level = ss.anderson_ksamp([x1,x2,x3,x4])
import numpy as np import copy import scipy.stats as ss def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: x1 = [38.7, 41.5, 43.8, 44.5, 45.5, 46.0, 47.7, 58.0] x2 = [39.2, 39.3, 39.7, 41.4, 41.8, 42.9, 43.3, 45.8] x3 = [34....
753
42
4Scipy
2
1Origin
42
Problem: How do we pass two datasets in scipy.stats.anderson_ksamp? The anderson function asks only for one parameter and that should be 1-d array. So I am wondering how to pass two different arrays to be compared in it? Further, I want to interpret the result, that is, telling whether the two different arrays are dr...
s, c_v, s_l = ss.anderson_ksamp([x1,x2]) result = c_v[2] >= s
import numpy as np import copy import scipy.stats as ss def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: x1 = [38.7, 41.5, 43.8, 44.5, 45.5, 46.0, 47.7, 58.0] x2 = [39.2, 39.3, 39.7, 41.4, 41.8, 42.9, 43.3, 45.8] elif test_cas...
754
43
4Scipy
3
0Difficult-Rewrite
42
Problem: I'm trying to use rollapply with a formula that requires 2 arguments. To my knowledge the only way (unless you create the formula from scratch) to calculate kendall tau correlation, with standard tie correction included is: >>> import scipy >>> x = [5.05, 6.75, 3.21, 2.66] >>> y = [1.65, 26.5, -5.93, 7.96] >>>...
import itertools as IT for col1, col2 in IT.combinations(df.columns, 2): def tau(idx): B = df[[col1, col2]].iloc[idx] return stats.kendalltau(B[col1], B[col2])[0] df[col1+col2] = pd.Series(np.arange(len(df)), index=df.index).rolling(3).apply(tau)
import numpy as np import pandas as pd import itertools as IT import copy import scipy.stats as stats def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: df = pd.DataFrame( [[1, 5, 2], [2, 4, 4], [3, 3, 1], [4, 2, 2], [5, 1, 4]], ...
755
44
4Scipy
2
1Origin
44
Problem: What is the canonical way to check if a SciPy CSR matrix is empty (i.e. contains only zeroes)? I use nonzero(): def is_csr_matrix_only_zeroes(my_csr_matrix): return(len(my_csr_matrix.nonzero()[0]) == 0) from scipy.sparse import csr_matrix print(is_csr_matrix_only_zeroes(csr_matrix([[1,2,0],[0,0,3],[4,0,5]]...
result = (sa.count_nonzero()==0)
import copy from scipy import sparse def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: sa = sparse.random(10, 10, density=0.01, format="csr", random_state=42) elif test_case_id == 2: sa = sparse.csr_matrix([]) return sa...
756
45
4Scipy
2
1Origin
45
Problem: What is the canonical way to check if a SciPy lil matrix is empty (i.e. contains only zeroes)? I use nonzero(): def is_lil_matrix_only_zeroes(my_lil_matrix): return(len(my_lil_matrix.nonzero()[0]) == 0) from scipy.sparse import csr_matrix print(is_lil_matrix_only_zeroes(lil_matrix([[1,2,0],[0,0,3],[4,0,5]]...
result = (sa.count_nonzero()==0)
import copy from scipy import sparse def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: sa = sparse.random(10, 10, density=0.01, format="lil", random_state=42) elif test_case_id == 2: sa = sparse.lil_matrix([]) return sa...
757
46
4Scipy
2
2Semantic
45
Problem: I am looking for a way to convert a nXaXb numpy array into a block diagonal matrix. I have already came across scipy.linalg.block_diag, the down side of which (for my case) is it requires each blocks of the matrix to be given separately. However, this is challenging when n is very high, so to make things more ...
result = block_diag(*a)
import numpy as np import copy from scipy.linalg import block_diag def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: np.random.seed(10) a = np.random.rand(100, 2, 2) elif test_case_id == 2: np.random.seed(20) ...
758
47
4Scipy
2
1Origin
47
Problem: I have the following code to run Wilcoxon rank-sum test print stats.ranksums(pre_course_scores, during_course_scores) RanksumsResult(statistic=8.1341352369246582, pvalue=4.1488919597127145e-16) However, I am interested in extracting the pvalue from the result. I could not find a tutorial about this. i.e.Give...
p_value = stats.ranksums(pre_course_scores, during_course_scores).pvalue
import numpy as np import copy from scipy import stats def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: np.random.seed(10) A = np.random.randn(10) B = np.random.randn(10) return A, B def generate_ans(data): ...
759
48
4Scipy
1
1Origin
48
Problem: I have the following code to run Wilcoxon rank-sum test print stats.ranksums(pre_course_scores, during_course_scores) RanksumsResult(statistic=8.1341352369246582, pvalue=4.1488919597127145e-16) However, I am interested in extracting the pvalue from the result. I could not find a tutorial about this. i.e.Give...
p_value = stats.ranksums(pre_course_scores, during_course_scores).pvalue return p_value
import numpy as np import copy from scipy import stats def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: np.random.seed(10) A = np.random.randn(10) B = np.random.randn(10) return A, B def generate_ans(data): ...
760
49
4Scipy
1
3Surface
48
Problem: How to calculate kurtosis (the fourth standardized moment, according to Pearson’s definition) without bias correction? I have tried scipy.stats.kurtosis, but it gives a different result. I followed the definition in mathworld. A: <code> import numpy as np a = np.array([ 1. , 2. , 2.5, 400. , 6. , ...
kurtosis_result = (sum((a - np.mean(a)) ** 4)/len(a)) / np.std(a)**4
import numpy as np import copy def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: a = np.array([1.0, 2.0, 2.5, 400.0, 6.0, 0.0]) elif test_case_id == 2: np.random.seed(42) a = np.random.randn(10) return a ...
761
50
4Scipy
2
1Origin
50
Problem: How to calculate kurtosis (according to Fisher’s definition) without bias correction? A: <code> import numpy as np import scipy.stats a = np.array([ 1. , 2. , 2.5, 400. , 6. , 0. ]) </code> kurtosis_result = ... # put solution in this variable BEGIN SOLUTION <code>
kurtosis_result = scipy.stats.kurtosis(a)
import numpy as np import copy import scipy.stats def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: a = np.array([1.0, 2.0, 2.5, 400.0, 6.0, 0.0]) elif test_case_id == 2: np.random.seed(42) a = np.random.randn(10) ...
762
51
4Scipy
2
2Semantic
50
Problem: I have a table of measured values for a quantity that depends on two parameters. So say I have a function fuelConsumption(speed, temperature), for which data on a mesh are known. Now I want to interpolate the expected fuelConsumption for a lot of measured data points (speed, temperature) from a pandas.DataFram...
spl = scipy.interpolate.RectBivariateSpline(x, y, z) result = spl(s, t, grid=False)
import numpy as np import copy import scipy.interpolate def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: s = np.linspace(-1, 1, 50) t = np.linspace(-2, 0, 50) return s, t def generate_ans(data): _a = data ...
763
52
4Scipy
1
1Origin
52
Problem: I have a table of measured values for a quantity that depends on two parameters. So say I have a function fuelConsumption(speed, temperature), for which data on a mesh are known. Now I want to interpolate the expected fuelConsumption for a lot of measured data points (speed, temperature) from a pandas.DataFram...
spl = scipy.interpolate.RectBivariateSpline(x, y, z) result = spl(s, t, grid=False) return result
import numpy as np import copy import scipy.interpolate def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: s = np.linspace(-1, 1, 50) t = np.linspace(-2, 0, 50) return s, t def generate_ans(data): _a = data ...
764
53
4Scipy
1
3Surface
52
Problem: I think my questions has something in common with this question or others, but anyway, mine is not specifically about them. I would like, after having found the voronoi tessallination for certain points, be able to check where other given points sit within the tessellination. In particular: Given say 50 extra-...
kdtree = scipy.spatial.cKDTree(points) _, result = kdtree.query(extraPoints)
import numpy as np import copy import scipy.spatial def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: points = [[0, 0], [1, 4], [2, 3], [4, 1], [1, 1], [2, 2], [5, 3]] extraPoints = [[0.5, 0.2], [3, 0], [4, 0], [5, 0], [4, 3]] ...
765
54
4Scipy
2
1Origin
54
Problem: I think my questions has something in common with this question or others, but anyway, mine is not specifically about them. I would like, after having found the voronoi tessallination for certain points, be able to check where other given points sit within the tessellination. In particular: Given say 50 extra-...
kdtree = scipy.spatial.cKDTree(points) _, index = kdtree.query(extraPoints) result = vor.point_region[index]
import numpy as np import copy import scipy.spatial def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: points = [[0, 0], [1, 4], [2, 3], [4, 1], [1, 1], [2, 2], [5, 3]] extraPoints = [[0.5, 0.2], [3, 0], [4, 0], [5, 0], [4, 3]] ...
766
55
4Scipy
2
2Semantic
54
Problem: I have a list of numpy vectors of the format: [array([[-0.36314615, 0.80562619, -0.82777381, ..., 2.00876354,2.08571887, -1.24526026]]), array([[ 0.9766923 , -0.05725135, -0.38505339, ..., 0.12187988,-0.83129255, 0.32003683]]), array([[-0.59539878, 2.27166874, 0.39192573, ..., -0.73741573,...
result = sparse.lil_matrix((len(vectors), max_vector_size)) for i, v in enumerate(vectors): result[i, :v.size] = v
import numpy as np import copy import scipy.sparse as sparse def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: np.random.seed(10) max_vector_size = 1000 vectors = [ np.random.randint(100, size=900), ...
767
56
4Scipy
2
1Origin
56
Problem: I have a binary array, say, a = np.random.binomial(n=1, p=1/2, size=(9, 9)). I perform median filtering on it using a 3 x 3 kernel on it, like say, b = nd.median_filter(a, 3). I would expect that this should perform median filter based on the pixel and its eight neighbours. However, I am not sure about the pla...
b = scipy.ndimage.median_filter(a, size=(3, 3), origin=(0, 1))
import numpy as np import copy import scipy.ndimage def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: a = np.zeros((5, 5)) a[1:4, 1:4] = np.arange(3 * 3).reshape((3, 3)) return a def generate_ans(data): _a = data ...
768
57
4Scipy
1
1Origin
57
Problem: I have a sparse matrix in csr format (which makes sense for my purposes, as it has lots of rows but relatively few columns, ~8million x 90). My question is, what's the most efficient way to access a particular value from the matrix given a row,column tuple? I can quickly get a row using matrix.getrow(row), but...
result = M[row,column]
import numpy as np import copy import tokenize, io from scipy.sparse import csr_matrix def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: arr = np.array( [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] ) ...
769
58
4Scipy
2
1Origin
58
Problem: I have a sparse matrix in csr format (which makes sense for my purposes, as it has lots of rows but relatively few columns, ~8million x 90). My question is, what's the most efficient way to access particular values from the matrix given lists of row,column indices? I can quickly get a row using matrix.getrow(r...
result = np.array(M[row,column]).squeeze()
import numpy as np import copy import tokenize, io from scipy.sparse import csr_matrix def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: arr = np.array( [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] ) ...
770
59
4Scipy
2
2Semantic
58
Problem: I have an array which I want to interpolate over the 1st axes. At the moment I am doing it like this example: import numpy as np from scipy.interpolate import interp1d array = np.random.randint(0, 9, size=(100, 100, 100)) new_array = np.zeros((1000, 100, 100)) x = np.arange(0, 100, 1) x_new = np.arange(0, 100,...
new_array = scipy.interpolate.interp1d(x, array, axis=0)(x_new)
import numpy as np import copy import tokenize, io import scipy.interpolate def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: np.random.seed(42) array = np.random.randint(0, 9, size=(10, 10, 10)) x = np.linspace(0, 10, 10) ...
771
60
4Scipy
1
1Origin
60
Problem: I'm trying to integrate X (X ~ N(u, o2)) to calculate the probability up to position `x`. However I'm running into an error of: Traceback (most recent call last): File "<ipython console>", line 1, in <module> File "siestats.py", line 349, in NormalDistro P_inner = scipy.integrate(NDfx,-dev,dev) TypeEr...
norm = (x-u)/o2 prob = scipy.integrate.quad(NDfx, -np.inf, norm)[0]
import numpy as np import math import copy import scipy.integrate def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: x = 2.5 u = 1 o2 = 3 elif test_case_id == 2: x = -2.5 u = 2 o2 ...
772
61
4Scipy
2
1Origin
61
Problem: I'm trying to integrate X (X ~ N(u, o2)) to calculate the probability up to position `x`. However I'm running into an error of: Traceback (most recent call last): File "<ipython console>", line 1, in <module> File "siestats.py", line 349, in NormalDistro P_inner = scipy.integrate(NDfx,-dev,dev) TypeEr...
norm = (x-u)/o2 prob = scipy.integrate.quad(NDfx, -np.inf, norm)[0] return prob
import numpy as np import math import copy import scipy.integrate def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: x = 2.5 u = 1 o2 = 3 elif test_case_id == 2: x = -2.5 u = 2 o2 ...
773
62
4Scipy
2
3Surface
61
Problem: Using scipy, is there an easy way to emulate the behaviour of MATLAB's dctmtx function which returns a NxN (ortho-mode normed) DCT matrix for some given N? There's scipy.fftpack.dctn but that only applies the DCT. Do I have to implement this from scratch if I don't want use another dependency besides scipy? A...
result = sf.dct(np.eye(N), axis=0, norm= 'ortho')
import numpy as np import copy import scipy.fft as sf def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: N = 8 elif test_case_id == 2: np.random.seed(42) N = np.random.randint(4, 15) return N def generat...
774
63
4Scipy
2
1Origin
63
Problem: Having difficulty generating a tridiagonal matrix from numpy arrays. I managed to replicate the results given here, but I'm not able to apply these techniques to my problem. I may also be misunderstanding the application of scipy.sparse.diag. For context, I'm working on a problem which requires the generation ...
result = sparse.spdiags(matrix, (1, 0, -1), 5, 5).T.A
import numpy as np import copy from scipy import sparse def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: matrix = np.array( [ [3.5, 13.0, 28.5, 50.0, 77.5], [-5.0, -23.0, -53.0, -95.0, -149....
775
64
4Scipy
2
1Origin
64
Problem: Give the N and P, I want to get a 2D binomial distribution probability matrix M, for i in range(N+1): for j in range(i+1): M[i,j] = choose(i, j) * p**j * (1-p)**(i-j) other value = 0 I want to know is there any fast way to get this matrix, instead of the for loop. the N may be bigger than 100,000 A:...
n = np.arange(N + 1, dtype=np.int64) dist = scipy.stats.binom(p=p, n=n) result = dist.pmf(k=np.arange(N + 1, dtype=np.int64)[:, None]).T
import numpy as np import copy import tokenize, io import scipy.stats def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: N = 3 p = 0.5 elif test_case_id == 2: np.random.seed(234) N = np.random.randint(6, ...
776
65
4Scipy
2
1Origin
65
Problem: I have the following data frame: import pandas as pd import io from scipy import stats temp=u"""probegenes,sample1,sample2,sample3 1415777_at Pnliprp1,20,0.00,11 1415805_at Clps,17,0.00,55 1415884_at Cela3b,47,0.00,100""" df = pd.read_csv(io.StringIO(temp),index_col='probegenes') df It looks like this ...
result = pd.DataFrame(data=stats.zscore(df, axis = 1), index=df.index, columns=df.columns)
import pandas as pd import io import copy from scipy import stats def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: temp = """probegenes,sample1,sample2,sample3 1415777_at Pnliprp1,20,0.00,11 1415805_at Clps,17,0.00,55 1415884_at Cela3...
777
66
4Scipy
2
1Origin
66
Problem: I have the following data frame: import pandas as pd import io from scipy import stats temp=u"""probegenes,sample1,sample2,sample3 1415777_at Pnliprp1,20,0.00,11 1415805_at Clps,17,0.00,55 1415884_at Cela3b,47,0.00,100""" df = pd.read_csv(io.StringIO(temp),index_col='probegenes') df It looks like this ...
result = pd.DataFrame(data=stats.zscore(df, axis = 0), index=df.index, columns=df.columns)
import pandas as pd import io import copy from scipy import stats def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: temp = """probegenes,sample1,sample2,sample3 1415777_at Pnliprp1,20,0.00,11 1415805_at Clps,17,0.00,55 1415884_at Cela3...
778
67
4Scipy
2
2Semantic
66
Problem: I have the following data frame: import pandas as pd import io from scipy import stats temp=u"""probegenes,sample1,sample2,sample3 1415777_at Pnliprp1,20,0.00,11 1415805_at Clps,17,0.00,55 1415884_at Cela3b,47,0.00,100""" df = pd.read_csv(io.StringIO(temp),index_col='probegenes') df It looks like this ...
indices = [('1415777_at Pnliprp1', 'data'), ('1415777_at Pnliprp1', 'zscore'), ('1415805_at Clps', 'data'), ('1415805_at Clps', 'zscore'), ('1415884_at Cela3b', 'data'), ('1415884_at Cela3b', 'zscore')] indices = pd.MultiIndex.from_tuples(indices) df2 = pd.DataFrame(data=stats.zscore(df, axis = 1), index=df.index, colu...
import pandas as pd import io import copy from scipy import stats def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: temp = """probegenes,sample1,sample2,sample3 1415777_at Pnliprp1,20,0.00,11 1415805_at Clps,17,0.00,55 1415884_at Cela3...
779
68
4Scipy
2
0Difficult-Rewrite
66
Problem: I have the following data frame: import pandas as pd import io from scipy import stats temp=u"""probegenes,sample1,sample2,sample3 1415777_at Pnliprp1,20,0.00,11 1415805_at Clps,17,0.00,55 1415884_at Cela3b,47,0.00,100""" df = pd.read_csv(io.StringIO(temp),index_col='probegenes') df It looks like this ...
indices = [('1415777_at Pnliprp1', 'data'), ('1415777_at Pnliprp1', 'zscore'), ('1415805_at Clps', 'data'), ('1415805_at Clps', 'zscore'), ('1415884_at Cela3b', 'data'), ('1415884_at Cela3b', 'zscore')] indices = pd.MultiIndex.from_tuples(indices) df2 = pd.DataFrame(data=stats.zscore(df, axis = 0), index=df.index, colu...
import numpy as np import pandas as pd import io import copy from scipy import stats def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: temp = """probegenes,sample1,sample2,sample3 1415777_at Pnliprp1,20,0.00,11 1415805_at Clps,17,0.00,55 ...
780
69
4Scipy
2
0Difficult-Rewrite
66
Problem: I'm searching for examples of using scipy.optimize.line_search. I do not really understand how this function works with multivariable functions. I wrote a simple example import scipy as sp import scipy.optimize def test_func(x): return (x[0])**2+(x[1])**2 def test_grad(x): return [2*x[0],2*x[1]] sp.o...
result = scipy.optimize.line_search(test_func, test_grad, np.array(starting_point), np.array(direction))[0]
import numpy as np import copy import scipy.optimize def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: starting_point = [1.8, 1.7] direction = [-1, -1] elif test_case_id == 2: starting_point = [50, 37] d...
781
70
4Scipy
2
1Origin
70
Problem: I'm trying to create a 2-dimensional array in Scipy/Numpy where each value represents the euclidean distance from the center. I'm very new to Scipy, and would like to know if there's a more elegant, idiomatic way of doing the same thing. I found the scipy.spatial.distance.cdist function, which seems promising,...
xs, ys = np.indices(shape) xs = xs.reshape(shape[0] * shape[1], 1) ys = ys.reshape(shape[0] * shape[1], 1) X = np.hstack((xs, ys)) mid_x, mid_y = (shape[0]-1)/2.0, (shape[1]-1)/2.0 result = distance.cdist(X, np.atleast_2d([mid_x, mid_y])).reshape(shape)
import numpy as np import copy from scipy.spatial import distance def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: shape = (6, 6) elif test_case_id == 2: shape = (10, 3) elif test_case_id == 3: np.random.se...
782
71
4Scipy
3
1Origin
71
Problem: I'm trying to create a 2-dimensional array in Scipy/Numpy where each value represents the Manhattan distance from the center. It's supposed to have the same shape as the first two dimensions of a 3-dimensional array (an image, created via scipy.misc.fromimage). I'm very new to Scipy, and would like to know if ...
xs, ys = np.indices(shape) xs = xs.reshape(shape[0] * shape[1], 1) ys = ys.reshape(shape[0] * shape[1], 1) X = np.hstack((xs, ys)) mid_x, mid_y = (shape[0]-1)/2.0, (shape[1]-1)/2.0 result = distance.cdist(X, np.atleast_2d([mid_x, mid_y]), 'minkowski', p=1).reshape(shape)
import numpy as np import copy from scipy.spatial import distance def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: shape = (6, 6) elif test_case_id == 2: shape = (10, 3) elif test_case_id == 3: np.random.se...
783
72
4Scipy
3
2Semantic
71
Problem: I'm trying to create a 2-dimensional array in Scipy/Numpy where each value represents the euclidean distance from the center. It's supposed to have the same shape as the first two dimensions of a 3-dimensional array (an image, created via scipy.misc.fromimage). I'm very new to Scipy, and would like to know if ...
xs, ys = np.indices(shape) xs = xs.reshape(shape[0] * shape[1], 1) ys = ys.reshape(shape[0] * shape[1], 1) X = np.hstack((xs, ys)) mid_x, mid_y = (shape[0]-1)/2.0, (shape[1]-1)/2.0 result = distance.cdist(X, np.atleast_2d([mid_x, mid_y])).reshape(shape) return result
import numpy as np import copy from scipy.spatial import distance def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: shape = (6, 6) elif test_case_id == 2: shape = (10, 3) elif test_case_id == 3: np.random.se...
784
73
4Scipy
3
3Surface
71
Problem: I would like to resample a numpy array as suggested here Resampling a numpy array representing an image however this resampling will do so by a factor i.e. x = np.arange(9).reshape(3,3) print scipy.ndimage.zoom(x, 2, order=1) Will create a shape of (6,6) but how can I resample an array to its best approximatio...
result = scipy.ndimage.zoom(x, zoom=(shape[0]/x.shape[0], shape[1]/x.shape[1]), order=1)
import numpy as np import copy import scipy.ndimage def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: shape = (6, 8) elif test_case_id == 2: shape = (6, 10) elif test_case_id == 3: shape = (4, 6) eli...
785
74
4Scipy
4
1Origin
74
Problem: I am having a problem with minimization procedure. Actually, I could not create a correct objective function for my problem. Problem definition • My function: yn = a_11*x1**2 + a_12*x2**2 + ... + a_m*xn**2,where xn- unknowns, a_m - coefficients. n = 1..N, m = 1..M • In my case, N=5 for x1,..,x5 and M=3 for y1,...
def residual_ans(x, a, y): s = ((y - a.dot(x**2))**2).sum() return s out = scipy.optimize.minimize(residual_ans, x0=x0, args=(a, y), method= 'L-BFGS-B').x
import numpy as np import copy def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: np.random.seed(42) a = np.random.rand(3, 5) x_true = np.array([10, 13, 5, 8, 40]) y = a.dot(x_true**2) x0 = np.array([...
786
75
4Scipy
2
1Origin
75
Problem: I am having a problem with minimization procedure. Actually, I could not create a correct objective function for my problem. Problem definition • My function: yn = a_11*x1**2 + a_12*x2**2 + ... + a_m*xn**2,where xn- unknowns, a_m - coefficients. n = 1..N, m = 1..M • In my case, N=5 for x1,..,x5 and M=3 for y...
def residual_ans(x, a, y): s = ((y - a.dot(x**2))**2).sum() return s bounds = [[x, None] for x in x_lower_bounds] out = scipy.optimize.minimize(residual_ans, x0=x0, args=(a, y), method= 'L-BFGS-B', bounds=bounds).x
import numpy as np import copy import scipy.optimize def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: np.random.seed(42) a = np.random.rand(3, 5) x_true = np.array([10, 13, 5, 8, 40]) y = a.dot(x_true**2) ...
787
76
4Scipy
1
0Difficult-Rewrite
75
Problem: I'm trying to solve a simple ODE to visualise the temporal response, which works well for constant input conditions using the new solve_ivp integration API in SciPy. For example: def dN1_dt_simple(t, N1): return -100 * N1 sol = solve_ivp(fun=dN1_dt_simple, t_span=time_span, y0=[N0,]) However, I wonder is i...
def dN1_dt (t, N1): return -100 * N1 + np.sin(t) sol = scipy.integrate.solve_ivp(fun=dN1_dt, t_span=time_span, y0=[N0,])
import numpy as np import copy import scipy.integrate def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: N0 = 10 time_span = [-0.1, 0.1] return N0, time_span def generate_ans(data): _a = data N0, time_span =...
788
77
4Scipy
1
1Origin
77
Problem: I’m trying to solve a simple ODE to visualise the temporal response, which works well for constant input conditions using the new solve_ivp integration API in SciPy. For example: def dN1_dt_simple(t, N1): return -100 * N1 sol = solve_ivp(fun=dN1_dt_simple, t_span=[0, 100e-3], y0=[N0,]) However, I wonder is...
def dN1_dt(t, N1): input = 1-np.cos(t) if 0<t<2*np.pi else 0 return -100*N1 + input sol = scipy.integrate.solve_ivp(fun=dN1_dt, t_span=time_span, y0=[N0,])
import numpy as np import copy import scipy.integrate def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: N0 = 1 time_span = [0, 10] return N0, time_span def generate_ans(data): _a = data N0, time_span = _a ...
789
78
4Scipy
1
0Difficult-Rewrite
77
Problem: I’m trying to solve a simple ODE to visualise the temporal response, which works well for constant input conditions using the new solve_ivp integration API in SciPy. For example: def dN1_dt_simple(t, N1): return -100 * N1 sol = solve_ivp(fun=dN1_dt_simple, t_span=time_span, y0=[N0,]) However, I wonder is i...
def dN1_dt (t, N1): return -100 * N1 + np.sin(t) sol = scipy.integrate.solve_ivp(fun=dN1_dt, t_span=time_span, y0=[N0,])
import numpy as np import copy import scipy.integrate def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: N0 = 10 time_span = [-0.1, 0.1] return N0, time_span def generate_ans(data): _a = data N0, time_span =...
790
79
4Scipy
1
0Difficult-Rewrite
77
Problem: I'm using scipy.optimize.minimize to solve a complex reservoir optimization model (SQSLP and COBYLA as the problem is constrained by both bounds and constraint equations). There is one decision variable per day (storage), and releases from the reservoir are calculated as a function of change in storage, within...
def f(a): def g(x): return x[a] return g for t in range (4): cons.append({'type':'ineq', 'fun': f(t)})
import numpy as np import copy from scipy.optimize import minimize def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: I = np.array((20, 50, 50, 80)) return I def generate_ans(data): _a = data def function(x): ...
791
80
4Scipy
1
1Origin
80
Problem: I have problems using scipy.sparse.csr_matrix: for instance: a = csr_matrix([[1,2,3],[4,5,6]]) b = csr_matrix([[7,8,9],[10,11,12]]) how to merge them into [[1,2,3],[4,5,6],[7,8,9],[10,11,12]] I know a way is to transfer them into numpy array first: csr_matrix(numpy.vstack((a.toarray(),b.toarray()))) but it won...
result = sparse.vstack((sa, sb)).tocsr()
import copy import tokenize, io from scipy import sparse def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: sa = sparse.random(10, 10, density=0.01, format="csr", random_state=42) sb = sparse.random(10, 10, density=0.01, format="csr", r...
792
81
4Scipy
1
1Origin
81
Problem: I have problems using scipy.sparse.csr_matrix: for instance: a = csr_matrix([[1,2,3],[4,5,6]]) b = csr_matrix([[7,8,9],[10,11,12]]) how to merge them into [[1,2,3,7,8,9],[4,5,6,10,11,12]] I know a way is to transfer them into numpy array first: csr_matrix(numpy.hstack((a.toarray(),b.toarray()))) but it won't w...
result = sparse.hstack((sa, sb)).tocsr()
import copy import tokenize, io from scipy import sparse def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: sa = sparse.random(10, 10, density=0.01, format="csr", random_state=42) sb = sparse.random(10, 10, density=0.01, format="csr", r...
793
82
4Scipy
1
2Semantic
81
Problem: I would like to write a program that solves the definite integral below in a loop which considers a different value of the constant c per iteration. I would then like each solution to the integral to be outputted into a new array. How do I best write this program in python? ∫2cxdx with limits between 0 and 1. ...
result = scipy.integrate.quadrature(lambda x: 2*c*x, low, high)[0]
import numpy as np import copy import scipy.integrate def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: c = 5 low = 0 high = 1 return c, low, high def generate_ans(data): _a = data c, low, high ...
794
83
4Scipy
1
1Origin
83
Problem: I would like to write a program that solves the definite integral below in a loop which considers a different value of the constant c per iteration. I would then like each solution to the integral to be outputted into a new array. How do I best write this program in python? ∫2cxdx with limits between 0 and 1. ...
result = scipy.integrate.quadrature(lambda x: 2*c*x, low, high)[0] return result
import numpy as np import copy import scipy.integrate def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: c = 5 low = 0 high = 1 return c, low, high def generate_ans(data): _a = data c, low, high ...
795
84
4Scipy
1
3Surface
83
Problem: First off, I'm no mathmatician. I admit that. Yet I still need to understand how ScyPy's sparse matrices work arithmetically in order to switch from a dense NumPy matrix to a SciPy sparse matrix in an application I have to work on. The issue is memory usage. A large dense matrix will consume tons of memory. Th...
V._update(zip(V.keys(), np.array(list(V.values())) + x))
import numpy as np import copy from scipy import sparse def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: V = sparse.random(10, 10, density=0.05, format="dok", random_state=42) x = 99 elif test_case_id == 2: V = spa...
796
85
4Scipy
2
1Origin
85
Problem: First off, I'm no mathmatician. I admit that. Yet I still need to understand how ScyPy's sparse matrices work arithmetically in order to switch from a dense NumPy matrix to a SciPy sparse matrix in an application I have to work on. The issue is memory usage. A large dense matrix will consume tons of memory. Th...
V.data += x
import copy from scipy import sparse def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: V = sparse.random(10, 10, density=0.05, format="coo", random_state=42) x = 100 elif test_case_id == 2: V = sparse.random(15, 15,...
797
86
4Scipy
2
2Semantic
85
Problem: First off, I'm no mathmatician. I admit that. Yet I still need to understand how ScyPy's sparse matrices work arithmetically in order to switch from a dense NumPy matrix to a SciPy sparse matrix in an application I have to work on. The issue is memory usage. A large dense matrix will consume tons of memory. Th...
V = V.copy() V.data += x V.eliminate_zeros() V.data += y V.eliminate_zeros()
import numpy as np import copy from scipy import sparse def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: V = sparse.random(10, 10, density=0.05, format="coo", random_state=42) x = 100 y = 99 elif test_case_id == 2:...
798
87
4Scipy
2
0Difficult-Rewrite
85
Problem: Basically, I am just trying to do a simple matrix multiplication, specifically, extract each column of it and normalize it by dividing it with its length. #csc sparse matrix self.__WeightMatrix__ = self.__WeightMatrix__.tocsc() #iterate through columns for Col in xrange(self.__WeightMatrix__.sh...
sa = sparse.csc_matrix(sa.toarray() / np.sqrt(np.sum(sa.toarray()**2, axis=0)))
import numpy as np import copy from scipy import sparse def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: sa = sparse.random(10, 10, density=0.3, format="csc", random_state=42) return sa def generate_ans(data): _a = data ...
799
88
4Scipy
1
1Origin
88