[Meng小白和你一起逐行读代码] 基于python和sklearn的Logistic回归分类器

基于python和sklearn的Logistic回归分类器

参考自:用Python从头开始实现一个神经网络
虽然我很菜,但要一直努力鸭!<&.&>

import numpy as np
import sklearn
from sklearn import*
import matplotlib.pyplot as plt
np.random.seed(5)
x,y=sklearn.datasets.make_moons(300,noise=0.30)
#print(x,y)
plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
#plt.show()
clf=sklearn.linear_model.LogisticRegressionCV()
clf.fit(x,y)
def plot_decision_boundary(pred_func):
    # Set min and max values and give it some padding
    #
    x_min, x_max = x[:, 0].min() - .5, x[:, 0].max() + .5
    y_min, y_max = x[:, 1].min() - .5, x[:, 1].max() + .5
    h = 0.01
    # Generate a grid of points with distance h between them
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
    # Predict the function value for the whole gid
    Z = pred_func(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    # Plot the contour and training examples
    plt.contour(xx, yy, Z, cmap=plt.cm.Spectral)
    plt.scatter(x[:, 0], x[:, 1], c=y, cmap=plt.cm.Spectral)
# Plot the decision boundary
plot_decision_boundary(lambda x: clf.predict(x))
plt.title("Logistic Regression")
plt.show()

1. 生成数据集

首先我们需要一个可以操作的数据集,scikit-learn提供了一些有用的数据集生成器,只需使用make_moons这个函数就可以。

np.random.seed(5)
x,y=sklearn.datasets.make_moons(300,noise=0.30)
#print(x,y)
plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
#plt.show()

np.random.seed(5)

相当于设置了一个盛有随机数的“聚宝盆”,一个数字代表一个“聚宝盆

  • 如果使用相同的seed( )值,则每次生成的随即数都相同;
  • 如果不设置这个值,则系统根据时间来自己选择这个值,此时每次生成的随机数因时间差异而不同。
  • 设置的seed()值仅一次有效
    参考于here and here

x,y=sklearn.datasets.make_moons(300,noise=0.30)

def make_moons(n_samples=100, shuffle=True, noise=None, random_state=None):
300: 点的数目
noise: 加入高斯噪声,大小可表示其混乱程度

plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
plt.scatter() 为绘制散点图函数

X = np.array([[0,1],[2,3],[4,5],[6,7],[8,9],[10,11],[12,13],[14,15],[16,17],[18,19]])
print(X[:,0] )
Output:[ 0 2 4 6 8 10 12 14 16 18]
x[:,0] 即取出位置信息的x坐标值
x[:,1] 即取出位置信息的y坐标值
s=40可改变点的大小
c=y
cmap=plt.cm.Spectral
是给label为1的点一种颜色,给label为0的点另一种颜色

2. 训练Logistic回归器

训练一个Logistic回归分类器,这个分类器的输入是坐标x、y,它的输出是预测的数据类型(0或1)。为了方便,我们使用scikit-learn中的Logistic Regression类。

clf=sklearn.linear_model.LogisticRegressionCV()
clf.fit(x,y)
def plot_decision_boundary(pred_func):
    # Set min and max values and give it some padding
    #
    x_min, x_max = x[:, 0].min() - .5, x[:, 0].max() + .5
    y_min, y_max = x[:, 1].min() - .5, x[:, 1].max() + .5
    h = 0.01
    # Generate a grid of points with distance h between them
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
    # Predict the function value for the whole gid
    Z = pred_func(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    # Plot the contour and training examples
    plt.contour(xx, yy, Z, cmap=plt.cm.Spectral)
    plt.scatter(x[:, 0], x[:, 1], c=y, cmap=plt.cm.Spectral)
# Plot the decision boundary
plot_decision_boundary(lambda x: clf.predict(x))
plt.title("Logistic Regression")
plt.show()

clf=sklearn.linear_model.LogisticRegressionCV()
定义一个LogisticRegressionCVclf

clf.fit(x,y) 类中的一个方法:训练模型
def fit(self, X, y, sample_weight=None):
可以直接Go to去看其定义

x_min, x_max = x[:, 0].min() - .5, x[:, 0].max() + .5
y_min, y_max = x[:, 1].min() - .5, x[:, 1].max() + .5
h = 0.01
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))

定义X、Y轴,然后生成网格点矩阵
np.meshgrid: Look here
np.arrange: Look here

Z = pred_func(np.c_[xx.ravel(), yy.ravel()])
注意函数的传递
xx.ravel():扁平化操作 Look here
np.c_添加列 np.r_[]添加行 Look here

Z = Z.reshape(xx.shape)
按照xx的格式修改矩阵 shape/reshape: here

plt.contour(xx, yy, Z, cmap=plt.cm.Spectral)
plt.coutourplt.cout.coutourf的区别:绘制轮廓,填充轮廓
coutour
coutourf
plot_decision_boundary(lambda x: clf.predict(x))
lambdahere

  • 7
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
制作Mininst格式的数据,研究sklearn库等机器学习算法与库用得到。C++的VS2017测试通过。适用于车牌和数字识别。下面是Skearn测试程序。 #导入必备的包 import numpy as np import struct import matplotlib.pyplot as plt import os ##加载svm模型 from sklearn import svm ###用于做数据预处理 from sklearn import preprocessing import time #加载数据的路径 path='.' def load_mnist_train(path, kind='train'): labels_path = os.path.join(path,'%s-labels-idx1-ubyte'% kind) images_path = os.path.join(path,'%s-images-idx3-ubyte'% kind) with open(labels_path, 'rb') as lbpath: magic, n = struct.unpack('>II',lbpath.read(8)) labels = np.fromfile(lbpath,dtype=np.uint8) with open(images_path, 'rb') as imgpath: magic, num, rows, cols = struct.unpack('>IIII',imgpath.read(16)) images = np.fromfile(imgpath,dtype=np.uint8).reshape(len(labels), 784) return images, labels def load_mnist_test(path, kind='t10k'): labels_path = os.path.join(path,'%s-labels-idx1-ubyte'% kind) images_path = os.path.join(path,'%s-images-idx3-ubyte'% kind) with open(labels_path, 'rb') as lbpath: magic, n = struct.unpack('>II',lbpath.read(8)) labels = np.fromfile(lbpath,dtype=np.uint8) with open(images_path, 'rb') as imgpath: magic, num, rows, cols = struct.unpack('>IIII',imgpath.read(16)) images = np.fromfile(imgpath,dtype=np.uint8).reshape(len(labels), 784) return images, labels train_images,train_labels=load_mnist_train(path) test_images,test_labels=load_mnist_test(path) X=preprocessing.StandardScaler().fit_transform(train_images) X_train=X[0:60000] y_train=train_labels[0:60000] print(time.strftime('%Y-%m-%d %H:%M:%S')) model_svc = svm.LinearSVC() #model_svc = svm.SVC() model_svc.fit(X_train,y_train) print(time.strftime('%Y-%m-%d %H:%M:%S')) ##显示前30个样本的真实标签和预测值,用图显示 x=preprocessing.StandardScaler().fit_transform(test_images) x_test=x[0:10000] y_pred=test_labels[0:10000] print(model_svc.score(x_test,y_pred)) y=model_svc.predict(x) fig1=plt.figure(figsize=(8,8)) fig1.subplots_adjust(left=0,right=1,bottom=0,top=1,hspace=0.05,wspace=0.05) for i in range(100): ax=fig1.add_subplot(10,10,i+1,xticks=[],yticks=[]) ax.imshow(np.reshape(test_images[i], [28,28]),cmap=plt.cm.binary,interpolation='nearest') ax.text(0,2,"pred:"+str(y[i]),color='red') #ax.text(0,32,"real:"+str(test_labels[i]),color='blue') plt.show()

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值