analitics

Pages

Sunday, December 16, 2018

Fix errors when write files.

The python is a very versatile programming language.
The tutorial for today is about:
  • check the type of variables;
  • see the list error of writelines with the list output;
  • fix errors for writelines;
One good example for some errors can be this:
>>> file.writelines(paragraphs)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: a bytes-like object is required, not 'str'
>>> file.writelines(paragraphs.decode('utf-8'))
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'list' object has no attribute 'decode'
Is a common issue for list and writing file.
The result of paragraphs is a list, see:
>>> type(paragraphs)
The list can be write with te writelines into the file like this:
>>> file = open("out.txt","wb")
>>> file.writelines([word.encode('utf-8') for word in paragraphs])
The file is a open file variable and the paragraphs is a list.

Thursday, December 13, 2018

Using pytorch - a simpler perspective.

Suppose this module PyTorch is a data extravagance circuit that allows us to filter information several times, and we can decide each time we decide the final result.
A simpler perspective of how to work with PyTorch can be explained by a simple example.
It's like a Christmas baby (PyTorch) that opens a multi-packed gift until it gets the final product - the desired gift.
The opening operations of the package involve smart moves called: forward and backward passes.
The child's feedback can be called: loss and backpropagate.
In this case, the child will try to remove from his package until he is satisfied and will not be lost (loss and backpropagate functions).
To compute the backward pass for a gradient and every time we backpropagate the gradient from a variable, the gradient is accumulative instead of being reset and replaced (most of networks designs call backward multiple times).
PyTorch comes with many loss functions.
Most of examples code create a mean square error loss function and later backpropagate the gradients based on the loss.
Will you ask me if the gift is shaped? I can tell you that the gift can contain from Verge à Saint-Nicolas (unidimensional) to complex (multidimensional) structures - the most simplistic and worn out is the square one (two-dimensional matrix).
This gift is packed with magic in mathematical functions which allows the child to understand what is in the gift.
But the child is more special. He recognizes forms (matrices, shapes, simple formulas) and this allows him to open parts of the gift.
El poate roti acesta parti din cadou (mm).
The mm is a matrix multiplication.
He can see the corners he can get from the gift.
ReLU stands for "rectified linear unit" and is a type of activation function.
Mathematically, it is defined as y = max(0, x).
He can see which parts of the gift are bigger or smaller so he can understand the gift.
This clamp function clamps all elements in input into the returns[ min, max ] and returns a resulting tensor:
The clamp should only affect gradients for values outside the min and max range.
The pow function power with the exponent.
The clone returns a copy of the self tensor. The copy has the same size and data type as self.
A common example is: clamp(min=0) is exactly ReLU().
PyTorch provides ReLU and its variants through the torch.nn module.
If you run the program to look at the output, you will understand that the child has only five operations left and is already pleased with the way the gift result.
The source code is based on one example from here:
import torch 
dtype = torch.float
device = torch.device("cpu")
batch,input,hidden,output = 2,10,2,5
x = torch.randn(batch,input,device=device,dtype=dtype)
y = torch.randn(hidden,output,device=device,dtype=dtype)
w1 = torch.randn(input,hidden,device=device,dtype=dtype)
w2 = torch.randn(hidden,output,device=device,dtype=dtype)

l_r = 1e-6
for t in range(5):
 h = x.mm(w1)
 h_r = h.clamp(min=0)
 y_p = h_r.mm(w2)
 loss = (y_p - y).pow(2).sum().item()
 print("t=",t,"loss=",loss,"\n")
 g_y_p = 2.0 * (y_p -y)
 g_w2 = h_r.t().mm(g_y_p)
 g_h_r = g_y_p.mm(w2.t())
 g_h = g_h_r.clone()
 g_h[h<0 -="l_r" 0="" g_w1="" g_w2="" n="" print="" w1=",w1," w2=",w2,">
The child's result after five operations.
...
t= 4 loss= 25.40263557434082

w1= tensor([[ 1.5933,  0.3818],
        [-1.0043, -1.3362],
        [ 0.5841, -1.9811],
        [ 2.3483,  0.5748],
        [ 0.5904, -0.2521],
        [-0.6612,  2.7945],
        [ 0.4841, -0.5894],
        [-1.4434, -0.1421],
        [-1.2712, -1.4269],
        [ 0.7929,  0.2040]]) w2= tensor([[ 1.7389,  0.4337,  0.4557,  1.3704,  0
.3819],
        [ 0.2937,  0.0212, -0.4604, -1.0564, -1.5403]])

Wednesday, December 12, 2018

Using pytorch - install it on Windows OS.

A few days ago I install the pytorch on my Windows 8.1 OS and today I will able to install on Fedora 29 distro.
I will try to make a series of pytorch tutorials with Linux and Windows OS on my blogs.
If you want to install it on Fedora 29 you need to follow my Fedora blog post.
For installation on Windows OS, you can read the official webpage.
Because I don't have a new CUDA GPU, the only one video card is an NVIDIA video card 740M on my laptop and my Linux is an Intel onboard video card, I''m not able to solve issues with CUDA and pytorch.
Anyway, this will be a good start to see how to use pytorch.
Let's start the install into default way on Scripts folder from my python version 3.6.4 folder installation.
C:\Python364\Scripts>pip3 install https://download.pytorch.org/whl/cpu/torch-1.0
.0-cp36-cp36m-win_amd64.whl
Collecting torch==1.0.0 from https://download.pytorch.org/whl/cpu/torch-1.0.0-cp
36-cp36m-win_amd64.whl
  Downloading https://download.pytorch.org/whl/cpu/torch-1.0.0-cp36-cp36m-win_am
d64.whl (71.0MB)
    100% |████████████████████████████████| 71.0MB 100kB/s
Installing collected packages: torch
  Found existing installation: torch 0.4.1
    Uninstalling torch-0.4.1:
      Successfully uninstalled torch-0.4.1
Successfully installed torch-1.0.0

C:\Python364\Scripts>pip3 install torchvision
After I install the pytorch python module I import the pytorch and torchvision python modules.
First, as I expected the CUDA feature:
>>> import torch
>>> torch.cuda.is_available()
False
Let's make another test with pytorch:
>>> x = torch.rand(76, 79)
>>> x.size()
torch.Size([76, 79])
>>> print(x)
tensor([[0.1981, 0.3841, 0.9276,  ..., 0.3753, 0.7137, 0.7702],
        [0.8202, 0.9564, 0.5590,  ..., 0.0914, 0.4983, 0.7163],
        [0.0864, 0.4588, 0.0669,  ..., 0.3939, 0.0318, 0.8650],
        ...,
        [0.9028, 0.8431, 0.8592,  ..., 0.3825, 0.2537, 0.7901],
        [0.2055, 0.3003, 0.8085,  ..., 0.0724, 0.9226, 0.9559],
        [0.3671, 0.1178, 0.3837,  ..., 0.7181, 0.5704, 0.9268]])
>>> torch.tensor([[1., -1.], [1., -1.]])
tensor([[ 1., -1.],
        [ 1., -1.]])
>>> torch.zeros([1, 4], dtype=torch.int32)
tensor([[0, 0, 0, 0]], dtype=torch.int32)
>>> torch.zeros([2, 4], dtype=torch.int32)
tensor([[0, 0, 0, 0],
        [0, 0, 0, 0]], dtype=torch.int32)
>>> torch.zeros([3, 4], dtype=torch.int32)
tensor([[0, 0, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0]], dtype=torch.int32)
You can make many tests and check your instalation.
This is a screenshot with all features show by dir with pytorch and torchvision:

Friday, December 7, 2018

Python Qt5 : simple checkbox example.

Today we created a simple tutorial about QCheckBox and QLabel.
The purpose of this tutorial is to use QCheckBox in a GUI interface.
When we check QCheckBox, this will change the text from a QLabel.
The variables used by QCheckBox are my_checkbox and my_label for QLabel.
The result of my source code is this:

Let's see the source code:
# -*- coding: utf-8 -*-
"""
@author: catafest
"""
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget, QCheckBox, QLabel, QApplication

class MyCheckBox(QWidget):
 def __init__(self):
  super().__init__()
 
  my_checkbox = QCheckBox("Check this , see result", self)
  my_checkbox.move(50,60)
  my_checkbox.stateChanged.connect(self.change_my_option)
  

  self.my_label = QLabel("You can visit free-tutorial.org ", self)
  self.my_label.move(50,30)

  #self.my_label.setAlignment(Qt.AlignCenter)
  
  self.setGeometry(420,420,640,100)
  self.setWindowTitle("free-tutorials.org PyQt5 ChecBox ")
  

  
 def change_my_option(self, state):
  if state  == Qt.Checked:
   self.my_label.setText("Thank's by free-tutorial.org")
  else:
   self.my_label.setText("You can visit free-tutorial.org")
   
if __name__ == '__main__':
 app = QApplication(sys.argv)
 win = MyCheckBox()
 win.show()
 sys.exit(app.exec_())

Wednesday, December 5, 2018

PySide2 and PyQt versions.

A short intro about this python module named PySide2 can be found on the Wikipedia webpage.
The purpose of this tutorial is to introduce concepts about licenses and develop python programs using ergonomic design interfaces with PySide2 and PyQt versions.

PySide2 is a Python binding of the cross-platform GUI toolkit Qt, currently developed by The Qt Company under the Qt for Python project. It is one of the alternatives to the standard library package Tkinter.
...
PySide was released under the LGPL in August 2009 by Nokia,[1] the former owners of the Qt toolkit, after Nokia failed to reach an agreement with PyQt developers Riverbank Computing[7] to change its licensing terms to include LGPL as an alternative license.
...


Now about the LGPL software license:

The GNU Lesser General Public License (LGPL) is a free software license published by the Free Software Foundation (FSF). The license allows developers and companies to use and integrate software released under the LGPL into their own (even proprietary) software without being required by the terms of a strong copyleft license to release the source code of their own components.

I wrote in the past about PySide and you can find on this blog or on my website.
Let's start installing Python using pip3.6.
C:\Python364>cd Scripts

C:\Python364\Scripts>pip3.6.exe install PySide2
Collecting PySide2
  Downloading https://files.pythonhosted.org/packages/10/ba/7448ec862655c356ade2
2351ed46c9260773186c37ba0d8ceea1ef8c7515/PySide2-5.11.2-5.11.2-cp35.cp36.cp37-no
ne-win_amd64.whl (128.7MB)
    100% |████████████████████████████████| 128.7MB 44kB/s
Installing collected packages: PySide2
Successfully installed PySide2-5.11.2
The PySide2 python module is another way to connect Qt with Python modules.
You can take a look at this python module at Qt website .
The source code is more simple but this can put the development in trouble if you try to follow the PyQt way.
Let's see a simple example. I create the main window for this example.

The layout of this window named main_layout is split into two: secondary_splitter_1 and secondary_splitter_2.
Into this, I add for each area the defined class named SecondaryWindow.
The four variables for this SecondaryWindow class are named like secondary_window_1, secondary_window_2, secondary_window_3 and secondary_window_4.
Interface programming with PySide2 and PyQt keeps a classic form of statements and then structured implementations. It seems simpler to create interfaces with PySide, but the development and community interest seems to be attracted to PyQt.
In both cases, the programming speed in the python programming language is required.
Error management is simpler and more limited in PySide2. I have noticed PyQt essential changes in developing even more advanced versions (see PyQt4 and PyQt5).
Let's see the source code:
import sys
from PySide2 import QtGui, QtCore, QtWidgets
from PySide2.QtGui import *
from PySide2.QtCore import *
from PySide2.QtWidgets import *

class SecondaryWindow(QtWidgets.QWidget):

    def __init__(self, label, parent=None):
        super(SecondaryWindow, self).__init__(parent)

        self.label = QtWidgets.QLabel(label, parent=self)
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setStyleSheet("QLabel {font-size:18px;color:blue}")

        self.main_layout = QtWidgets.QVBoxLayout()
        self.main_layout.addWidget(self.label)
        self.setLayout(self.main_layout)

class MainWindow(QtWidgets.QWidget):

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.secondary_window_1 = SecondaryWindow("1", parent=self)
        self.secondary_window_2 = SecondaryWindow("2", parent=self)
        self.secondary_window_3 = SecondaryWindow("3", parent=self)
        self.secondary_window_4 = SecondaryWindow("4", parent=self)

        self.secondary_splitter_1 = QtWidgets.QSplitter(QtCore.Qt.Horizontal, parent=self)
        self.secondary_splitter_1.addWidget(self.secondary_window_1)
        self.secondary_splitter_1.addWidget(self.secondary_window_2)

        self.secondary_splitter_2 = QtWidgets.QSplitter(QtCore.Qt.Horizontal, parent=self)
        self.secondary_splitter_2.addWidget(self.secondary_window_3)
        self.secondary_splitter_2.addWidget(self.secondary_window_4)

        self.main_splitter = QtWidgets.QSplitter(QtCore.Qt.Vertical, parent=self)
        self.main_splitter.addWidget(self.secondary_splitter_1)
        self.main_splitter.addWidget(self.secondary_splitter_2)

        self.main_layout = QtWidgets.QVBoxLayout()
        self.main_layout.addWidget(self.main_splitter)
        self.setLayout(self.main_layout)

        self.setWindowTitle("PySide2 example")
        self.resize(220, 220)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main_window = MainWindow()
    main_window.show()
    sys.exit(app.exec_())

Thursday, November 29, 2018

Python Qt5 : submenu example.

Using my old example I will create a submenu with PyQt5.
First, you need to know the submenu works like the menu.
Let's see the result:

The source code is very simple:
# -*- coding: utf-8 -*-
"""
@author: catafest
"""
import sys
from PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication, QDesktopWidget, QMenu
from PyQt5.QtGui import QIcon

class Example(QMainWindow):
    #init the example class to draw the window application    
    def __init__(self):
        super().__init__()    
        self.initUI()
    #create the def center to select the center of the screen         
    def center(self):
        # geometry of the main window
        qr = self.frameGeometry()
        # center point of screen
        cp = QDesktopWidget().availableGeometry().center()
        # move rectangle's center point to screen's center point
        qr.moveCenter(cp)
        # top left of rectangle becomes top left of window centering it
        self.move(qr.topLeft())
    #create the init UI to draw the application
    def initUI(self):               
        #create the action for the exit application with shortcut and icon
        #you can add new action for File menu and any actions you need
        exitAct = QAction(QIcon('exit.png'), '&Exit', self)        
        exitAct.setShortcut('Ctrl+Q')
        exitAct.setStatusTip('Exit application')
        exitAct.triggered.connect(qApp.quit)
        #create the status bar for menu 
        self.statusBar()
        #create the menu with the text File , add the exit action 
        #you can add many items on menu with actions for each item
        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(exitAct)
        
        # add submenu to menu 
        submenu = QMenu('Submenu',self)

        # some dummy actions
        submenu.addAction('Submenu 1')
        submenu.addAction('Submenu 2')
           
        # add to the top menu
        menubar.addMenu(submenu)
        #resize the window application 
        self.resize(640, 480)
        #draw on center of the screen 
        self.center()
        #add title on windows application 
        self.setWindowTitle('Simple menu')
        #show the application
        self.show()
        #close the UI class
        
if __name__ == '__main__':
    #create the application 
    app = QApplication(sys.argv)
    #use the UI with new  class
    ex = Example()
    #run the UI 
    sys.exit(app.exec_())