Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

ML | Word Encryption using Keras

  • Last Updated : 16 Oct, 2019

Machine Learning is something which is one of the most in-demand fields of today’s tech market. It is very interesting to learn how to teach your system to do some specific things by its own. Today we will take our first small step in discovering machine learning with the help of libraries like Tensorflow and Numpy. We will create a neural structure with one neuron whose only purpose in life will be to change the characters fed by us into other characters by following a specific pattern whose examples are stored by us in the sample data from which machine will learn.

Libraries Used :

  • TensorFlow: Learn to install TensorFlow from here
  • NumPy: Learn to install numpy from here

    Attention reader! Don’t stop learning now. Get hold of all the important Machine Learning Concepts with the Machine Learning Foundation Course at a student-friendly price and become industry ready.



    Code : Importing Libraries






    # importing libraries
    import tensorflow as tf
    import numpy as np 
    from tensorflow import keras

    We will also be using Keras which is neural network library written in Python and is preadded in Tensorflow library.

    Working of Model :
    The aim of given example is to take input code from user and then encrypt it so that no one will be able to understand it without knowing the key of it. Here we will see the message character by character and replace it with the character having an ASCII value 1 + ASCII value of given character. But first of all, we will create a neural structure to do such work for us. We will call it model here and define it using Keras. Here keras.Sequential defines that our model will be sequential or the model is linear stack of layers and then we will define the kind of layer(We will use a densely connected neural network(NN) layer) with the number of layers or units we want. Finally, we will give the number of neurons we want as input_shape and will compile the model with optimizer and loss. Optimizer and loss are the 2 functions that will help our model to work in the correct direction. The loss will calculate the error of the prediction made by our model and optimizer will check that error and move the model in the direction in which error will decrease.

    Code : Creating Sequential Model




    # creating the simplest neural structure with only 
    # one layer and that only have one neuron
    model = keras.Sequential([keras.layers.Dense(units = 1
                                                 input_shape =[1])])
      
    # compiling model with optimizer to make predictions and 
    # loss to keep checking the accuracy of the predictions
    model.compile(optimizer ='sgd', loss ='mean_squared_error')

    After this, we will specify our training data as Numpy array which will connect all the values of x to the respective y and then we will train our model on the given data with model.fit. Here Epochs will specify the number of times our model will work on the training data to increase its accuracy using Loss and Optimizer.


    Code :




    # here we will give sample data with which program 
    # will learn and make predictions on its basis
    xs = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 
                  dtype = float)
    ys = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 
                  dtype = float)
      
    # we will fit the data in the model and the epochs
    # is the number of times model will run sample data to
    # increase its accuracy
    model.fit(xs, ys, epochs = 1000)

    Lastly, we will take the Input from the user and will break it down to characters by using tuple function, then we will save all these characters into a list. Now we will create a for loop and will send each character one at a time in our model to make the prediction and will print all the predictions so that they together form an encrypted message which will not be easy to understand until you know the key to it.

    Code :




    # taking input from user
    code = input("code is: ")
    n = len(code)
      
    # dividing the input message into its characters
    c = tuple(code)
    d = list(c)
      
    # predicting the output for each character and printing it
    for i in range(0, n):
        s = ord(d[i]) 
        x = model.predict([s])
        print(chr(x), end ="")
      

    Complete Implementation –




    # importing libraries 
    import tensorflow as tf
    import numpy as np 
    from tensorflow import keras
      
    # creating the simplest neural structure 
    # with only one layer and that only have one neuron
    model = keras.Sequential([keras.layers.Dense(units = 1
                                                 input_shape =[1])])
    # compiling model with optimizer to make predictions and 
    # loss to keep checking the accuracy of the predictions
    model.compile(optimizer ='sgd', loss ='mean_squared_error')
      
    # here we will give sample data with which program will learn 
    # and make predictions on its basis
    xs = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype = float)
    ys = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], dtype = float)
      
    # we will fit the data in the model and the epochs is number of
    # times model will run sample data to increase its accuracy
    model.fit(xs, ys, epochs = 1000)
      
    # taking input from user
    code = "Vaibhav Mehra writing for GeeksforGeeks"
    n = len(code)
      
    # dividing the input message into its characters
    c = tuple(code)
    d = list(c)
      
    # predicting the output for each character and printing it
    for i in range(0, n):
        s = ord(d[i]) 
        x = model.predict([s])
        print(chr(x), end ="")

    Output :

    Wbjcibw!Nfisb!xsjujoh!gps!HffltgpsHfflt
    



    My Personal Notes arrow_drop_up
  • Recommended Articles
    Page :