CPN ML: how do i get a product containing a certain element, from a list - ml

I'm trying to make a function with arguments a and bs, that will check if list bs contains a product whos first element is a.
If list bs contains a product whos first element is a, then that product is returned.
The function is giving a nondescriptive error relating to a file "evalloop.sml".
fun matchFirstElement ([], _) = ("V70",["2.4T","V70a1"],(20,25),"MT1") |
matchFirstElement (b::bs, a) = if (a = #1 b) then b else getProdRule(bs, a);

Related

Function that multiplies element of a list/array by a number in python

I want to create a function that receives an array or a list , and then multiply each element by a Integer number, for example 5.
Def Multiply ( ListOrArray )
...
#Return another list with the same quantity of elements but multiplied by 5.
Functional programming in Python makes it quite easy to implement, as you can see in the following snippet:
my_numbers = [1,2,3,4,5]
results = list(map(lambda x: x*5, my_numbers))
print(results)
More information about map, lambda and related functions:
https://www.learnpython.org/en/Map,_Filter,_Reduce
Probably you could try the following
list = [1,2,3]
def multiplier (a):
b =[]
for i in list:
i = i*5
b.append(i)
return b
a=list
print(multiplier(a))
or
def multiplier(*args):
b=[]
for a in args:
a = a*5
b.append(a)
return b
print(multiplier(5,6,7))

how to iteratively pick out one attribute in an object, and stack the rest attributes into an array, Python3

I have an object with a, b, c, d four attributes. Each attribute is a vector.
I want to pick one attribute out and assemble the rest attributes into an 2-dimensional array. And do it for every attribute.
For example:
import numpy as np
class Obj:
def __init__(self, a, b, c, d):
self.a = a
self.b = b
self.c = c
self.d = d
b = np.array([1,1,1,1,1])
a = 0*b
c = 2*b
d = 3*b
obj1 = Obj(a, b, c, d)
# take attribute a for example
pick = obj1.a
x = np.column_stack((obj1.b, obj1.c, obj1.d))
# then pick attribute b, c, and d, one at a time, and assemble the rest.
Is there a way to iterate over all attributes? Because in real case, there may be 40 attributes.
Thanks

What would be an idiomatic F# way to scale a list of (n-tuples or list) with another list, also arrays?

Given:
let weights = [0.5;0.4;0.3]
let X = [[2;3;4];[7;3;2];[5;3;6]]
what I want is: wX = [(0.5)*[2;3;4];(0.4)*[7;3;2];(0.3)*[5;3;6]]
would like to know an elegant way to do this with lists as well as with arrays. Additional optimization information is welcome
You write about a list of lists, but your code shows a list of tuples. Taking the liberty to adjust for that, a solution would be
let weights = [0.5;0.4;0.3]
let X = [[2;3;4];[7;3;2];[5;3;6]]
X
|> List.map2 (fun w x ->
x
|> List.map (fun xi ->
(float xi) * w
)
) weights
Depending on how comfortable you are with the syntax, you may prefer a oneliner like
List.map2 (fun w x -> List.map (float >> (*) w) x) weights X
The same library functions exist for sequences (Seq.map2, Seq.map) and arrays (in the Array module).
This is much more than an answer to the specific question but after a chat in the comments and learning that the question was specifically a part of a neural network in F# I am posting this which covers the question and implements the feedforward part of a neural network. It makes use of MathNet Numerics
This code is an F# translation of part of the Python code from Neural Networks and Deep Learning.
Python
def backprop(self, x, y):
"""Return a tuple ``(nabla_b, nabla_w)`` representing the
gradient for the cost function C_x. ``nabla_b`` and
``nabla_w`` are layer-by-layer lists of numpy arrays, similar
to ``self.biases`` and ``self.weights``."""
nabla_b = [np.zeros(b.shape) for b in self.biases]
nabla_w = [np.zeros(w.shape) for w in self.weights]
# feedforward
activation = x
activations = [x] # list to store all the activations, layer by layer
zs = [] # list to store all the z vectors, layer by layer
for b, w in zip(self.biases, self.weights):
z = np.dot(w, activation)+b
zs.append(z)
activation = sigmoid(z)
activations.append(activation)
F#
module NeuralNetwork1 =
//# Third-party libraries
open MathNet.Numerics.Distributions // Normal.Sample
open MathNet.Numerics.LinearAlgebra // Matrix
type Network(sizes : int array) =
let mutable (_biases : Matrix<double> list) = []
let mutable (_weights : Matrix<double> list) = []
member __.Biases
with get() = _biases
and set value =
_biases <- value
member __.Weights
with get() = _weights
and set value =
_weights <- value
member __.Backprop (x : Matrix<double>) (y : Matrix<double>) =
// Note: There is a separate member for feedforward. This one is only used within Backprop
// Note: In the text layers are numbered from 1 to n with 1 being the input and n being the output
// In the code layers are numbered from 0 to n-1 with 0 being the input and n-1 being the output
// Layers
// 1 2 3 Text
// 0 1 2 Code
// 784 -> 30 -> 10
let feedforward () : (Matrix<double> list * Matrix<double> list) =
let (bw : (Matrix<double> * Matrix<double>) list) = List.zip __.Biases __.Weights
let rec feedfowardInner layer activation zs activations =
match layer with
| x when x < (__.NumLayers - 1) ->
let (bias, weight) = bw.[layer]
let z = weight * activation + bias
let activation = __.Sigmoid z
feedfowardInner (layer + 1) activation (z :: zs) (activation :: activations)
| _ ->
// Normally with recursive functions that build list for returning
// the final list(s) would be reversed before returning.
// However since the returned list will be accessed in reverse order
// for the backpropagation step, we leave them in the reverse order.
(zs, activations)
feedfowardInner 0 x [] [x]
In weight * activation * is an overloaded operator operating on Matrix<double>
Related back to your example data and using MathNet Numerics Arithmetics
let weights = [0.5;0.4;0.3]
let X = [[2;3;4];[7;3;2];[5;3;6]]
first the values for X need to be converted to float
let x1 = [[2.0;3.0;4.0];[7.0;3.0;2.0];[5.0;3;0;6;0]]
Now notice that x1 is a matrix and weights is a vector
so we can just multiply
let wx1 = weights * x1
Since the way I validated the code was a bit more than most I will explain it so that you don't have doubts to its validity.
When working with Neural Networks and in particular mini-batches, the starting numbers for the weights and biases are random and the generation of the mini-batches is also done randomly.
I know the original Python code was valid and I was able to run it successfully and get the same results as indicated in the book, meaning that the initial successes were within a couple of percent of the book and the graphs of the success were the same. I did this for several runs and several configurations of the neural network as discussed in the book. Then I ran the F# code and achieved the same graphs.
I also copied the starting random number sets from the Python code into the F# code so that while the data generated was random, both the Python and F# code used the same starting numbers, of which there are thousands. I then single stepped both the Python and F# code to verify that each individual function was returning a comparable float value, e.g. I put a break point on each line and made sure I checked each one. This actually took a few days because I had to write export and import code and massage the data from Python to F#.
See: How to determine type of nested data structures in Python?
I also tried a variation where I replaced the F# list with Linked list, but found no increase in speed, e.g. LinkedList<Matrix<double>>. Was an interesting exercise.
If I understand correctly,
let wX = weights |> List.map (fun w ->
X |> List.map (fun (a, b, c) ->
w * float a,
w * float b,
w * float c))
This is an alternate way to achieve this using Math.Net: https://numerics.mathdotnet.com/Matrix.html#Arithmetics

Perl: array splitting and complex merging

I have the following string A B C D E F G H I J. I want to make an array out of it, so I use this
my #string = split/(\W)/, $text;
It works ok, and I get an array of 20 lines looking like this:
A
B
C
D
...
Now, I want to split this array in a given number of pieces (let's say 4 in this case), thus resulting I imagine in 4 smaller arrays of 5 lines each, looking like this #1 = A, ,B, ,C , #2 = ,D, ,E,, #3 = F, ,G, ,H and #4 = ,I, ,J,.
Finally, I want to interleave these 4 arrays in order to get an output array in which I first have the first line of each array, the the second line of each array, and so on... the final thing looking like this :
A
F
D
I
B
G
E
J
C
H
How to achieve this?
To make a slice of an array in Perl:
my #oldArray = (a, ,b, ,c, ,d, ,e, ,f, ,g, h, ,i, ,j, );
my #newArray1 = #oldArray[elemIndex1,elemIndex2,elemIndexN];
OR
my #newArray1 = #oldArray[firstElemIndex..lastElemIndex]
Where elemIndex is the index of the element you want in the newArray array.
firstElemIndex..lastElemIndex is used when you want consecutive indexes to be in the sliced array.
To add elements at the end of an array:
push(#interleavedArray,$newArray1[elemIndex]);
Where $newArray1[elemIndex] is the element from #newArray1 you want to add to #interleavedArray
To add elements in order:
Just do a for loop:
for my $index (0..3){
push(#interleavedArray,$newArray1[$index]);
push(#interleavedArray,$newArray2[$index]);
push(#interleavedArray,$newArray3[$index]);
push(#interleavedArray,$newArray4[$index]);
}

Haskell - check whether a 2D list has the same number of rows as columns

I have a 2D list [[Int]] in Haskell and I want to check two things:
whether the list has the sam number of rows as columns
whether the rows have the sam number of elements
For instance:
[[1,2,3], [1,55,9]] has the same number of rows as columns - here 2 - and each row has the same number of elements namely 3.
But
[[1,2], [1,55], [4,7]] has the same number of elements in each row though it has unequal number of rows and columns namely 3r 2c.
yet another example:
[[1,2], [1,55], [4,7,8]] has neither the same number of rows as columns nor each row has the same number of elements.
Actually step 1 includes step 2, am I right??
My attempt:
So what I attempted so far, is this:
listIsEqual :: [[Int]] -> Bool
listIsEqual myList = (all (\x -> length x == (length myList)) )
Right now I get the following error mesage:
Couldn't match expected type `Bool' with actual type `[a0] -> Bool'
In the return type of a call of `all'
Probable cause: `all' is applied to too few arguments
In the expression: (all (\ x -> length x == (length myList)))
In an equation for `listIsEqual':
listIsEqual myList = (all (\ x -> length x == (length myList)))
Could anyone tell me where the problem is?
Is there also any other ways to solve this problem?
GHC's error messages aren't always the most helpful, but in this case it got it right.
Probable cause: `all' is applied to too few arguments
And indeed, you forgot the second argument to all:
listIsEqual myList = all (\x -> length x == length myList) myList
^^^^^^
For the second task, you can map the length of every row (the number of columns in that row) defining a function
let columnLengths rows = map length rows
Prelude> columnLengths [[1,2], [1,55], [4,7,8]]
[2,2,3]
Now that we have a list containing the lengths of the columns, we have to check whether they are all equal. The function nub in Data.List removes duplicates from a list.
let columnsLengthEqual = (==) 1 . length . nub . columnLengths
Or all together
let columnsLengthEqual = (==) 1 . length . nub . map length
Matrix respecting your criteria, are squared matrix then checking if the square of first 's row's length is equal to the number of element should be ok.
isSquaredMatrix xs#(h:_) = ((^2) . length $ h) == (length . concat $ xs)
isSquaredMatrix _ = True
But as it has been pointed out by hammar, this is incorrect since we can have positive outcome using wrong input.
# isSquaredMatrix [[1,2,3],[4,5],[6,7,8,9]]
True -- But this is false
#John,
we use # into pattern matching when we want to refer to the whole type at the same time we have break it down. An example should give you more insight,
Usually we can define an exhaustive function working on list using pattern matching as follow.
actOnList [] = -- do something when we encounter an empty list
actOnList (x:xs) = -- do something with h, and do another stuff with xs
For example,
actOnList [] = []
actOnList (x:xs) =
if (pred x)
then x:xs
else actOnList xs
Here my function consumme the list until a predicate is satisfied.
We can imagine skipUntilMeetAChar
skipUntilMeetAChar :: [Char] -> Char -> [Char]
skipUntilMeetAChar [] c = []
skipUntilMeetAChar (x:xs) c =
if (x==c)
then x:xs
else actOnList xs c
As you see when the char is met we'd like to return the list as it, not only the tail, then to do so we need to reconstruct our list using the head x and the tail xs. This can be overcome using #.
skipUntilMeetAChar :: String -> Char -> String
skipUntilMeetAChar [] c = []
skipUntilMeetAChar l#(x:xs) c =
if (x==c)
then l
else actOnList xs c
Now, regarding ($) operator, this is again some syntactic sugar.
As function application are left associative, this lead us to extensively use bracket to reorder the application of our function, as in the example below.
# f3 (f2 (f1 (f0 x)))
Then to avoid the pain of managing closing parentheses, dollars operator $ have been introduce and then our previous expression become.
# f3 $ f2 $ f1 $ f0 x
Which is definitely more readable and easiest to write.
Note that this operator is defined as follow.
($) :: (a -> b) -> a -> b
f $ x = f x
And I advise you to learn more about it consulting the following introduction material.

Resources