One place for hosting & domains

      How To Build a Customer List Management App with React and TypeScript


      The author selected the Tech Education Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      TypeScript has brought a lot of improvement into how JavaScript developers structure and write code for apps, especially web applications. Defined as a superset of JavaScript, TypeScript behaves identically to JavaScript but with extra features designed to help developers build larger and more complex programs with fewer or no bugs. TypeScript is increasingly gaining popularity; adopted by major companies like Google for the Angular web framework. The Nest.js back-end framework was also built with TypeScript.

      One of the ways to improve productivity as a developer is the ability to implement new features as quickly as possible without any concern over breaking the existing app in production. To achieve this, writing statically typed code is a style adopted by many seasoned developers. Statically typed programming languages like TypeScript enforce an association for every variable with a data type; such as a string, integer, boolean, and so on. One of the major benefits of using a statically typed programming language is that type checking is completed at compile time, therefore developers can see errors in their code at a very early stage.

      React is an open-source JavaScript library, which developers use to create high-end user interfaces for scalable web applications. The great performance and dynamic user interfaces built with React for single-page applications make it a popular choice among developers.

      In this tutorial, you will create a customer list management application with a separate REST API backend and a frontend built with React and TypeScript. You will build the backend using a fake REST API named json-server. You’ll use it to quickly set up a CRUD (Create, Read, Update, and Delete) backend. Consequently you can focus on handling the front-end logic of an application using React and TypeScript.

      Prerequisites

      To complete this tutorial, you will need:

      Step 1 — Installing TypeScript and Creating the React Application

      In this step, you will install the TypeScript package globally on your machine by using the Node Package Manager (npm). After that, you will also install React and its dependencies, and check that your React app is working by running the development server.

      To begin, open a terminal and run the following command to install TypeScript:

      • npm install -g typescript

      Once the installation process is complete, execute the following command to check your installation of TypeScript:

      You will see the current version installed on your machine:

      Output

      Version 3.4.5

      Next, you will install the React application by using the create-react-app tool to set up the application with a single command. You'll use the npx command, which is a package runner tool that comes with npm 5.2+. The create-react-app tool has built-in support for working with TypeScript without any extra configuration required. Run the following command to create and install a new React application named typescript-react-app:

      • npx create-react-app typescript-react-app --typescript

      The preceding command will create a new React application with the name typescript-react-app. The --typescript flag will set the default filetype for React components to .tsx.

      Before you complete this section, the application will require moving from one port to another. To do that, you will need to install a routing library for your React application named React Router and its corresponding TypeScript definitions. You will use yarn to install the library and other packages for this project. This is because yarn is faster, especially for installing dependencies for a React application. Move into the newly created project folder and then install React Router with the following command:

      • cd typescript-react-app
      • yarn add react-router-dom

      You now have the React Router package, which will provide the routing functionality within your project. Next, run the following command to install the TypeScript definitions for React Router:

      • yarn add @types/react-router-dom

      Now you'll install axios, which is a promised-based HTTP client for browsers, to help with the process of performing HTTP requests from the different components that you will create within the application:

      Once the installation process is complete, start the development server with:

      Your application will be running on http://localhost:3000.

      React application homepage

      You have successfully installed TypeScript, created a new React application, and installed React Router in order to help with navigating from one page of the application to another. In the next section, you will set up the back-end server for the application.

      Step 2 — Creating a JSON Server

      In this step, you'll create a mock server that your React application can quickly connect with, as well as use its resources. It is important to note that this back-end service is not suitable for an application in production. You can use Nest.js, Express, or any other back-end technology to build a RESTful API in production. json-server is a useful tool whenever you need to create a prototype and mock a back-end server.

      You can use either npm or yarn to install json-server on your machine. This will make it available from any directory of your project whenever you might need to make use of it. Open a new terminal window and run this command to install json-server while you are still within the project directory:

      • yarn global add json-server

      Next, you will create a JSON file that will contain the data that will be exposed by the REST API. For the objects specified in this file (which you'll create), a CRUD endpoint will be generated automatically. To begin, create a new folder named server and then move into it:

      Now, use nano to create and open a new file named db.json:

      Add the following content to the file:

      /server/db.json

      {
          "customers": [
              {
                  "id": 1,
                  "first_name": "Customer_1",
                  "last_name": "Customer_11",
                  "email": "customer1@mail.com",
                  "phone": "00000000000",
                  "address": "Customer_1 Address",
                  "description": "Customer_1 description"
              },
              {
                  "id": 2,
                  "first_name": "Customer_2",
                  "last_name": "Customer_2",
                  "email": "customer2@mail.com",
                  "phone": "00000000000",
                  "address": "Customer_2 Adress",
                  "description": "Customer_2 Description"
              }
          ]
      }
      

      The JSON structure consists of a customer object, which has two datasets assigned. Each customer consists of seven properties: id, description, first_name, last_name, email, phone, and address.

      Save and exit the file.

      By default, the json-server runs on port 3000—this is the same port on which your React application runs. To avoid conflict, you can change the default port for the json-server. To do that, move to the root directory of the application:

      • cd ~/typescript-react-app

      Open the application with your preferred text editor and create a new file named json-server.json:

      Now insert the following to update the port number:

      /json-server.json

      {
          "port": 5000
      }
      

      This will act as the configuration file for the json-server and it will ensure that the server runs on the port specified in it at all times.

      Save and exit the file.

      To run the server, use the following command:

      • json-server --watch server/db.json

      This will start the json-server on port 5000. If you navigate to http://localhost:5000/customers in your browser, you will see the server showing your customer list.

      Customer list shown by json-server

      To streamline the process of running the json-server, you can update package.json with a new property named server to the scripts object as shown here:

      /package.json

      {
      ...
        "scripts": {
          "start": "react-scripts start",
          "build": "react-scripts build",
          "test": "react-scripts test",
          "eject": "react-scripts eject",
          "server": "json-server --watch server/db.json"
        },
      ...
      }
      

      Save and exit the file.

      Now anytime you wish to start the json-server, all you have to do is run yarn server from the terminal.

      You've created a simple REST API that you will use as the back-end server for this application. You also created a customer JSON object that will be used as the default data for the REST API. Lastly, you configured an alternative port for the back-end server powered by json-server. Next, you will build reusable components for your application.

      Step 3 — Creating Reusable Components

      In this section, you will create the required React components for the application. This will include components to create, display, and edit the details of a particular customer in the database respectively. You'll also build some of the TypeScript interfaces for your application.

      To begin, move back to the terminal where you have the React application running and stop the development server with CTRL + C. Next, navigate to the ./src/ folder:

      Then, create a new folder named components inside of it and move into the new folder:

      • mkdir components
      • cd components

      Within the newly created folder, create a customer folder and then move into it:

      • mkdir customer
      • cd customer

      Now create two new files named Create.tsx and Edit.tsx:

      • touch Create.tsx Edit.tsx

      These files are React reusable components that will render the forms and hold all the business logic for creating and editing the details of a customer respectively.

      Open the Create.tsx file in your text editor and add the following code:

      /src/components/customer/Create.tsx

      import * as React from 'react';
      import axios from 'axios';
      import { RouteComponentProps, withRouter } from 'react-router-dom';
      
      export interface IValues {
          first_name: string,
          last_name: string,
          email: string,
          phone: string,
          address: string,
          description: string,
      }
      export interface IFormState {
          [key: string]: any;
          values: IValues[];
          submitSuccess: boolean;
          loading: boolean;
      }
      
      

      Here you've imported React, axios, and other required components necessary for routing from the React Router package. After that you created two new interfaces named IValues and IFormState. TypeScript interfaces help to define the specific type of values that should be passed to an object and enforce consistency throughout an application. This ensures that bugs are less likely to appear in your program.

      Next, you will build a Create component that extends React.Component. Add the following code to the Create.tsx file immediately after the IFormState interface:

      /src/components/customer/Create.tsx

      ...
      class Create extends React.Component<RouteComponentProps, IFormState> {
          constructor(props: RouteComponentProps) {
              super(props);
              this.state = {
                  first_name: '',
                  last_name: '',
                  email: '',
                  phone: '',
                  address: '',
                  description: '',
                  values: [],
                  loading: false,
                  submitSuccess: false,
              }
          }
      }
      export default withRouter(Create)
      

      Here you've defined a React component in Typescript. In this case, the Create class component accepts props (short for “properties”) of type RouteComponentProps and uses a state of type IFormState. Then, inside the constructor, you initialized the state object and defined all the variables that will represent the rendered values for a customer.

      Next, add these methods within the Create class component, just after the constructor. You'll use these methods to process customer forms and handle all changes in the input fields:

      /src/components/customer/Create.tsx

      ...
                values: [],
                loading: false,
                submitSuccess: false,
            }
        }
      
        private processFormSubmission = (e: React.FormEvent<HTMLFormElement>): void => {
                e.preventDefault();
                this.setState({ loading: true });
                const formData = {
                    first_name: this.state.first_name,
                    last_name: this.state.last_name,
                    email: this.state.email,
                    phone: this.state.phone,
                    address: this.state.address,
                    description: this.state.description,
                }
                this.setState({ submitSuccess: true, values: [...this.state.values, formData], loading: false });
                axios.post(`http://localhost:5000/customers`, formData).then(data => [
                    setTimeout(() => {
                        this.props.history.push('/');
                    }, 1500)
                ]);
            }
      
            private handleInputChanges = (e: React.FormEvent<HTMLInputElement>) => {
                e.preventDefault();
                this.setState({
                    [e.currentTarget.name]: e.currentTarget.value,
            })
        }
      
      ...
      export default withRouter(Create)
      ...
      

      The processFormSubmission() method receives the details of the customer from the application state and posts it to the database using axios. The handleInputChanges() uses React.FormEvent to obtain the values of all input fields and calls this.setState() to update the state of the application.

      Next, add the render() method within the Create class component immediately after the handleInputchanges() method. This render() method will display the form to create a new customer in the application:

      /src/components/customer/Create.tsx

      ...
        public render() {
            const { submitSuccess, loading } = this.state;
            return (
                <div>
                    <div className={"col-md-12 form-wrapper"}>
                        <h2> Create Post </h2>
                        {!submitSuccess && (
                            <div className="alert alert-info" role="alert">
                                Fill the form below to create a new post
                        </div>
                        )}
                        {submitSuccess && (
                            <div className="alert alert-info" role="alert">
                                The form was successfully submitted!
                                </div>
                        )}
                        <form id={"create-post-form"} onSubmit={this.processFormSubmission} noValidate={true}>
                            <div className="form-group col-md-12">
                                <label htmlFor="first_name"> First Name </label>
                                <input type="text" id="first_name" onChange={(e) => this.handleInputChanges(e)} name="first_name" className="form-control" placeholder="Enter customer's first name" />
                            </div>
                            <div className="form-group col-md-12">
                                <label htmlFor="last_name"> Last Name </label>
                                <input type="text" id="last_name" onChange={(e) => this.handleInputChanges(e)} name="last_name" className="form-control" placeholder="Enter customer's last name" />
                            </div>
                            <div className="form-group col-md-12">
                                <label htmlFor="email"> Email </label>
                                <input type="email" id="email" onChange={(e) => this.handleInputChanges(e)} name="email" className="form-control" placeholder="Enter customer's email address" />
                            </div>
                            <div className="form-group col-md-12">
                                <label htmlFor="phone"> Phone </label>
                                <input type="text" id="phone" onChange={(e) => this.handleInputChanges(e)} name="phone" className="form-control" placeholder="Enter customer's phone number" />
                            </div>
                            <div className="form-group col-md-12">
                                <label htmlFor="address"> Address </label>
                                <input type="text" id="address" onChange={(e) => this.handleInputChanges(e)} name="address" className="form-control" placeholder="Enter customer's address" />
                            </div>
                            <div className="form-group col-md-12">
                                <label htmlFor="description"> Description </label>
                                <input type="text" id="description" onChange={(e) => this.handleInputChanges(e)} name="description" className="form-control" placeholder="Enter Description" />
                            </div>
                            <div className="form-group col-md-4 pull-right">
                                <button className="btn btn-success" type="submit">
                                    Create Customer
                                </button>
                                {loading &&
                                    <span className="fa fa-circle-o-notch fa-spin" />
                                }
                            </div>
                        </form>
                    </div>
                </div>
            )
        }
      ...
      

      Here, you created a form with the input fields to hold the values of the first_name, last_name, email, phone, address, and description of a customer. Each of the input fields have a method handleInputChanges() that runs on every keystroke, updating the React state with the value it obtains from the input field. Furthermore, depending on the state of the application, a boolean variable named submitSuccess will control the message that the application will display before and after creating a new customer.

      You can see the complete code for this file in this GitHub repository.

      Save and exit Create.tsx.

      Now that you have added the appropriate logic to the Create component file for the application, you'll proceed to add contents for the Edit component file.

      Open your Edit.tsx file within the customer folder, and start by adding the following content to import React, axios, and also define TypeScript interfaces:

      /src/components/customer/Edit.tsx

      import * as React from 'react';
      import { RouteComponentProps, withRouter } from 'react-router-dom';
      import axios from 'axios';
      
      export interface IValues {
          [key: string]: any;
      }
      export interface IFormState {
          id: number,
          customer: any;
          values: IValues[];
          submitSuccess: boolean;
          loading: boolean;
      }
      

      Similarly to the Create component, you import the required modules and create IValues and IFormState interfaces respectively. The IValues interface defines the data type for the input fields' values, while you'll use IFormState to declare the expected type for the state object of the application.

      Next, create the EditCustomer class component directly after the IFormState interface block as shown here:

      /src/components/customer/Edit.tsx

      ...
      class EditCustomer extends React.Component<RouteComponentProps<any>, IFormState> {
          constructor(props: RouteComponentProps) {
              super(props);
              this.state = {
                  id: this.props.match.params.id,
                  customer: {},
                  values: [],
                  loading: false,
                  submitSuccess: false,
              }
          }
      }
      export default withRouter(EditCustomer)
      

      This component takes the RouteComponentProps<any> and an interface of IFormState as a parameter. You use the addition of <any> to the RouteComponentProps because whenever React Router parses path parameters, it doesn’t do any type conversion to ascertain whether the type of the data is number or string. Since you're expecting a parameter for uniqueId of a customer, it is safer to use any.

      Now add the following methods within the component:

      /src/components/customer/Edit.tsx

      ...
          public componentDidMount(): void {
              axios.get(`http://localhost:5000/customers/${this.state.id}`).then(data => {
                  this.setState({ customer: data.data });
              })
          }
      
          private processFormSubmission = async (e: React.FormEvent<HTMLFormElement>): Promise<void> => {
              e.preventDefault();
              this.setState({ loading: true });
              axios.patch(`http://localhost:5000/customers/${this.state.id}`, this.state.values).then(data => {
                  this.setState({ submitSuccess: true, loading: false })
                  setTimeout(() => {
                      this.props.history.push('/');
                  }, 1500)
              })
          }
      
          private setValues = (values: IValues) => {
              this.setState({ values: { ...this.state.values, ...values } });
          }
          private handleInputChanges = (e: React.FormEvent<HTMLInputElement>) => {
              e.preventDefault();
              this.setValues({ [e.currentTarget.id]: e.currentTarget.value })
          }
      ...
      }
      
      export default withRouter(EditCustomer)
      

      First, you add a componentDidMount() method, which is a lifecycle method that is being called when the component is created. The method takes the id obtained from the route parameter to identify a particular customer as a parameter, uses it to retrieve their details from the database and then populates the form with it. Furthermore, you add methods to process form submission and handle changes made to the values of the input fields.

      Lastly, add the render() method for the Edit component:

      /src/components/customer/Edit.tsx

      ...
          public render() {
              const { submitSuccess, loading } = this.state;
              return (
                  <div className="App">
                      {this.state.customer &&
                          <div>
                              < h1 > Customer List Management App</h1>
                              <p> Built with React.js and TypeScript </p>
      
                              <div>
                                  <div className={"col-md-12 form-wrapper"}>
                                      <h2> Edit Customer </h2>
                                      {submitSuccess && (
                                          <div className="alert alert-info" role="alert">
                                              Customer's details has been edited successfully </div>
                                      )}
                                      <form id={"create-post-form"} onSubmit={this.processFormSubmission} noValidate={true}>
                                          <div className="form-group col-md-12">
                                              <label htmlFor="first_name"> First Name </label>
                                              <input type="text" id="first_name" defaultValue={this.state.customer.first_name} onChange={(e) => this.handleInputChanges(e)} name="first_name" className="form-control" placeholder="Enter customer's first name" />
                                          </div>
                                          <div className="form-group col-md-12">
                                              <label htmlFor="last_name"> Last Name </label>
                                              <input type="text" id="last_name" defaultValue={this.state.customer.last_name} onChange={(e) => this.handleInputChanges(e)} name="last_name" className="form-control" placeholder="Enter customer's last name" />
                                          </div>
                                          <div className="form-group col-md-12">
                                              <label htmlFor="email"> Email </label>
                                              <input type="email" id="email" defaultValue={this.state.customer.email} onChange={(e) => this.handleInputChanges(e)} name="email" className="form-control" placeholder="Enter customer's email address" />
                                          </div>
                                          <div className="form-group col-md-12">
                                              <label htmlFor="phone"> Phone </label>
                                              <input type="text" id="phone" defaultValue={this.state.customer.phone} onChange={(e) => this.handleInputChanges(e)} name="phone" className="form-control" placeholder="Enter customer's phone number" />
                                          </div>
                                          <div className="form-group col-md-12">
                                              <label htmlFor="address"> Address </label>
                                              <input type="text" id="address" defaultValue={this.state.customer.address} onChange={(e) => this.handleInputChanges(e)} name="address" className="form-control" placeholder="Enter customer's address" />
                                          </div>
                                          <div className="form-group col-md-12">
                                              <label htmlFor="description"> Description </label>
                                              <input type="text" id="description" defaultValue={this.state.customer.description} onChange={(e) => this.handleInputChanges(e)} name="description" className="form-control" placeholder="Enter Description" />
                                          </div>
                                          <div className="form-group col-md-4 pull-right">
                                              <button className="btn btn-success" type="submit">
                                                  Edit Customer </button>
                                              {loading &&
                                                  <span className="fa fa-circle-o-notch fa-spin" />
                                              }
                                          </div>
                                      </form>
                                  </div>
                              </div>
                          </div>
                      }
                  </div>
              )
          }
      ...    
      

      Here, you created a form to edit the details of a particular customer, and then populated the input fields within that form with the customer's details that your application's state obtained. Similarly to the Create component, changes made to all the input fields will be handled by the handleInputChanges() method.

      You can see the complete code for this file in this GitHub repository.

      Save and exit Edit.tsx.

      To view the complete list of customers created within the application, you’ll create a new component within the ./src/components folder and name it Home.tsx:

      • cd ./src/components
      • nano Home.tsx

      Add the following content:

      /src/components/Home.tsx

      import * as React from 'react';
      import { Link, RouteComponentProps } from 'react-router-dom';
      import axios from 'axios';
      
      interface IState {
          customers: any[];
      }
      
      export default class Home extends React.Component<RouteComponentProps, IState> {
          constructor(props: RouteComponentProps) {
              super(props);
              this.state = { customers: [] }
          }
          public componentDidMount(): void {
              axios.get(`http://localhost:5000/customers`).then(data => {
                  this.setState({ customers: data.data })
              })
          }
          public deleteCustomer(id: number) {
              axios.delete(`http://localhost:5000/customers/${id}`).then(data => {
                  const index = this.state.customers.findIndex(customer => customer.id === id);
                  this.state.customers.splice(index, 1);
                  this.props.history.push('/');
              })
          }
      }
      

      Here, you've imported React, axios, and other required components from React Router. You created two new methods within the Home component:

      • componentDidMount(): The application invokes this method immediately after a component is mounted. Its responsibility here is to retrieve the list of customers and update the home page with it.
      • deleteCustomer(): This method will accept an id as a parameter and will delete the details of the customer identified with that id from the database.

      Now add the render() method to display the table that holds the list of customers for the Home component:

      /src/components/Home.tsx

      ...
      public render() {
              const customers = this.state.customers;
              return (
                  <div>
                      {customers.length === 0 && (
                          <div className="text-center">
                              <h2>No customer found at the moment</h2>
                          </div>
                      )}
                      <div className="container">
                          <div className="row">
                              <table className="table table-bordered">
                                  <thead className="thead-light">
                                      <tr>
                                          <th scope="col">Firstname</th>
                                          <th scope="col">Lastname</th>
                                          <th scope="col">Email</th>
                                          <th scope="col">Phone</th>
                                          <th scope="col">Address</th>
                                          <th scope="col">Description</th>
                                          <th scope="col">Actions</th>
                                      </tr>
                                  </thead>
                                  <tbody>
                                      {customers && customers.map(customer =>
                                          <tr key={customer.id}>
                                              <td>{customer.first_name}</td>
                                              <td>{customer.last_name}</td>
                                              <td>{customer.email}</td>
                                              <td>{customer.phone}</td>
                                              <td>{customer.address}</td>
                                              <td>{customer.description}</td>
                                              <td>
                                                  <div className="d-flex justify-content-between align-items-center">
                                                      <div className="btn-group" style={{ marginBottom: "20px" }}>
                                                          <Link to={`edit/${customer.id}`} className="btn btn-sm btn-outline-secondary">Edit Customer </Link>
                                                          <button className="btn btn-sm btn-outline-secondary" onClick={() => this.deleteCustomer(customer.id)}>Delete Customer</button>
                                                      </div>
                                                  </div>
                                              </td>
                                          </tr>
                                      )}
                                  </tbody>
                              </table>
                          </div>
                      </div>
                  </div>
              )
          }
      ...
      

      In this code block, you retrieve the lists of customers from the application's state as an array, iterate over it, and display it within an HTML table. You also add the customer.id parameter, which the method uses to identify and delete the details of a particular customer from the list.

      Save and exit Home.tsx.

      You've adopted a statically typed principle for all the components created with this application by defining types for the components and props through the use of interfaces. This is one of the best approaches to using TypeScript for a React application.

      With this, you've finished creating all the required reusable components for the application. You can now update the app component with links to all the components that you have created so far.

      Step 4 — Setting Up Routing and Updating the Entry Point of the Application

      In this step, you will import the necessary components from the React Router package and configure the App component to render different components depending on the route that is loaded. This will allow you to navigate through different pages of the application. Once a user visits a route, for example /create, React Router will use the path specified to render the contents and logic within the appropriate component defined to handle such route.

      Navigate to ./src/App.tsx:

      Then replace its content with the following:

      /src/App.tsx

      import * as React from 'react';
      import './App.css';
      import { Switch, Route, withRouter, RouteComponentProps, Link } from 'react-router-dom';
      import Home from './components/Home';
      import Create from './components/customer/Create';
      import EditCustomer from './components/customer/Edit';
      
      class App extends React.Component<RouteComponentProps<any>> {
        public render() {
          return (
            <div>
              <nav>
                <ul>
                  <li>
                    <Link to={'/'}> Home </Link>
                  </li>
                  <li>
                    <Link to={'/create'}> Create Customer </Link>
                  </li>
                </ul>
              </nav>
              <Switch>
                <Route path={'/'} exact component={Home} />
                <Route path={'/create'} exact component={Create} />
                <Route path={'/edit/:id'} exact component={EditCustomer} />
              </Switch>
            </div>
          );
        }
      }
      export default withRouter(App);
      

      You imported all the necessary components from the React Router package and you also imported the reusable components for creating, editing, and viewing customers' details.

      Save and exit App.tsx.

      The ./src/index.tsx file is the entry point for this application and renders the application. Open this file and import React Router into it, then wrap the App component inside a BrowserRouter:

      /src/index.tsx

      import React from 'react';
      import ReactDOM from 'react-dom';
      import './index.css';
      import App from './App';
      import { BrowserRouter } from 'react-router-dom'; 
      import * as serviceWorker from './serviceWorker';
      ReactDOM.render(
          <BrowserRouter>
              <App />
          </BrowserRouter>
          , document.getElementById('root')
      );
      serviceWorker.unregister();
      

      React Router uses the BrowserRouter component to make your application aware of the navigation, such as history and current path.

      Once you've finished editing Index.tsx, save and exit.

      Lastly, you will use Bootstrap to add some style to your application. Bootstrap is a popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first projects on the web. It allows developers to build an appealing user interface without having to write too much CSS. It comes with a responsive grid system that gives a web page a finished look that works on all devices.

      To include Bootstrap and styling for your application, replace the contents of ./src/App.css with the following:

      /src/App.css

      @import 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css';
      
      .form-wrapper {
        width: 500px;
        margin: 0 auto;
      }
      .App {
        text-align: center;
        margin-top: 30px;
      }
      nav {
        width: 300px;
        margin: 0 auto;
        background: #282c34;
        height: 70px;
        line-height: 70px;
      }
      nav ul li {
        display: inline;
        list-style-type: none;
        text-align: center;
        padding: 30px;
      }
      nav ul li a {
        margin: 50px 0;
        font-weight: bold;
        color: white;
        text-decoration: none;
      }
      nav ul li a:hover {
        color: white;
        text-decoration: none;
      }
      table {
        margin-top: 50px;
      }
      .App-link {
        color: #61dafb;
      }
      @keyframes App-logo-spin {
        from {
          transform: rotate(0deg);
        }
        to {
          transform: rotate(360deg);
        }
      }
      

      You have used Bootstrap here to enhance the look and feel of the application by giving it a default layout, styles, and color. You have also added some custom styles, particularly to the navigation bar.

      Save and exit App.css.

      In this section, you have configured React Router to render the appropriate component depending on the route visited by the user and also added some styling to make the application more attractive to users. Next, you will test all the functionality implemented for the application.

      Step 5 — Running Your Application

      Now that you have set up the frontend of this application with React and TypeScript by creating several reusable components, and also built a REST API with the json-server, you can run your app.

      Navigate back to the project’s root folder:

      • cd ~/typescript-react-app

      Next run the following command to start your app:

      Note: Make sure your server is still running in the other terminal window. Otherwise, start it with: yarn server.

      Navigate to http://localhost:3000 to view the application from your browser. Then proceed to click on the Create button and fill in the details of a customer.

      Create customer page

      After entering the appropriate values in the input fields, click on the Create Customer button to submit the form. The application will redirect you back to your homepage once you're done creating a new customer.

      View customers page

      Click the Edit Customer button for any of the rows and you will be directed to the page that hosts the editing functionality for the corresponding customer on that row.

      Edit customer page

      Edit the details of the customer and then click on Edit Customer to update the customer’s details.

      You've run your application to ensure all the components are working. Using the different pages of your application, you've created and edited a customer entry.

      Conclusion

      In this tutorial you built a customer list management app with React and TypeScript. The process in this tutorial is a deviation from using JavaScript as the conventional way of structuring and building applications with React. You've leveraged the benefits of using TypeScript to complete this front-end focused tutorial.

      To continue to develop this project, you can move your mock back-end server to a production-ready back-end technology like Express or Nest.js. Furthermore, you can extend what you have built in this tutorial by adding more features such as authentication and authorization with different tools like the Passport.js authentication library.

      You can find the complete source code for the project on GitHub.



      Source link

      9 Steps to Build an Online Store and Become Your Own Boss in 2019


      While traditional careers have their benefits, there’s something very appealing about being your own boss. You can work whenever, however, and wherever you want to while still pursuing your passion. The tricky part is knowing how to get started.

      With accessible and easy-to-use tools such as WordPress and WooCommerce, setting up shop online is relatively simple. By launching an e-commerce store, you can take your product ideas to the web and access the vast pool of customers available there.

      This article will walk you through the steps to build your online store with WordPress and WooCommerce and become your own boss in no time. Let’s go!

      Your Store Deserves WooCommerce Hosting

      Sell anything, anywhere, anytime on the world’s biggest eCommerce platform.

      9 Steps to Build an Online Store and Become Your Own Boss

      The very first thing you’ll need to start an online store is a product customers will want to buy. We can’t help you with that, unfortunately — your idea has to be all your own! You’ll also need a way to manufacture your product, either by doing it yourself, hiring a company to do it, or some combination of the two.

      Once you’re done, you’ll be ready to set up your online store and start selling your merchandise, which is where the steps below will come in handy.

      Step 1: Secure Your Web Hosting and Domain Name

      The first two things you need to start any kind of website are a hosting provider and a domain name. Your hosting provider will store your website’s files, while your domain name provides an address where customers can find your store.

      If you’re building a WordPress site (which we recommend), you might also want to consider WordPress hosting. These types of plans are explicitly geared towards the platform, and the servers they run on will be optimized.

      Our shared WordPress hosting plans, for example, are ideal for new WordPress sites. You’ll have access to our 24/7 tech support team, and plans are cost-effective, starting at just $2.59 per month for a single site.

      DreamHost’s Shared WordPress Hosting page.

      What’s more, we can also help you register your domain name. You can quickly check the availability of your desired web address, then register it once you’ve found the perfect fit.

      DreamHost’s domain name search.

      Simply fill in some information to complete the process. Domains usually start at $11.99, but if you’re also hosting your site with a shared WordPress plan, you’ll get yours for free.

      Step 2: Set Up WordPress and WooCommerce

      Regardless of your current host, a WordPress hosting plan likely comes with the platform pre-installed or with a one-click installation option. In some cases, you may need to install WordPress manually.

      Next, you’ll need to set up WooCommerce — a premiere e-commerce solution for WordPress (we’ve compared it to other competitors and think it’s the best ecommerce platform available).

      The first step is to install and activate the WooCommerce plugin.

      The WooCommerce plugin.

      Once this is complete, you’ll be prompted to configure your store using the onboarding wizard — fill in the fields as best you can now, or come back to this step later.

      Step 3: Identify Your ‘Value Proposition’

      Before you begin creating content for your e-commerce business, consider identifying and writing out your value proposition. This is simply a statement explaining the mission and value of your business and products.

      Two of the most important questions your value proposition should answer are:

      1. What problem does my product solve for customers?
      2. What makes my approach to this problem unique compared to other similar businesses?

      Establishing your value proposition now should help you create content later. Also, any copy, product, or long-form content (such as a blog post) should reflect the values you identified in your proposition.

      We’d also suggest sharing your value proposition with customers on your website. Most companies do this on an About page or as a ‘Mission Statement.’ Here’s ours as an example:

      The DreamHost About page.

      Sharing your values with customers can help demonstrate why your product is relevant to them. Plus, you might win over customers who might have otherwise purchased from your competition.

      Step 4: Create Your Product Pages

      Now you’re ready to go back to setting up your online store. Navigate to Products > Add New within WordPress to start adding your first item. There are a lot of settings to consider here, but your priority should be your product photos and description.

      Taking Quality Product Photos

      Showcasing your products in their (literal) best light is crucial. Unprofessional, low-quality photos make your site seem untrustworthy, which will discourage customers from opening their wallet.

      As such, make sure your product photos are well-lit and taken in front of a clean background. If you can, take pictures from a variety of angles, and include some close-ups of unique details to help catch customers’ eyes.

      A product photo of a throw pillow from Wayfair.

      Once you have your product photos, make sure to optimize them with a plugin such as ShortPixel or Optimole before uploading them to your site. This will help prevent large media files from slowing your site down.

      Writing Captivating Product Descriptions

      You’ll also want to craft your product descriptions carefully, to help convince site visitors to become paying customers. Keep your value proposition in mind when you’re writing, and make sure to point out information about how the product will benefit customers.

      A product description for a throw pillow from Wayfair.

      It’s vital to make your description easy to scan, as ‘skimming’ content has become more popular over the years. Keeping paragraphs short, while using formatting techniques such as bullet points and subheadings, can convey more information than a brutal wall of text.

      Specifying Product Data

      Finally, for this section, you’ll want to configure the settings in the Product Data section of the product editor. Here you’ll set your product’s price, add a SKU number and shipping information, specify if it comes in any variations (e.g., other colors or sizes), and more.

      The product data section of the WooCommerce Product Editor.

      Take your time with these, as they’re an essential aspect of your store and business. Once you have the basics down, you may want to consider setting up Linked Products to help cross-sell other store items and enable reviews to add some social proof to your site.

      Step 5: Configure Your Tax Settings

      In the U.S., each state has laws regarding sales tax for internet-based retailers. It’s not a bad idea to talk with a tax attorney before your business gets up and running, but at the very least, you should familiarize yourself with the laws in your area.

      To set up sales tax for your products in WooCommerce, navigate to WooCommerce > Settings > General within WordPress. Make sure the Enable taxes setting is checked, then save your changes.

      The Enable taxes setting in WooCommerce.

      If there wasn’t one before, you should now see a Tax setting tab at the top of your WooCommerce Settings page. Click on it, then configure the settings on the page.

      You can determine whether your prices will automatically include tax at checkout and what information WooCommerce should use to calculate tax for each product. It’s also possible to add Standard, Reduced, and Zero tax rates if needed.

      Step 6: Specify Your Shipping Methods

      Shipping is a make-or-break aspect of running a store. As such, in the Shipping settings tab, you can add practically as many options as you want to implement a delivery strategy.

      If you’re going to make your products available in a wide range of locations, you might want to create ‘shipping zones.’

      They essentially let you offer different rates to customers depending on where they’re located. If you also want to charge extra for international shipping, you can do so here.

      Step 7: Decide Which Payment Gateway to Offer

      In the Payments settings tab, you can specify how customers can pay for their products. By default, WooCommerce will set up Stripe and PayPal vendors for you.

      The Payment Methods settings in WooCommerce.

      However, you can add additional gateways — including popular solutions such as Square and Amazon Pay — with WooCommerce extensions. In addition, you can enable your customers to pay with a check, cash, or by bank transfer.

      The gateways you decide to offer are ultimately up to you, based on familiarity, ease of use, and transaction fees. However, it’s also important to consider your customers, as these criteria are also their primary concerns. As such, gateways such as PayPal are usually a given.

      Step 8: Run Through Your WooCommerce Search Engine Optimization (SEO) Checklist

      You’re almost ready to welcome customers to your store, but first, they need to be able to find it. SEO is the answer. By optimizing your content for search engines, you’ll make it more likely customers can find you while searching for products online.

      As with many site aspects, WordPress plugins can help. Yoast SEO is a highly rated and effective plugin that can help manage on-page SEO factors such as keyword usage, permalinks, and readability.

      The Yoast SEO plugin from the WordPress Plugin Directory.

      If you want something a little more specialized, you can also look into the Yoast WooCommerce SEO plugin.

      The Yoast WooCommerce SEO plugin.

      It’s better suited to WooCommerce than the free version, and can also help promote your products on social media. At $49 per year, it’s cost-effective and may be a solid investment, especially if it helps to bring in a few more organic customers via search engine.

      Step 9: Publish and Promote Your E-Commerce Website

      While you can keep refining your site, you’ll want to publish at this point — think of it as laying down a ‘marker.’ You’ll also want to make sure customers know who you are and what you do. Promoting your site on social media and through email marketing campaigns can help get you started.

      Fortunately, there are a variety of WooCommerce extensions available to help. You can choose popular services such as Drip, MailChimp, and even Instagram to promote your products to followers and subscribers.

      The WooCommerce Instagram extension.

      Marketing will be an ongoing responsibility, so investing in some tools to help you streamline your efforts will be worth it in the long run. The extensions mentioned above range from free to $79 per year. You can also search the WordPress Plugin Directory for more free solutions, although you may find functionality lacks depending on the plugin.

      Building an Online Store

      No one said becoming your own boss was easy, and there’s a lot of work that goes into starting a brand new business. However, WordPress and WooCommerce can simplify many of the tasks required to get your e-commerce site up and running.

      Ready to set up an online shop? Our WooCommerce hosting packages make it easy to sell anything, anywhere, anytime on the world’s biggest eCommerce platform.



      Source link

      How To Build a Deep Learning Model to Predict Employee Retention Using Keras and TensorFlow


      The author selected Girls Who Code to receive a donation as part of the Write for DOnations program.

      Introduction

      Keras is a neural network API that is written in Python. It runs on top of TensorFlow, CNTK, or Theano. It is a high-level abstraction of these deep learning frameworks and therefore makes experimentation faster and easier. Keras is modular, which means implementation is seamless as developers can quickly extend models by adding modules.

      TensorFlow is an open-source software library for machine learning. It works efficiently with computation involving arrays; so it’s a great choice for the model you’ll build in this tutorial. Furthermore, TensorFlow allows for the execution of code on either CPU or GPU, which is a useful feature especially when you’re working with a massive dataset.

      In this tutorial, you’ll build a deep learning model that will predict the probability of an employee leaving a company. Retaining the best employees is an important factor for most organizations. To build your model, you’ll use this dataset available at Kaggle, which has features that measure employee satisfaction in a company. To create this model, you’ll use the Keras sequential layer to build the different layers for the model.

      Prerequisites

      Before you begin this tutorial you’ll need the following:

      Step 1 — Data Pre-processing

      Data Pre-processing is necessary to prepare your data in a manner that a deep learning model can accept. If there are categorical variables in your data, you have to convert them to numbers because the algorithm only accepts numerical figures. A categorical variable represents quantitive data represented by names. In this step, you’ll load in your dataset using pandas, which is a data manipulation Python library.

      Before you begin data pre-processing, you’ll activate your environment and ensure you have all the necessary packages installed to your machine. It’s advantageous to use conda to install keras and tensorflow since it will handle the installation of any necessary dependencies for these packages, and ensure they are compatible with keras and tensorflow. In this way, using the Anaconda Python distribution is a good choice for data science related projects.

      Move into the environment you created in the prerequisite tutorial:

      Run the following command to install keras and tensorflow:

      • conda install tensorflow keras

      Now, open Jupyter Notebook to get started. Jupyter Notebook is opened by typing the following command on your terminal:

      Note: If you're working from a remote server, you'll need to use SSH tunneling to access your notebook. Please revisit step 2 of the prerequisite tutorial for detailed on instructions on setting up SSH tunneling. You can use the following command from your local machine to initiate your SSH tunnel:

      • ssh -L 8888:localhost:8888 your_username@your_server_ip

      After accessing Jupyter Notebook, click on the anaconda3 file, and then click New at the top of the screen, and select Python 3 to load a new notebook.

      Now, you'll import the required modules for the project and then load the dataset in a notebook cell. You'll load in the pandas module for manipulating your data and numpy for converting the data into numpy arrays. You'll also convert all the columns that are in string format to numerical values for your computer to process.

      Insert the following code into a notebook cell and then click Run:

      import pandas as pd
      import numpy as np
      df = pd.read_csv("https://raw.githubusercontent.com/mwitiderrick/kerasDO/master/HR_comma_sep.csv")
      

      You've imported numpy and pandas. You then used pandas to load in the dataset for the model.

      You can get a glimpse at the dataset you're working with by using head(). This is a useful function from pandas that allows you to view the first five records of your dataframe. Add the following code to a notebook cell and then run it:

      df.head()
      

      Alt Checking the head for the dataset

      You'll now proceed to convert the categorical columns to numbers. You do this by converting them to dummy variables. Dummy variables are usually ones and zeros that indicate the presence or absence of a categorical feature. In this kind of situation, you also avoid the dummy variable trap by dropping the first dummy.

      Note: The dummy variable trap is a situation whereby two or more variables are highly correlated. This leads to your model performing poorly. You, therefore, drop one dummy variable to always remain with N-1 dummy variables. Any of the dummy variables can be dropped because there is no preference as long as you remain with N-1 dummy variables. An example of this is if you were to have an on/off switch. When you create the dummy variable you shall get two columns: an on column and an off column. You can drop one of the columns because if the switch isn't on, then it is off.

      Insert this code in the next notebook cell and execute it:

      feats = ['department','salary']
      df_final = pd.get_dummies(df,columns=feats,drop_first=True)
      

      feats = ['department','salary'] defines the two columns for which you want to create dummy variables. pd.get_dummies(df,columns=feats,drop_first=True) will generate the numerical variables that your employee retention model requires. It does this by converting the feats that you define from categorical to numerical variables.

      Step 1

      You've loaded in the dataset and converted the salary and department columns into a format the keras deep learning model can accept. In the next step, you will split the dataset into a training and testing set.

      Step 2 — Separating Your Training and Testing Datasets

      You'll use scikit-learn to split your dataset into a training and a testing set. This is necessary so you can use part of the employee data to train the model and a part of it to test its performance. Splitting a dataset in this way is a common practice when building deep learning models.

      It is important to implement this split in the dataset so the model you build doesn't have access to the testing data during the training process. This ensures that the model learns only from the training data, and you can then test its performance with the testing data. If you exposed your model to testing data during the training process then it would memorize the expected outcomes. Consequently, it would fail to give accurate predictions on data that it hasn't seen.

      You'll start by importing the train_test_split module from the scikit-learn package. This is the module that will provide the splitting functionality. Insert this code in the next notebook cell and run:

      from sklearn.model_selection import train_test_split
      

      With the train_test_split module imported, you'll use the left column in your dataset to predict if an employee will leave the company. Therefore, it is essential that your deep learning model doesn't come into contact with this column. Insert the following into a cell to drop the left column:

      X = df_final.drop(['left'],axis=1).values
      y = df_final['left'].values
      

      Your deep learning model expects to get the data as arrays. Therefore you use numpy to convert the data to numpy arrays with the .values attribute.

      You're now ready to convert the dataset into a testing and training set. You'll use 70% of the data for training and 30% for testing. The training ratio is more than the testing ratio because you'll need to use most of the data for the training process. If desired, you can also experiment with a ratio of 80% for the training set and 20% for the testing set.

      Now add this code to the next cell and run to split your training and testing data to the specified ratio:

      X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
      

      Step 2

      You have now converted the data into the type that Keras expects it to be in (numpy arrays), and your data is split into a training and testing set. You'll pass this data to the keras model later in the tutorial. Beforehand you need to transform the data, which you'll complete in the next step.

      Step 3 — Transforming the Data

      When building deep learning models it is usually good practice to scale your dataset in order to make the computations more efficient. In this step, you'll scale the data using the StandardScaler; this will ensure that your dataset values have a mean of zero and a unit variable. This transforms the dataset to be normally distributed. You'll use the scikit-learn StandardScaler to scale the features to be within the same range. This will transform the values to have a mean of 0 and a standard deviation of 1. This step is important because you're comparing features that have different measurements; so it is typically required in machine learning.

      To scale the training set and the test set, add this code to the notebook cell and run it:

      from sklearn.preprocessing import StandardScaler
      sc = StandardScaler()
      X_train = sc.fit_transform(X_train)
      X_test = sc.transform(X_test)
      

      Here, you start by importing the StandardScaler and calling an instance of it. You then use its fit_transform method to scale the training and testing set.

      You have scaled all your dataset features to be within the same range. You can start building the artificial neural network in the next step.

      Step 4 — Building the Artificial Neural Network

      Now you will use keras to build the deep learning model. To do this, you'll import keras, which will use tensorflow as the backend by default. From keras, you'll then import the Sequential module to initialize the artificial neural network. An artificial neural network is a computational model that is built using inspiration from the workings of the human brain. You'll import the Dense module as well, which will add layers to your deep learning model.

      When building a deep learning model you usually specify three layer types:

      • The input layer is the layer to which you'll pass the features of your dataset. There is no computation that occurs in this layer. It serves to pass features to the hidden layers.
      • The hidden layers are usually the layers between the input layer and the output layer—and there can be more than one. These layers perform the computations and pass the information to the output layer.
      • The output layer represents the layer of your neural network that will give you the results after training your model. It is responsible for producing the output variables.

      To import the Keras, Sequential, and Dense modules, run the following code in your notebook cell:

      import keras
      from keras.models import Sequential
      from keras.layers import Dense
      

      You'll use Sequential to initialize a linear stack of layers. Since this is a classification problem, you'll create a classifier variable. A classification problem is a task where you have labeled data and would like to make some predictions based on the labeled data. Add this code to your notebook to create a classifier variable:

      classifier = Sequential()
      

      You've used Sequential to initialize the classifier.

      You can now start adding layers to your network. Run this code in your next cell:

      classifier.add(Dense(9, kernel_initializer = "uniform",activation = "relu", input_dim=18))
      

      You add layers using the .add() function on your classifier and specify some parameters:

      • The first parameter is the number of nodes that your network should have. The connection between different nodes is what forms the neural network. One of the strategies to determine the number of nodes is to take the average of the nodes in the input layer and the output layer.

      • The second parameter is the kernel_initializer. When you fit your deep learning model the weights will be initialized to numbers close to zero, but not zero. To achieve this you use the uniform distribution initializer. kernel_initializer is the function that initializes the weights.

      • The third parameter is the activation function. Your deep learning model will learn through this function. There are usually linear and non-linear activation functions. You use the relu activation function because it generalizes well on your data. Linear functions are not good for problems like these because they form a straight line.

      • The last parameter is input_dim, which represents the number of features in your dataset.

      Now you'll add the output layer that will give you the predictions:

      classifier.add(Dense(1, kernel_initializer = "uniform",activation = "sigmoid"))
      

      The output layer takes the following parameters:

      • The number of output nodes. You expect to get one output: if an employee leaves the company. Therefore you specify one output node.

      • For kernel_initializer you use the sigmoid activation function so that you can get the probability that an employee will leave. In the event that you were dealing with more than two categories, you would use the softmax activation function, which is a variant of the sigmoid activation function.

      Next, you'll apply a gradient descent to the neural network. This is an optimization strategy that works to reduce errors during the training process. Gradient descent is how randomly assigned weights in a neural network are adjusted by reducing the cost function, which is a measure of how well a neural network performs based on the output expected from it.

      The aim of a gradient descent is to get the point where the error is at its least. This is done by finding where the cost function is at its minimum, which is referred to as a local minimum. In gradient descent, you differentiate to find the slope at a specific point and find out if the slope is negative or positive—you're descending into the minimum of the cost function. There are several types of optimization strategies, but you'll use a popular one known as adam in this tutorial.

      Add this code to your notebook cell and run it:

      classifier.compile(optimizer= "adam",loss = "binary_crossentropy",metrics = ["accuracy"])
      

      Applying gradient descent is done via the compile function that takes the following parameters:

      • optimizer is the gradient descent.
      • loss is a function that you'll use in the gradient descent. Since this is a binary classification problem you use the binary_crossentropy loss function.
      • The last parameter is the metric that you'll use to evaluate your model. In this case, you'd like to evaluate it based on its accuracy when making predictions.

      You're ready to fit your classifier to your dataset. Keras makes this possible via the .fit() method. To do this, insert the following code into your notebook and run it in order to fit the model to your dataset:

      classifier.fit(X_train, y_train, batch_size = 10, epochs = 1)
      

      Fitting the dataset

      The .fit() method takes a couple of parameters:

      • The first parameter is the training set with the features.

      • The second parameter is the column that you're making the predictions on.

      • The batch_size represents the number of samples that will go through the neural network at each training round.

      • epochs represents the number of times that the dataset will be passed via the neural network. The more epochs the longer it will take to run your model, which also gives you better results.

      Step 4

      You've created your deep learning model, compiled it, and fitted it to your dataset. You're ready to make some predictions using the deep learning model. In the next step, you'll start making predictions with the dataset that the model hasn't yet seen.

      Step 5 — Running Predictions on the Test Set

      To start making predictions, you'll use the testing dataset in the model that you've created. Keras enables you to make predictions by using the .predict() function.

      Insert the following code in the next notebook cell to begin making predictions:

      y_pred = classifier.predict(X_test)
      

      Since you've already trained the classifier with the training set, this code will use the learning from the training process to make predictions on the test set. This will give you the probabilities of an employee leaving. You'll work with a probability of 50% and above to indicate a high chance of the employee leaving the company.

      Enter the following line of code in your notebook cell in order to set this threshold:

      y_pred = (y_pred > 0.5)
      

      You've created predictions using the predict method and set the threshold for determining if an employee is likely to leave. To evaluate how well the model performed on the predictions, you will next use a confusion matrix.

      Step 6 — Checking the Confusion Matrix

      In this step, you will use a confusion matrix to check the number of correct and incorrect predictions. A confusion matrix, also known as an error matrix, is a square matrix that reports the number of true positives(tp), false positives(fp), true negatives(tn), and false negatives(fn) of a classifier.

      • A true positive is an outcome where the model correctly predicts the positive class (also known as sensitivity or recall).
      • A true negative is an outcome where the model correctly predicts the negative class.
      • A false positive is an outcome where the model incorrectly predicts the positive class.
      • A false negative is an outcome where the model incorrectly predicts the negative class.

      To achieve this you'll use a confusion matrix that scikit-learn provides.

      Insert this code in the next notebook cell to import the scikit-learn confusion matrix:

      from sklearn.metrics import confusion_matrix
      cm = confusion_matrix(y_test, y_pred)
      cm
      

      The confusion matrix output means that your deep learning model made 3305 + 375 correct predictions and 106 + 714 wrong predictions. You can calculate the accuracy with: (3305 + 375) / 4500. The total number of observations in your dataset is 4500. This gives you an accuracy of 81.7%. This is a very good accuracy rate since you can achieve at least 81% correct predictions from your model.

      Output

      array([[3305, 106], [ 714, 375]])

      You've evaluated your model using the confusion matrix. Next, you'll work on making a single prediction using the model that you have developed.

      Step 7 — Making a Single Prediction

      In this step you'll make a single prediction given the details of one employee with your model. You will achieve this by predicting the probability of a single employee leaving the company. You'll pass this employee's features to the predict method. As you did earlier, you'll scale the features as well and convert them to a numpy array.

      To pass the employee's features, run the following code in a cell:

      new_pred = classifier.predict(sc.transform(np.array([[0.26,0.7 ,3., 238., 6., 0.,0.,0.,0., 0.,0.,0.,0.,0.,1.,0., 0.,1.]])))
      

      These features represent the features of a single employee. As shown in the dataset in step 1, these features represent: satisfaction level, last evaluation, number of projects, and so on. As you did in step 3, you have to transform the features in a manner that the deep learning model can accept.

      Add a threshold of 50% with the following code:

      new_pred = (new_pred > 0.5)
      new_pred
      

      This threshold indicates that where the probability is above 50% an employee will leave the company.

      You can see in your output that the employee won't leave the company:

      Output

      array([[False]])

      You might decide to set a lower or higher threshold for your model. For example, you can set the threshold to be 60%:

      new_pred = (new_pred > 0.6)
      new_pred
      

      This new threshold still shows that the employee won't leave the company:

      Output

      array([[False]])

      In this step, you have seen how to make a single prediction given the features of a single employee. In the next step, you will work on improving the accuracy of your model.

      Step 8 — Improving the Model Accuracy

      If you train your model many times you'll keep getting different results. The accuracies for each training have a high variance. In order to solve this problem, you'll use K-fold cross-validation. Usually, K is set to 10. In this technique, the model is trained on the first 9 folds and tested on the last fold. This iteration continues until all folds have been used. Each of the iterations gives its own accuracy. The accuracy of the model becomes the average of all these accuracies.

      keras enables you to implement K-fold cross-validation via the KerasClassifier wrapper. This wrapper is from scikit-learn cross-validation. You'll start by importing the cross_val_score cross-validation function and the KerasClassifier. To do this, insert and run the following code in your notebook cell:

      from keras.wrappers.scikit_learn import KerasClassifier
      from sklearn.model_selection import cross_val_score
      

      To create the function that you will pass to the KerasClassifier, add this code to the next cell:

      def make_classifier():
          classifier = Sequential()
          classifier.add(Dense(9, kernel_initializer = "uniform", activation = "relu", input_dim=18))
          classifier.add(Dense(1, kernel_initializer = "uniform", activation = "sigmoid"))
          classifier.compile(optimizer= "adam",loss = "binary_crossentropy",metrics = ["accuracy"])
          return classifier
      

      Here, you create a function that you'll pass to the KerasClassifier—the function is one of the arguments that the classifier expects. The function is a wrapper of the neural network design that you used earlier. The passed parameters are also similar to the ones used earlier in the tutorial. In the function, you first initialize the classifier using Sequential(), you then use Dense to add the input and output layer. Finally, you compile the classifier and return it.

      To pass the function you've built to the KerasClassifier, add this line of code to your notebook:

      classifier = KerasClassifier(build_fn = make_classifier, batch_size=10, nb_epoch=1)
      

      The KerasClassifier takes three arguments:

      • build_fn: the function with the neural network design
      • batch_size: the number of samples to be passed via the network in each iteration
      • nb_epoch: the number of epochs the network will run

      Next, you apply the cross-validation using Scikit-learn's cross_val_score. Add the following code to your notebook cell and run it:

      accuracies = cross_val_score(estimator = classifier,X = X_train,y = y_train,cv = 10,n_jobs = -1)
      

      This function will give you ten accuracies since you have specified the number of folds as 10. Therefore, you assign it to the accuracies variable and later use it to compute the mean accuracy. It takes the following arguments:

      • estimator: the classifier that you've just defined
      • X: the training set features
      • y: the value to be predicted in the training set
      • cv: the number of folds
      • n_jobs: the number of CPUs to use (specifying it as -1 will make use of all the available CPUs)

      Now you have applied the cross-validation, you can compute the mean and variance of the accuracies. To achieve this, insert the following code into your notebook:

      mean = accuracies.mean()
      mean
      

      In your output you'll see that the mean is 83%:

      Output

      0.8343617910685696

      To compute the variance of the accuracies, add this code to the next notebook cell:

      variance = accuracies.var()
      variance
      

      You see that the variance is 0.00109. Since the variance is very low, it means that your model is performing very well.

      Output

      0.0010935021002275425

      You've improved your model's accuracy by using K-Fold cross-validation. In the next step, you'll work on the overfitting problem.

      Step 9 — Adding Dropout Regularization to Fight Over-Fitting

      Predictive models are prone to a problem known as overfitting. This is a scenario whereby the model memorizes the results in the training set and isn't able to generalize on data that it hasn't seen. Typically you observe overfitting when you have a very high variance on accuracies. To help fight over-fitting in your model, you will add a layer to your model.

      In neural networks, dropout regularization is the technique that fights overfitting by adding a Dropout layer in your neural network. It has a rate parameter that indicates the number of neurons that will deactivate at each iteration. The process of deactivating nerurons is usually random. In this case, you specify 0.1 as the rate meaning that 1% of the neurons will deactivate during the training process. The network design remains the same.

      To add your Dropout layer, add the following code to the next cell:

      from keras.layers import Dropout
      
      classifier = Sequential()
      classifier.add(Dense(9, kernel_initializer = "uniform", activation = "relu", input_dim=18))
      classifier.add(Dropout(rate = 0.1))
      classifier.add(Dense(1, kernel_initializer = "uniform", activation = "sigmoid"))
      classifier.compile(optimizer= "adam",loss = "binary_crossentropy",metrics = ["accuracy"])
      

      You have added a Dropout layer between the input and output layer. Having set a dropout rate of 0.1 means that during the training process 15 of the neurons will deactivate so that the classifier doesn't overfit on the training set. After adding the Dropout and output layers you then compiled the classifier as you have done previously.

      You worked to fight over-fitting in this step with a Dropout layer. Next, you'll work on further improving the model by tuning the parameters you used while creating the model.

      Step 10 — Hyperparameter Tuning

      Grid search is a technique that you can use to experiment with different model parameters in order to obtain the ones that give you the best accuracy. The technique does this by trying different parameters and returning those that give the best results. You'll use grid search to search for the best parameters for your deep learning model. This will help in improving model accuracy. scikit-learn provides the GridSearchCV function to enable this functionality. You will now proceed to modify the make_classifier function to try out different parameters.

      Add this code to your notebook to modify the make_classifier function so you can test out different optimizer functions:

      from sklearn.model_selection import GridSearchCV
      def make_classifier(optimizer):
          classifier = Sequential()
          classifier.add(Dense(9, kernel_initializer = "uniform", activation = "relu", input_dim=18))
          classifier.add(Dense(1, kernel_initializer = "uniform", activation = "sigmoid"))
          classifier.compile(optimizer= optimizer,loss = "binary_crossentropy",metrics = ["accuracy"])
          return classifier
      

      You have started by importing GridSearchCV. You have then made changes to the make_classifier function so that you can try different optimizers. You've initialized the classifier, added the input and output layer, and then compiled the classifier. Finally, you have returned the classifier so you can use it.

      Like in step 4, insert this line of code to define the classifier:

      classifier = KerasClassifier(build_fn = make_classifier)
      

      You've defined the classifier using the KerasClassifier, which expects a function through the build_fn parameter. You have called the KerasClassifier and passed the make_classifier function that you created earlier.

      You will now proceed to set a couple of parameters that you wish to experiment with. Enter this code into a cell and run:

      params = {
          'batch_size':[20,35],
          'epochs':[2,3],
          'optimizer':['adam','rmsprop']
      }
      

      Here you have added different batch sizes, number of epochs, and different types of optimizer functions.

      For a small dataset like yours, a batch size of between 20–35 is good. For large datasets its important to experiment with larger batch sizes. Using low numbers for the number of epochs ensures that you get results within a short period. However, you can experiment with bigger numbers that will take a while to complete depending on the processing speed of your server. The adam and rmsprop optimizers from keras are a good choice for this type of neural network.

      Now you're going to use the different parameters you have defined to search for the best parameters using the GridSearchCV function. Enter this into the next cell and run it:

      grid_search = GridSearchCV(estimator=classifier,
                                 param_grid=params,
                                 scoring="accuracy",
                                 cv=2)
      

      The grid search function expects the following parameters:

      • estimator: the classifier that you're using.
      • param_grid: the set of parameters that you're going to test.
      • scoring: the metric you're using.
      • cv: the number of folds you'll test on.

      Next, you fit this grid_search to your training dataset:

      grid_search = grid_search.fit(X_train,y_train)
      

      Your output will be similar to the following, wait a moment for it to complete:

      Output

      Epoch 1/2 5249/5249 [==============================] - 1s 228us/step - loss: 0.5958 - acc: 0.7645 Epoch 2/2 5249/5249 [==============================] - 0s 82us/step - loss: 0.3962 - acc: 0.8510 Epoch 1/2 5250/5250 [==============================] - 1s 222us/step - loss: 0.5935 - acc: 0.7596 Epoch 2/2 5250/5250 [==============================] - 0s 85us/step - loss: 0.4080 - acc: 0.8029 Epoch 1/2 5249/5249 [==============================] - 1s 214us/step - loss: 0.5929 - acc: 0.7676 Epoch 2/2 5249/5249 [==============================] - 0s 82us/step - loss: 0.4261 - acc: 0.7864

      Add the following code to a notebook cell to obtain the best parameters from this search using the best_params_ attribute:

      best_param = grid_search.best_params_
      best_accuracy = grid_search.best_score_
      

      You can now check the best parameters for your model with the following code:

      best_param
      

      Your output shows that the best batch size is 20, the best number of epochs is 2, and the adam optimizer is the best for your model:

      Output

      {'batch_size': 20, 'epochs': 2, 'optimizer': 'adam'}

      You can check the best accuracy for your model. The best_accuracy number represents the highest accuracy you obtain from the best parameters after running the grid search:

      best_accuracy
      

      Your output will be similar to the following:

      Output

      0.8533193637489285

      You've used GridSearch to figure out the best parameters for your classifier. You have seen that the best batch_size is 20, the best optimizer is the adam optimizer and the best number of epochs is 2. You have also obtained the best accuracy for your classifier as being 85%. You've built an employee retention model that is able to predict if an employee stays or leaves with an accuracy of up to 85%.

      Conclusion

      In this tutorial, you've used Keras to build an artificial neural network that predicts the probability that an employee will leave a company. You combined your previous knowledge in machine learning using scikit-learn to achieve this. To further improve your model, you can try different activation functions or optimizer functions from keras. You could also experiment with a different number of folds, or, even build a model with a different dataset.

      For other tutorials in the machine learning field or using TensorFlow, you can try building a neural network to recognize handwritten digits or other DigitalOcean machine learning tutorials.



      Source link