逻辑回归之python实践
数据集样例:
4.6,3.2,1.4,0.2,Iris-setosa
5.3,3.7,1.5,0.2,Iris-setosa
5.0,3.3,1.4,0.2,Iris-setosa
7.0,3.2,4.7,1.4,Iris-versicolor
6.4,3.2,4.5,1.5,Iris-versicolor
6.9,3.1,4.9,1.5,Iris-versicolor
6.3,3.3,6.0,2.5,Iris-virginica
5.8,2.7,5.1,1.9,Iris-virginica
7.1,3.0,5.9,2.1,Iris-virginica
相关损失函数,梯度下降求解最小theta的公式见另一篇转载文章,
相关说明:
X数据集,为m x n 维矩阵,m条数据,n个特征
theta:n x 1维矩阵
y标签:X*theta的m x 1维矩阵
实践代码:
# -*- coding: UTF-8 -*-
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#sigmoid函数定义
def sigmoid_function(x):
return 1./(1+np.exp(-x))
#损失函数定义
def cost_comput(theta,X,y):
# m:shape of matrix
m=X.shape[0]
theta_2=theta.reshape(len(theta),1)
cost=-1/m*(transpose(y)*log(sigmoid_function(X.dot(theta_2)))+transpose(1-y)*log(1-sigmoid_function(X.dot(theta_2))))
return cost[0][0]
#梯度下降实现
def grad_comput(alpha,iter,theta,X,y):
m=np.shape(X)[0]
xt=X.transpose()
for i in range(0,iter):
hyposisi=X.dot(theta)
loss=xt.dot(hyposisi-y)*1/m
#lost=np.around(loss, decimals=2)
theta=theta-alpha*loss
return theta
#预测函数
def predict(x,theta):
m,n=np.shape(x)
# x_test=np.ones((m,n+1))
# x_test[:,:-1]=x
r=np.dot(x,theta)
return r
iris_data=pd.read_csv('C:/Users/Administrator/pycode/irisdata.csv',header=None)
#只取0和2列作为特征
X=iris_data.iloc[:,[0,2]].values
#print m,n
#前100条数据
train_data=X[0:100,:]
m,n=np.shape(train_data)
lable_1=np.zeros(50)
lable_2=np.ones(50)
#定义标签,前50条为0类,后50条为1类
label_data=np.vstack((lable_1,lable_2)).reshape(m,1)
#theta为2x1维矩阵
theta=np.ones((n,1))
alpha=0.01#学习率,梯度下降步长
iternum=100#循环次数
#print np.shape(train_data),np.shape(label_data),np.shape(theta)
#训练theta,得到结果[[-0.10604249]
#[ 0.37697862]]
newtheta=grad_comput(alpha,iternum,theta,train_data,label_data)
print newtheta
#定义测试数据集,实际标签为【0,1,0,1】
x_data= np.array([[5.7,1.5], [6.5,4.6], [5.5,1.3], [5.0,3.5]])
result=predict(x_data,newtheta)
print np.around(result)#四舍五入取整,可以近似看做类别
plt.scatter(X[:50, 0], X[:50, 1],color='red', marker='o', label='setosa') # 前50个样本的散点图
plt.scatter(X[50:100, 0], X[50:100, 1],color='blue', marker='x', label='versicolor') # 中间50个样本的散点图
xz=np.array([4.0,5.0,7.0])
#画一条直线x1*theta1+x2*theta2=1,x2相当于是y,如果按照四舍五入来算,应是0.5
#不是1,直线上方是1类,直线下方是0类
xy=1-newtheta[0][0]/newtheta[1][0]*xz
print xy
plt.plot(xz,xy)
#plt横纵轴说明
plt.xlabel('petal length')
plt.ylabel('sepal length')
plt.legend(loc=2) # 把说明放在左上角,具体请参考官方文档
plt.show()
#plt.scatter(X[0:50,0],X[0:50,1],color='red',marker='o',label='se')
#plt.show()
测试结果: