Exemplo n.º 1
0
    def fit(self, X, Y):
        """
        Train a linear classifier using the perceptron learning algorithm.

        Note that this will only work if X is a sparse matrix, such as the
        output of a scikit-learn vectorizer.
        """
        self.find_classes(Y)

        # First determine which output class will be associated with positive
        # and negative scores, respectively.
        Ye = self.encode_outputs(Y)

        # Initialize the weight vector to all zeros.
        self.w = np.zeros(X.shape[1])

        X = X.toarray()

        # Iteration through sparse matrices can be a bit slow, so we first
        # prepare this list to speed up iteration.
        XY = list(zip(X, Ye))

        lam = 1 / len(Y)
        for i in range(1, self.n_iter):
            x, y = random.choice(XY)
            n = 1 / (lam * i)
            score = blas.ddot(x, self.w)
            self.w = (1 - n * lam) * self.w
            if score * y < 1:
                a = n * y
                blas.daxpy(x, self.w, a=a)
Exemplo n.º 2
0
    def _solve(self, b, tol):
        import numpy as np
        from scipy.linalg.blas import dasum, daxpy, ddot

        A = self._A
        M = self._M
        tol *= dasum(b)
        # Initialize.
        x = np.zeros(b.shape)
        r = b.copy()
        z = M(r)
        rz = ddot(r, z)
        p = z.copy()
        # Iterate.
        while True:
            Ap = A(p)
            alpha = rz / ddot(p, Ap)
            x = daxpy(p, x, a=alpha)
            r = daxpy(Ap, r, a=-alpha)
            if dasum(r) < tol:
                return x
            z = M(r)
            beta = ddot(r, z)
            beta, rz = beta / rz, beta
            p = daxpy(p, z, a=beta)
Exemplo n.º 3
0
Arquivo: core.py Projeto: dwtang/scarf
def _update_A_b_blas(A, b, row, pivot):
    """Subtract a multiple of the row A[row, :] from all other rows.

  Implemented with BLAS routines wrapped by scipy.
  """
    x = np.copy(A[:, pivot])
    x[row] = 0.0  # mask this row
    blas.daxpy(x=x, y=b, a=-b[row])  # y += a * x
    # A += alpha * x * A[row, :]; do it in transpose since A is in C-order.
    blas.dger(alpha=-1.0, x=A[row, :], y=x, a=A.T, overwrite_a=1)
Exemplo n.º 4
0
    def merge(self, other):

        assert other.k == self.k
        self.ata = \
            daxpy(other.ata, self.ata, n=self.ata.shape[0], a=1.0, incx=1, incy=1)

        self.atb =\
            daxpy(other.atb, self.atb, n=self.atb.shape[0], a=1.0, incx=1, incy=1)

        return self
Exemplo n.º 5
0
 def P(x):
     x -= asarray(x * X * X.T)[0, :]
     if not normalized:
         x -= x.sum() / n
     else:
         x = daxpy(e, x, a=-ddot(x, e))
     return x
Exemplo n.º 6
0
 def P(x):
     x -= asarray(x * X * X.T)[0, :]
     if not normalized:
         x -= x.sum() / n
     else:
         x = daxpy(e, x, a=-ddot(x, e))
     return x
Exemplo n.º 7
0
    def add(self, a, b, c=1.0):
        assert c > 0
        assert a.shape[0] == self.k
        self.copy(a)

        # print "before dspr----------\nata {}".format(self.ata)
        # print "da-------da {}".format(self.da)

        # use ata as return?
        self.ata = dspr(n=self.k,
                        alpha=c,
                        x=self.da,
                        incx=1,
                        ap=self.ata,
                        lower=1)

        # print "after dspr ==========\nata {}".format(self.ata)
        if b != 0:
            # print "before daxpy ---------\natb {}".format(self.atb)
            self.atb = daxpy(x=self.da,
                             y=self.atb,
                             n=self.k,
                             a=b,
                             incx=1,
                             incy=1)
            # print "after daxpy ==========\n atb {}".format(self.atb)

        return self
Exemplo n.º 8
0
 def _solve(self, b, tol):
     A = self._A
     M = self._M
     tol *= dasum(b)
     # Initialize.
     x = zeros(b.shape)
     r = b.copy()
     z = M(r)
     rz = ddot(r, z)
     p = z.copy()
     # Iterate.
     while True:
         Ap = A(p)
         alpha = rz / ddot(p, Ap)
         x = daxpy(p, x, a=alpha)
         r = daxpy(Ap, r, a=-alpha)
         if dasum(r) < tol:
             return x
         z = M(r)
         beta = ddot(r, z)
         beta, rz = beta / rz, beta
         p = daxpy(p, z, a=beta)
 def _solve(self, b, tol):
     A = self._A
     M = self._M
     tol *= dasum(b)
     # Initialize.
     x = zeros(b.shape)
     r = b.copy()
     z = M(r)
     rz = ddot(r, z)
     p = z.copy()
     # Iterate.
     while True:
         Ap = A(p)
         alpha = rz / ddot(p, Ap)
         x = daxpy(p, x, a=alpha)
         r = daxpy(Ap, r, a=-alpha)
         if dasum(r) < tol:
             return x
         z = M(r)
         beta = ddot(r, z)
         beta, rz = beta / rz, beta
         p = daxpy(p, z, a=beta)
Exemplo n.º 10
0
def rand_fourier_series_1d(x, kmax, density=1, rand=None):
    """
    Parameters
    ----------
    x : array-like
        Arry of positions (arbitrary dimension)
    kmax : int
        Maximum wavenumber (integer form)
    density : float (default: 1)
        Fraction of modes up to cutoff to populate
    rand : np.random.RandomState or None (default: None)
        Random state, needed for determinism
        
    Returns
    -------
    f : array-like
        Values of the random function F(x)
    """
    if rand is None:
        rand = np.random.RandomState()
    flags = rand.rand(kmax + 1)
    n = 0
    f = np.zeros_like(x)
    kx = np.zeros_like(x)
    g = np.zeros_like(x)
    for k, flag in enumerate(flags):
        if flag < density:
            a, b = rand.randn(2)
            np.multiply((2 * np.pi * k), x, out=kx)
            np.cos(kx, out=g)
            daxpy(g, f, a=a)
            np.sin(kx, out=g)
            daxpy(g, f, a=b)
            n += 1
    f /= n**0.5
    return f
Exemplo n.º 11
0
def run_daxpy(N, l):

    x = randn(N).astype('float64')
    y = randn(N).astype('float64')

    start = time.time()
    for i in range(0, l):
        y = daxpy(x, y, a=2.0)
    end = time.time()

    timediff = (end - start)
    mflops = (2 * N) * l / timediff
    mflops *= 1e-6

    size = "%d" % (N)
    print("%14s :\t%20f MFlops\t%20f sec" % (size, mflops, timediff))
Exemplo n.º 12
0
def run_daxpy(N, l):

    x = randn(N).astype("float64")
    y = randn(N).astype("float64")

    start = time.time()
    for i in range(0, l):
        y = daxpy(x, y, a=2.0)
    end = time.time()

    timediff = end - start
    mflops = (2 * N) * l / timediff
    mflops *= 1e-6

    size = "%d" % (N)
    print("%14s :\t%20f MFlops\t%20f sec" % (size, mflops, timediff))
Exemplo n.º 13
0
                                                          -sequence_len:])
    predicted_freq_slices = np.append(predicted_freq_slices,
                                      pred_next_slice,
                                      axis=0)

# Convert back to (real,imag) complex representation in freq domain
predicted_freq_slices_unflattened = \
     np.reshape(predicted_freq_slices, (-1, freq_dim//2, 2)).view('complex64').reshape(-1, freq_dim//2).astype('complex128')

# Apply inverse FFT to get back time-domain windows
pred_time_slices = np.fft.irfft(predicted_freq_slices_unflattened)

# Reassemble full time domain signal by adding overlapping windows
reassembled = np.zeros(window_size + (len(pred_time_slices) - 1) * slide)
for i in range(0, len(pred_time_slices)):
    daxpy(pred_time_slices[i], reassembled, offy=slide * i)

# Plot some of the first generated time-domain data as a check
plot_sample_base = sequence_len * slide
plt.plot(reassembled[plot_sample_base:plot_sample_base + window_size])
plt.show()

# Scale time-domain data to have max at 32767, for 16-bit wav output
reassembled_scale = np.max(np.abs(reassembled))
reassembled = reassembled * (32767 / reassembled_scale)

print("Spectrum of output audio")
specgram = plt.specgram(reassembled, NFFT=window_size, Fs=slide)
plt.show()

# Overwrite output to out.wav
Exemplo n.º 14
0
 def merge(self, ne):
     self.ata = blas.daxpy(self.ata, ne.ata)
     self.atb = blas.daxpy(self.atb, ne.atb)
Exemplo n.º 15
0
 def add(self, a, b, c=1.0):
     self.dspr(self.upper, self.k, 1.0, a, 1, self.ata)
     if b != 0:
         self.atb = blas.daxpy(a, self.atb, a=c * b)
Exemplo n.º 16
0
print ("numpy no memopt", t3-t2)



t2 = time.time()
for i in range(N):
    out_scipy = saxpy(a,b,a=A)
t3 = time.time()
print ("scipy saxpy", t3-t2)

af = numpy.asfortranarray(a)
bf = numpy.asfortranarray(b)
print ("af.shape", af.shape, "a.shape", a.shape, "af.dtype", af.dtype)
t2 = time.time()
for i in range(N):
    out_scipy_f = daxpy(af,bf,a=A)
t3 = time.time()
print ("scipy saxpy fortran", t3-t2)


out_nfrom = n_axpby(a,b,A,B)
t2 = time.time()
for i in range(1):
    out_nfrom = n_axpby(a,b,A,B)
t3 = time.time()
print ("numpy frompyfunc", t3-t2)

from itertools import chain

out_map =  numpy.fromiter(chain.from_iterable(map(lambda y: A * y[0] + B * y[1], zip(a,b))), dtype=a.dtype).reshape(a.shape)
t2 = time.time()
Exemplo n.º 17
0
            for j in range(i, self.rank):
                self.ata[i][j] = triAtA[pos]
                self.ata[j][i] = triAtA[pos]
                if i == j:
                    self.ata[i][j] += regParam
                pos += 1

    def solve(self, ne, regParam):
        self.constructSymmeticAtA(ne.ata, regParam)
        x = nnls(self.ata, ne.atb)
        ne.reset()
        return list(x[0])


if __name__ == "__main__":
    A = [[1, 3], [3, 9]]
    b = [1, 3]
    print nnls(A, b)
    print blas.daxpy([1, 3], [1, 1], a=0.5)
    solver = NNLS(3)
    solver.constructSymmeticAtA([1, 4, 5, 2, 6, 3], 0.5)
    print solver.ata

    encoder = localIndexEncoder(5)

    for i in range(5):
        for j in range(5):
            encoded = encoder.encode(i, j)
            print encoded, (i, j) == (encoder.getblockId(encoded),
                                      encoder.getlocalIdx(encoded))
Exemplo n.º 18
0
from scipy.linalg.blas import (dasum, daxpy, ddot)

n=3000
x=np.array([float(i+1) for i in range(n)])

y=np.zeros(n)
for i in range(n):
    y[i]=float(i*i)

alpha=0.8
z=y.copy()

t=timeit.default_timer()
for i in range(10000) :
    for j in range(len(y)):
        y[j]+=alpha*x[j]
print "Time for native python vector combination:", timeit.default_timer()-t

y[:]=z[:]
t=timeit.default_timer()
for i in range(10000) :
    y[:]+= alpha*x[:]
print "Time for numpy vector combination:        ", timeit.default_timer()-t

y[:]=z[:]
t=timeit.default_timer()
for i in range(10000) :
    y = daxpy(x, y, a=alpha)
print "Time for BLAS vector combination:         ", timeit.default_timer()-t