当前位置:   article > 正文

吴恩达老师机器学习-ex3

吴恩达老师机器学习-ex3

使用逻辑回归

导入库,因为这次的数据是mat文件,需要使用scipy库中的loadmat进行读取数据。

通过对数据类型的分析,发现是字典类型,查看该字典的键,可以发现又X,y等关键字。

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import scipy.io as sio
  4. #读取数据
  5. path = "./ex3data1.mat"
  6. data = sio.loadmat(path)
  7. X = data.get("X")
  8. Y = data.get("y")

这个问题可以看出是逻辑回归问题,只不过是一对多的问题,代价函数都是一样的。

  1. def cost_func(theta,X,Y,lamda):
  2. z = X @ theta
  3. A = 1/(1+np.exp(-z))
  4. m = len(X)
  5. cost = -(np.sum(Y*np.log(A)+(1-Y)*np.log(1-A)))/m
  6. reg = np.sum(np.power(theta[1:],2))*(lamda/(2*m))
  7. return cost+reg

梯度下降,其实只是梯度项,方便后面调用minimize优化

  1. def gradient_descent(theta,X,Y,lamda):
  2. m = len(X)
  3. z = X @ theta
  4. A = 1 / (1 + np.exp(-z))
  5. reg = theta[1:] * (lamda / m)
  6. reg = np.insert(reg, 0, values=0, axis=0)
  7. first = (X.T@(A - Y)) / m
  8. return first+reg

新添入X0=1

  1. X = np.insert(X,0,values=1,axis=1)
  2. Y = Y.flatten()

对于一对多的问题,需要建立多个逻辑回归,在这道问题中,共有十个分类,则需要建立十个逻辑回归。使用for循环,每次迭代都得到一个theta向量。

  1. from scipy.optimize import minimize
  2. def one_vs_all(X,Y,lamda,k):
  3. n = X.shape[1]
  4. theta_all = np.zeros((k,n))
  5. for i in range(1,k+1):
  6. theta_i = np.zeros(n,)
  7. res = minimize(fun=cost_func,
  8. x0=theta_i,
  9. args=(X,Y==i,lamda),
  10. method='TNC',
  11. jac=gradient_descent)
  12. theta_all[i-1,:] = res.x
  13. return theta_all

先初始化lamda和k

写出预测函数,一对多的预测就是计算出假设函数。假设函数输出的是概率,选取概率最大的对应的下标。

最后计算一下预测的准确率。

  1. lamda = 1
  2. K = 10
  3. theta_final = one_vs_all(X,Y,lamda,K)
  4. print(theta_final)
  5. def predict(X,theta_final):
  6. z = X @ theta_final.T
  7. h = 1/(1+np.exp(-z))
  8. h_argmax = np.argmax(h,axis=1)
  9. return h_argmax+1
  10. y_pred = predict(X, theta_final)
  11. acc = np.mean(y_pred == Y)
  12. # 0.9446
  13. print(acc)

使用神经网络

导入库,因为这次的数据是mat文件,需要使用scipy库中的loadmat进行读取数据。

通过对数据类型的分析,发现是字典类型,查看该字典的键,可以发现又X,y等关键字。

同时,导入参数文件

  1. import numpy as np
  2. import scipy.io as sio
  3. #读取数据
  4. path = "./ex3data1.mat"
  5. data = sio.loadmat(path)
  6. X = data.get("X")
  7. Y = data.get("y")
  8. X = np.insert(X,0,values=1,axis=1)
  9. Y = Y.flatten()
  10. #读取权重
  11. path_weights = "./ex3weights.mat"
  12. theta = sio.loadmat(path_weights)
  13. # print(theta)
  14. # print(type(theta))
  15. theta1 = theta.get("Theta1")
  16. theta2 = theta.get("Theta2")
  17. # print(theta1.shape)
  18. # print(theta2.shape)

前向传播

  1. z2 = X@theta1.T
  2. a2 = 1/(1+np.exp(-z2))
  3. a2 = np.insert(a2,0,values=1,axis=1)
  4. z3 = a2@theta2.T
  5. h = 1/(1+np.exp(-z3))
  6. # print(h)
  7. # print(h.shape)

预测

一对多的预测就是计算出假设函数。假设函数输出的是概率,选取概率最大的对应的下标。

最后计算一下预测的准确率。

  1. h_argmax = np.argmax(h,axis=1)
  2. h_argmax = h_argmax+1
  3. acc = np.mean(h_argmax==Y)
  4. print(acc)

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号