Está en la página 1de 7

16/10/2020 Perceptron Simple-Introducción a la Inteligencia Artificial - Jupyter Notebook

Inteligencia artificial en las


Radiocomunicaciones
Introducción a la Inteligencia Artificial

La Inteligencia artificial es el campo científico de la informática que se centra en la creación de


programas y mecanismos que pueden mostrar comportamientos considerados inteligentes. En
otras palabras, la AI es el concepto según el cual “las máquinas piensan como seres humanos”.

Normalmente, un sistema de AI es capaz de analizar datos en grandes cantidades (big data),


identificar patrones y tendencias y, por lo tanto, formular predicciones de forma automática, con
rapidez y precisión.

Ejemplo:
Conjunto de datos flor iris

h ttps://es.wikipedia.org/wiki/Conjunto_de_datos_flor_iris
(https://es.wikipedia.org/wiki/Conjunto_de_datos_flor_iris)

localhost:8888/notebooks/OneDrive - itm.edu.co/Semestre II-2020/RadioComunicaciones/Perceptron Simple-Introducción a la Inteligencia Artificial.ipynb 1/6


In [16]: import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
In [20]: class Perceptron():

def init (self,eta=0.01,n_iter=50, random_state=1):


self.eta=eta
self.n_iter=n_iter
self.random_state=random_state

def fit(self,x,y):
rgen=np.random.RandomState(self.random_state)
self.w_=rgen.normal(loc=0.0,scale=0.01,size=1+x.shape[1])
self.errors_=[]

for _ in range(self.n_iter):
errors=0
for xi,target in zip(x,y):
update=self.eta*(target-self.predict(xi))
self.w_[1:] += update * xi
self.w_[0] += update
errors += int(update != 0.0)

self.errors_.append(errors)
return self

def net_input(self,x):
return np.dot(x,self.w_[1:])+self.w_[0]

def predict(self,x):
return np.where(self.net_input(x) >= 0.0,1,-1)

df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris

y=df.iloc[0:100,4].values
y=np.where(y=='Iris-setosa',1,-1)
# print(y)
x=df.iloc[0:100,[0,2]].values
# print(x)
# # # plot data
plt.scatter(x[:50, 0], x[:50, 1],
color='red', marker='o', label='setosa')
plt.scatter(x[50:100, 0], x[50:100, 1],
color='blue', marker='x', label='versicolor')
plt.xlabel('sepal length [cm]')
plt.ylabel('petal length [cm]')
plt.legend(loc='upper left')
plt.show()

ppn=Perceptron(eta=0.5,n_iter=10)
ppn.fit(x,y)
# a=ppn.predict(x)
Out[20]: < main .Perceptron at 0x2842ea42bb0>

In [21]: ppn.w_

Out[21]: array([ 2.01624345, 3.39388244, -9.10528172])

In [22]: ppn=Perceptron(eta=0.5,n_iter=10) ppn.fit(x,y)


a=ppn.predict(x) print(a)
print(y)

[ 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
-1 -1 -1 -1]
[ 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
-1 -1 -1 -1]
Ejercicio:
Entrenar el algoritmo del Perceptron Simple para reconocer la función AN
D y OR, verificar que pasa con la XOR

Nota: Graficar los puntos

In [24]: #función AND


x=np.array([[-1, -1],[1,-1],[-1,1],[1,1]])
y=np.array([-1,-1,-1,1])
and_ppn=Perceptron(eta=0.5,n_iter=10)
pd # Location of
In dataset
[12]:
ive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data" names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'Class'] irisdata
ad()
m first four columns to X variable
, 0:4] # Assign data from first fifth columns to y variable
t_dtypes(include=[object])

#Salida: array(['Iris-setosa', 'Iris-versicolor', 'Iris-virgini # print(y)

Out[12]: array(['Iris-setosa', 'Iris-versicolor', 'Iris-virginica'], dtype=object)

In [14]: from sklearn import preprocessing le = preprocessing.LabelEncoder() y = y.apply(le.fit_transform)


from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20)

Class
0 0
1 0
2 0
3 0
4 0
.. ...
145 2
146 2
147 2
148 2
149 2

[150 rows x 1 columns]

Consultar métodos de estandarización de datos


h ttps://scikit-learn.org/stable/auto_examples/preprocessing/plot_all_scaling.html (https://scikit- l
earn.org/stable/auto_examples/preprocessing/plot_all_scaling.html)

In [6]: from sklearn.preprocessing import StandardScaler scaler = StandardScaler()


scaler.fit(X_train)
X_train = scaler.transform(X_train) X_test = scaler.transform(X_test)

In [7]: from sklearn.neural_network import MLPClassifier


mlp = MLPClassifier(hidden_layer_sizes=(10, 10, 10), max_iter=1000) mlp.fit(X_train, y_train.values.ravel())
predictions = mlp.predict(X_test) print(predictions)

[0 2 2 2 2 1 1 0 0 1 0 1 2 2 2 0 2 2 0 0 1 2 0 0 0 1 0 2 2 2]
Evaluar el algoritmo

La Matriz de confusión
En el campo de la inteligencia artificial una matriz de confusión es una herramienta que permite la
visualización del desempeño de un algoritmo que se emplea en aprendizaje supervisado. Cada
columna de la matriz representa el número de predicciones de cada clase, mientras que cada fila
representa a las instancias en la clase real. Uno de los beneficios de las matrices de confusión es
que facilitan ver si el sistema está confundiendo lasdiferentes clases o resultadosde la
clasificación.

Interpretación de matriz de confusión de h ttps://www.iartificial.net/precision-recall-f1-accuracy-en-


clasificacion/ (https://www.iartificial.net/precision-recall-f1-accuracy-en-clasificacion/)

In [9]:from sklearn.metrics import classification_report, confusion_matrix print(confusion_matrix(y_test,predictions))


print(classification_report(y_test,predictions))

[[11 0 0]
[ 0 5 0]
[ 0 1 13]]
precision recall f1-score support

0 1.00 1.00 1.00 11


1 0.83 1.00 0.91 5
2 1.00 0.93 0.96 14

accuracy 0.97 30
macro avg 0.94 0.98 0.96 30
weighted avg 0.97 0.97 0.97 30

También podría gustarte