How to Fix Problems w/ create-react-app

Possible Problems

You run npx create-react-app my-app and it only tells you npx installed without generating a new project.

You successfully create a new React project but there’s no server.js file in the project. It may give you this error when you run npm start: “missing script: start”

Solution

Installing create-react-app globally is now discouraged. Instead uninstall globally installed create-react-app package by doing:

npm uninstall -g create-react-app

Then, just try creating a new React project:

npx create-react-app my-app

Local Environment Setup for React Development (Mac)

  1. Check Node is up to date
  2. Install VSCode (optional)
  3. Create React app
  4. Run app

1. Check Node is up to date

Go to https://nodejs.org/en/

The left button shows the latest stable version of Node. In this case, it’s 12.18.1

Check your Node version in Terminal with this command:

node --version

Make sure your version is the latest stable version.

2. Install VSCode

You don’t have to use VSCode as your code editor, but many recommend it because it has a lot of extensions that make it really easy to work with React.

Go to https://code.visualstudio.com. Download for Mac

3. Create React app

In Terminal:

npx create-react-app my-app

If that doesn’t work, install with npm or yarn:

npm init react-app my-app
yarn create react-app my-app

4. Run app

cd my-app
npm start or yarn start

You should automatically be taken to your browser. It should show this page:

Node.js User Authentication with Bcrypt

In this lesson, we will be allowing users to create accounts, disguising their passwords to prevent hackers from stealing them, saving the accounts in a MongoDB database, and allowing users to log in with their account info.

In your project directory in Terminal, use this command to create a package.json file for your project

npm init -y

Any project that is using Node.js needs a package.json file. The file contains the project’s dependencies, source control information, and specific metadata.

Now install all the packages that our project will need using npm.

npm i express body-parser ejs mongoose bcrypt

I will show you how to set up the app.js file, but you’ll have to design the ejs (or html) and css files on your own.

In general, though, you’ll want to include something like this in your login & signup files:

<form action="/login" method="POST">
   <div class="form-group">
       <label for="email">Email</label>
       <input type="email" class="form-control" name="username">
   </div>
   <div class="form-group">
        <label for="password">Password</label>
        <input type="password" class="form-control" name="password">
   </div>
   <button type="submit" class="btn btn-dark">Login</button>
</form>

You will need a form that has an action parameter that posts to a route. You will take the user’s input using named input tags that can be referenced in the server file.

In your app.js file, require all the packages we installed earlier. Also create a saltRounds variable and set it to 10. We will use it later to salt our passwords.

const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const saltRounds = 10;

More standard setup:

const app = express();

app.use(express.static("public"));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
  extended: true
}));

mongoose.connect("mongodb://localhost:27017/authtestDB", {useNewUrlParser: true});

Create the User Model in MongoDB:

const userSchema = new mongoose.Schema ({
  email: String,
  password: String
});


const User = new mongoose.model("User", userSchema);

Set up the get routes so users can get to the different pages:

app.get("/", function(req, res){
  res.render("home");
});

app.get("/login", function(req, res){
  res.render("login");
});

app.get("/register", function(req, res){
  res.render("register");
});

Handle users entering their information into the login and register forms:

Posting to the Register Route

As you can see, we are using the bcrypt hash function. The function takes in the password given by the user in the request, the number of salt rounds (defined above), or times we want our password to be salted , and a callback function that can either return an error or the hashed (encrypted) password.

A new user based on our Mongo User Model is created using the username from the request and the encrypted password. Then, that user is saved into the MongoDB. If successful, the server will navigate the user to pages that require authentication.

app.post("/register", function(req, res){
  bcrypt.hash(req.body.password, saltRounds, function(err, hash) {
    const newUser =  new User({
      email: req.body.username,
      password: hash
    });
    newUser.save(function(err){
      if (err) {
        console.log(err);
      } else {
        res.render("secrets");
      }
    });
  });

});
Posting to the Login Route

First, using the findOne function, we see if there are any emails in our database that match the one inputted by the user. This findOne function can return either an error or a found user/ matching user. If a user is found for the inputted email, bcrypt will proceed to compare the inputted password with the password for the email in the database. If it’s another match (result === true), the server will navigate the user to pages that require authentication.

app.post("/login", function(req, res){
  const username = req.body.username;
  const password = req.body.password;

  User.findOne({email: username}, function(err, foundUser){
    if (err) {
      console.log(err);
    } else {
      if (foundUser) {
        bcrypt.compare(password, foundUser.password, function(err, result) {
          if (result === true) {
            res.render("secrets");
          }
        });
      }
    }
  });
});

Neural Networks: Perceptrons & Sigmoid Neurons

A neural network is a deep learning system that is modeled after the human brain and the way biological organisms learn.

A perceptron is a single layer of a neural network. It takes in a few binary inputs, or yes or no inputs, and outputs a single binary output. Binary objects can have a value of either 0 (meaning no) or 1 (meaning yes). This is a model of a perceptron:

It looks confusing, but you don’t have to understand all of the symbols. Just know that x1, x2, and x3 are the 3 binary inputs into the neural network, the big circle in the middle is the decider, and the z is the yes or no output.

As an example, let’s use a perceptron to decide if I will or will not go out to get food. I will put in some considerations (x1, x2, x3) and make a yes or no decision. These will be my inputs, or factors that will affect my decision of whether to eat out or not:

  • x1 = Food at home = 0
  • x2 = Tired = 1
  • x3 = Have cash = 1

If I have food at home, I will not go out to eat. If I have cash and/or I’m too tired to cook, I will go out to eat. But what if all 3 of these conditions are true? I have food at home, but I also have cash. Then, we have a conflicting yes and no. That’s why we need to add weights to our perceptron.

Weights are multipliers that show how important each input is to our final decision. I will add some weights to our inputs:

  • x1 = Food at home = 1 x -3
  • x2 = Tired = 1 x 3
  • x3 = Have cash = 1 x 6

So if there was a day when I had food at home, I was tired, and I had cash: -3 + 3 + 6 = 6. I get 6 which is not a binary (0 or 1) output. Now that we’ve added weights, we have to figure out a way to change the output to be yes or no.

(By the way the w1, w2, and w3 in the above diagram are the weights added to the inputs)

We can achieve this by using sigmoid neurons instead of perceptrons. Sigmoid neurons are basically the same as perceptrons except they use decimals between 0 and 1 to make sure our output always comes out as a number between 0 and 1.

Let’s modify our inputs to reflect more ambiguous circumstances using sigmoid neurons. Let’s say I have food at home, but I don’t like the food. I’m only kind of tired. I barely have enough cash. I will give them values between 0 and 1 based on the particular situation.

  • x1 = Food at home = 0.5
  • x2 = Tired = 0.3
  • x3 = Have cash = 0.9

Now we will add the same weights:

  • x1 = Food at home = 0.5 x -3
  • x2 = Tired = 0.3 x 3
  • x3 = Have cash = 0.9 x 6

-1.5 + 0.9 + 5.4 = 4.8

Then, we would take the number 4.8 and turn it into a number between 0 and 1 using the sigmoid function.

An entire neural network is a multilayer perceptron or multiple layers of sigmoid neurons.

What is Theano?

Theano is an open source Python library for building neural networks.

In its most basic form, Theano is an optimizing compiler for mathematical expressions. It is specially designed to handle the computation required for large neural network algorithms used in Deep Learning.

Theano is written in Python & works well with Python libraries such as NumPy.

It was created at MILA (Montreal Institute for Learning Algorithms) at the University of Montreal. Development on the project started in 2007 and Theano has been around for over a decade. It is a pioneer in the field of Deep Learning research and development. It is the tool behind many research breakthroughs.

What is Keras?

Keras is a high-level framework for building and training deep learning models with relatively low amounts of code. It’s designed to make creating neural networks as simple as possible.

Although, it doesn’t run on its own. Keras is a front-end wrapper that runs on top of more complicated tools– TensorFlow or Theano. This means that you make your model in Keras, but behind the scenes it’s being converted to TensorFlow or Theano code.

One helpful feature of Keras is that it is designed to have best practices built in, so using the default settings is usually a safe bet. This makes it even easier for beginners.

Loading Data in TensorFlow

In order to train a Machine Learning model, you need training data. TensorFlow offers multiple methods of loading datasets. These are your three main options:

  1. Preload data into memory
  2. Feed data at request
  3. Set up a custom data pipeline

Option 1: Preload data into memory

Preload all your data into memory and pass it to TensorFlow

  • Easiest and fastest approach
  • All of the data must fit in your computer’s memory
  • Uses regular Python code, no TensorFlow

Option 2: Feed data at request

Portions of your data are fed to TensorFlow periodically, as TensorFlow requests it, instead of preloading it all at once

  • Gives you more control, but also more manual responsibility
  • Work with larger datasets
  • Normal Python code

Option 3: Set up a custom data pipeline

A data pipeline lets TensorFlow load data into memory by itself as it needs it

  • Can hold as much data as you want
  • Requires some TensorFlow code
  • Supports parallel processing (makes training larger datasets more efficient)

Use the straightforward preloading method if your dataset is smaller. Use the data pipeline if your dataset is extremely large

Building a Simple Model in TensorFlow

What are we building?

We will be building a very simple TensorFlow model that adds two numbers together. This will seem trivial, but it’s an uncomplicated way to introduce yourself to TensorFlow and making models.

How to build it

  1. Open PyCharm and create a new project
  2. Save the project with a .py extension. For example, addition.py

Now, time to code.

import os
import tensorflow as tf

First, we import the things we will need into our Python project. We add the as tf when we import TensorFlow so you don’t have to type the entire name out each time you want to access it.

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

Then, we add this line to prevent TensorFlow from flooding the screen with a bunch of log messages, like it normally does. It makes the output easier to read.

X = tf.placeholder(tf.float32, name="X")
Y = tf.placeholder(tf.float32, name="Y")

Here we define the X and Y input nodes. We are defining them as placeholder nodes that will get a different value each time we run it. In the parentheses, we set their data types and give them names.

addition = tf.add(X, Y, name="addition")

This node does the actual adding. We are basically asking it to add X and Y in this line. We also must give it a name.

# create the session
with tf.Session() as session:

     result = session.run(addition, feed_dict={X: [5], Y: [3]})
     print(result)

# output: [ 8. ]

We need to create a TensorFlow session to run the addition operation on X and Y. We input values for X and Y with the feed_dict parameter.

We are feeding the model arrays because TensorFlow always works with tensors, or multi-dimensional arrays.

You can now run your code.

import os
import tensorflow as tf

# Turn off TensorFlow warning messages in program output    (limits # of log messages)
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

# Define the nodes
X = tf.placeholder(tf.float32, name="X")
Y = tf.placeholder(tf.float32, name="Y")

addition = tf.add(X, Y, name="addition")

# Create the session
with tf.Session() as session:

    result = session.run(addition, feed_dict={X: [1, 5, 6], Y: [3, 4, 5]})

    print(result)

Since the inputs are arrays, you can put multiple numbers for X and Y. The output for the above should be [ 4. 9. 11. ]

This simple program may have seemed over-complicated just to do addition, but it taught you the basic structure of creating and running a TensorFlow model:

  1. Define a model
  2. Create a session
  3. Pass in data
  4. Send it to TensorFlow for execution

How to Install TensorFlow

TensorFlow is a tool to build machine learning models. Learn about it here.

Before we install TensorFlow, we have to install a programming language to use to write code in TensorFlow. TensorFlow works with multiple languages including JavaScript and Python. In this tutorial, we’re going to be downloading Python. How to install Python.

We will be installing TensorFlow with pip so make sure you have pip installed on your computer. You can check if you have pip installed by typing this line in Terminal:

pip3 --version

It should install by itself when you install Python so you shouldn’t have to worry about that.

Now we will install TensorFlow with the command below. It will install in your $HOME directory. If you don’t want this, find a tutorial that shows you how to use a virtual environment. I personally haven’t had luck with this strategy.

pip3 install --user --upgrade tensorflow 

Verify the install with this line:

python3 -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))"