Saturday, May 30, 2020

React + React Native Basics in 2020-2021

I am writing new blog posts for technologies every year because they change, they evolve. JavaScript today is nothing like the JavaScript 10 years ago. Today's topic is React and React Native. This is a narrative style cheat sheet of React Basics. It is my hope to organize those concepts in a cohesive way. It will tell you how the concepts are connected, but to find out more, to dive deeper, it is important to seek out external tutorials and resources. 

React is the declarative way to create web components, as opposed to vanilla javascript uses imperative, step by step, line by line instructional programming. ReactDOM inserts React components and render them onto a web page. Babel translates JSX to JavaScript and HTML that the browser can understand. 

Vanilla JavaScript is imperative. React is declarative. Just say you want a behavior / element, it will be there. No need to tell the computer step by step what to do. If the data (state) changes, the view will change to reflect that. It's like having smart elements that just know what to do. 

Repeated elements (groups of HTML tags) are great candidates to break up and to be rewritten as components.

React is a library for building user interface. 

The most important concept in React is components. The functionality, codes are organized into components that become UI elements. Every custom react component uses the extends keyword to inherit from the React.Component class. 

Why JavaScript? It is a great time to learn modern JavaScript (ES6), you can now code both front end and back end (full stack) with JavaScript, even use it for Augmented Reality, Animation, interactivity, games, and machine learning (via Tensorflow.js). 

Post in progress, in construction. Updated daily.

Getting Started
If you want to start with a seed app, try the create-react-app
Provides basic seeding, basic scaffolding
All the javascript files are in the src folder.

Normal to see the node_module folder in all node and react apps. That's where the packages are installed. 

To get a quick start you can use CDN served React using unpackaged instead of npm install

Basic Node commands
Start the node app in command line
$ npm start

install the latest and greatest
npm install npm@latest -g

Launches the placeholder app in localhost:3000

Check versions
node -v
npm -v

Key Concepts in React:

Declarative program : opposite of imperative programming, where we specify step-by-step instruction, implementing behaviors in details. In declarative programming we tell React what we want back, like a component. HTML is a declarative, because we don't need to implement every detail just tell the browser to render a <div>.

JSX : 

JSX mix html and javascript together. Write html with javascript. Uses camel case like javascript. 

Most common way to create react element is not use createElement but using JSX
const element = <div className='container'>Hello World</div>
ReactDOM.render(element, rootElement)

React uses JavaScript to write HTML codes using JSX.
const my_html = <h1>Hello World</h1>
It is a combination of JavaScript and HTML, won't validate in vanilla JavaScript. 

JSX philosophy is perhaps for your code to resemble the web components, the declarative nature of html tags,less like pure javascript spaghetti code.

Browser engines don't support JSX and translating JSX to JavaScript that's why we need libraries like Babel to make that translation from JSX to JavaScript. There's a Babel playground where you can see the interpreter in action. Try translating JSX code into Js. 

Components are great for reusable code in react. Perhaps the most important concept. 

React components, building blocks of the virtual DOM.
Every component needs a render function because it needs to know how to render the component to web page. 
React components auto attach props. When we use it it also knows which props we are referring to. It knows we want to use it

Functional component is good for a simple quick function. 

The components codes are organized into the components folder in the src subdirectory. 

To be frank, a component is a block of reusable code. 

This inside the component refers to the component 

Declarative UI

React core concept

React components rely on data passed to be dynamic

When writing babel code use the script tag <script type="text/babel"></script> instead of the regular javascript tag. 

Functional components describe how UI should look based on states and properties 

When writing JSX, we may also see {} which surrounds JavaScript expressions {my javascript expression}. it cannot interpolate complex JavaScript logic such as control flow. But can handle expressions and ternary operators. JavaScript inside {} will be interpolated. 
{{}} is interpolated as an empty object. 
hyphen? todo

New component tag name needs to be capitalized. When inspect the type of object, the element will not show as a normal HTML tag such as a tag, but a special component, custom component, with custom tag name reusable using custom component. 

When initializing, component calls construct, super if any inheritance and yes generally it will, to enable the component, setState to give initial values to the state.

State management. Track state. 

react.createElement() API is different from the createElement API on document
textText becomes children
just specify the type of element and pass in property value pairs as an object
can also pass in children as an array
react for creating the elements
react dom for rendering elements to the page


Babel is the javascript compiler
tryout playground available
compile JSX to vanilla javascript

is used to convert JSX code to JavaScript, which is understood by the browser. We use the script tag with text/babel as type to tell Babel this code needs to be compiled. Babel will insert a new script tag on the page in JavaScript that the browser Js engine can understand. 

Apparently the best practice is not to use Babel stand alone. 

React Core
    React core does not have the request module - one example why we need ReactDOM. 
ReactDOM : insert components into DOM. Takes components insert into DOM.
Babel : compatibility, helps convert JSX to JavaScript (Browsers can understand Js code, not JSX)
React Native : Build mobile apps using just JavaScript. Write once, deploy any where. Supports iOS and Android. Dependency is React. JavaScript is bundled, transpiled from ES7 ES6 ESNext down to ES5 code. Also minified (Source: CS50 Harvard). Multiple JavaScript files compiled into a one big JavaScript bundle. Separate threads for UI, layout, JavaScript (which is Single Thread and can get locked up). Prerequisite of React Native learning is to know core React concepts

Link to React, ReactDOM, and Babel using script tags in the headers.

Basic unit of react organized around components. It inherits from React.component. Usually contains a render function. 

class CappedComponentName extends React.component{
        return <h1>Some HTML Code</h1>

Props : objects that are passed to elements. It looks similar to JSON, but unlike JSON which can only handle strings, props can handle other JavaScript data types. 
React uses setState to change state props.

Arrow function: 
Benefit of using arrow function, is to handle the event variable and bind this correctly. this object can get kind of funky in js. 

Best practice:

A workaround best practice to ensure compatibility is to compile JSX to JavaScript before deployment. 

What is the different between props and states. States is something the component may want to track and modify. Props is somewhat like initialization, configuration, like states but with fewer changes

Use case:
    React can convert JSON data quickly to HTML
    React is really good for repetitive HTML, generating a lot of HTML templates repetitively which vary with data
    React components make coding easy
    React helps developer handles States
    React helps HTML page display data
Performance : 
    Virtual DOM computing and re-rendering with delta change only makes React performant, less expensive DOM rendering, refreshing, layout change with data.
    Virtual DOM manages delta update by monitoring changes and understand what constitutes a re-render, re-render partially, instead of regenerating DOM from scratch, which is costly and expensive

In general, front end development frameworks help reduce DOM manipulation work, and improves code quality 

Post in progress, in construction. Updated daily.

React components are independent, easy to maintain, reusable. Describe how components should look based on states, properties. state can be think of as a configuration

In constructor we define the state of the component, what does the component needs to keep track of
this.state = {} property value pairs. state can be think of as a configuration

State is dynamic
State contains data that can change. In contrast with props. 

State is used on a class component not a functional component. 

Initial state vs changes of state

Styling React  | Make React App Pretty
Use React UI, Material UI
React UI includes cards, breadcrumbs, tree, accordian, 

Render function
Related concept : Virtual DOM
React Render function takes 2 arguments : element, target

For the return function to span multiple lines in render use ().




We still need to call ReactDOM.render() and give it the location and component to render in order to display the UI on the page. 


If data changes, in an eligible event, can trigger changes to all the components that use the data. 

React modules
import React from 'react'
that's the core react module. There is also a react module for react web (react-dom) and react native (mobile). Used to be one big app. 
Even have a module for VR. 


main top level component, 
a wrapper for the rest of the project. Point to other component code. 

main css file, 
Can organize css for other components, 
one css file per component. 

coveres teseting
index.css --> css for the index.html

is good for ignoring sensitive information, large uneccessary files such as node_modules, etc.  such as data files. 

not specific to react
 common in all node projects
 contain information about the app, such as author dependencies, such as react-dom, react-scripts (used by create-react-app)
package.json the file that describes the node project
also describes dependencies

npm install command will install these dependencies

Best practice: 

When removing a .js or .css file be sure to also remove any related import statements.

Divide a web app into logical components to organize, render and update with data. 

serviceworker for push notifications.
React modules
react core is used for creating elements
react dom is used for rendering the elements to the DOM

React createElement method creates an element using React instead of using the vanilla javascript. This element can used and manipulated using react easily.

Make your React app look pretty using React Bootstrap as a starter. Animate your app using React Spring. 
React Fragment
Can render elements side by side which is other wise not possible
Great for rendering tables which has a lot of tags side by side

short hand <></> is the functional equivalent of fragments in JSX

React Dev console
React UI Kit for rapid prototyping. React bootstrap. 

React Developer Tool

As of 2020, the react developer tool has 1283 plus reviews, and 2mm users in the chrome extension store!

React hook 

Introduced around 2019, a React function. Reusable function. 

Sunday, May 10, 2020

Intro to Data Visualization

REPOST from Medium with permission

Data Visualization in Machine Learning — Beyond the Basics

This is not a tutorial. These are my notes from various Machine Learning articles and tutorials. My personal cheatsheet for interviews and reviews. Any feedback and corrections are welcome. If you’d like to read more, please let me know as well. These notes are more applicable for python users. Does not include ggplot, great for R.

Prerequisites and Dependencies

This tutorial and overview is python based so we use matplotlib.pyplot. These commands can be run in command line and in Python Notebook with just a bit of modifications. Any reference to plt means the function is from the matplotlib library.
import matplotlib.pyplot as plt
# will get object does not have bar, scatter.... function_name error # if not imported

Plot a Bar Chart

Bar chart, bin chart: useful for frequency analysis, distributions and counts.
labels = ['A','B','C','D','E','F','G']
nums = [13,24,5,8,7,10,11]
xs = range(len(nums)) #[0, 1, 2, 3, 4, 5, 6]
#xs is a convention variable name for x axis,nums)
plt.ylabel("Customize y label") 
plt.title("Customize graph label") #display the plot

Don’t be deceived by its simple look. Frequency analysis is very powerful in data EDA, stats and machine learning.

Plot a Histogram

Histogram will automatically divide data into bins.
import matplotlib.pyplot as plt
import pandas as pd
nums = [99, 1, 3, 5, 7,33, 23,684, 13, 3 ,0, 4]
# <matplotlib.axes._subplots.AxesSubplot object at 0x10d340d90>
# returns object in memory

Also useful for visualizing distribution and outliers.

Scatter Plot

How is scatter plot beyond the basics? Scatter plot is extremely intuitive yet powerful. Just plot the vertical coordinate and horizontal coordinate of each data point in the sample to get its scatter plot. If the relationship is non-linear, or there may be the presence of an outlier, these targets will be clearly visible in the scatter plot. In the case of many features i.e. dimensions, a scatterplot matrix can be used.
Below is a screenshot of pandas scatterplot matrix in the official documentation.

Clearly the relationship is not linear. The diagonal is the variable vs itself, so it’s showing a distribution graph instead of scatter plot. Neat, looks like the variable is normally distributed.
Scatterplot is a great first visual. Too many features? Try sampling or generating data subsets before visualizing.
Use pandas.DataFrame.describe() to summarize and describe datasets that are simply too big. This function will generate summary stats.
Scatterplots are useful for pairwise comparison of features.
Scatterplots can go beyond two dimensions. We can use marker size and color to illustrate the 3rd dimension, even 4th dimension as in the famous TED talk of economical inequality. The presenter even used timeline (animation) as the 5th dimension.

Visualizing Error

Youtube deep learning star Sraj shows a 3D visual of error function while altering y intercept aka bias and slope for linear regression. The global optima i.e. the global minimum in this case is the goal of gradient descent algorithm.
Error functions have shapes and can be visualized. Local optima which prevents your model from improving can potentially be visualized.

Gradient can be visualize as directional arrows that travel in the direction of the global minima along the shape of the 3D plot. It can also be visualized as a field of arrows in a matrix.
Each residual (y_i — y_hat) can be visualize as a vertical line connecting the data point with the fitted line in linear regression.

Data Scientists Love Box Plots

Why? It displays essential stats about distribution in a concise visual form. Aka candle stick plot. Also popular in finance.
Max, 3rd Quartile, Median, 1st Quartile, min.
This is known as the box and whisker graph too. It’s popular among statisticians. Used to visualize range. It can be drawn horizontally.
What’s between Q3 and Q1? The interquartile range, which used in analyzing outliers. Q1–1.5*IQR is too low, Q3+1.5*IQR is too high.
Box whisker plot displays outliers as a dot!
Check out Boston University’s Blood Pressure dataset box whisker plot with outliers.


Did you say heat map? Heat map has been in and out of favor. Web analytics still use heat map to track events and clicks on a webpage to identify key screen real estates. Why should we use heat map for machine learning?
It turns out that generating a heat map of all the feature variables — feature variables as row headers and column headers, and the variable vs itself on the diagonal— is extremely powerful way to visualize relationships between variables in high dimensional space.
For example, a correlation matrix with heat map coloring. A covariance matrix with heat map coloring. Even a massive confusion matrix with coloring.
Think less about the traditional use of heat map, but more like color is another dimension that can visually summarize the underlining data.
Correlation Matrix Heat Maps are frequently seen on Kaggle, for exploratory data analysis (EDA).

More Data Visualization Magic

Did you know that you can visualize decision trees using graphviz. It may output a very large PNG file. Remember the split of decision tree is not always stable — consistent over time. Take it with a grain of salt. The benefit of visualizing a decision tree is to understand where and how machines made decision splits. Decision tree boundaries can be visualized too, see screenshot below from Sklearn documentation.

Visualizing models, decision boundaries and prediction results may give hints whether the model is indeed a good fit or it is a poor fit for the data. For example, it is high bias to ignore the nature of our data if use a straight line to fit a circular scatter of dots.
Researchers even visualized different optimizers to see their descend to minimize loss.
Did you know you can create interactive plots using Plotly right in Jupyter Notebook? Interactive plots allow you to visualize complex data, toggle and change parameters. For example you can slide to change values of your hyperparameters and visualize how the model performance change in gridsearch and other systematic search of the space.

Machine Learning for Beginners Resources

Uniqtech guide to Machine Learning. This guide explains the difference between machine learning, traditional programming, machine learning w...