ML | Word Encryption using Keras

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
  • Code : Importing Libraries



    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

    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

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # 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')

    chevron_right

    
    

    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 :

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    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)

    chevron_right

    
    

    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 :

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    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 ="")
      

    chevron_right

    
    

    Complete Implementation –

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # 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 ="")

    chevron_right

    
    

    Output :

    Wbjcibw!Nfisb!xsjujoh!gps!HffltgpsHfflt
    


    My Personal Notes arrow_drop_up

    Coder of Languages like C, C++, Python and Arduino Highly interested in Robotics and Machine Learning Microsoft Technology Associate on the topic of Cloud Fundamentals

    If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




    Article Tags :
    Practice Tags :


    Be the First to upvote.


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.