import pandas as pd
import numpy as np
import matplotlib. pyplot as plt
iris_df= pd. read_csv( '../data/iris/iris.data' )
iris_df. columns= [ 'sepal length' , 'sepal width' , 'petal length' , 'petal width' , 'class' ]
iris_df. head( )
sepal length
sepal width
petal length
petal width
class
0
4.9
3.0
1.4
0.2
Iris-setosa
1
4.7
3.2
1.3
0.2
Iris-setosa
2
4.6
3.1
1.5
0.2
Iris-setosa
3
5.0
3.6
1.4
0.2
Iris-setosa
4
5.4
3.9
1.7
0.4
Iris-setosa
iris_df. info( )
iris_df. describe( ) . T
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 149 entries, 0 to 148
Data columns (total 5 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 sepal length 149 non-null float64
1 sepal width 149 non-null float64
2 petal length 149 non-null float64
3 petal width 149 non-null float64
4 class 149 non-null object
dtypes: float64(4), object(1)
memory usage: 5.9+ KB
count
mean
std
min
25%
50%
75%
max
sepal length
149.0
5.848322
0.828594
4.3
5.1
5.8
6.4
7.9
sepal width
149.0
3.051007
0.433499
2.0
2.8
3.0
3.3
4.4
petal length
149.0
3.774497
1.759651
1.0
1.6
4.4
5.1
6.9
petal width
149.0
1.205369
0.761292
0.1
0.3
1.3
1.8
2.5
y= iris_df. iloc[ 0 : 99 , 4 ] . values
y= np. where( y== 'Iris-setosa' , - 1 , 1 )
x= iris_df. iloc[ 0 : 99 , [ 0 , 2 ] ] . values
plt. scatter( x[ : 49 , 0 ] , x[ : 49 , 1 ] , color= 'red' , marker= 'o' , label= 'setosa' )
plt. scatter( x[ 49 : 99 , 0 ] , x[ 49 : 99 , 1 ] , color= 'blue' , marker= 'x' , label= 'setosa' )
plt. xlabel( 'length' )
plt. ylabel( 'width' )
plt. legend( loc= 'upper left' )
plt. show( )
class Perceptron :
def __init__ ( self, eta= 0.01 , n_iter= 10 ) :
self. eta= eta
self. n_iter= n_iter
def net_input ( self, x) :
"""
获取净输入
:param x: DataFrame
:return matrix:
"""
return np. dot( x, self. w_[ 1 : ] ) + self. w_[ 0 ]
def predict ( self, x) :
"""
获取二分类的预测值,0为分界
:param x:DataFrame
:return:
"""
return np. where( self. net_input( x) >= 0.0 , 1 , - 1 )
def fit ( self, x, y) :
self. w_= np. zeros( 1 + x. shape[ 1 ] )
self. errors_= [ ]
for _ in range ( self. n_iter) :
errors= 0
for xi, target in zip ( x