1.1 Linear regression - the algorithm adopts factors of an equation to approximate training data and get lowest cost.
In course were presented two methods to archive that:
1.1.1 gradient descent - iterative way - in each iteration a cost function should be closer to a local minimum. The main requirements and uses:
- needs to choose alpha - if too big - increases cost, if too low - increases number of steps to get a minimum of cost function,
- needs many iterations,
- recommended for large number of features,
1.1.2 normal equation - not iterative way to find θ. The main features of this algorithm:
- no alpha factor
- don't iterate to find minimum of cost function
- require to calculate (XT*X)-1 what gives complexity O(n3), so is slow for large number of features
- could meet problem with matrix inversion (require some additional operations to calculation(remove redundant features or use regularization)
1.2 Logistic regression - it is classification algorithm that gives binary output.
For more than 2 classes (n-classes) there is used n-functions algorithm and then to get most possible class, it is chosen function with highest output probability. Met problems:
- choose correct decision boundary
- additional optimization algorithms (Conjugate gradient, BFGS, L-BFGS) - usually faster but more complex.
The goal is to minimize the cost function. For multi-class classification the algorithm looks for function maximizing h function.
1.3 Neutral networks - it is classification algorithm consists of nodes layers reflecting human brain:
- one neutral network layer is exactly logistic regression so neutral network is complex classifier and it can solve more complex problems
- requires initialization of weight by random values to avoid symmetry
- requires calculation of forward and back propagation (this is expensive operation)
There is example of neutral network with 3 layers - 2 input nodes, 3 nodes hidden layer, 2 nodes in output layer and 2 bias nodes.
Function calculating output of node is:
$$ h_{\theta}(x) = \frac{1}{1+e^{-{\theta}^Tx}}$$
Using θ(j-1) (a matrix of weights controlling function mapping from layer j-1 to layer j) it is calculated an activation function factor of node i in layer j and an output from node m of previous layer:
The cost function is minimized by iterative improving θ values. For Neutral Networks it is required to calculate error function. There are following equations to calculate it: for last layer:
$$ \delta = h_{\theta}(x)-y $$
for layers 1...L-1 (where L is number of network layers)
$$ \delta^{(l)} = ((\theta^{(l)})^T\delta^{(l+1)}.*a^{(l)}.*(1-a^{(l)}) $$
and back propagation delta:
$$ \Delta_n = \sum_{i=1}^m\delta_n^i*a_{n-1}$$
and derivative of cost function (adaptation gradient)
regularization factor is removed for first layer. Gradient calculation is very expensive and should be used only as confirmation of simplified numerical solution - approximation of derivative:
There are many methods to create SVM, below only more important:
1.4.1 non-kernel ("linear kernel"): used when there is many features but not many training data. This algorithm is similar to logistic regression
1.4.2 Polynomial kernel - used when there is significant count of training data
1.4.2 Gaussian kernel: used when there is not many features but significant count of training data
$$ min_Θ C \sum_{i=1}^{m}y^{(i)}cost_1(Θ^Tf^{(i)})+(1−y^{(i)})cost_0(θ^Tf^{(i)})+\frac{1}{2}\sum_{j=1}^{n}Θ_j^2 $$
2. Unsupervised Learning - group of algorithms looking for data similarities and aggregate them in defined number of classes.
- if number of classes not forced, it should be defined on basis of a cost function for trained algorithm (elbow method).
2.1 K-means - K number of centroids randomly initialized from training set. Then data are assigned to centroid where cost function is lowest. Iteratively mean of each class is moving to get lowest cost in each class.
This kind of algorithm is used to partitioning data or assign to groups dimensions of products ex. sizes of dresses (S, M, L)
$$J(c^{(1)},...,c^{(m)}, \mu_1,...,\mu_K)= \frac{1}{m}\sum_{i=1}^{m}\lVert x^{(i)} - \mu_{c^{(i)}} \rVert ^2$$
where m - number of training data, K number of centroids (number of classes)
2.2 PCA (Principal Component Analysis) - dimension reductions used in data compression or to reduce data for visualization. Algorithm remove one or more dimensions of each parameter.
Covariance matrix is calculated by:
$$ \Sigma= \frac{1}{m}\sum_{i=1}^m (x^{(i)})(x^{(i)})^T $$
2.3 Anomaly detection - algorithm used to detection anomalies in data. This algorithm can be replaced with supervised learning algorithms but it is used when there is a huge number of correct data and a few or no case showing anomalies. Algorithm used to detect anomalies of engines, CPU load, etc.
it bases on the Gaussian distribution so anomaly is detected if if P(x) < ε, where ε is defined threshold.
3. Other ideas
3.1 Recommender Systems - algorithms used by video streaming portals, social media and stores portals to suggest other films, friends or products which can be interesting for customer. Problem could be resolved by linear regression but it is subjective ratio how something is deep in some category, how much someone like specific characteristic of product. Usually system has only a few information about customer or it has no his preferences. That's why it is used collaborative filtering algorithm.
The goal is to minimize cost function
$$ J(x, \theta)= \frac{1}{2} \sum_{(i,j):r(i,j)=1}((\theta^{(j)})^Tx^{(i)}-y^{(i,j)})^2+\frac{\lambda}{2}\sum_{i=1}^{n_m}\sum_{k=1}^{n}(x_k^{(i)})^2+\frac{\lambda}{2}\sum_{j=1}^{n_u}\sum_{k=1}^{n}(\theta_k^{(j)})^2$$
where nu -a number of customer, nm - a number of products, r(i,j)=1 - flag if customer rated product, y(i,j) - value of customer rating.
3.2 Online learning - system where there is no limit of input data. Algorithm is constantly learning and improving its predictions. This require to use proper α.
Data can be also processed in parallel in batch. This can be archived MapReduce algorithm.
Batch gradient descent:
$$ \theta_j=\theta_j - \alpha\frac{1}{m}\sum_{i=1}^{m}(h_{\theta}(x^{(i)})-y^{(i)})x_j^{(i)} $$
where m is number of data in batch. Each sum calculated in parallel and then combined to one equation.
This is a nutshell of presented algorithms in Andrew's course. More tips and ideas I will present in next article.
I had always aversion to Python but finally I forced myself to try it. I am developing myself in machine learning area and most examples and algorithm sources are in Python - life forced me.
In this post in a nut shell I describe basic and most important topic of language like:
- why it was created?
- who use it and why?
- a very short characteristic of language and biggest differences which I noticed.
Python was created 1985 by Guido van Rossun as an interpreted, interactive, object-oriented high level language. Name of language is after Monty Python's Flying Circus TV comedy series. It was designed to be readable and easy to run in academic environment. It uses dynamic data typing validated in runtime. It supports functional programming and it is possible to compile Python code into bytecode usually in bigger applications.
It is good to add that till this year (2020) there were two major versions: 2.x and 3.x. Since 2008 when version 3 was introduced, the older version has been still developed. Versions are incompatible to themselves, so when you learn Python focus on which version you use.
When I write this post current version is 3.8.3 but I trained on 3.6.9 and I used only a few features of the language.
Creator cared of interactive console so each command can be added add-hoc and executed. Probably that's why this language won in scientific community, where code doesn't need to be compiled to be executed.
Currently in Python we can find a lot of tools and libraries to load data, process it and present it (plotters, etc.). Dynamic data type definition is useful when we experiment with code but from my point of view can be dangerous during runtime, when we can meet type incompatibility in runtime.
How Python stand out from the rest languages? The first difference is that Python required some code layout. It doesn't use semicolons and braces so it requires lines and indentations. This is what doesn't convince me to Python. Of course I like pretty formatted code but I acclimated to braces and I don't belief that we can live without them.
Other differences that language uses words "not", "and" and "or" in conditional statements.
Python widely support list. Programmer can add lists, multiply elements, search and simply filter it by two or there additional signs.
defdecorator(annotatedText):# definition of annotationdeftext_generator(old_function):defnew_function(*args,**kwds):returnannotatedText+' '+old_function(*args,**kwds)returnnew_functionreturntext_generator# it returns the new generator# Usage@decorator('prefix')# text attached before function resuldefreturn_text(text):returntext# Now return_text is decorated and reassigned into itselfprint(return_text('myText'))# 'prefix myText'
In this article I will describe what is Elm, how to start adventure with it and some details about this language. I am still exploring this language so please forgive some mistakes.
1. What is Elm lang?
Elm is statically typed strongly functional language compiled to JavaScript. Structure of code is similar to Python - Elm
doesn't use braces but requires indentations. Strong typing protects developer from most of technical errors and unknown state of application. All technical errors are caught
in compile time and developer is informed about them by detailed messages which usually contains suggestion how to fix it.
2. What tools includes Elm?
Elm command support development and module upgrading. The most useful command are:
elm init - initialize project structure. creates src directory and elm.json file.
elm repl - starts interactive programming session,
elm reactor - runs local web server to see project
elm make - compile code to JavaScript
elm install - fetches packages
and less popular:
elm-test init - creates tests dictionary with example sources and updates test dependence in elm.json
elm bump - updates version of packages depending on this changing package
elm diff - detects changes between versions of packages
elm publish - publish your code in elm lang repository
For more detail please check documentation.
3. How to start?
Using npm Elm tools can be installed by few commands:
npm install elm
npm install elm-format
npm install elm-test
and then to initialize first project
elm init
and initialize test to this project
elm-test init
In project dictionary there are created directories and files:
src - directory where should be stored production sources
tests - directory with test sources
elm.json - file with project description and dependence, ex. below
When project is initialized, we can create first elm application.
I use IntelliJ with Elm plug-in, however it is possible to create elm source file in notepad and save file with elm suffix.
When elm file is created, it should be compiled to JavaScript. It is done by command
elm make src/Main.elm
By default is created a file "index.html" with JavaScript included.
4. Architecture
In a null shell about architecture of Elm.
Elm uses pattern Model View Update. To update view is used virtual DOM tree,
where each update operation creates new copy of virtual DOM tree, then each
new copy is compared with previous one and then all changes are applied
finally on real DOM tree in one big batch. This solution much improves changes on real DOM tree.
All variables in Elm are immutable by design. It offers:
- simple types:
Bool
Int
Float
Char
String
- complex types:
typed List is a linked list what simplify operations on it. List can be created by collecting elements one type in square brackets
[elem, elem, elem]
or add new elements by calling
elem :: [elem]
array is also typed as List and can be created from List. Array allows for direct access to each field
tuple is a set of different type elements and is typed as well. tuple is created by collecting elements in round brackets
( elemA, elemB, elemC )
record is a structure of data. Record is created by collecting name of data and values in braces
var1 = { field1 = elemA, field2 = elemB }
or
var1 = RecordType elemA elemB
where record's variables must be in the same order as in definition
type alias RecordType = { field1 : String, field2 : Int}
Maybe is wrapper on object to avoid null pointers. It contains values: Just with value or Nothing.
- custom type - created by developer
type UserStatus = Regular | Visitor
- special types
"_" has special meaning. It represents any type. It can be used as default value in case construction or as unused input of function
unit type "()" - represent empty value
inline function requires "\" before declaration
\elem -> elem + 1
redirecting function result to the funtion on the left "<|" or right "|>" function
Let / if / case constructions
let
definition in
function body
case variable of
case_element -> body handling case _ -> body of default handling
if condition then
body else
body
Modules:
When application is bigger and bigger it is required to split code into separated files. Elm defines each separate file as module. Each module can contain private or public elements, what is defined in header of elm file.
there is also possible to make mix of those solutions, ex.
import Module as M exposing (exposing_fun1,exposing_fun2)
if there is need to move modules to subfolders, module name is preceded with folder path separated with dot (similar to Java packages), ex
module folder1.folder2.ModuleName exposing (..)
To compile application it is needed only to indicate main module of application.
source: https://elmprogramming.com/
Ports
Elm can be run as separated from surrounding world or can communicate with it. When Elm need to communicate with JavaScript it is required to add port specifier.
1
moduleMainTableexposing(..)
When communication is from Elm to JavaScrit it is required only defining port function in Elm and callback function in JavaScript.
1
2
3
4
5
6
7
---ELM---portsendData:String->Cmdmsg--JavaScript----app.ports.sendData.subscribe(function(data){alert("Data from Elm: "+data);});
In other way in Elm it is required to define subscriptions parameter in Browser.element, handling port function and in JavaScript code call function.
Similar to other languages, "main" function is defined as entry point to application. If compilation is run with other output than /dev/null, error is thrown.
6. Test
At the beginning it is required to install elm-test
npm install elm-test
what modifies the file "elm.json".
Test module shares developers a few tools, what are:
Test - test definition
Expect - set of assertions
Fuzz - tool to generate random data and run test for each generated value
Yesterday I did small exercise. I upgraded one of my old applications from xml (web.xml) configuration to class version as a first step to later upgrading.
There was no problems until I run application and all world could see everything what only an authorized user should see.
I couldn't find simple example which I could I adopt to my needs so I decided to describe this by my self.
Some examples proposed to extend
AbstractSecurityWebApplicationInitializer, other proposed to import just
import security configuration but it wasn't work as I expected. I created servlet initializer as below.
This is my first meet with Spring Integration. I started with version 4.3 so I will not mention of older version which I don't know.
For whom who don't know what is it Spring Integration. In a nutshell, this is a framework to create flows between betweens input adapters and endpoints.
In a short story I describe what I'd like to reach.
I've got some configuration in XML version which is included in to class version of configuration. I have as well test context (class version) which override some beens - adapters from/to external world). I'd like to translate this XML to have:
consistent configuration in production and test code,
to be able override production configuration of some adapters (ex. file adapters)
to use inline transformations (not included in example).
Below I added a sample of configuration for class version and commented out a equivalent XML code.
As you can see all of used channels must be defined manualy in XML version. In class version I defined only those which I'd like add some additional behaviour.
Is it true that in Java we can't change Spring Integration configuration with simple editor an restart applicaton - we need compile this configuration but we have plenty of possibilities to do.
Starting from version 5.0 there is additional implementation supporting mixed configuration in test, ex.
@SpringIntegrationTest
MockIntegrationContext
However this works in other way than overrding bean definition as I did it. This stops current MessageHandler lifecycle and replace condext with mocked bean.
In version 5 it was added as well DSL to make configuration more readable. More information in [1]
Today I'd like to write about my first experiences with STMicroelectronic. My set is Nucleo board with STM32F466RE chipset - 160Mhz with 512k flesh memory.
I started from looking for articles and YouTube tutorials about hardware platrorm. I didn't know difference between Raspberry PI and Andurino. I found a few interesting [in resources] and then I decided to buy STM32 hardware platform with at least 256kB flash memory.
Next step was to choose IDE. I'd like to use IntelliJ because daily I work in this IDE, unfortunately JetBrains has other tool with separate licence and not so popular as other IDEs. Finally I chosen Atollic TrueSTUDIO for STM32 9.2.0 especially it is supported by tool STM32Cube MX.
STM32Cube MX is a tool to generate project for selected IDE with C code initializing selected by developer modules and ports of STM32 processor.
To create and load first program on microchip we need to install compiler. I am using Linux system that's why I executed commands:
My hardware platform has integrated ST-link and storage where I can copy my binary file and load it automatically on my STM microchip. No additional tool needed.
At the beginning I used external libraries libopencm3 [5] with examples. However there is no tool to generate initializing methods like STM32Cube MX what it is useful at the beginning.
I watched presentation [10] and I was inspired to create code in C++. Bartosz convincing that C++ takes similar resources. In come cases is even much better then code from C compiler.
Till now I created following projects basing on examples:
Change GPIO port state. Both sources of code have example of blinking LED. I used my own external LED to blink.
Read GPIO port state. We can read state of each pin. For pin 1 it will be value 0 or 1, for pin 2 value 0 or 2 and so on. I closed selected pin with 3.3V source.
Communicate via serial port USART. I get connected using ST-link integrated with nucleo board and by external ST-link module.
Read system time. This operation looks different than in OS Linux system. We need to open timer module of chip and then we can read counter.
Ethernet connection. I have Ethernet module with chip ENC28J60. I connected it to SPI connectors however I couldn't run it. :( After spend some time I found correct example and adopted it in my project [8]. It works fine. However I don't know why one request is processed 4 times. Maybe clock of buffer reader is too fast. I must check it.
DAC - set voltage on output an modulate speaker.
ADC - read voltage on input in range 0-3,3V.
Store and read data from flash memory [9]. I have to change memory mapper file.