PyQt5 window

If you do not have PyQT5 installed, you should install it first.
In a terminal you can type:

sudo apt-get install python3-pyqt5

If you are on a Windows or Mac computer, you can download PyQT5 from: https://www.riverbankcomputing.com/software/pyqt/download5

Related courses:

PyQt5 window

You can create a PyQT5 window using the code below:

import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QIcon
 
class App(QWidget):
 
    def __init__(self):
        super().__init__()
        self.title = 'PyQt5 simple window - pythonspot.com'
        self.left = 10
        self.top = 10
        self.width = 640
        self.height = 480
        self.initUI()
 
    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.show()
 
if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())

We set the window size using the setGeometry(left,top,width,height) method. The window title is set using setWindowTitle(title). Finally show() is called to display the window.

Run with:

python3 window.py

pyqt5-window

Download PyQT5 Code

The output should look similar to the screenshot above (depending on your operating system).

Introduction

Welcome to my Python Course! 

Python is a general-purpose computer programming language.
This course is suitable for both Python 2 and Python 3.

Related Courses:

Download Python

To run Python code, you will need one of these programs:

For terminal only: Apple Mac OS X, Microsoft Windows, Linux/UNIX

pycharm
PyCharm, a popular Python editor

Run Python code

A python program should be save as a file with a .py extension.
Try this code:

print("Hello World!")
print("This is a Python program.")

Expected output:

Hello World!
This is a Python program

If you are using the interpreter use:

python program.py

Python strings

python-string
a string, series of characters
A string is a series of characters, they are mostly used to display text.

To define a string simply type text between quotes. Python accepts single, double and triple quotes.

Related Courses:

String input and output

To output text (string) to the screen:

s = "hello world"
print(s)

To get text from keyboard:

name = input("Enter name: ")
print(name)

If you use an old Python version (2.x), you need to use:

name = raw_input("Enter name: ")
print(name)

To test your version:
python –version

String Comparison

To test if two strings are equal use the equality operator (==).

#!/usr/bin/python
 
sentence = "The cat is brown"
q = "cat"
 
if q == sentence:
    print('strings equal')

To test if two strings are not equal use the inequality operator (!=)

#!/usr/bin/python
 
sentence = "The cat is brown"
q = "cat"
 
if q != sentence:
    print('strings equal')

String Slices (part 2)

A string is a series of characters, they are mostly used to display text.

To define a string simply type text between quotes. Python accepts single, double and triple quotes.

Related Courses:

String Index

Python indexes the characters of a string, every index is associated with a unique character. For instance, the characters in the string ‘python’ have indices:

String
String numbering

Characters in string

The 0th index is used for the first character of a string. Try the following:

#!/usr/bin/python
 
s = "Hello Python"
print(s)      # prints whole string
print(s[0])   # prints "H"
print(s[1]) # prints "e"

String Slicing

Given a string s, the syntax for a slice is:

s[ startIndex : pastIndex ]

The startIndex is the start index of the string. pastIndex is one past the end of the slice.

If you omit the first index, the slice will start from the beginning. If you omit the last index, the slice will go to the end of the string. For instance:

#!/usr/bin/python
 
s = "Hello Python"
print(s[0:2]) # prints "He"
print(s[2:4]) # prints "ll"
print(s[6:])  # prints "Python"

k nearest neighbors

Computers can automatically classify data using the k-nearest-neighbor algorithm.

For instance: given the sepal length and width, a computer program can determine if the flower is an Iris Setosa, Iris Versicolour or another type of flower.

Related courses

Dataset
We start with data, in this case a dataset of plants.

Each plant has unique features: sepal length, sepal width, petal length and petal width. The measurements of different plans can be taken and saved into a spreadsheet.

The type of plant (species) is also saved, which is either of these classes:

  • Iris Setosa (0)
  • Iris Versicolour (1)
  • Iris Virginica (2)

Put it all together, and we have a dataset:

Machine Learning Dataset

We load the data. This is a famous dataset, it’s included in the module. Otherwise you can load a dataset using python pandas.

import matplotlib
matplotlib.use('GTKAgg')
 
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn import neighbors, datasets
 
# import some data to play with
iris = datasets.load_iris()
 
# take the first two features
X = iris.data[:, :2]  
y = iris.target
 
print(X)

X contains the first two features, being the rows sepal length and sepal width. The Y list contains the classes for the features.

Plot data
We will use the two features of X to create a plot. Where we use X[:,0] on one axis and X[:,1] on the other.

import matplotlib
matplotlib.use('GTKAgg')
 
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn import neighbors, datasets
 
# import some data to play with
iris = datasets.load_iris()
 
# take the first two features
X = iris.data[:, :2]  
y = iris.target
h = .02  # step size in the mesh
 
# Calculate min, max and limits
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
 
# Put the result into a color plot
plt.figure()
plt.scatter(X[:, 0], X[:, 1])
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.title("Data points")
plt.show()

This will output the data:
scatter plot

Classify with k-nearest-neighbor
We can classify the data using the kNN algorithm. We create and fit the data using:

clf = neighbors.KNeighborsClassifier(n_neighbors, weights='distance')
clf.fit(X, y)

And predict the class using

clf.predict()

This gives us the following code:

import matplotlib
matplotlib.use('GTKAgg')
 
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn import neighbors, datasets
 
n_neighbors = 6
 
# import some data to play with
iris = datasets.load_iris()
 
# prepare data
X = iris.data[:, :2]  
y = iris.target
h = .02 
 
# Create color maps
cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA','#00AAFF'])
cmap_bold = ListedColormap(['#FF0000', '#00FF00','#00AAFF'])
 
# we create an instance of Neighbours Classifier and fit the data.
clf = neighbors.KNeighborsClassifier(n_neighbors, weights='distance')
clf.fit(X, y)
 
# calculate min, max and limits
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                     np.arange(y_min, y_max, h))
 
# predict class using data and kNN classifier
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
 
# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.figure()
plt.pcolormesh(xx, yy, Z, cmap=cmap_light)
 
# Plot also the training points
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold)
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.title("3-Class classification (k = %i)" % (n_neighbors))
plt.show()

which outputs the plot using the 3 classes:

knn classes, machine learning

Prediction
We can use this data to make predictions. Given the position on the plot (which is determined by the features), it’s assigned a class. We can put a new data on the plot and predict which class it belongs to.

The code below will make prediction based on the input given by the user:

import numpy as np
from sklearn import neighbors, datasets
from sklearn import preprocessing 
 
n_neighbors = 6
 
# import some data to play with
iris = datasets.load_iris()
 
# prepare data
X = iris.data[:, :2]  
y = iris.target
h = .02 
 
# we create an instance of Neighbours Classifier and fit the data.
clf = neighbors.KNeighborsClassifier(n_neighbors, weights='distance')
clf.fit(X, y)
 
# make prediction
sl = raw_input('Enter sepal length (cm): ')
sw = raw_input('Enter sepal width (cm): ')
dataClass = clf.predict([[sl,sw]])
print('Prediction: '),
 
if dataClass == 0:
    print('Iris Setosa')
elif dataClass == 1:
    print('Iris Versicolour')
else:
    print('Iris Virginica')

Example output:
prediction, machine learning

Deep Learning

Deep learning is the new big trend in Machine Learning. It is about artificial neural networks (ANN for short) that consists of many layers.

While artificial neural networks have existed for over 40 years, the Machine Learning field had a big boost partly due to hardware improvements.

Related course: Data Science: Deep Learning in Python

Neural networks
In the field of Machine Learning, artificial neural networks (ANN) are computational models that are inspired by the field of biology: biological neural networks.

The (human) brain has a network of neurons, approximately 86 billion neurons (estimated number). Neurons are used to transfer information from A to B. During this process it passes neurons which are activated by the brain.

A neuron receives input signals from other signals using its receivers (called ‘dendrites’). The neuron has a threshold, if the amount of signals are above its treshold it will send an electric pulse to the dendrites of other neurons (the output of a neuron is called ‘terminals’).

Neuron, source: wikimedia
Neuron, source: wikimedia

Artificial Neural Networks
An artificial neural network (ANN) is a mathematical model that is modeled after biological neural networks. Just like biological neural networks have dendrites (input) and terminals (outputs), every ANN has an input node and an output node. Every ANN has connected nodes which are setup in layers. The individual nodes have inputs and outputs, similar to the biological neuron.

aritificial-neural-network
Artificial neural network, 2 layer

Consider the task of digital character recognition. The input is an image containing a character. The output is the character that is recognized. Neurons in the first layer are activated once an input image is given, starting a chain reaction. In the image below you see several of the neurons are activated. Each neuron acts according to rules (training data). If a node is not activated it remains gray. The output is based on the layer of neurons directly before it.

Related course: Data Science: Deep Learning in Python

Why is it called ‘Deep Learning’?
When Artificial neural networks were first created, roughly 40 years ago, the neural networks were only 2 layers deep. During this period there had been computational limitations preventing the scientists from adding more layers. These days it is common to have neural networks that have 10+ or 100+ layers.

Posts navigation

1 2 3 4 34 35 36