Search This Blog

Featured Post

Machine Learning, Big Data, AI, Deep Learning

Saturday, December 8, 2018

Quantum Computing

This is a post for summarize my knowledge in Quantum Computer.

What is Quantum Computing?


Quantum Computing is the application of Quantum mechanics concept in computer design,  computer manufacturing and all possible Quantum theories usage in the scope of computer .

Quantum mechanics is a fundamental theory in physics which describes nature at the smallest scales of energy levels of atoms (原子) and subatomic particles (亞原子粒子). 

In traditional computer, we use ' bit'  as unit to describe a status of computing result, each individual status called pattern, and generally understand as 0 or 1. 

In Quantum computer, we use the energy level (能階) for an electron in an atom concept in quantum mechanics to represent the status. The lowest energy level in Quantum mechanics is called Ground State(基態), which is 0 in traditional computer concept; and Excited state (激發態) is represent of  certain energy level, which could be understand as 1 in traditional computer concept. 
However, the difference  of Quantum Computer to Traditional Computer is that there are many "pattern" in between 0 and 1 because the energy level of Excited state could be many. Therefore, if we define the lowest energy level or say ground state as 0, a certain mount of energy level or say excited state as 1, then the range of energy level between ground state 0 and defined excited state 1 could be an individual pattern. We could therefore have three patterns, 0 pattern ,1 pattern and  0/1 pattern in Quantum computer. With such computing design, quantum computer could achieve a larger amount and more efficient calculation in compare with traditional computer.

Superposition and entanglement


Superposition(疊加原理) is a principle that states while we do not know the state of an object at a given time, it is possible that it is in all states simultaneously, as long as we do not look at it to check its state. The way that energy and mass become correlated to interact with each other regardless of distance is called entanglement(量子纏結). 

Concept of Spin (自旋)

Stern 與 Gerlach 於 1921 年發現銀原子束在不均勻磁場中分為兩道。 Pauli 為解釋原子光譜的多重態,於 1924 年提出電子的「兩值性」( two-valuedness )。後來 Goudsmidt 與 Uhlenbeck 提議電子有 spin (一般直譯為「自旋」),即刻被 Ehrenfest 與 Pauli 指出:不可能!因為若從電子的磁偶極矩估計,自轉的速度會違背相對論。 Pauli 是對的,因為後來 Dirac1928 年發現,電子的這一性質來自相對論與量元物理的結合,與自轉根本無關。筆者因此主張不可以訛譯訛──不能說電子有自旋。那要如何說呢?說電子有「兩儀性」 [1] ──它在外加磁場中表現「上儀」及「下儀」。為描述這一性質,我們定電子的「儀數」為 1/2 。

這一說法可以推廣:質子與中子的儀數也是 1/2 ,光元的儀數是 1 ,介子的儀數是 0 ,等等。 Pauli 復於 1940 年從量元場論( quantum field theory )證明:儀數為整數的粒子都是合群粒子( bosons ),儀數為半整數的粒子都是不合群粒子( fermions )。一群相同粒子( identical particles )在溫平衡下的分布依其群性( statistics )而不同。 1933 年, Heisenberg 更提出質子與中子是同一種粒子的不同狀態,另有「同種儀」( isospin )的性質,它們的「同種儀數」為 1/2 。




Reference:







course: 

Saturday, October 20, 2018

CPU MPU MPU DSP

CPU > MPU > MCU

CPU = Central Processing Unit
DSP = Digital Processing Procossing/Unit
MPU = Micro Processor Unit
MCU = Micro Controller Unit

RTOS = Real Time Operating System
For MPU, Integrity、QNX、VxWorks
For MCU, Nucleus、ThreadX、Unison OS、ucOS II/III

Reference:
https://www.digitimes.com.tw/iot/article.asp?cat=130&cat1=45&cat2=25&id=0000424643_ee45qu335sxgr42fqo53o

Friday, October 19, 2018

Learning C

This post is for recording the learning process of  C.

Start from the very beginning - Bootloader

Bootloader is a piece of program that runs before any operating system is running.
The bootloaders are generally written in 16-bit assembly(also called Real mode), then the bits can be extended to 32-bit(Protected mode).
So the bootloaders must be written in 16-bit assembly.

https://createyourownos.blogspot.com/

Download Required:
NASM assember
https://www.nasm.us/docs.php

QEMU simulator
https://qemu.weilnetz.de/

Chosen Compiler 


Grammar

#include <stdio.h>   //library to run printf & scanf
int main()   // int is keyword and main is the identifier. Main identifier is  must for C programming. Main identifier is a integer, so at last return 0 inside the container means the main identifier is 0 so the program end
{ // a container start
        printf(" Hello, World!") ;   //printf is output function , the " ; " is a must for each statement
        return 0;  // "; " always here even at the end
} // a container end

Keywords

Keywords in C Language
autodoubleintstruct
breakelselongswitch
caseenumregister typedef
charexternreturnunion
continueforsignedvoid
doifstatic while
defaultgotosizeofvolatile
constfloatshortunsigned

Identifier

Rules for writing an identifier

1.) A valid identifier can have letters (both uppercase and lowercase letters), digits and underscores.
2.) The first letter of an identifier should be either a letter or an underscore. However, it is discouraged to start an identifier name with an underscore.
3.) There is no rule on length of an identifier. However, the first 31 characters of identifiers are discriminated by the compiler.

Variables and Constants

Variables:

{ ...
int examresult = 95;  // exam result is  variable
...}

Rules for naming a variable in C

1.) A variable name can have letters (both uppercase and lowercase letters), digits and underscore only.
2.) The first letter of a variable should be either a letter or an underscore. However, it is discouraged to start variable name with an underscore. It is because variable name that starts with an underscore can conflict with system name and may cause error.
3.) There is no rule on how long a variable can be. However, only the first 31 characters of a variable are checked by the compiler. So, the first 31 letters of two variables in a program should be different.

Constants:

{ ...
const double PI = 3.14 // PI is  constant
...}


Different types of constants
  1. Integer constants
    • decimal constant(base 10) : 0, -9, 22 etc
    • octal constant(base 8): 021, 077, 033 etc
    • hexadecimal constant(base 16): 0x7f, 0x2a, 0x521 etc
  2. Floating-point constants
    • Numeric constant that has either a fractional form or an exponent form
    • e.g. -2.0,  0.0000234, -0.22E-5
  3. Character constants
    • a constant which uses single quotation around characters. For example: 'a', 'l', 'm', 'F'
  4. Escape Sequences
    • Escape SequencesCharacter
      \bBackspace
      \fForm feed
      \nNewline
      \rReturn
      \tHorizontal tab
      \vVertical tab
      \\Backslash
      \'Single quotation mark
      \"Double quotation mark
      \?Question mark
      \0Null character
  5. String constants
    • "good"             //string constant
    • ""                     //null string constant
    • "      "               //string constant of six white space
    • "x"                   //string constant having single character.
    • "Earth is round\n"         //prints string with newline
  6. Enumeration constants
    • enum color {yellow, green, black, white};
    • Here, color is a variable and yellow, green, black and white are the enumeration constants having value 0, 1, 2 and 3 respectively

Data Types


  1. Fundamental Data Types
    • Integer types
    • Floating type
    • Character type
  2. Derived Data Types
    • Arrays
    • Pointers
    • Structures
    • Enumeration
C Qualifiers
Qualifiers alters the meaning of base data types to yield a new data type

  • Size qualifiers
    • long double i;
  • Sign qualifiers
    • unsigned int positiveInteger;
  • Constant qualifiers
    • const int cost = 20;
  • Volatile qualifiers
    • A variable should be declared volatile whenever its value can be changed by some external sources outside the program. Keyword volatile is used for creating volatile variables.



E-Book:



The C book

Monday, September 17, 2018

Neural Network : CNN, RNN & DNN

Neural Network 神經網絡

Some basic knowledge are required to better understand what is Neural Network.

  • Linear Regression 
  • Sigmoid Squashing Function
  • Rectified linear unit
  • Derivation
  • Error
Two important types of artificial neuron

  • perceptron neuron
  • sigmoid neuron

Perceptron Neuron

  • Detemine output with Weight and Bias
  • Each perceptron has only one output
  • input x usually zero or one
  • output = wx + b
    • w = weight
    • b = bias

Sigmoid Neuron

  • Detemine output with Weight and Bias, plus sigmoid σσ
  • Each perceptron has only one output
  • input x between zero or one
  • output = σ (wx + b)
    • w = weight
    • b = bias
    • σ =sigmoid
  • sigmoid function: σz = 1+ (1 / 1 + e^(-z))
  • Or ,  output = 1 /  1 +  exp (−jwjxjb)
Reference: https://en.wikipedia.org/wiki/Derivative#Rules_for_basic_functions


Reference:
https://brohrer.github.io/how_neural_networks_work.html

http://www.neuralnetworksanddeeplearning.com

Architecture of Neural Network



Feedforward Neural Network : neural networks where the output from one layer is used as input to the next layer. There are no loops in the network - information is always fed forward, never fed back. 

Recurrent Neural Network: Neural networks where the output from one layer is used as input to the next layer with loops in a limited duration of time in the network.




CNN - Convolutional Neural Network 卷積神經網絡

CNN is about space?


RNN - Recurrent Neural Network 

RNN is about time?

DNN - Deep Neural Network


Saturday, June 9, 2018

10/06/2018 Convolutional Neural Networks for Visual Recognition

Convolutional Neural Networks for Visual Recognition


Lecture 1 introduction


Lecture 2 Image Classification Pipeline


Lecture 3 Loss Functions and Optimization


Lecture 4 Introduction to Neural Network


Lecture 5 Convolutional Neural Networks


Lecture 6 Training Neural Networks


Lecture 7 Training Neural Networks II


Lecture 8 Deep Learning Software


Lecture 9 CNN Architectures


Lecture 10 Recurrent Neural Networks


Lecture 11 Detection and Segmentation


Lecture 12 Visualizing and Understanding


Lecture 13 Generative Model


Lecture 14 Deep Reinforcement Learning


Lecture 15 Efficient Methods and Hardware for Deep Learning


Lecture 16 Adversarial Examples and adversaial Training



The above materials are provided by http://cs231n.stanford.edu/
This blog post only organized for easier personal learning purpose.

Book:
Deep Learning By Ian Goodfellow and Yoshua Bengio and Aaron Courville
http://www.deeplearningbook.org/



Wednesday, June 6, 2018

06/06/2018 Integrate Github in visual Studio

1. Open github account
2. Create a repository in github
3. Clone the HTTPS link of the repository 
4. in visual studio termina or terminal, type
  • git config --global user.name xxxxx
  • git clone urllink (from step 3)

https://www.theregister.co.uk/2015/12/07/visual_studio_code_git_integration/

5. git pull urllink
6. git remote add name urllink
7. git push name

Saturday, June 2, 2018

Machine Learning, Big Data, AI, Deep Learning

Machine Learning

Machine Learning learn how to combine input to produce useful predictions on never-before-seen data.

Fundamental concept in Machine learning

Feature (x) - variable input
Label (y) - things predicting
example - a particular instance of data x
  • labeled example - instances of features (x) with labels (y)
  • unlabeled example- instances of features (x) without labels (y) 
Models - defines relationship between features and label
Training - creating or learning the model, show the model with labeled exmples to enable the model gradually learn the relationships of features and label
Inference - apply the trained model to unlabeled examples for prediction.

Model types

  • Regression - predict continuous value
  • Classification - predict discrete value

Linear Regression

y = mx +c
y = b +wx

y - labels
x - feature
b - bias
w - weight of the feature

To infer (predict) y, substitute the value into x.

Empirical risk minimization - a process in supervised learning, a machine learning algorithm build a model by examining many examples and attempting to find a model that minimize lose.

Loss - a number show how bad the model's prediction was on a single example. If the prediction is perfect, the loss is zero; otherwise, the loss is greater.

Squared loss - the square of the difference between the label and the prediction

Interpretation
http://www.leeds.ac.uk/educol/documents/00003759.htm
https://www.khanacademy.org/math/calculus-home/taking-derivatives-calc
https://www.khanacademy.org/math/multivariable-calculus/multivariable-derivatives/partial-derivative-and-gradient-articles/a/introduction-to-partial-derivatives

Reducing Loss

An iterative approach to training a model

A Machine Learning model is trained by starting with an initial guess for the weights and bias and iteratively adjusting those guesses until learning the weights and bias with the lowest possible loss.

Iterate until overall loss stops changing or at least changes extremely slowly. When that happens, we say that the model has converged. (examine all possible value of w1)

Convex problems have only one minimum; that is, only one place where the slope is exactly 0.


Gradient descent to training a model

The first stage in gradient descent is to pick a starting value (a starting point) for w1.  The starting point doesn't matter much; therefore, many algorithms simply set w1 to 0 or pick a random value.
The gradient descent algorithm then calculates the gradient of the loss curve at the starting point. The gradient if the loss curve is equal to the derivative (slope) of the curve, and tells you which way is "warmer" or "colder." When there are multiple weights, the gradient is a vector of partial derivatives with respect to the weights.

 A gradient is a vector with two characteristics:

  • a direction
  • a magnitude
Gradient descent algorithms multiply the gradient by a scalar known as the learning rate (also sometimes called step size) to determine the next point.

Hyperparameters are the knobs that programmers tweak in machine learning algorithms.

If  a learning rate that is too small, learning will take too long.
If a learning rate is too large, the next point will perpetually bounce haphazardly across the bottom of the well like a quantum mechanics experiment gone horribly wrong.


Goldilocks value is related to how flat the loss function is. If you know the gradient of the loss function is small then you can safely try a larger learning rate, which compensates for the small gradient and results in a larger step size


Stochastic gradient descent (SGD)

In gradient descent, a batch is the total number of examples you use to calculate the gradient in a single iteration.  A large data set with randomly sampled examples probably contains redundant data. In fact, redundancy becomes more likely as the batch size grows. Some redundancy can be useful to smooth out noisy gradients, but enormous batches tend not to carry much more predictive value than large batches.

Stochastic gradient descent (SGD) get the right gradient on average for much less computation by choosing examples at random from data set. We could estimate (albeit, noisily) a big average from a much smaller one. SGD uses only a single example (a batch size of 1) per iteration. Given enough iterations, SGD works but is very noisy. The term "stochastic" indicates that the one example comprising each batch is chosen at random.

Mini-batch stochastic gradient descent (mini-batch SGD)  is a compromise between full-batch iteration and SGD. A mini-batch is typically between 10 and 1,000 examples, chosen at random. Mini-batch SGD reduces the amount of noise in SGD but is still more efficient than full-batch.


Tensorflow

Big Data


Big data is not about the size of the data, it is about the value within the data.

Big Data Analytics

A collection of frameworks for generate valuable equation (regression)
  • MapReduce Framework
  • Hadoop Distributed File System (HDFS)
  • Cluster

Data in Big Data

  • Structured data
  • Semi-structure data
  • Unstructured data

Big Data 4V 


Justification on deploy big data in 4 directions

  1. Volume  - Data Quantity
  2. Velocity - Data Speed
  3. Variety - Data Types
  4. Varecity (Analytics)

Justification 4V via two level

  1. Distributed Computation
  2. Distributed Storage

Data Charactrristics

  • Activity Data
  • Conversation Data
  • Photo and Video image data
  • Sensor Data
  • The Internet of Things Data

AI - Artificial Intelligence

Machine Learning

Creating algorithms

Deep Learning

Using deep neural networks (NN) to automatically learn hierarchical representations


Machine Learning Task

  1. Classification - Predict a class of an object
  2. Regression - Predict a continuous value for an object 
  3. Clustering - group similar object together
  4. Dimensionality reduction - " compress " data from a high- dimensional representation into a lower-dimensional one
  5. Ranking
  6. Recommendations - filter a small subset of objects from a large collection and recommend them to a user

Deep Learning

Commonly use deep learning toolkits

Caffe
CNTK
Tensorflow
Theano
Torch

Common use networks
  • ConvNets: AlexNet, OxfordNet, GoogleNet
  • RecurrentNets: plain RNN, LSTM/GRU, bidirectional RNN
  • Sequential modeling with attention.
Compare of toolkits reference
https://github.com/zer0n/deepframeworks/blob/master/README.md?utm_source=tuicool&utm_medium=referral

Reference

Convolutional Neural Networks for Visual Recognition
http://derekwaikl.blogspot.com/2018/06/convolutional-neural-networks-for.html


Deep Learning Tutorials
http://deeplearning.net/tutorial/

Stanford Deep Learning
http://deeplearning.stanford.edu/




Books to read:

Bengio Y. Learning Deep Architectures for AI[J]. Foundations & Trends® in Machine Learning, 2009, 2(1):1-127.

Hinton G E, Salakhutdinov R R. Reducing the Dimensionality of Data with Neural Networks[J]. Science, 2006, 313(5786):504-507.

He K, Zhang X, Ren S, Sun J. Deep Residual Learning for Image Recognition. arXiv:1512.03385, 2015.

Srivastava R K, Greff K, Schmidhuber J. Highway networks. arXiv:1505.00387, 2015.

Thursday, May 17, 2018

18/5/2018 Electricity

Voltage

newton - The newton (symbol: N) is the International System of Units (SI) derived unit of force. One newton is the force needed to accelerate one kilogram of mass at the rate of one metre per second squared in direction of the applied force.


F = m ⋅ a
1N = 1 kg ⋅ 1 m/s2


Joule - is a derived unit of energy.  It is equal to the energy transferred to (or work done on) an object when a force of one newton acts on that object in the direction of its motion through a distance of one metre

Watt - a unit of power. It is defined as a derived unit of 1 joule per second,[1] and is used to quantify the rate of energy transfer.

Ohm's law -  states that the current through a conductor between two points is directly proportional to the voltage across the two points.

I = V / R

dBm - unit of level used to indicate that a power ratio is expressed in decibels (dB) with reference to one milliwatt (mW)

Rectifier -  is an electrical device that converts alternating current (AC), which periodically reverses direction, to direct current (DC), which flows in only one direction.

AC (Alternating Current)

DC (Direct Current)

Sunday, May 13, 2018

14/5/2018 Communication using waves

Frequency, wavelength, amplitude and wave speed



The amplitude, a, of a wave is the distance from the centre line (or the still position) to the top of a crest or to the bottom of a trough. Be careful with this quantity - the centre line is not always given in a diagram. Amplitude is measured in metres (m). The greater the amplitude of a wave then the more energy it is carrying.

The wavelength, λ, of a wave is the distance from any point on one wave to the same point on the next wave along. (The symbol is a Greek letter, 'lambda'.) To avoid confusion, it is best to measure wavelength from the top of a crest to the top of the next crest, or from the bottom of a trough to the bottom of the next trough. Wavelength is also measured in metres (m) - it is a length after all.

The frequency, f, of a wave is the number of waves passing a point in a certain time. We normally use a time of one second, so this gives frequency the unit hertz (Hz), since one hertz is equal to one wave per second.

Don't get confused with this quantity frequency. It is not a distance traveled by waves, nor is it a speed, although it is linked to both of these quantities. For water waves and sound waves the unit hertz is usually good enough but radio and TV waves have such a high frequency that the kilohertz (kHz) or even the megahertz (MHz) are better units.

1 kHz = 1,000 Hz
1 MHz = 1,000,000 Hz

The speed (or sometimes you might see it called velocity) of a wave, v, is how far the wave travels in a certain time.

Wave speed is measured in metres per second (m/s).

All the electromagnetic waves travel at 300,000,000 metres per second (3 x 108 m/s). Sound travels at about 340 metres per second.

Copy out the following table and complete it to give you a summary of these four important quantities used in waves.
Quantity Symbol Unit
amplitude
wavelength
frequency
wave speed

Wednesday, May 9, 2018

09/05/2018 Database SQL

SQL command


DDL: Data Definition Language

Command Description
create To create new table or database
alter For alteration
truncate Delete data from table
drop To drop a table
rename To rename a table


DML: Data Manipulation Language

Command Description
insert To insert a new row
update To update existing row
delete To delete a row
merge Merging two rows or two tables


TCL: Transaction Control Language

Command Description
commit to permanently save
rollback to undo change
savepoint to save temporarily


DCL: Data Control Language

Command Description
grant grant permission of right
revoke take back permission.


DQL: Data Query Language

Command Description
select retrieve records from one or more table

Monday, April 30, 2018

01/05/2018 Database

Dealing with resistance to change

ADKAR

Awareness
Desire
Knowledge
Ability
Reinforcement

Object-oriented analysis

-----
Class
-----
Description
-----
Object
-----

Monday, April 23, 2018

24/4/2018 SQLAlchemy


Flow of building connection with database via SQLAlchemy

Create Engine


Step

Key Code

Inspect

Connecting
>>> from sqlalchemy import create_engine
>>> engine = create_engine('sqlite:///:memory:', echo=True)
Map Declare
>>> from sqlalchemy.ext.declarative import declarative_base
>>> Base = declarative_base()
>>> from sqlalchemy import Column, Integer, String
>>> class User(Base):
...     __tablename__ = 'users'
...
...     id = Column(Integer, primary_key=True)
...     name = Column(String)
...     fullname = Column(String)
...     password = Column(String)
...
...     def __repr__(self):
...        return "<User(name='%s', fullname='%s', password='%s')>" % (
...                             self.name, self.fullname, self.password)
>>> User.__table__ 
Table('users', MetaData(bind=None),
  Column('id', Integer(), table=<users>, primary_key=True, nullable=False),
  Column('name', String(), table=<users>),
  Column('fullname', String(), table=<users>),
  Column('password', String(), table=<users>), schema=None)

Tuesday, April 17, 2018

18/4/2018 SQLAlchemy

Engine



To connect a database, use create_engine() from sqlalchemy. The create_engine() function produce an engine object based on a URL. The URLs follow RFC-1738.


>>>engine = create_engine(dialect+driver://username:password@host:port/database)
The above engine creates a Dialect object tailored towards the database and creates a Pool object which establish a DBAPI connection. However, it's first still not yet established until  Engine.connect()  method is called or an operation which is dependent on this method such as Engine.execute() is invoked.

Monday, April 16, 2018

17/04/2018 SQLAlchemy

SQLAlchemy

Consists of two components
  • Core = a fully featured SQL abstraction toolkit, providing a smooth layer of abstraction over a wide variety of DBAPI implementations and behaviors, as well as a SQL Expression Language which allows expression of the SQL language via generative Python expressions
  • ORM = Object Relational Mapper

16/04/2018 Request, Idea

Requests

Flask requests used Requests library from python. Request is terms from HTTP/1.1. HTTP/1.1 is defined under RFC 2616.

HTTP messages consist of requests from client to server and responses from server to client.

Request and Response messages use the generic message format of RFC 822 for transferring entities (the payload of the message). Both types of message consist of a start-line, zero or more header fields (also known as "headers"), an empty line (i.e., a line with nothing preceding the CRLF) indicating the end of the header fields, and possibly a message-body.

HTTP header fields, which include general-header, request-header, response-header, and entity-header fields, follow the same generic format as that given in Section 3.1 of RFC 822. Each header field consists of a name followed by a colon (":") and the field value.

The message-body (if any) of an HTTP message is used to carry the entity-body associated with the request or response.

There are a few header fields which have general applicability for both request and response messages, but which do not apply to the entity being transferred. These header fields apply only to the message being transmitted.

general-header included Cache-Control, Connection, Date, Pragma, Trailer, Transfer Encoding, Upgrade, Via, Warning.

Idea

Thinking of creating a logbook like webpage to record learning log and sharing knowledge. Generally idea is the page would separate into two parts. Left part is the main content and the right part is the log or comment. The log or comment on the right generally show in one sheet but related with the different part on the left with a linked line.