1. 多分类逻辑回归

自动识别手写数字

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.io import loadmat
from scipy.optimize import minimize
#  加载mat数据
def load_data(path):data = loadmat(path)X = data['X']y = data['y']return X,y
def plot_an_image(X):"""随机打印一个数字"""pick_one = np.random.randint(0, 5000)   # 随机选择行数image = X[pick_one, :]                # 提取一行中400个像素点fig, ax = plt.subplots(figsize=(1, 1))   # 一行一列的图像ax.matshow(image.reshape((20, 20)), cmap='gray_r')   # reshape函数将image重置为20*20的矩阵plt.xticks([])  # 去除x刻度plt.yticks([])  # 去除x刻度plt.show()print('this should be {}'.format(y[pick_one]))  # 输出图像代表的值def plot_100_image(X):"""随机画100个数字"""sample_idx = np.random.choice(np.arange(X.shape[0]), 100)  # 随机选100个样本sample_images = X[sample_idx, :]  # (100,400)fig, ax_array = plt.subplots(nrows=10, ncols=10, sharey=True, sharex=True, figsize=(8, 8))for row in range(10):for column in range(10):ax_array[row, column].matshow(sample_images[10 * row + column].reshape((20, 20)),cmap='gray_r')plt.xticks([])plt.yticks([])plt.show()
# 定义sigmoid函数
def sigmoid(z):return 1 / (1 + np.exp(-z))
# 代价函数 不惩罚theta0 l是正则化常数
def regularized_cost(theta, X, y, l):thetaReg = theta[1:]first = (-y*np.log(sigmoid(X@theta))) + (y-1)*np.log(1-sigmoid(X@theta))reg = (thetaReg@thetaReg)*l / (2*len(X))return np.mean(first) + reg
#带惩罚的梯度下降
def regularized_gradient(theta, X, y, l):thetaReg = theta[1:]first = (1 / len(X)) * X.T @ (sigmoid(X @ theta) - y)# 这里人为插入一维0,使得对theta_0不惩罚,方便计算reg = np.concatenate([np.array([0]), (l / len(X)) * thetaReg])return first + reg# 多分类
def one_vs_all(X, y, l, K):     # k是标签数"""generalized logistic regressionargs:X: feature matrix, (m, n+1) # with incercept x0=1y: target vector, (m, )l: lambda constant for regularizationK: numbel of labelsreturn: trained parameters"""all_theta = np.zeros((K, X.shape[1]))  # (10, 401)for i in range(1, K + 1):theta = np.zeros(X.shape[1])y_i = np.array([1 if label == i else 0 for label in y])ret = minimize(fun=regularized_cost, x0=theta, args=(X, y_i, l), method='TNC',    # 返回一组符合十种数字的参数jac=regularized_gradient, options={'disp': True})all_theta[i - 1, :] = ret.xreturn all_thetadef predict_all(X, all_theta):h = sigmoid(X @ all_theta.T)  # 注意的这里的all_theta需要转置h_argmax = np.argmax(h, axis=1)  #找到每一行最大值的索引h_argmax = h_argmax + 1   #数组是0索引 需要加一个return h_argmax# X, y = load_data('ex3data1.mat')
# print(X.shape, y.shape)
# plot_an_image(X)
# plot_100_image(X)
raw_X, raw_y = load_data('ex3data1.mat')
X = np.insert(raw_X, 0, 1, axis=1) # (5000, 401)
y = raw_y.flatten()  # 这里消除了一个维度,方便后面的计算 or .reshape(-1) (5000,)all_theta = one_vs_all(X, y, 1, 10)
all_theta  # 每一行是一个分类器的一组参数
y_pred = predict_all(X, all_theta)
accuracy = np.mean(y_pred == y)
print ('accuracy = {0}%'.format(accuracy * 100))

2. 使用神经网络进行手写数字识别

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.io import loadmat
from scipy.optimize import minimizedef load_weight(path):data = loadmat(path)return data['Theta1'], data['Theta2']
#  1.读取已经计算好的参数
theta1, theta2 = load_weight('ex3weights.mat')
print(theta1.shape, theta2.shape)X, y = load_data('ex3data1.mat')
y = y.flatten()
X = np.insert(X, 0, values=np.ones(X.shape[0]), axis=1)  #在第一列插入一列零a1 = X
z2 = a1 @ theta1.Tz2 = np.insert(z2, 0, 1, axis=1)  #第二层加一列a0
a2 = sigmoid(z2)z3 = a2 @ theta2.T    # 第三层
a3 = sigmoid(z3)y_pred = np.argmax(a3, axis=1) + 1
accuracy = np.mean(y_pred == y)
print ('accuracy = {0}%'.format(accuracy * 100))  # accuracy = 97.52%

吴恩达机器学习神经网络作业(python实现)相关推荐

  1. 吴恩达机器学习 神经网络 作业1(用已经求好的权重进行手写数字分类) Python实现 代码详细解释

    整个项目的github:https://github.com/RobinLuoNanjing/MachineLearning_Ng_Python 里面可以下载进行代码实现的数据集 题目介绍: In t ...

  2. 吴恩达机器学习课后作业Python实现(一):线性回归

    目录 前言 单变量线性回归 代码实现 数据集准备 代价函数 梯度下降 跑模型并预测 绘制线性模型及代价函数图 多元线性回归 代码实现 结果图 前言         写本篇文章的主要目的是记录自己机器学 ...

  3. 3. 吴恩达机器学习课程-作业3-多分类和神经网络

    fork了别人的项目,自己重新填写,我的代码如下 https://gitee.com/fakerlove/machine-learning/tree/master/code 代码原链接 文章目录 3. ...

  4. 6. 吴恩达机器学习课程-作业6-SVM

    fork了别人的项目,自己重新填写,我的代码如下 https://gitee.com/fakerlove/machine-learning/tree/master/code 代码原链接 文章目录 6. ...

  5. 4. 吴恩达机器学习课程-作业4-神经网络学习

    fork了别人的项目,自己重新填写,我的代码如下 https://gitee.com/fakerlove/machine-learning/tree/master/code 代码原链接 文章目录 4. ...

  6. 1. 吴恩达机器学习课程-作业1-线性回归

    fork了别人的项目,自己重新填写,我的代码如下 https://gitee.com/fakerlove/machine-learning/tree/master/code 代码原链接 文章目录 1. ...

  7. 吴恩达ex3_吴恩达机器学习 EX3 作业 第一部分多分类逻辑回归 手写数字

    1 多分类逻辑回归 逻辑回归主要用于分类,也可用于one-vs-all分类.如本练习中的数字分类,输入一个训练样本,输出结果可能为0-9共10个数字中的一个数字.一对多分类训练过程使用"一对 ...

  8. 8. 吴恩达机器学习课程-作业8-异常检测和推荐系统

    fork了别人的项目,自己重新填写,我的代码如下 https://gitee.com/fakerlove/machine-learning/tree/master/code 代码原链接 文章目录 8. ...

  9. 7. 吴恩达机器学习课程-作业7-Kmeans and PCA

    fork了别人的项目,自己重新填写,我的代码如下 https://gitee.com/fakerlove/machine-learning/tree/master/code 代码原链接 文章目录 7. ...

最新文章

  1. 交换机配置软件crt安装_非常详细的锐捷二层交换机配置教程,适合新手小白
  2. Algs4-1.4.12找出两个有序数组的公共元素-方法1
  3. .net程序员转战android第一篇---环境部署
  4. QML识别模块identifiedmodules
  5. c语言 二进制压缩算法_使用C ++解释的二进制搜索算法
  6. Protobuf生成Java代码(命令行)
  7. Codeforces 699D Fix a Tree 并查集
  8. 微软发布 VS Code Jupyter 插件!不止 Python,多语言的 Jupyter Notebook支持来了!
  9. Redis笔记(六)Redis的消息通知
  10. easyui关于validatebox实现多重规则验证的实践
  11. 英语总结系列(九):百忙中依然坚持的九月
  12. 苹果电脑怎样禁用首字母自动大写?
  13. CTWing-中国电信IoT物联网平台设备接入实战
  14. ENGLISH资料收集(3)-英语日期的正确表达
  15. 2020年日历_2020年农历阳历表,2020年日历表,2020年黄历
  16. Python 将图片合成视频
  17. NBA得分后卫阅兵:科比榜首麦蒂第9 小AI获至高赞誉
  18. 2014 IT互联网公司校招应届生待遇大全
  19. 对国内游戏产业的无力吐槽
  20. 什么是线程线程和进程的区别

热门文章

  1. Servlet JSP和Spring MVC初学指南 PDF
  2. (转载)C语言右移运算符的问题(特别当与取反运算符一起时)
  3. python 列表函数
  4. [算法] 十个经典排序算法
  5. DSP5509项目之用FFT识别钢琴音调(5)之开始傅里叶变换
  6. vs2017编译网狐荣耀服务端的心得
  7. Mac SavePanel 保存文件的GUI代码
  8. JAVA学习笔记-this隐式参数
  9. 使用 Time Machine 恢复 .ssh等隐藏文件夹
  10. hdu4614 Vases and Flowers 线段树+二分