PyTorch – Feature Extraction in Convents

PyTorch – Feature Extraction in Convents ”; Previous Next Convolutional neural networks include a primary feature, extraction. Following steps are used to implement the feature extraction of convolutional neural network. Step 1 Import the respective models to create the feature extraction model with “PyTorch”. import torch import torch.nn as nn from torchvision import models Step 2 Create a class of feature extractor which can be called as and when needed. class Feature_extractor(nn.module): def forward(self, input): self.feature = input.clone() return input new_net = nn.Sequential().cuda() # the new network target_layers = [conv_1, conv_2, conv_4] # layers you want to extract` i = 1 for layer in list(cnn): if isinstance(layer,nn.Conv2d): name = “conv_”+str(i) art_net.add_module(name,layer) if name in target_layers: new_net.add_module(“extractor_”+str(i),Feature_extractor()) i+=1 if isinstance(layer,nn.ReLU): name = “relu_”+str(i) new_net.add_module(name,layer) if isinstance(layer,nn.MaxPool2d): name = “pool_”+str(i) new_net.add_module(name,layer) new_net.forward(your_image) print (new_net.extractor_3.feature) Print Page Previous Next Advertisements ”;

PyTorch – Quick Guide

PyTorch – Quick Guide ”; Previous Next PyTorch – Introduction PyTorch is defined as an open source machine learning library for Python. It is used for applications such as natural language processing. It is initially developed by Facebook artificial-intelligence research group, and Uber’s Pyro software for probabilistic programming which is built on it. Originally, PyTorch was developed by Hugh Perkins as a Python wrapper for the LusJIT based on Torch framework. There are two PyTorch variants. PyTorch redesigns and implements Torch in Python while sharing the same core C libraries for the backend code. PyTorch developers tuned this back-end code to run Python efficiently. They also kept the GPU based hardware acceleration as well as the extensibility features that made Lua-based Torch. Features The major features of PyTorch are mentioned below − Easy Interface − PyTorch offers easy to use API; hence it is considered to be very simple to operate and runs on Python. The code execution in this framework is quite easy. Python usage − This library is considered to be Pythonic which smoothly integrates with the Python data science stack. Thus, it can leverage all the services and functionalities offered by the Python environment. Computational graphs − PyTorch provides an excellent platform which offers dynamic computational graphs. Thus a user can change them during runtime. This is highly useful when a developer has no idea of how much memory is required for creating a neural network model. PyTorch is known for having three levels of abstraction as given below − Tensor − Imperative n-dimensional array which runs on GPU. Variable − Node in computational graph. This stores data and gradient. Module − Neural network layer which will store state or learnable weights. Advantages of PyTorch The following are the advantages of PyTorch − It is easy to debug and understand the code. It includes many layers as Torch. It includes lot of loss functions. It can be considered as NumPy extension to GPUs. It allows building networks whose structure is dependent on computation itself. TensorFlow vs. PyTorch We shall look into the major differences between TensorFlow and PyTorch below − PyTorch TensorFlow PyTorch is closely related to the lua-based Torch framework which is actively used in Facebook. TensorFlow is developed by Google Brain and actively used at Google. PyTorch is relatively new compared to other competitive technologies. TensorFlow is not new and is considered as a to-go tool by many researchers and industry professionals. PyTorch includes everything in imperative and dynamic manner. TensorFlow includes static and dynamic graphs as a combination. Computation graph in PyTorch is defined during runtime. TensorFlow do not include any run time option. PyTorch includes deployment featured for mobile and embedded frameworks. TensorFlow works better for embedded frameworks. PyTorch – Installation PyTorch is a popular deep learning framework. In this tutorial, we consider “Windows 10” as our operating system. The steps for a successful environmental setup are as follows − Step 1 The following link includes a list of packages which includes suitable packages for PyTorch. https://drive.google.com/drive/folders/0B-X0-FlSGfCYdTNldW02UGl4MXM All you need to do is download the respective packages and install it as shown in the following screenshots − Step 2 It involves verifying the installation of PyTorch framework using Anaconda Framework. Following command is used to verify the same − conda list “Conda list” shows the list of frameworks which is installed. The highlighted part shows that PyTorch has been successfully installed in our system. Mathematical Building Blocks of Neural Networks Mathematics is vital in any machine learning algorithm and includes various core concepts of mathematics to get the right algorithm designed in a specific way. The importance of mathematics topics for machine learning and data science is mentioned below − Now, let us focus on the major mathematical concepts of machine learning which is important from Natural Language Processing point of view − Vectors Vector is considered to be array of numbers which is either continuous or discrete and the space which consists of vectors is called as vector space. The space dimensions of vectors can be either finite or infinite but it has been observed that machine learning and data science problems deal with fixed length vectors. The vector representation is displayed as mentioned below − temp = torch.FloatTensor([23,24,24.5,26,27.2,23.0]) temp.size() Output – torch.Size([6]) In machine learning, we deal with multidimensional data. So vectors become very crucial and are considered as input features for any prediction problem statement. Scalars Scalars are termed to have zero dimensions containing only one value. When it comes to PyTorch, it does not include a special tensor with zero dimensions; hence the declaration will be made as follows − x = torch.rand(10) x.size() Output – torch.Size([10]) Matrices Most of the structured data is usually represented in the form of tables or a specific matrix. We will use a dataset called Boston House Prices, which is readily available in the Python scikit-learn machine learning library. boston_tensor = torch.from_numpy(boston.data) boston_tensor.size() Output: torch.Size([506, 13]) boston_tensor[:2] Output: Columns 0 to 7 0.0063 18.0000 2.3100 0.0000 0.5380 6.5750 65.2000 4.0900 0.0273 0.0000 7.0700 0.0000 0.4690 6.4210 78.9000 4.9671 Columns 8 to 12 1.0000 296.0000 15.3000 396.9000 4.9800 2.0000 242.0000 17.8000 396.9000 9.1400 PyTorch – Neural Network Basics The main principle of neural network includes a collection of basic elements, i.e., artificial neuron or perceptron. It includes several basic inputs such as x1, x2….. xn which produces a binary output if the sum is greater than the activation potential. The schematic representation of sample neuron is mentioned below − The output generated can be considered as the weighted sum with activation potential or bias. $$Output=sum_jw_jx_j+Bias$$ The typical neural network architecture is described below − The layers between input and output are referred to as hidden layers, and the density and type of connections between layers is the configuration. For example, a fully connected configuration has all the neurons of layer L connected to those of L+1. For a more pronounced localization, we can connect only a local neighbourhood, say nine

PyTorch – Discussion

Discuss PyTorch ”; Previous Next PyTorch is an open source machine learning library for Python and is completely based on Torch. It is primarily used for applications such as natural language processing. PyTorch is developed by Facebook”s artificial-intelligence research group along with Uber”s “Pyro” software for the concept of in-built probabilistic programming. Print Page Previous Next Advertisements ”;

PyTorch – Visualization of Convents

PyTorch – Visualization of Convents ”; Previous Next In this chapter, we will be focusing on the data visualization model with the help of convents. Following steps are required to get a perfect picture of visualization with conventional neural network. Step 1 Import the necessary modules which is important for the visualization of conventional neural networks. import os import numpy as np import pandas as pd from scipy.misc import imread from sklearn.metrics import accuracy_score import keras from keras.models import Sequential, Model from keras.layers import Dense, Dropout, Flatten, Activation, Input from keras.layers import Conv2D, MaxPooling2D import torch Step 2 To stop potential randomness with training and testing data, call the respective data set as given in the code below − seed = 128 rng = np.random.RandomState(seed) data_dir = “../../datasets/MNIST” train = pd.read_csv(”../../datasets/MNIST/train.csv”) test = pd.read_csv(”../../datasets/MNIST/Test_fCbTej3.csv”) img_name = rng.choice(train.filename) filepath = os.path.join(data_dir, ”train”, img_name) img = imread(filepath, flatten=True) Step 3 Plot the necessary images to get the training and testing data defined in perfect way using the below code − pylab.imshow(img, cmap =”gray”) pylab.axis(”off”) pylab.show() The output is displayed as below − Print Page Previous Next Advertisements ”;

PyTorch – Word Embedding

PyTorch – Word Embedding ”; Previous Next In this chapter, we will understand the famous word embedding model − word2vec. Word2vec model is used to produce word embedding with the help of group of related models. Word2vec model is implemented with pure C-code and the gradient are computed manually. The implementation of word2vec model in PyTorch is explained in the below steps − Step 1 Implement the libraries in word embedding as mentioned below − import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F Step 2 Implement the Skip Gram Model of word embedding with the class called word2vec. It includes emb_size, emb_dimension, u_embedding, v_embedding type of attributes. class SkipGramModel(nn.Module): def __init__(self, emb_size, emb_dimension): super(SkipGramModel, self).__init__() self.emb_size = emb_size self.emb_dimension = emb_dimension self.u_embeddings = nn.Embedding(emb_size, emb_dimension, sparse=True) self.v_embeddings = nn.Embedding(emb_size, emb_dimension, sparse = True) self.init_emb() def init_emb(self): initrange = 0.5 / self.emb_dimension self.u_embeddings.weight.data.uniform_(-initrange, initrange) self.v_embeddings.weight.data.uniform_(-0, 0) def forward(self, pos_u, pos_v, neg_v): emb_u = self.u_embeddings(pos_u) emb_v = self.v_embeddings(pos_v) score = torch.mul(emb_u, emb_v).squeeze() score = torch.sum(score, dim = 1) score = F.logsigmoid(score) neg_emb_v = self.v_embeddings(neg_v) neg_score = torch.bmm(neg_emb_v, emb_u.unsqueeze(2)).squeeze() neg_score = F.logsigmoid(-1 * neg_score) return -1 * (torch.sum(score)+torch.sum(neg_score)) def save_embedding(self, id2word, file_name, use_cuda): if use_cuda: embedding = self.u_embeddings.weight.cpu().data.numpy() else: embedding = self.u_embeddings.weight.data.numpy() fout = open(file_name, ”w”) fout.write(”%d %dn” % (len(id2word), self.emb_dimension)) for wid, w in id2word.items(): e = embedding[wid] e = ” ”.join(map(lambda x: str(x), e)) fout.write(”%s %sn” % (w, e)) def test(): model = SkipGramModel(100, 100) id2word = dict() for i in range(100): id2word[i] = str(i) model.save_embedding(id2word) Step 3 Implement the main method to get the word embedding model displayed in proper way. if __name__ == ”__main__”: test() Print Page Previous Next Advertisements ”;

Sequence Processing with Convents

PyTorch – Sequence Processing with Convents ”; Previous Next In this chapter, we propose an alternative approach which instead relies on a single 2D convolutional neural network across both sequences. Each layer of our network re-codes source tokens on the basis of the output sequence produced so far. Attention-like properties are therefore pervasive throughout the network. Here, we will focus on creating the sequential network with specific pooling from the values included in dataset. This process is also best applied in “Image Recognition Module”. Following steps are used to create a sequence processing model with convents using PyTorch − Step 1 Import the necessary modules for performance of sequence processing using convents. import keras from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D import numpy as np Step 2 Perform the necessary operations to create a pattern in respective sequence using the below code − batch_size = 128 num_classes = 10 epochs = 12 # input image dimensions img_rows, img_cols = 28, 28 # the data, split between train and test sets (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.reshape(60000,28,28,1) x_test = x_test.reshape(10000,28,28,1) print(”x_train shape:”, x_train.shape) print(x_train.shape[0], ”train samples”) print(x_test.shape[0], ”test samples”) y_train = keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) Step 3 Compile the model and fit the pattern in the mentioned conventional neural network model as shown below − model.compile(loss = keras.losses.categorical_crossentropy, optimizer = keras.optimizers.Adadelta(), metrics = [”accuracy”]) model.fit(x_train, y_train, batch_size = batch_size, epochs = epochs, verbose = 1, validation_data = (x_test, y_test)) score = model.evaluate(x_test, y_test, verbose = 0) print(”Test loss:”, score[0]) print(”Test accuracy:”, score[1]) The output generated is as follows − Print Page Previous Next Advertisements ”;

PyTorch – Recursive Neural Networks

PyTorch – Recursive Neural Networks ”; Previous Next Deep neural networks have an exclusive feature for enabling breakthroughs in machine learning understanding the process of natural language. It is observed that most of these models treat language as a flat sequence of words or characters, and use a kind of model which is referred as recurrent neural network or RNN. Many researchers come to a conclusion that language is best understood with respect to hierarchical tree of phrases. This type is included in recursive neural networks that take a specific structure into account. PyTorch has a specific feature which helps to make these complex natural language processing models a lot easier. It is a fully-featured framework for all kinds of deep learning with strong support for computer vision. Features of Recursive Neural Network A recursive neural network is created in such a way that it includes applying same set of weights with different graph like structures. The nodes are traversed in topological order. This type of network is trained by the reverse mode of automatic differentiation. Natural language processing includes a special case of recursive neural networks. This recursive neural tensor network includes various composition functional nodes in the tree. The example of recursive neural network is demonstrated below − Print Page Previous Next Advertisements ”;

Neural Networks to Functional Blocks

PyTorch – Neural Networks to Functional Blocks ”; Previous Next Training a deep learning algorithm involves the following steps − Building a data pipeline Building a network architecture Evaluating the architecture using a loss function Optimizing the network architecture weights using an optimization algorithm Training a specific deep learning algorithm is the exact requirement of converting a neural network to functional blocks as shown below − With respect to the above diagram, any deep learning algorithm involves getting the input data, building the respective architecture which includes a bunch of layers embedded in them. If you observe the above diagram, the accuracy is evaluated using a loss function with respect to optimization of the weights of neural network. Print Page Previous Next Advertisements ”;

PyTorch – Terminologies

PyTorch – Terminologies ”; Previous Next In this chapter, we will discuss some of the most commonly used terms in PyTorch. PyTorch NumPy A PyTorch tensor is identical to a NumPy array. A tensor is an n-dimensional array and with respect to PyTorch, it provides many functions to operate on these tensors. PyTorch tensors usually utilize GPUs to accelerate their numeric computations. These tensors which are created in PyTorch can be used to fit a two-layer network to random data. The user can manually implement the forward and backward passes through the network. Variables and Autograd When using autograd, the forward pass of your network will define a computational graph − nodes in the graph will be Tensors, and edges will be functions that produce output Tensors from input Tensors. PyTorch Tensors can be created as variable objects where a variable represents a node in computational graph. Dynamic Graphs Static graphs are nice because user can optimize the graph up front. If programmers are re-using same graph over and over, then this potentially costly up-front optimization can be maintained as the same graph is rerun over and over. The major difference between them is that Tensor Flow’s computational graphs are static and PyTorch uses dynamic computational graphs. Optim Package The optim package in PyTorch abstracts the idea of an optimization algorithm which is implemented in many ways and provides illustrations of commonly used optimization algorithms. This can be called within the import statement. Multiprocessing Multiprocessing supports the same operations, so that all tensors work on multiple processors. The queue will have their data moved into shared memory and will only send a handle to another process. Print Page Previous Next Advertisements ”;

PyTorch – Recurrent Neural Network

PyTorch – Recurrent Neural Network ”; Previous Next Recurrent neural networks is one type of deep learning-oriented algorithm which follows a sequential approach. In neural networks, we always assume that each input and output is independent of all other layers. These type of neural networks are called recurrent because they perform mathematical computations in a sequential manner completing one task after another. The diagram below specifies the complete approach and working of recurrent neural networks − In the above figure, c1, c2, c3 and x1 are considered as inputs which includes some hidden input values namely h1, h2 and h3 delivering the respective output of o1. We will now focus on implementing PyTorch to create a sine wave with the help of recurrent neural networks. During training, we will follow a training approach to our model with one data point at a time. The input sequence x consists of 20 data points, and the target sequence is considered to be same as the input sequence. Step 1 Import the necessary packages for implementing recurrent neural networks using the below code − import torch from torch.autograd import Variable import numpy as np import pylab as pl import torch.nn.init as init Step 2 We will set the model hyper parameters with the size of input layer set to 7. There will be 6 context neurons and 1 input neuron for creating target sequence. dtype = torch.FloatTensor input_size, hidden_size, output_size = 7, 6, 1 epochs = 300 seq_length = 20 lr = 0.1 data_time_steps = np.linspace(2, 10, seq_length + 1) data = np.sin(data_time_steps) data.resize((seq_length + 1, 1)) x = Variable(torch.Tensor(data[:-1]).type(dtype), requires_grad=False) y = Variable(torch.Tensor(data[1:]).type(dtype), requires_grad=False) We will generate training data, where x is the input data sequence and y is required target sequence. Step 3 Weights are initialized in the recurrent neural network using normal distribution with zero mean. W1 will represent acceptance of input variables and w2 will represent the output which is generated as shown below − w1 = torch.FloatTensor(input_size, hidden_size).type(dtype) init.normal(w1, 0.0, 0.4) w1 = Variable(w1, requires_grad = True) w2 = torch.FloatTensor(hidden_size, output_size).type(dtype) init.normal(w2, 0.0, 0.3) w2 = Variable(w2, requires_grad = True) Step 4 Now, it is important to create a function for feed forward which uniquely defines the neural network. def forward(input, context_state, w1, w2): xh = torch.cat((input, context_state), 1) context_state = torch.tanh(xh.mm(w1)) out = context_state.mm(w2) return (out, context_state) Step 5 The next step is to start training procedure of recurrent neural network’s sine wave implementation. The outer loop iterates over each loop and the inner loop iterates through the element of sequence. Here, we will also compute Mean Square Error (MSE) which helps in the prediction of continuous variables. for i in range(epochs): total_loss = 0 context_state = Variable(torch.zeros((1, hidden_size)).type(dtype), requires_grad = True) for j in range(x.size(0)): input = x[j:(j+1)] target = y[j:(j+1)] (pred, context_state) = forward(input, context_state, w1, w2) loss = (pred – target).pow(2).sum()/2 total_loss += loss loss.backward() w1.data -= lr * w1.grad.data w2.data -= lr * w2.grad.data w1.grad.data.zero_() w2.grad.data.zero_() context_state = Variable(context_state.data) if i % 10 == 0: print(“Epoch: {} loss {}”.format(i, total_loss.data[0])) context_state = Variable(torch.zeros((1, hidden_size)).type(dtype), requires_grad = False) predictions = [] for i in range(x.size(0)): input = x[i:i+1] (pred, context_state) = forward(input, context_state, w1, w2) context_state = context_state predictions.append(pred.data.numpy().ravel()[0]) Step 6 Now, it is time to plot the sine wave as the way it is needed. pl.scatter(data_time_steps[:-1], x.data.numpy(), s = 90, label = “Actual”) pl.scatter(data_time_steps[1:], predictions, label = “Predicted”) pl.legend() pl.show() Output The output for the above process is as follows − Print Page Previous Next Advertisements ”;