I want to do a product of a matrix M x N (M timestamps with N fractures each) and a vector M x 1 to get a vector of size N x 1, so the timestamp dimension is eliminated. How can I do that?
An example:
import keras.backend as K
a = K.constant([[1,2,3],[1,2,3]])
print(a.shape)
b = K.constant([[1],[2]])
print(b.shape)
result = K.dot(K.transpose(a),b)
print(result.shape)
print(K.eval(result))
# print
(2, 3)
(2, 1)
(3, 1)
[[3.]
[6.]
[9.]]
Related
This question already has an answer here:
Haskell get all the numbers whose sum is X
(1 answer)
Closed last year.
I'm Trying to create a program that finds every paritions of a number.
For example the ways to decompose 4 are:
[1, 1, 1, 1]
[1, 1, 2]
[1, 3]
[2, 2]
[4]
I've done it in Python with:
n = 4
x = [0 for i in range(n+1)]
t = [0 for i in range(n+1)]
x[0] = 1
def partition(i):
for j in range(x[i-1], (n - t[i-1])//2 + 1):
x[i] = j
t[i] = t[i-1] + j
partition(i+1)
x[i] = n - t[i-1]
print(x[1:i+1])
partition(1)
But i need to write it in Haskell. Is there any way?
Here's a hint:
It will be valuable to reverse the order while thinking about this, so you are trying to generate:
[1, 1, 1, 1]
[2, 1, 1]
[2, 2]
[3, 1]
[4]
So, first choose every possible first element, here 1, 2, 3, or 4. Say we've chosen 1, then there are 3 remaining. We can recursively compute all the partitions of 3, and then prepend 1 to each of them.
(Oh, that's not quite right! Still a good place to start. But you will have e.g. [1,2,1] generated, so you will need to add a parameter, I think, saying "don't generate any numbers greater than m")
And we have to make sure to get the base case right. How many partitions are there of 0? There is one, the empty partition!
You can also translate it very literally using mutable vectors. The main difference is that you need to separate reads and writes very explicitly in Haskell, so it becomes a bit more messy.
This is what I came up with without understanding your algorithm:
import Data.Foldable ( for_ )
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Unboxed.Mutable as M
main :: IO ()
main = do
let n = 4
x <- M.replicate (n + 1) 0
t <- M.replicate (n + 1) 0
M.write x 0 1
let partition i = do
x' <- M.read x (i - 1)
t' <- M.read t (i - 1)
for_ [x' .. (n - t') `quot` 2] $ \j -> do
M.write x i j
t' <- M.read t (i - 1)
M.write t i (t' + j)
partition (i + 1)
t' <- M.read t (i - 1)
M.write x i (n - t')
x' <- V.freeze (M.slice 1 i x)
print (V.toList x')
partition 1
So I am trying to refresh my knowledge. I tried finding the answer to this question here and I am not still not sure how to answer this.
Basically if I have a 2D index array (call it a) of shape (x, z) and a 3D array (call it b) of shape (x, y, z), then I want a 2D array (call it c) which has the property that the i,j element of c, c[i, j] = b[i, a[i, j], j]. Shape of c is (x, z)
To summarize:
a.shape = (x, z)
b.shape = (x, y, z)
c[i, j] = b[i, a[i, j], j]
c.shape = (x, z)
I tried to use the following code, but did not get the results I desire.
import numpy as np
input = numpy.random.randn(3, 5, 10)
target_np = np.random.randint(high = 5, low = 1, size = (3, 10))
q = input[:, np.ravel(target_np),:]
print(q.shape)
The result was
(3, 30, 10)
I am trying to rotate some seismic data held in a numpy nd-array. This array has dimensions (N-receiver, M-sources,3-source_channels, 3-receiver channels, K-time channels).
I know how to set up the rotation if applied to a single time stamp (t_i) over a single receiver & single source station. The actual Z, R, T, N, E, notation isn't important for the general problem, just know that the transformation is defined like so:
In python, for a single timestamp I'd probably code up something like:
import numpy as np
a = 50.0 # example alpha
b = 130 # example beta
a_rotation = np.asarray([[1,0,0],[0,np.cos(a),np.sin(a)],[0,-np.sin(a),np.cos(a)]])
b_rotation = np.asarray([[1,0,0],[0,-np.cos(b),-np.sin(b)],[0,np.sin(b),-np.cos(b)]])
# pretend the zn's are actual float data
single_timeslice_data = np.asarray([[zz,zn,ze],[nz,nn,ne],[ez,en,ee]])
# operation w numpy matrix rotation
rotated_channels = a_rotation # single_timeslice_data # b_rotation
So my question is twofold:
How do I apply this matrix product with numpy over all timesteps?
ex: (3 x 3) * (3 x 3 x K) * (3 x 3)
How do I do this matrix product with numpy when there may be an arbitrary number of other dimensions?
ex: (3 x 3) * (N x M x 3 x 3 x K) * (3 x 3)
1)
(3 x 3) * (3 x 3 * K) * (3 * 3) = (3 x 3 x K)
np.einsum('ab,bcK,cd->adK', Arr1, Arr2, Arr3)
2)
(3 x 3) * (N x M x 3 x 3 x K) * (3 x 3) = (N x M x 3 x 3 x K)
np.einsum('ab,NMbcK,cd->NMadK', Arr1, Arr2, Arr3)
My current code is below. I think all of the functions, except for the last one are correct. What I'm trying to achieve with changeValueMatrix is to give a matrix, a matrix position and a value and then that value will replace the one that is at the current position. I've managed to reach the position and to change the value but I can only return the row on which I changed it and not the whole matrix. I am a Haskell beginner and I've only learned recursion just now but it would be ideal to use it here if possible.
type Matrix a = [[a]]
type MatrixDimension = (Int,Int)
type MatrixPosition = (Int,Int)
matrixDimension :: Matrix a -> MatrixDimension
matrixDimension m = (length m, length (head m))
returnValueList :: Int -> [a] -> a
returnValueList 0 (x:xs) = x
returnValueList i(x:xs) = returnValue (i-1)(xs)
changeValueList :: Int -> a -> [a] -> [a]
changeValueList 0 value (x:xs) = (value:xs)
changeValueList i value (x:xs) = x:(changeValueList (i-1) (value) (xs))
returnValueMatrix :: MatrixPosition-> Matrix a -> a
returnValueMatrix(m,n) matrix = returnValueList n (returnreturnValueList matrix)
changeValueMatrix :: MatrixPosition -> a -> Matrix a -> Matrix a
changeValueMatrix(0,c) value (x:xs) = a:xs
where a = changeValueList c value x
changeValueMatrix(r,c) valor (x:xs) =
where
row = returnValueList r (x:xs)
b = changeValueList c value row
You can build changeValueMatrix from the functions you’ve already defined:
changeValueMatrix :: MatrixPosition -> a -> Matrix a -> Matrix a
changeValueMatrix (r, c) value matrix
= changeValueList r -- (3)
(changeValueList c value -- (2)
(returnValueList r matrix)) -- (1)
matrix
At (1) you look up the row at index r in matrix, at (2) you replace the element at column c in that row with value, and at (3) you replace the row at index r in matrix with the modified row. For example:
-- Given: mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
changeValueMatrix (1, 1) 0 mat
==
changeValueList 1
(changeValueList 1 0
(returnValueList 1 mat))
mat
==
changeValueList 1
(changeValueList 1 0 [4, 5, 6])
mat
==
changeValueList 1 [4, 0, 6] mat
==
[ [1, 2, 3]
, [4, 0, 6]
, [7, 8, 9]
]
If you want a version of this using explicit recursion, which only traverses the rows once, you can inline the definition of changeValueList into changeValueMatrix:
changeValueMatrix (0, c) value (x : xs)
= changeValueList c value x : xs
changeValueMatrix (r, c) value (x : xs)
= x : changeValueMatrix (r - 1, c) value xs
Be aware that your code has a few failure cases, though:
Negative indices will produce infinite loops because you only test for 0 and recur with i - 1 on any other number
Overly large indices will run into the end of the list and crash because you don’t handle the [] case—the pattern matches are non-exhaustive, which the compiler will point out when enabling all warnings with -Wall
Similarly, matrices of zero width or height are representable, but these functions don’t handle the possibility (e.g. matrixDimension calls head on a possibly-empty list); you can avoid this using Data.List.NonEmpty or Data.Array as your backing type, the latter of which is also more efficient
Let S be the subset of the set of ordered pairs of integers defined recursively by
Basis step: (0, 0) ∈ S.
Recursive step: If (a,b) ∈ S,
then (a,b + 1) ∈ S, (a + 1, b + 1) ∈ S, and (a + 2, b + 1) ∈ S.
List the elements of S produced by the first four application
def subset(a,b):
base=[]
if base == []:
base.append((a,b))
return base
elif (a,b) in base:
base.append(subset(a,b+1))
base.append(subset(a+1,b+1))
base.append(subset(a+2,b+1))
return base
for number in range(0,5):
for number2 in range(0,5):
print(*subset(number,number2))
The output is
(0, 0)
(0, 1)
(0, 2)
(0, 3)
(0, 4)
(1, 0)
(1, 1)
(1, 2)
(1, 3)
(1, 4)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 0)
(3, 1)
(3, 2)
(3, 3)
(3, 4)
(4, 0)
(4, 1)
(4, 2)
(4, 3)
(4, 4)
But the correct answer is more than what I got.
(0, 1), (1, 1), and (2, 1) are all in S. If we apply the recursive step to these we add (0, 2), (1, 2), (2, 2), (3, 2), and (4, 2). The next round gives us (0, 3), (1, 3), (2, 3), (3, 3), (4, 3), (5, 3), and (6, 3). And a fourth set of applications adds (0,4), (1,4), (2,4), (3,4), (4,4), (5,4), (6,4), (7,4), and (8,4).
What did I do wrong with my code?
Is this what you want ? Based on the result you wanted :
def subset(a):
#Returns a list that contains all (i, a + 1) from i = 0 to i = (a + 1) * 2 + 1
return [(i, a + 1) for i in range((a + 1) * 2 + 1)]
setList = []
for i in range(4):
setList += subset(i) #Fill a list with subset result from i = 0 -> 3
print(setList)
If you want to use a recursive function, you can do that too :
def subset(a, b):
if a < b * 2:
#Returns a list that contains (a, b) and unzipped result of subset(a + 1, b)
#Otherwise it would add a list in the list
return [(a, b), *subset(a + 1, b)]
else:
return [(a, b)] #If deepest element of recursion, just return [(a, b)]
setList = []
for i in range(5):
setList += subset(0, i)
print(setList)