AI Phyton
AI Phyton
AI BASICS
print (‘’) print (‘hello world): this is a string, which means textual data. We can also
use double quotes (“”)
we can print the textual data on the terminal window, by using print.
Then we can have variables, associated with labels. We can define a variable “age” by
typing:
If we want to print the value of the age variable, then we need to use the print
function, but in this case, we don’t use the ‘’, because we don’t want the textual data
we want the value (20):
print(age)
when we run it, 20 appears. If we want to change the value to 30, we need to set the
variable more at the bottom.
We should separate multiple words with “_”, to make variables more readable. For
example:
first_name = ‘Mosh’
We can also have Boolean variables that we can either set to true or false, for
example:
note: we can’t subtract a string from an integer (number). We can use int before a
variable of a string to make it a number, and subtractable by another integer. For
example:
birth_year = input(‘Enter your birth year: ‘): we use the space at the end to put the
answer on the output window. Let’s consider the answer is 1982.
age = 2020 – int(birth_year)
print(age)
We run the program, answering that our birth year is 1982, and it gives us our age: 38.
If we want to convert a variable to a string or to a Boolean, we can use these codes: str
and bool, respectively.
ARITMETIC OPERATIONS
print (10 + 3): the solution will be 13. We can also do print (10 – 3)
x = 10
x = x + 3 or x += 3: the answer is 13
Note: just like in simple math, multiplication and division are higher order than
addition and we can also use () for the same purposes.
x=3>2
print (x)
The answer will be True. There are other symbols: >=, <=, <, == (equality), != (not
equal)
price = 25
print(price > 10 and price < 30)
Solution: True
price = 5
print(price > 10 or price < 30)
IF STATEMENTS
temperature = 35
The comment next to the # isn’t part of the code, it’s just a note. When the
temperature is 35, we get the if message, when it’s 25 we get the else message.
Weight: 170
How?
Weight = input (“Weight: “): the variable weight inputs the answer of the person about
their weight
Unit = input(“(K)g or (L)bs: “): the variable unit inputs the answer of the person about
either it’s Kg or Lbs.
If unit == “K”:
converted = weight / 0.45
print(“weight in Lbs: “ + converted)
else:
converted = weight * 0.45
print(“weight in Kgs: “ + converted)
Class 1
Sintax:
Variables:
It´s a “container” of values, such as numbers or text. Syntax can also be considered a
variable, after it is defined. We need to run it until the green check appears, if we want
this variables to be considered:
We can do operations with variables, depending on its time. If they are numbers, we
can, for example, substract them.
However, if they are surnames, of course we can’t do the same. There will be an error
string “str” type.
Instead, we can add the names, but not like in an addiction operation. We simply put
them together in this case, but it’s coded in the same way that numbers would be:
If we want to add a space, we can add ‘ ‘ in the middle (with a space between
characters):
We can also add more numbers (e.g., 2, 3, 4, 5, 6, 7) to encode more options. The
current year, as encoded before, is 2022, and it’s going to be added one of the options
of numbers.
When the name is equal to “Sara” (or any other name that isn’t Mario), the “if”
condition says that the machine should say “Hey, I don’t know your name”. If we
change it to name = “Mario” it says, “Hi Mario!”:
We can also add more operations with “print”, for example, another thing to say to
Mario: (we can also put it in the same () as hi mario. \n new line or \n\ new line +
tab)
“def” is used to define a function. Every time we want to define one, we should run the
program until the green check appears:
In this case, name = Mario because that was coded previously (?). We can change the
name before, or we can change it specifically in this code:
Phyton Basics 2
VECTOR: It contains several ordered numerical values and has a shape, which specifies
how many values are contained. Also, the direction is important (horizontal/row or
vertical/column). The attribute shape is used to print the shape of a vector.
If we multiply it by a scalar number, the shape doesn’t change.
the shape of the row vector is (1,3) which means it is a row vector with three
numbers “1”, like this: (in programming language we call them arrays)
When we multiply it by a scalar number, like 2, the shape of the vector remains the
same, but the number shown is multiplied: instead of a row of “1”, we get a row of “2”:
If we want to create a column vector, we give the number of rows (3) followed by
the number of columns (1):
MATRIX: Vector of 2 or more dimensions (e.g., 2D matrix can have n rows and m
columns). They can be multiplied by a scalar number, resulting in the same shape but
each element is multiplied by the scalar.
they can also be multiplied by a vector OR by other matrices using the matrix
product. A and B are matrices of shape (n, k) and (l, m), so they matrix product is
possible only if k = l. The resulting matrix in this case would be (n, m)
Let’s define a random matrix (meaning it’s filled with random numbers), with 3 rows
and 4 columns (3, 4):
We need to make sure we run numpy import BEFORE we run this, that’s where the
random numbers come from. In this case, the sample imported generates numbers
between 0 and 1.
We can multiply the matrix by a scalar (2), and all the numbers will be multiplied by 2
without changing the shape of the matrix:
We can also make a matrix product, by multiplying (@) the one row by the matrix,
resulting in only 1 row:
DATA VISUALIZATION
The most common way to visualize data with phyton is by using this library - matplotlib
- Similarly to numpy, we need to import it (we can import only the pyplot in this case):
By clicking on the (x) we can see all the variables we have so far, and in this case
identify the random sample one, with 1000 random values:
If we want to change the mean of the histogram, we can for example add a number
(e.g., +10):
If we want to change the standard deviation, we can multiply it by a number (e.g., 0.1*)
and it will get more centered in 10.
STEP FUNTION: it has a constant value, usually 0 and another constant value for the
opposite condition, usually 1:
Now we are using a function from numpy called linear space (np.linspace), in which we
take 100 equally-space points between (-3, 3) for the x, and the y is the step function
for each number c in the x coordinates:
In this case, the output is 0 for half of them and 1 after that.
To change where this function “jumps”, we need to change the step function,
changing the number on the “if” instruction:
And the function will now look like this:
SIGMOID FUNCTION: It’s similar to the step function, but it’s continuous and it is
defined by this equation.
Cat and dog example: Imagine we are building a machine that scans the image of a cat
or dog and decides which one it is. We need to pay attention to a lot of variables, and
give a huge number of rules to follow, considering that we can have different types of
angles and image quality (e.g., black and white). For that, we need to use machine
learning:
We build a model/engine and give it lots and lots of data (e.g., we give it
thousands of pictures of cats and dogs). The model will find and learn patterns while it
studies the input data. The more input data, the more accurate it will become.
STEPS
Online music store. Users sign with their age and gender. The store makes a
recommendation on albums they are likely to buy, based on their info.
We need to build a data and fill it with some sample data based on the existing users.
As it learns patterns in the data, we can ask the model to make predictions. Example:
The model can say jazz, or hip-hop, or whatever, and based on that it will make
recommendations.
In this case, 0 represents a female and 1 represents a male. Let’s make some
assumptions based on the data set (made up):
We can assume that men between 20 and 25 like hip-hop, men from 26
to 30 like jazz and when they are older than 30, they prefer classical
music.
For women, we assume they like dance music if they are 20 – 25,
acoustic if they are 26 – 30 and classical when older than 30.
We can import an algorithm from a library. In this case we are going to use
DecisionTreeClassifier
model = DecisionTreeClassifier()
model.fit (X, y)
LAB 1
First, we need to import prebuilt libraries, full of functions that we will need to use:
For this we would only need a standard machine, but in the future, we might need to
add a GPU or something like that. This is not our local computer; it’s simulated on
google colab.
The perceptron is described by the formula on the 1st picture. When the sum of all our
inputs doesn’t exceed (…). It’s discontinuous.
For the first input we use the default color (blue - 0), and for the 1 we have the color
red.
The input array has 4 rows of 2
numbers, while the target array is a
column with 4 rows.
Now we need to define a step activation function (define when it “jumps) x > 0:
return 1 / else -1.
Rather than having 0 and 1 as our binary classes, we should use -1 and 1:
We create “epoch” in range (100), which means we repeat the learning step for a
maximum of 100 epochs (repetitions). The number of epochs you need depends on the
complexity of the problem.
We have 4 training patterns (4 rows). Usually perceptrons have hundreds of training
patterns, this is only an example. It computes the weight activation according to the 1 st
formula.
Initially, the output would be wrong. We compute the error as the difference between
the output and desired label. This difference is used to adjust the model. W and b are
the updates for the perceptron.
After clicking both “runs”, we are ready to train our classifiers. Now we use the sigmoid
function, and we use target_perceptron to replace 0 with -1
According to the 1st input, the machine “saw” (0, 0) and so the target output should be
1, but it gave -1, which is an error of -2.
BREAK – special instruction to stop the rule (when we interrupt training because the
function was already learnt)
The column shows the value of the error, which decreases with the number of epochs
(the 2nd function is defined for 500 epochs).
Because we used random numbers to initialize the function, we might get slightly
different results.
OR FUNCTION
in this case there are more red dots, so one line should be able to
separate blue and red. After just 4 epochs, the train_perceptron was
able to reach 0 error (step function only)
1st we need to import information from the website, and also from “pandas”, which as
relevant information to manipulate the data.
Here we have our first 10 samples, which will be used as a training set.
We use numpy to convert the samples to vectors (arrays). We also need to standardize
the product in order to simplify the algorithm mean 0 and variance 1