├── MachinLN ├── README.md ├── 机器学习-001:MachineLN之三要素.md ├── 机器学习-002:MachineLN之模型评估.md ├── 机器学习-003:MachineLN之dl.md ├── 机器学习-004:DeepLN之CNN解析.md ├── 机器学习-005:DeepLN之CNN权重更新(笔记).md ├── 机器学习-006:DeepLN之CNN源码.md ├── 机器学习-007:MachineLN之激活函数.md ├── 机器学习-008:DeepLN之BN.md ├── 机器学习-009:MachineLN之数据归一化.md ├── 机器学习-010:MachineLN之样本不均衡.md ├── 机器学习-011:MachineLN之过拟合.md ├── 机器学习-012:MachineLN之优化算法.md ├── 机器学习-013:MachineLN之kNN.md ├── 机器学习-014:MachineLN之kNN源码.md ├── 机器学习-015:MachineLN之感知机.md ├── 机器学习-016:MachineLN之感知机源码.md ├── 机器学习-017:MachineLN之逻辑回归.md ├── 机器学习-018:MachineLN之逻辑回归源码.md ├── 机器学习-019:MachineLN之SVM(1).md ├── 机器学习-020:MachineLN之SVM(2).md ├── 机器学习-021:MachineLN之SVM源码.md └── 机器学习-022:MachineLN之RL.md ├── README.md ├── TensorFlow-Tutorials ├── 00_multiply.ipynb ├── 00_multiply.py ├── 01_linear_regression.ipynb ├── 01_linear_regression.py ├── 02_logistic_regression.ipynb ├── 02_logistic_regression.py ├── 03_net.ipynb ├── 03_net.py ├── 04_modern_net.ipynb ├── 04_modern_net.py ├── 05_convolutional_net.ipynb ├── 05_convolutional_net.py ├── 06_autoencoder.ipynb ├── 06_autoencoder.py ├── 07_lstm.ipynb ├── 07_lstm.py ├── 08_word2vec.ipynb ├── 08_word2vec.py ├── 09_tensorboard.ipynb ├── 09_tensorboard.py ├── 10_save_restore_net.ipynb ├── 10_save_restore_net.py ├── 11_gan.ipynb ├── 11_gan.py └── README.md ├── Tensorflow-estimator-classification ├── 00_mnist.py ├── 01_map.png ├── 01_pascal.py ├── 02_pascal_alexnet.py ├── 03_pascal_vgg.py ├── 04_pascal_vgg_finetune.py ├── 05_alexnet_conv1.py ├── 05_alexnet_eval.py ├── 05_alexnet_nn.py ├── 05_vgg_eval.py ├── 05_vgg_nn.py ├── 05_vgg_tsne.py ├── 06_pascal_alexnet_mixup.py ├── MNIST-data │ ├── README.md │ ├── t10k-images-idx3-ubyte.gz │ ├── t10k-labels-idx1-ubyte.gz │ ├── train-images-idx3-ubyte.gz │ └── train-labels-idx1-ubyte.gz ├── README.md ├── eval.py ├── gpu_conf.sh ├── pascal_alexnet_mixup.png ├── pascal_vgg.png └── pascal_vgg_finetune.png ├── Tensorflow ├── 3_2_HelloWorld.py ├── 4_2_AutoEncoer.py ├── 4_4_MLP.py ├── 5_2_CNN_MNIST.py ├── 5_3_CNN_CIFAR10.py ├── 6_1_AlexNet.py ├── 6_2_VGG.py ├── 6_3_InceptionNet.py ├── 6_4_ResNet.py ├── 7_1_Word2Vec.py ├── 7_2_LSTM.py ├── 7_3_BiRNN.py ├── 8_2_PolicyNetwork.py ├── 8_3_GridWorld.py ├── 8_3_Value_Network.py ├── 9_1_TensorBoard.py ├── 9_2_MultiGPU.py ├── 9_3_Distributed.py ├── README.md └── Tensorflow and Word2vec.txt ├── face_detection ├── README.md ├── 人脸检测——AFLW准备人脸.md ├── 人脸检测——fcn.md ├── 人脸检测——mtcnn思想,生成negative、positive、part样本。.md ├── 人脸检测——准备非人脸.md ├── 人脸检测——滑动窗口篇(训练和实现).md ├── 人脸检测——生成矫正人脸——cascade-cnn的思想,-但是mtcnn的效果貌似更赞.md └── 人脸检测——矫正人脸生成标签.md ├── ml_in_action ├── Perceptron.py ├── README.md ├── bayes.py ├── kNN.py ├── logRegres.py ├── svmMLiA.py ├── treePlotter.py └── trees.py ├── tensorflow_in_action ├── README.md ├── 学习笔记TF001_ 什么是TensorFlow.md ├── 学习笔记TF002_ 怎么安装TensorFlow.md ├── 学习笔记TF003_数据流图定义、执行、可视化.md ├── 学习笔记TF004_张量表示、类型、形状、计算.md ├── 学习笔记TF005_Graph对象、Session对象、占位符.md ├── 学习笔记TF006_Variable对象、名称作用域.md ├── 学习笔记TF007_Tensor、Graph、Op、Variable、占位符、Session、名称作用域、Board综合例子.md ├── 学习笔记TF008_机器学习基础 线性回归.md ├── 学习笔记TF009_对数几率回归.md ├── 学习笔记TF010_softmax分类.md ├── 学习笔记TF011_多层神经网络.md ├── 学习笔记TF012_卷积网络简述.md ├── 学习笔记TF013_卷积、跨度、边界填充、卷积核.md ├── 学习笔记TF014_卷积层、激活函数、池化层、归一化层、高级层.md ├── 学习笔记TF015_加载图像、图像格式、图像操作、颜色.md ├── 学习笔记TF016_CNN实现、数据集、TFRecord、加载图像、模型、训练、调试.md ├── 学习笔记TF017_自然语言处理、RNN、LSTM.md ├── 学习笔记TF018_词向量、维基百科语料库训练词向量模型.md ├── 学习笔记TF019_序列分类、IMDB影评分类.md ├── 学习笔记TF020_序列标注、手写小写字母OCR数据集、双向RNN.md ├── 学习笔记TF021_预测编码、字符级语言建模、ArXiv摘要.md ├── 学习笔记TF022_产品环境模型部署、Docker镜像、Bazel工作区、导出模型、服务器、客户端.md ├── 学习笔记TF023_下载、缓存、属性字典、惰性属性、覆盖数据流图、资源.md ├── 学习笔记TF024_TensorFlow实现Softmax Regression(回归)识别手写数字.md ├── 学习笔记TF025_自编码器.md ├── 学习笔记TF026_多层感知机.md ├── 学习笔记TF027_卷积神经网络.md ├── 学习笔记TF028_实现简单卷积网络.md ├── 学习笔记TF029_实现进阶卷积网络.md ├── 学习笔记TF030_实现AlexNet.md ├── 学习笔记TF031_实现VGGNet.md ├── 学习笔记TF032_实现Google Inception Net.md ├── 学习笔记TF033_实现ResNet.md ├── 学习笔记TF034_实现Word2Vec.md ├── 学习笔记TF035_实现基于LSTM语言模型.md ├── 学习笔记TF036_实现Bidirectional LSTM Classifier.md ├── 学习笔记TF037_实现强化学习策略网络.md ├── 学习笔记TF038_实现估值网络.md ├── 学习笔记TF039_TensorBoard.md ├── 学习笔记TF040_多GPU并行.md ├── 学习笔记TF041_分布式并行.md ├── 学习笔记TF042_TF.Learn、分布式Estimator、深度学习Estimator.md ├── 学习笔记TF043_TF.Learn 机器学习Estimator、DataFrame、监督器Monitors.md ├── 学习笔记TF044_TF.Contrib组件、统计分布、Layer、性能分析器tfprof.md ├── 学习笔记TF045_人工智能、深度学习、TensorFlow、比赛、公司.md ├── 学习笔记TF046_TensoFlow开发环境,Mac、Ubuntu、Linux、Windows,CPU版本、GPU版本.md ├── 学习笔记TF047_PlayGround、TensorBoard.md ├── 学习笔记TF048_TensorFlow 系统架构、设计理念、编程模型、API、作用域、批标准化、神经元函数优化.md ├── 学习笔记TF049_TensorFlow 模型存储加载、队列线程、加载数据、自定义操作.md ├── 学习笔记TF050_TensorFlow源代码解析.md └── 学习笔记TF051_生成式对抗网络.md └── tf-API ├── README.md ├── tf-API-研读1:tf-nn,tf-layers,-tf-contrib概述.md ├── tf-API-研读2:math.md └── tf-API-研读3:Building-Graphs.md /MachinLN/机器学习-001:MachineLN之三要素.md: -------------------------------------------------------------------------------- 1 | 2 | **开篇废话:** 3 | 4 | 机器学习解决的问题和李航老师统计学习方法所描述的统计学问题不谋而合。李老师定义为统计学习三要素:方法=模型+策略+算法。这不光是统计学习必经之路,这也是ML、DL三大关键所在,如果你这三块系统化了以后,都可以往里套。 5 | 6 | 学习机器学习必由之路:(1)模型。(2)策略。(3)算法。 7 | 8 | 那么我的理解: 9 | 10 | **(1)模型** 11 | 12 | 模型:官方一点就是:所要学习的条件概率或决策函数;譬如一个数学问题就是你针对解决问题列的方程组,而对于统计学来说就是我们常见的:感知机、K近邻、贝叶斯、决策树、逻辑回归、SVM等,有人就会说这不都是机器学习模型啊,我可以告诉你还真是,在不同的领域叫法是有点差别的,在经济里的统计系那么就是统计模型,在cv,nlp就是ML模型,自己瞎猜的,如果不对欢迎指出;在DL中的模型就是CNN、RNN、DNN、RBM等等。 13 | 14 | **(2)策略** 15 | 16 | 策略:就是说你这个模型想让它按照怎么样的准则去学习,然后选择你认为的最优模型。(这地方为什么加个你认为,这就是关键,因为同一个模型有人最后只能做到98%,而有人做到99%,当然track很多,data augmentation还是必要的)其实策略就是我们通常说的损失函数(loss function)、代价函数(cost function)等,主要有:0-1损失函数,平方损失函数,绝对损失函数,对数损失函数,交叉熵等,其实这一些在推荐系统中也称之为相似度(也可以称为距离)的度量方法,简单一点像基于用户的相似度,基于商品相似度等,其实就是求的距离,那么求距离的方法就多了:欧式距离、马氏距离、汉明距离、余弦距离、皮尔逊距离等,其实很多东西都是相通的。如果你理解到这里我感觉你已经入门了,“昨夜西风调碧树,独上高楼,望尽天涯路”。(我这人喜欢吹牛逼,爱吹不要紧,一定要落实,否则前功尽弃,做自己做好自己) 17 | 18 | 当然李航老师书中还提到了经验风险和结构风险,结构风险其实就是加正则化,或者惩罚项,有:L1、L2、dropout等等。 19 | 20 | **(3)算法** 21 | 22 | 算法:通俗一点就是解决问题的方法,一提到算法大家很快想到的是:排序、贪心、最短路径、字符串匹配等等,而这里的算法是你选择的使策略最小化的方法,有最小二乘法、牛顿法(想多了解一些数学可以看看泰勒级数,有时面试会问到)、梯度下降等,同样你要选择适合你的模型的优化方法,ML和DL有很多优化方法,不要迷失了方向,适合自己的才是最好的。 23 | 24 | **(4)总结** 25 | 26 | 当你这三块都很了解了,那么你就可以启程远航了,恭喜你到了第二境界:“衣带渐宽终不悔,为伊消得人憔悴”,惭愧的是目前鄙人还停留在“昨夜西风调碧树,独上高楼,望尽天涯路”。 27 | 28 | ——2017年最后一篇文章 29 | 30 | ![image](http://upload-images.jianshu.io/upload_images/4618424-6e7db5ede6a7778c?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 31 | 32 | 33 | 34 | 版权声明:本文为博主原创文章,未经博主允许不得转载。有问题可以加微信:lp9628(注明CSDN)。 35 | -------------------------------------------------------------------------------- /MachinLN/机器学习-002:MachineLN之模型评估.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 开篇废话: 4 | 5 | 很多文章其实都是将书中的东西、网上课程、或者别人的论文的东西总结一下,发出来,但是个人感觉还是加入个人的理解,然后加上一些工程中遇到的问题一起发出来会更好些。 6 | 7 | 正如学习再多tricks,不如踩一遍坑。 模型评估的标准有很多,但是适合自己的才是好的,我本人就比较喜欢看loss,而有些人更加关注准确率。 8 | 9 | 回想上学时候我们基本接受的都是被动接收知识,其实教的再好都不如好的提问,学习独立思考的能力,我学习的很多东西不是在课堂上老师所谓的教,而是在面试过程中面试官的提问,在项目中老板的提问、客户的提问,每次我都能学到很多东西,因为他们问的我很多有点含糊,或者不会,然后就回来自己学习总结,接下来又去被问,又学习又总结,也因此刚毕业换了几次工作,看到这里大家肯定感觉我是奇葩中奇葩,其实我不反对,别人怎么看我并不重要,只要自己知道自己想要的是什么就好,有人可能会问,刚毕业就换工作是不是不太好? 我可以跟你说没关系,迈开第一步,万事大吉。 10 | 11 | 那么我的问题是: 12 | 13 | (1)为什么要评估模型? 14 | 15 | (2)评估模型有哪些方法? 16 | 17 | (3)不同的方法针对什么问题? 18 | 19 | (4)根据评估的结果如何调优? 20 | 21 | (5)根据评估结果怎么判定模型训练完成? 22 | 23 | 看到这里你的答案是什么? 那么下面是我的答案,欢迎批评指正。 24 | 25 | (1)为什么要评估模型? 26 | 27 | 其实我们去评估模型最终是为了,得到符合我们数据或者是业务的最优模型,但是这往往不是一蹴而就的,反而使得评估模型通常成了下一步我们调参或者调优的一个参考。 28 | 29 | (2)评估模型有哪些方法? 30 | 31 | 通常很多书籍中不会将loss(MachineLN之三要素中策略,也就是你的损失函数、目标函数的值)作为模型的评估标准,反而loss是一个很重要的标准,他将左右你调参过程中的很多参数,并且可以成为你判定是否模型训练完成的标准,譬如我们看到loss一直波动比较大,我们很自然的会想到是你的学习率太大了吧,后来loss开始波动很大,回来慢慢的平稳下降,这可能是数据分布的影响,可能是你样本的预处理方式;个人喜欢看loss,而准确率有时候在很长时间里波动不会很大;看到这里不要迷糊,总之还是那句话自己去踩踩坑,比什么都重要。 32 | 33 | 模型评估的方法相比大家都不陌生,只要看过一些机器学习的基础知识都可以知道一些,我在想要不要再写一下呢,纠结中... 34 | 35 | 评价的方法有: 36 | 37 | 错误率(error rate)= a个样本分类错误/m个样本精度(accuracy)= 1 -错误率 38 | 39 | 误差(error):学习器实际预测输出与样本的真是输出之间的差异(差异的标准可以定义为相似度或者距离)。 40 | 41 | 训练误差(training error):即经验误差。学习器在训练集上的误差。 42 | 43 | 泛化误差(generalization error):学习器在新样本上的误差。 44 | 45 | 真正例(True Positive,TP):真实类别为正例,预测类别为正例。 46 | 47 | 假正例(False Positive,FP):真实类别为负例,预测类别为正例。 48 | 49 | 假负例(False Negative,FN):真实类别为正例,预测类别为负例。 50 | 51 | 真负例(True Negative,TN):真实类别为负例,预测类别为负例。 52 | 53 | ![image](http://upload-images.jianshu.io/upload_images/4618424-6286432751d9c83a?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 54 | 55 | **ROC:** 纵轴:真正例率 TPR;横轴:假正例率FPR; 56 | 57 | ![image](http://upload-images.jianshu.io/upload_images/4618424-b4119ada9be31a13?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 58 | 59 | **AUC:**ROC曲线下面的面积。 60 | 61 | **准确率,又称查准率(Precision,P);** 62 | 63 | ![image](http://upload-images.jianshu.io/upload_images/4618424-9805847e7a3deecc?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 64 | 65 | **召回率,又称查全率(Recall,R):(例如在人脸检测中有多少人脸检测到了,漏掉了多少人脸)** 66 | 67 | ![image](http://upload-images.jianshu.io/upload_images/4618424-61aa9658db9936b4?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 68 | 69 | 等; 70 | 71 | 上面基本上是分类模型的评价标准,而在回归模型中,一般都是通过距离或者相似度来衡量(欧氏距离等)。有点乱,可以去看看周老师的机器学习一书。 72 | 73 | (3)不同的方法针对什么问题? 74 | 75 | 在(2)中回答过了。 76 | 77 | (4)根据评估的结果如何调优?(都是基于深度学习的,?) 78 | 79 | * 当训练集的效果(准确率)上不去,和贝叶斯估计(人的表现)存在一定差距的时候:(1)增加模型的复杂度。 或者直接多加几层。(2)现在目前效果非常好的一些模型:resnet,inception等。(3)重新选择优化函数:AdamOptimizer,MomentumOptimizer,RMSPropOptimizer等等。 80 | 81 | * 训练集效果表现好,测试集效果表现不好:(1)增加训练样本的数量。(2)正则化:L2范数,dropout等(dropout原理是什么呢?使随机使神经元失活,相当于把一个复杂的模型拆分开,测试后时候凑到一起,集成学习的思想,又刹不住闸了。。。)。(3)还要观察训练样本和测试样本的分布是否一致。(4)交叉验证。 82 | 83 | * 还有像样本预处理:(1)归一化:img/255.0,img-0.5, img*2,将数据转化为[-1,1].(2)减去均值除以方差。(3)减去样本各通道的均值。 84 | 85 | * 还有loss的选择啊,多标签单分类适合用softmax_cross_entropy(对于多标签多分类的要用多个softmax),多标签多分类常用sigmoid_cross_entropy。 86 | 87 | * data augmentation。 88 | 89 | * 还要注意BN的使用,学习率的选择,batch_size的大小。 90 | 91 | 可以参考博客:http://blog.csdn.net/u014365862/article/details/78519727 92 | 93 | 深度学习的这么坑你都遇到过吗?:http://blog.csdn.net/u014365862/article/details/77961624 94 | 95 | (5)根据评估结果怎么判定模型训练完成? 96 | 97 | 很多人都说:loss不再怎么变化,或者准确率不再怎么变化,ML书中一般都是交叉验证选最好的,但是dl中往往是选择什么时候停止,其实真实的情况往往是这个样子的(如下图),开始模型是欠拟合的,随着迭代次数的增多,模型会慢慢收敛,但是过了一个点以后,会呈现过拟合,这种情况怎么调参? 有哪些解决方法? 哦,发现自己好烦,我同事和大家一样也很烦我,说我问题真多,哈哈。。。我在迁移学习过程中一般都是从更新最后一层参数开始,根据自己的数据量来判断要更新最后几层的参数,更新多了会过拟合,少了会欠拟合,当然你还可以设置正则化等等。 98 | 99 | ![image.png](http://upload-images.jianshu.io/upload_images/4618424-04ea97d9e780d070.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 100 | 101 | 102 | (6)总结 103 | 104 | 模型评估还是很重要的,但注意不同的标准可能评估的结果有点差异,还想简单提一下,偏差和方差的问题,后面的学习中可能会用到,先看一下这张图(其实就是上面那张图),其实我们模型的误差Error = Bias + Variance + Noise。 鱼和熊掌不可兼得。 105 | 106 | 可以参考:http://blog.csdn.net/u014365862/article/details/76360351。 107 | 108 | ![image](http://upload-images.jianshu.io/upload_images/4618424-352788ab73ed0d7f?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 109 | 110 | ![image](http://upload-images.jianshu.io/upload_images/4618424-1e979c54b29c1552?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 111 | 112 | 113 | 114 | 版权声明:本文为博主原创文章,未经博主允许不得转载。有问题可以加微信:lp9628(注明CSDN)。 115 | -------------------------------------------------------------------------------- /MachinLN/机器学习-003:MachineLN之dl.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 开篇废话: 4 | 5 | 嫌废话太多可以直接跳到正文哦。 6 | 7 | 对外人提起人工智能感觉很牛逼很了不起、高大上或者一些其他的吹捧、羡慕的词都出来,那么今天就通过一篇文章带到dl的世界,如果你是小白这篇文章会感觉挺好玩,如果你是大牛,你会感觉这个玩意谁不会?!不管怎么样请保持平常心,因为深度学习很普通,并且现在很多人感觉已经遇到了瓶颈,大牛都在寻找其他更好的方法,但不得不承认dl确实比传统机器学习的方法好,先看一下dl的局限性,给你挖一些坑自己去填可好?(1)目前深度学习需要大量数据;(2)深度学习目前还是太表浅,没有足够的能力进行迁移;(3)迄今深度学习没有自然方式来处理层级架构;(3)迄今为止的深度学习无法进行开放推理;(4)迄今为止的深度学习不够透明;(5)迄今为止,深度学习并没有很好地与先验知识相结合;(6)到目前为止,深度学习还不能从根本上区分因果关系和相关关系;(7)深度学习假设世界是大体稳定的,采用的方式可能是概率的;(8)到目前为止,深度学习只是一种良好的近似,其答案并不完全可信;(9)到目前为止,深度学习还难以在工程中使用;以上是Gary Marcus提出对深度学习的系统性批判,文章地址:https://arxiv.org/ftp/arxiv/papers/1801/1801.00631.pdf;那么我的问题又来了,以上9个方面为什么?搞明白了局限性再去思考值不值得学习,不要随大流,李开复老师有句话说的好:千万不要让别人驾驶你的生命之车,你要稳稳地坐在司机的位置上,决定自己何时要停、倒车、转弯、加速、刹车。可以参考别人的意见,但不要随波逐流。估计有人又开始骂了,你tm的废话真多,赶紧上干货,呃,不好意思,能再说几句吗?好吧,总之不建议大家都来追潮流,当大家都去做一件事情的时候,那么机会往往在相反的方向上;估计很多人都记得那条让人深思的技术成熟的曲线,先是疯狂的上去,然后又快速的下来,然后缓慢的爬行;又有人说你太悲观了,过去已去,把握现在,未来谁知?实时确实是这样,大多数人也都这样做的,包括我。 8 | 9 | 说了这么多废话,该回到dl了。简单说一下AI;AI=感知+理解+决策,目前的dl就是处理AI中的理解问题,无论是人脸检测、识别、行人检测、车辆检测、车道线、语音识别等等;感知就是获取图像、语音等的设备,决策像无人驾驶中来不及刹车时,左右是沟,中间是人,你怎么决策?损人利己?还是损己利人?哲学问题,扯得远了,但是真要商用,确实要面临的问题很多。 10 | 11 | 那么我的问题是? 12 | 13 | (1)你学dl的目的是什么? 14 | 15 | (2)你喜欢你现在的工作吗?dl对你现在的工作有什么帮助? 16 | 17 | (3)如果那天dl热潮过了,你还有还什么技能可能养家糊口? 18 | 19 | 接下来不解答上面问题了,而是看一个手写体识别的代码,带你进入word世界: 20 | 21 | 咱们顺着代码的流程走一遍,估计会有很多坑,有坑时好事,正如学习再多tricks,不如猜一遍坑,(你废话真多,好了好了我不说了)后面的一些文章会逐渐来填起来;are you ready? 22 | 23 | 这是一段cnn的代码来决解手写体数字识别,(初学者会问了cnn是什么?有坑了?自己填去啊,哈哈) 24 | 25 | (1)开始导入一下tensorflow,和去获取一下mnist的数据,用于后面的训练和测试![image](http://upload-images.jianshu.io/upload_images/4618424-d0b360cb96b2177f?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 26 | 27 | (2)定义卷积:(问题:卷积是什么? 为什么用卷积?作用是什么?) 28 | 29 | ![image](http://upload-images.jianshu.io/upload_images/4618424-49ee09f530913d40?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 30 | 31 | (3)定义池化:(问题和上面一样,别嫌我话多,面试时候会问到) 32 | 33 | ![image.png](http://upload-images.jianshu.io/upload_images/4618424-a84a0a4ca7afd07e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 34 | 35 | 36 | (4)定义BN:(问题和上面一样) 37 | 38 | ![image](http://upload-images.jianshu.io/upload_images/4618424-eab4d774297cf02a?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 39 | 40 | (5)初始化参数:卷积核参数;全连接参数; 41 | 42 | ![image](http://upload-images.jianshu.io/upload_images/4618424-4ff1ea5cdcc1af51?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 43 | 44 | (6)该盖楼了。 45 | 46 | ![image.png](http://upload-images.jianshu.io/upload_images/4618424-c1d62c9ce85e4e36.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 47 | 48 | 49 | (7)训练模型,其中含有了(机器学习三要素中的模型、策略、算法;还有机器学习之模型评估中的loss和准确率),有了上面的基础,下面代码就好理解了。 50 | 51 | ![image](http://upload-images.jianshu.io/upload_images/4618424-ce7a91c7abb87162?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 52 | 53 | ![image](http://upload-images.jianshu.io/upload_images/4618424-a1d7b714e4226e28?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 54 | 55 | (8)一些参数和占位符。 56 | 57 | ![image](http://upload-images.jianshu.io/upload_images/4618424-90134ba442644cce?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 58 | 59 | # 上面的代码整合起来就可以跑了; 60 | 61 | 看一下结果: loss会慢慢降,而准确率会突变,这又是为什么? 62 | 63 | ![image](http://upload-images.jianshu.io/upload_images/4618424-e04eb32b1b5f121a?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 64 | 65 | 说明:像一些衰减和正则化的方法里边没加,后面会慢慢补充,下面给大家一个简单定义模型的框架: 66 | 67 | ![image](http://upload-images.jianshu.io/upload_images/4618424-bc4cda3fd34b7700?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 68 | 69 | ![image](http://upload-images.jianshu.io/upload_images/4618424-17697657140047c0?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 70 | 71 | (9)总结:入门级的感觉这个就够了,把上面的代码玩透了,调调参,挖了坑一定要填起来,要不前功尽弃;到这里是一个节点说明你想明白了,你想学习dl,那就关注我们吧,一起坚持下去,MachineLN与你一年之约,只要想学什么时候开始都不晚。 72 | 73 | 推荐阅读: 74 | 75 | 1. [MachineLN之三要素](http://mp.weixin.qq.com/s?__biz=MzU3MTM3MTIxOQ==&mid=2247483841&idx=2&sn=e4a3cff7b12c48af237c577c487ba3a1&chksm=fce07a7dcb97f36be5003c3018b3a391070bdc4e56839cb461d226113db4c5f24032e0bf5809&scene=21#wechat_redirect) 76 | 77 | 2. [MachineLN之模型评估](http://mp.weixin.qq.com/s?__biz=MzU3MTM3MTIxOQ==&mid=2247483872&idx=2&sn=8436e1eb9055d3a372278ee8688cd703&chksm=fce07a5ccb97f34a4490f60304b206c741d2395149c2c2e68bddb3faf7daf9121ca27a5d6a97&scene=21#wechat_redirect) 78 | 79 | ![image.png](http://upload-images.jianshu.io/upload_images/4618424-ab37d62464cc2796.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 80 | 81 | 82 | 83 | 84 | 版权声明:本文为博主原创文章,未经博主允许不得转载。有问题可以加微信:lp9628(注明CSDN)。 85 | -------------------------------------------------------------------------------- /MachinLN/机器学习-004:DeepLN之CNN解析.md: -------------------------------------------------------------------------------- 1 | 开篇废话: 2 | 3 | 很感谢谭哥的开篇废话这四个字,让我把一些废话说出来了,是时候还给谭哥了。因为废话太多会让人感觉,没有能力净废话。 4 | 5 | 今天我开始从头学习CNN,上一篇MachineLN之深度学习入门坑太多了,需要慢慢的填起来。那么我的问题是: 6 | 7 | (1)为什么要提出cnn? 8 | 9 | (2)cnn的结构是怎么样子的? 10 | 11 | (3)cnn中各层的含义是什么? 12 | 13 | 看到这里你的答案是什么? 那么下面是我的答案,欢迎批评指正。 14 | 15 | **(1)为什么要提出cnn?** 16 | 17 | 嫌字太多直接看图,或者简单总结为cnn**参数少好学习**。 18 | 19 | **卷积神经网络**是在神经网络的理论基础上形成的深度学习网络,它是一种特殊的多层神经网络。而传统的神经网络是一个全连接的网络结构(后面会提到),它上一层的每一个神经元与下一层的每一个神经元均有连接。这种结构有以下缺点:1、在处理声音和图像数据的时候,由于声音和图像的输入维度较高,包含数百个以上的变量,例如,输入图像的像素是100×100,假设隐含层要学习100维的特征 (即隐含层有 100 个神经元),那么全连接网络就要学100×100×100个参数,即100万个权重参数,这样的网络结构在使用BP算法训练的时候,不但训练速度慢,而且需要的训练样本的数量也越多,若训练样本数量不足,会产生过拟合现象,学习得到的模型没有实用性。2、传统神经网络的结构对输入数据的特点的考虑不足,以图像识别为例,将同一幅图像做很小的位移,传统神经网络对其会很敏感,会当成是不同的图像,无法根据训练过程对该类数据特征进行优化处理。3、传统神经网络因为与输入数据是全连接的,无法识别训练数据中的局部区域特征,可是卷积神经网络可以单独学习识别该局部区域特征。 20 | 21 | **==>看一下图(借用大神的图)吧: 主要看第一个(10的12次幂)和第四个(10k)图的参数数量相差10的8次幂倍,已经到了亿级别了。(local conv意思是每个卷积核是不同的,也就是后面提到的它不是权值共享)** 22 | 23 | ![image](http://upload-images.jianshu.io/upload_images/4618424-0496ff657fc51883?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 24 | 25 | ![image](http://upload-images.jianshu.io/upload_images/4618424-918179e78134f561?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 26 | 27 | **(2)cnn的结构是怎么样子的?** 28 | 29 | 下面是最经典的cnn结构,如果你关注cnn发展过程,是这样子的:LeNet5->AlexNet->VGG->Inception_v1(v2,v3)->resnet->Inception_v4->xception->resnet_v2->Inception_resnet等等,还有一些移动端的小模型(mobilenet、shuffleNet)。 30 | 31 | ![image](http://upload-images.jianshu.io/upload_images/4618424-d03660c647084f25?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 32 | 33 | * 1\. 学过数字图像处理的应该学过卷积,像sobel算子等一些边缘检测,像一些均值滤波、中值滤波等等,只是这个卷积核我们称为fliters;但是和卷积神经网络中是不一样的,cnn中的卷积核往往是很多个,并且卷积中的卷积核值是通过学习得到的。**卷积的流程:**以一个很简单的图示展示卷积的流程:(下面只是一个简单的演示,真实情况下一般都是m个输入n个输出,对应[m,n,kernel_size,kernel_size]) 34 | 35 | ![image](http://upload-images.jianshu.io/upload_images/4618424-1ce00bdf4f836fa3?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 36 | 37 | * 2\. 池化流程,在一个给定的区域内,譬如2*2的区域取最大值(最大池化)、平均值(平均池化),(还有随机池化等)然后设置步长一般为2(就是下一步3*3的区域走到哪里),这样遍历完后,图像大小则会变为原来的二分之一。下面是最大池化和平均池化。 38 | 39 | ![image](http://upload-images.jianshu.io/upload_images/4618424-c3f317322e84cfa4?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 40 | 41 | **(3)cnn中各层的含义是什么?** 42 | 43 | **卷积层的作用:** 44 | 45 | * 1\. 权值共享,减少训练参数;一个卷积核与 输入map的不同区域做卷积时,它的参数是固定不变的。在CNN里,这叫做权值更享,那么为什么说减少训练参数呢? 没有对比不能说少了或者多了,在上面的为什么提出cnn中已经解释了。 46 | 47 | * 2\. 不同的卷积核可以提取不同的特征; 48 | 49 | **池化层的作用:** 50 | 51 | 减少参数。通过对卷积后的特征图降维,有效减少后续层需要的参数,但是下面的才是内涵所在: 52 | 53 | * 1\. 使构建更深层次的网络变得可行; 54 | 55 | * 2\. 使得filters获得更多的全局和contextual(上下文)信息; 56 | 57 | * 3\. 使训练可行,也可以说使得训练变得更高效,主要是针对深层次的网络结构来说; 58 | 59 | * 4\. 使得 特征map大小和数量进行更好的选择(权衡)。例如,就用输入到全连接层的前一层conv来说,特征map太大的话,特征数量就不易太多,通过pooling,使得特征map变小,特征map数量就可以更多。 60 | 61 |     (那么为什么要特征map更多呢?好处在哪里?) 62 | 63 | * 答:因为每个特征map对应一个filters,特征map越多对应更多的filters,而不同的filters提取的是图像中不同方面的特征,也就是说filters越多对图像不同特征的提取越多。 64 | 65 | * 5. 还有局部旋转不变性哦,其中像素在邻域发生微小位移时,池化层的输出是不变的。这就使网络的鲁棒性增强了,有一定抗扰动的作用。 66 | 67 | **最后层:全连结层(FC)** 68 | 69 | 这个简单提一下,水太深; 70 | 71 | * 1. FC在整个卷积神经网络中起到“分类器”的作用; 72 | 73 | * 2. 目前由于全连接层参数冗余(仅全连接层参数就可占整个网络参数80%左右),像ResNet和GoogLeNet等均用全局平均池化(GAP)取代FC来融合学到的深度特征,最后用softmax等损失函数作为网络目标函数训练模型。 74 | 75 | * 3\. FC越来越不被看好。 76 | 77 | 说明:我只是根据自己的理解写了下来,我又不是大牛、大神,只是一个小罗罗,希望大家能给给予批评指正,另外挖的坑太多,欢迎投稿,救救我。 78 | 79 | **展望:** 80 | 81 | 接下来请关注手撕cnn; 82 | 83 | 接下来请关注cnn实现; 84 | 85 | 接下来请关注:但之后dl将告一段落,补习传统机器学习的理论知识 到 实践; 86 | 87 | 后面再开始进入dl:搭建通用分类模型框架(vgg,resnet,inception等);人脸检测系列;人脸识别系列;验证码识别系列;通用OCR系列;年龄性别识别;rnn预测;强化学习;一起走进无人驾驶;之间还会插入数据结构和算法; 88 | 89 | 目前自己在瓶颈期,真的掉坑里了,整理总结前行,一直在路上。 90 | 91 | machinelp与你一年之约,你准备好了吗? 92 | 93 | 推荐阅读: 94 | 95 | 1. [MachineLN之三要素](http://mp.weixin.qq.com/s?__biz=MzU3MTM3MTIxOQ==&mid=2247483841&idx=2&sn=e4a3cff7b12c48af237c577c487ba3a1&chksm=fce07a7dcb97f36be5003c3018b3a391070bdc4e56839cb461d226113db4c5f24032e0bf5809&scene=21#wechat_redirect) 96 | 97 | 2. [MachineLN之模型评估](http://mp.weixin.qq.com/s?__biz=MzU3MTM3MTIxOQ==&mid=2247483872&idx=2&sn=8436e1eb9055d3a372278ee8688cd703&chksm=fce07a5ccb97f34a4490f60304b206c741d2395149c2c2e68bddb3faf7daf9121ca27a5d6a97&scene=21#wechat_redirect) 98 | 99 | 3. [MachinLN之dl](http://mp.weixin.qq.com/s?__biz=MzU3MTM3MTIxOQ==&mid=2247483894&idx=2&sn=63333c02674e15e84159e064073fe563&chksm=fce07a4acb97f35cc38f75dc891a19129e2406270d04b739cfa9b8a28f9780b4e2a65a7cd39b&scene=21#wechat_redirect) 100 | 101 | ![image.png](http://upload-images.jianshu.io/upload_images/4618424-12277859f8b95664.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 102 | 103 | 版权声明:本文为博主原创文章,未经博主允许不得转载。有问题可以加微信:lp9628(注明CSDN)。 104 | -------------------------------------------------------------------------------- /MachinLN/机器学习-005:DeepLN之CNN权重更新(笔记).md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 我想说: 4 | 5 | 学习dl不去深层的扒扒,没有理论的支撑是不行的,今天分享一篇笔记,另加读者的心得,很棒。 6 | 7 | 读者分享数据挖掘心得: 8 | 9 | 我跟你讲一下在实际项目中我们是怎么做数据挖掘的。1:定义业务问题,很多人认为机器学习越高大上的算法越厉害,其实不是这样的,每类算法都有特定的业务场景。机器学习主要分为有监督无监督和半监督,当拿到业务问题时,要看业务场景下哪类算法比较好。比如做风控我们会用决策树,做点击率预估我们会用LR。这里你要清楚每个算法的优缺点,比如为什么我要用决策树不用随机森林,为什么用LR不用SVM 2:根据模型做数据的收集和整合(比如爬虫,建立数据仓库,用户画像,使用spark做数据统计和清洗等等) 3:拿到数据以后,怎么建立有效的特征 因为数据不可能都是完整的,会有缺失值和异常值 这个时候需要根据业务做一些业务场景下的替代,比如用平均值代替缺失值,用中值代替异常值  4:数据特征的向量化表示 比如LR,LR这个模型要求输入的数据必须是0到1之间的,但是我们的数据不可能都是0到1之间的,这个时候就需要对数据进行向量化表示(比如离散化也叫做one hot encoding,归一化)文本数据使用(tf-idf word2vec)等等  5:建立有效的损失函数 把数据跑到LR中,需要一种方法来迭代数据的误差,比如Logloss function 我们的目的就是不断迭代求出误差的最小值 6:怎么快速求出模型 这里比如离线数据下我们会使用梯度下降算法迭代模型 实时数据下我们会使用ftrl算法迭代模型 7:模型的评估 比如使用AUC  8:模型的调整 比如过拟合我们会使用正则项,pca降维 这里比如会用交叉验证算出正则向的系数 其实大部分数据挖掘场景下都是这个套路。 10 | 11 | 下面是cnn权重更新详解: 12 | 13 | ![image](http://upload-images.jianshu.io/upload_images/4618424-297fefaff2cafacf?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 14 | 15 | ![image](http://upload-images.jianshu.io/upload_images/4618424-f90621471d133cf8?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 16 | 17 | ![image](http://upload-images.jianshu.io/upload_images/4618424-f14605a48d867181?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 18 | 19 | ![image.png](http://upload-images.jianshu.io/upload_images/4618424-28d59074a5c792d6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 20 | 21 | 22 | ![image.png](http://upload-images.jianshu.io/upload_images/4618424-e2bd8d2db6baee8b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 23 | 24 | 25 | 还可以参考: 26 | 27 | 1. 反向传播和它的直观理解:http://blog.csdn.net/u014365862/article/details/54728707 28 | 29 | 2\. UFLDL教程:http://deeplearning.stanford.edu/wiki/index.php/UFLDL教程 30 | 31 | 3. http://www.moonshile.com/post/juan-ji-shen-jing-wang-luo-quan-mian-jie-xi#toc_11 32 | 33 | 推荐阅读: 34 | 35 | 1. [MachineLN之三要素](http://mp.weixin.qq.com/s?__biz=MzU3MTM3MTIxOQ==&mid=2247483841&idx=2&sn=e4a3cff7b12c48af237c577c487ba3a1&chksm=fce07a7dcb97f36be5003c3018b3a391070bdc4e56839cb461d226113db4c5f24032e0bf5809&scene=21#wechat_redirect) 36 | 37 | 2. [MachineLN之模型评估](http://mp.weixin.qq.com/s?__biz=MzU3MTM3MTIxOQ==&mid=2247483872&idx=2&sn=8436e1eb9055d3a372278ee8688cd703&chksm=fce07a5ccb97f34a4490f60304b206c741d2395149c2c2e68bddb3faf7daf9121ca27a5d6a97&scene=21#wechat_redirect) 38 | 39 | 3. [MachinLN之dl](http://mp.weixin.qq.com/s?__biz=MzU3MTM3MTIxOQ==&mid=2247483894&idx=2&sn=63333c02674e15e84159e064073fe563&chksm=fce07a4acb97f35cc38f75dc891a19129e2406270d04b739cfa9b8a28f9780b4e2a65a7cd39b&scene=21#wechat_redirect) 40 | 41 | 4. [DeepLN之CNN解析](http://mp.weixin.qq.com/s?__biz=MzU3MTM3MTIxOQ==&mid=2247483906&idx=1&sn=2eceda7d9703d5315638739e04d5b6e7&chksm=fce079becb97f0a8b8dd2e34a9e757f23757cf2699c397707bfaa677c9f8204c91508840d8f7&scene=21#wechat_redirect) 42 | 43 | ![image](http://upload-images.jianshu.io/upload_images/4618424-3428c5287d46ebb9?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 44 | 45 | 46 | 47 | 版权声明:本文为博主原创文章,未经博主允许不得转载。有问题可以加微信:lp9628(注明CSDN)。 48 | -------------------------------------------------------------------------------- /MachinLN/机器学习-006:DeepLN之CNN源码.md: -------------------------------------------------------------------------------- 1 | 2 | 我想说: 3 | 4 | 可能一直关注我更新文章的童鞋,可能看出我的布局,基本是先搭一个框架然后挖坑去填,这可能是我做事情一个优点,当接触到新事物总是能快速建立一个框架,然后去慢慢填,可能刚开始建立的框架是错的,但是没关系,后面随着认知的加深慢慢去改,这可能与我数学比较好有点关系(又开始了...对你无语!!!),跟着清华宁向东老师学习管理学半年,感觉在宁老师上课方式跟我学习知识有点相似(当然应该是我跟宁老师相似),框架搭好挖坑去填,然后多问为什么?另外我也一直反对老师上课用ppt,为什么不用板书,由以前的事半功倍,变成现在事倍功半,反而让学生课后要花更多时间去自己琢磨学习,爱学习的还好,就像我这种不爱学习的简直是大坑。清华老校长梅贻琦先生的话:大学者,非有大楼之谓也,而有大师之谓也。 5 | 6 | 今天我们来研究cnn的源码,不用dl框架,前边文章已经对卷积、池化、全连结、前向传播、后向传播等做了铺垫,还少了激活函数(稍微提一下,使解决非线性成为可能,同时选择不当会导致梯度后向传播失败的问题)、BN(解决训练过程中数据弥散、加速训练,抗过拟合、弥补激活函数造成梯度后向传播失败的问题)等文章,后面会慢慢填起来。 7 | 8 | 又是截图哈哈,个人观点:好代码是敲出来的;从来不是搬出来的; 9 | 10 | 开始顺代码: 11 | 12 | ![image.png](http://upload-images.jianshu.io/upload_images/4618424-434dd0cc1b5ad36f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 13 | 14 | 15 | ![image.png](http://upload-images.jianshu.io/upload_images/4618424-7a0e3f6e1d2ffb76.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 16 | 17 | ![image.png](http://upload-images.jianshu.io/upload_images/4618424-4a93f5645b5046e9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 18 | 19 | ![image.png](http://upload-images.jianshu.io/upload_images/4618424-90dcb21ff3dd7a7b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 20 | 21 | ![image.png](http://upload-images.jianshu.io/upload_images/4618424-47fb284474252b4f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 22 | 23 | ![image.png](http://upload-images.jianshu.io/upload_images/4618424-e54a4e679f340fcd.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 24 | 25 | ![image.png](http://upload-images.jianshu.io/upload_images/4618424-ad3690cd09215f88.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 26 | 27 | ![image.png](http://upload-images.jianshu.io/upload_images/4618424-4a32f5a9660e143b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 28 | 29 | ![image.png](http://upload-images.jianshu.io/upload_images/4618424-e810593680f35f3a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 30 | 31 | ![image.png](http://upload-images.jianshu.io/upload_images/4618424-93fffada1d02c1fa.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 32 | 33 | ![image.png](http://upload-images.jianshu.io/upload_images/4618424-60797c548e39ae84.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 34 | 35 | ![image.png](http://upload-images.jianshu.io/upload_images/4618424-464e7c63af4d87f0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 36 | 37 | ![image.png](http://upload-images.jianshu.io/upload_images/4618424-d587460b28e7f356.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 38 | 39 | 40 | 推荐阅读: 41 | 42 | 1. [MachineLN之三要素](http://mp.weixin.qq.com/s?__biz=MzU3MTM3MTIxOQ==&mid=2247483841&idx=2&sn=e4a3cff7b12c48af237c577c487ba3a1&chksm=fce07a7dcb97f36be5003c3018b3a391070bdc4e56839cb461d226113db4c5f24032e0bf5809&scene=21#wechat_redirect) 43 | 44 | 2. [MachineLN之模型评估](http://mp.weixin.qq.com/s?__biz=MzU3MTM3MTIxOQ==&mid=2247483872&idx=2&sn=8436e1eb9055d3a372278ee8688cd703&chksm=fce07a5ccb97f34a4490f60304b206c741d2395149c2c2e68bddb3faf7daf9121ca27a5d6a97&scene=21#wechat_redirect) 45 | 46 | 3. [MachinLN之dl](http://mp.weixin.qq.com/s?__biz=MzU3MTM3MTIxOQ==&mid=2247483894&idx=2&sn=63333c02674e15e84159e064073fe563&chksm=fce07a4acb97f35cc38f75dc891a19129e2406270d04b739cfa9b8a28f9780b4e2a65a7cd39b&scene=21#wechat_redirect) 47 | 48 | 4. [DeepLN之CNN解析](http://mp.weixin.qq.com/s?__biz=MzU3MTM3MTIxOQ==&mid=2247483906&idx=1&sn=2eceda7d9703d5315638739e04d5b6e7&chksm=fce079becb97f0a8b8dd2e34a9e757f23757cf2699c397707bfaa677c9f8204c91508840d8f7&scene=21#wechat_redirect) 49 | 50 | [5\. DeepLN之手撕CNN权值更新(笔记)](http://mp.weixin.qq.com/s?__biz=MzU3MTM3MTIxOQ==&mid=2247483927&idx=1&sn=132b90eb009022d2d792303e6d824df7&chksm=fce079abcb97f0bd9b893889a7c8232c0254e447277b930ab8e35ea1f9c49e57c0fc66bab239&scene=21#wechat_redirect) 51 | 52 | ![image.png](http://upload-images.jianshu.io/upload_images/4618424-35eca4d01471376b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 53 | 54 | 55 | 版权声明:本文为博主原创文章,未经博主允许不得转载。有问题可以加微信:lp9628(注明CSDN)。 56 | -------------------------------------------------------------------------------- /MachinLN/机器学习-007:MachineLN之激活函数.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 很长一段时间都在想,有些问题不去弄明白为什么,遇到瓶颈就傻逼了,一个bug整你一个月,原来只是一个细节问题,就好如:你不知道从哪里来? 又怎么知道往哪里去? 现在遗留的小问题,将来都会是大问题! 4 | 5 | 真的,有时候需要回过头来重新开始,整理总结再去前行,也许会走的更远。 6 | 7 | 那么我的问题是: 8 | 9 | (1)什么是激活函数? 10 | 11 | (2)激活函数的作用是什么? 12 | 13 | (3)激活函数有哪些? 14 | 15 | (4)各自的优缺点是什么?(解答完1、2、3,就有了答案了) 16 | 17 | 看到这里,你的答案是什么? 下面是我的答案: 18 | 19 | (1)什么是激活函数? 20 | 21 | 激活函数就是加在在神经元后的函数,下图所示(例如我们前边提到的在cnn卷积候连接的函数relu,还有Sigmoid、tanh、prelu等等),那么它有什么用呢?不加会怎么样?(2)中回答; 22 | 23 | ![image.png](http://upload-images.jianshu.io/upload_images/4618424-e5e308aaded8c071.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 24 | 25 | 26 | 当然你也最好了解下面概念,到提起梯度消失就容易理解了,正是因为这么饱和把梯度会传的时候越来越小,使得更新参数失败,整个网络瘫痪: 27 | 28 | ![image.png](http://upload-images.jianshu.io/upload_images/4618424-1b73e1f039dd7ebe.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 29 | 30 | 31 | (2)激活函数的作用是什么? 32 | 33 | 简单说:为了解决非线性问题,不加激活函数只能处理线性问题。 34 | 35 | 下面图来自公众号忆臻笔记,一个用心在做的公众号。 36 | 37 | 先来看一个图:左侧的网络对应其下方的数学表达式,是一个线性方程(如果这里你还问为什么,那么see you),令其为0,可以画出一条直线,就是右侧的图了,右上方就是y>0的区域,左下方就是y<0的区域,对吧? 那么它是线性的。 38 | 39 | ![image.png](http://upload-images.jianshu.io/upload_images/4618424-8013f4f9543424ca.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 40 | 41 | 42 | 那么你再看下面这个图:网络结构用右侧的表达式表示。 43 | 44 | ![image](http://upload-images.jianshu.io/upload_images/4618424-17dcf6f042d1e57d?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 45 | 46 | 你可以将右侧的表达式整理一下,其实它是这样的,你会发现原来是它也是线性的。 47 | 48 | ![image.png](http://upload-images.jianshu.io/upload_images/4618424-3fb20633a3b37718.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 49 | 50 | 51 | 对,你想的没错,没有激活函数的网络只能处理线性问题(佩服大牛!),在看下面的图,在神经元后加上激活函数,至少可以保证输出是非线性的,那么能解决非线性问题吗?再往下走。 52 | 53 | ![image.png](http://upload-images.jianshu.io/upload_images/4618424-8dec9077d08dfab0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 54 | 55 | 然后看下图,多个神经元的情况: 56 | 57 | ![image.png](http://upload-images.jianshu.io/upload_images/4618424-eb43d05735772411.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 58 | 59 | 60 | 在看一下大神的图: 61 | 62 | ![image.png](http://upload-images.jianshu.io/upload_images/4618424-c4748d4ad624a9b7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 63 | 64 | 65 | 是的通过加上激活函数就可以解决这种非线性问题; 66 | 67 | ![image.png](http://upload-images.jianshu.io/upload_images/4618424-e4f8c72a289afcd4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 68 | 69 | 70 | (3)激活函数有哪些? 71 | 72 | 详细介绍一个sigmod的激活函数:![image.png](http://upload-images.jianshu.io/upload_images/4618424-9372232da6705810.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 73 | 74 | 75 | 左侧是sigmoid函数图,右侧是sigmoid导数的函数图,由[DeepLN之CNN权重更新](http://mp.weixin.qq.com/s?__biz=MzU3MTM3MTIxOQ==&mid=2247483927&idx=1&sn=132b90eb009022d2d792303e6d824df7&chksm=fce079abcb97f0bd9b893889a7c8232c0254e447277b930ab8e35ea1f9c49e57c0fc66bab239&scene=21#wechat_redirect)中的公式5,可知在梯度回传过程中激活函数的影响梯度的问题,当数据落在sigmoid导数的红色区域时就会造成梯度很小,甚至梯度消失;这个问题可以通过改善激活函数来改善,当然也可以通过改变激活函数的输入x来改善,怎么改善?把x重新拉回到0附近不就ok了吗!那么你想到了什么?BN啊!!!那么你还有什么方法?修改激活函数啊,说过了,还有什么?resdual啊!!!对吗?哦,那么还可以有什么?当然真实使用的时候都是一起使用的,例如resdual+bn+relu等(当然bn还有其他作用,这只是其一)。 76 | 77 | ![image](http://upload-images.jianshu.io/upload_images/4618424-16848a7aa66d378b?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 78 | 79 | ![image](http://upload-images.jianshu.io/upload_images/4618424-3f72c649b2acde00?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 80 | 81 | 激活函数还有**tanh函数、**ReLU函数、**ELU函数、PReLU函数等,为什么提取出来? 解决什么问题? 上面提到的左饱和、右饱和或者称为单侧抑制,对你理解这么激活函数有什么帮助?** 82 | 83 | 展望,接下来更新: 84 | 85 | DeepLN之BN; 86 | 87 | MachineLN之过拟合; 88 | 89 | MachineLN之数据归一化; 90 | 91 | DeepLN之优化(sgd等): 92 | 93 | ... 94 | 95 | 感觉这些是在一起的,之后补习传统机器学习的理论知识 到 实践; 96 | 97 | 还有之前提到的; 98 | 99 | 推荐阅读: 100 | 101 | 1. [MachineLN之三要素](http://mp.weixin.qq.com/s?__biz=MzU3MTM3MTIxOQ==&mid=2247483841&idx=2&sn=e4a3cff7b12c48af237c577c487ba3a1&chksm=fce07a7dcb97f36be5003c3018b3a391070bdc4e56839cb461d226113db4c5f24032e0bf5809&scene=21#wechat_redirect) 102 | 103 | 2. [MachineLN之模型评估](http://mp.weixin.qq.com/s?__biz=MzU3MTM3MTIxOQ==&mid=2247483872&idx=2&sn=8436e1eb9055d3a372278ee8688cd703&chksm=fce07a5ccb97f34a4490f60304b206c741d2395149c2c2e68bddb3faf7daf9121ca27a5d6a97&scene=21#wechat_redirect) 104 | 105 | 3. [MachinLN之dl](http://mp.weixin.qq.com/s?__biz=MzU3MTM3MTIxOQ==&mid=2247483894&idx=2&sn=63333c02674e15e84159e064073fe563&chksm=fce07a4acb97f35cc38f75dc891a19129e2406270d04b739cfa9b8a28f9780b4e2a65a7cd39b&scene=21#wechat_redirect) 106 | 107 | 4. [DeepLN之CNN解析](http://mp.weixin.qq.com/s?__biz=MzU3MTM3MTIxOQ==&mid=2247483906&idx=1&sn=2eceda7d9703d5315638739e04d5b6e7&chksm=fce079becb97f0a8b8dd2e34a9e757f23757cf2699c397707bfaa677c9f8204c91508840d8f7&scene=21#wechat_redirect) 108 | 109 | [5\. DeepLN之手撕CNN权值更新(笔记)](http://mp.weixin.qq.com/s?__biz=MzU3MTM3MTIxOQ==&mid=2247483927&idx=1&sn=132b90eb009022d2d792303e6d824df7&chksm=fce079abcb97f0bd9b893889a7c8232c0254e447277b930ab8e35ea1f9c49e57c0fc66bab239&scene=21#wechat_redirect) 110 | 111 | 6. [DeepLN之CNN源码](http://mp.weixin.qq.com/s?__biz=MzU3MTM3MTIxOQ==&mid=2247483948&idx=1&sn=d1edce6e99dac0437797404d15714876&chksm=fce07990cb97f086f2f24ec8b40bb64b588ce657e6ae8d352d4d20e856b5f0e126eaffc5ec99&scene=21#wechat_redirect) 112 | 113 | ![image](http://upload-images.jianshu.io/upload_images/4618424-3e8d004c8823f126?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 114 | 115 | 116 | 117 | 版权声明:本文为博主原创文章,未经博主允许不得转载。有问题可以加微信:lp9628(注明CSDN)。 118 | -------------------------------------------------------------------------------- /MachinLN/机器学习-016:MachineLN之感知机源码.md: -------------------------------------------------------------------------------- 1 | 2 | 我想说: 3 | 4 | 其实很多东西还是要靠自己,靠自己去完成最大的一点就是远离舒适区,试想一下自己每时每刻都要为下一顿能不能吃上饭而奋斗,是一种什么样的体验,估计你连想都不敢想;最近又听到说下岗的问题,有一个人说他除了收钱什么都不会,有时候也要多培养点自己的能力,做好一项,其他的也了解(当然也不了太多),多给自己备好能力,远离舒适区,但无论在哪里都有这么一批人,那你考虑过没有公司万一不景气,第一个下岗的会是谁?下岗了又可以迅速跨到别的领域的又是谁?我做不到这一点,但我在加油,要永远记住:公司不养闲人!比你优秀的人比你还努力,你还好意思说你不会?不会可以学啊,不学永远不会,哈哈,言辞过激了吗,也不知道咋地,最近着魔了吧!!! 5 | 6 | 除了宁向东的清华管理学课,又在书单中加了香帅的北大金融学课,我也不是想什么都会,装逼啥滴,我也只是想每周拿出两个小时,学点管理学和金融学的的思维方式而已。 7 | 8 | 下面是加详细注释的感知机代码:又是截图,记住好代码都是敲出来的!下面代码要结合感知机原理来看:[MachineLN之感知机](http://mp.weixin.qq.com/s?__biz=MzU3MTM3MTIxOQ==&mid=2247484156&idx=1&sn=5e3e5baab2701bda0c17ef0edb60bac0&chksm=fce07940cb97f056eae2cd8e52171092e893886d731f6bfaaec685ec67400ec82dd1288a04fa&scene=21#wechat_redirect) 9 | 10 | 但是代码很方便理解,还有图示: 11 | 12 | 1\. 原始形式的感知机算法: 13 | 14 | ![image](http://upload-images.jianshu.io/upload_images/4618424-61fd8bfb209d6a29?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 15 | 16 | ![image](http://upload-images.jianshu.io/upload_images/4618424-e638e559c0cf4bcd?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 17 | 18 | ![image](http://upload-images.jianshu.io/upload_images/4618424-87a7b41bd4aa95d0?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 19 | 20 | ![image](http://upload-images.jianshu.io/upload_images/4618424-469bbfa3386a4b24?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 21 | 22 | ![image](http://upload-images.jianshu.io/upload_images/4618424-2b69de5411a722fe?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 23 | 24 | ![image](http://upload-images.jianshu.io/upload_images/4618424-07bf7640e65ab998?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 25 | 26 | 用来显示样本点 和 分类线: 27 | 28 | ![image](http://upload-images.jianshu.io/upload_images/4618424-2d1d258f55f85cb6?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 29 | 30 | 看一下感知机的分类结果: 31 | 32 | 33 | ![image](http://upload-images.jianshu.io/upload_images/4618424-dce56335661c9cfd?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 34 | 35 | * * * 36 | 37 | 2\. 对偶形式的感知机算法 (对偶形式要计算gram矩阵) 38 | 39 | ![image](http://upload-images.jianshu.io/upload_images/4618424-509d7fea59dcb821?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 40 | 41 | 原理跟上面原始感知机对偶算法差不多,所以只加了简单注释: 42 | 43 | ![image](http://upload-images.jianshu.io/upload_images/4618424-d5acdbdd1eae2487?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 44 | 45 | ![image](http://upload-images.jianshu.io/upload_images/4618424-e8b5f6554951718e?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 46 | 47 | 推荐阅读: 48 | 49 | 1. [机器学习-1:MachineLN之三要素](http://blog.csdn.net/u014365862/article/details/78955063) 50 | 51 | 2. [机器学习-2:MachineLN之模型评估](http://blog.csdn.net/u014365862/article/details/78959353) 52 | 53 | 3. [机器学习-3:MachineLN之dl](http://blog.csdn.net/u014365862/article/details/78980142) 54 | 55 | 4. [机器学习-4:DeepLN之CNN解析](http://blog.csdn.net/u014365862/article/details/78986089) 56 | 57 | 5. [机器学习-5:DeepLN之CNN权重更新(笔记)](http://blog.csdn.net/u014365862/article/details/78959211) 58 | 59 | 6. [机器学习-6:DeepLN之CNN源码](http://blog.csdn.net/u014365862/article/details/79010248) 60 | 61 | 7. [机器学习-7:MachineLN之激活函数](http://blog.csdn.net/u014365862/article/details/79007801) 62 | 63 | 8. [机器学习-8:DeepLN之BN](http://blog.csdn.net/u014365862/article/details/79019518) 64 | 65 | 9. [机器学习-9:MachineLN之数据归一化](http://blog.csdn.net/u014365862/article/details/79031089) 66 | 67 | 10. [机器学习-10:MachineLN之样本不均衡](http://blog.csdn.net/u014365862/article/details/79040390) 68 | 69 | 11. [机器学习-11:MachineLN之过拟合](http://blog.csdn.net/u014365862/article/details/79057073) 70 | 71 | 12. [机器学习-12:MachineLN之优化算法](http://blog.csdn.net/u014365862/article/details/79070721) 72 | 73 | 13. [机器学习-13:MachineLN之kNN](http://blog.csdn.net/u014365862/article/details/79091913) 74 | 75 | 14. [机器学习-14:MachineLN之kNN源码](http://blog.csdn.net/u014365862/article/details/79101209) 76 | 77 | 15. [](http://mp.blog.csdn.net/postedit/79135612)[机器学习-15:MachineLN之感知机](http://blog.csdn.net/u014365862/article/details/79135612) 78 | 79 | 16. [机器学习-16:MachineLN之感知机源码](http://blog.csdn.net/u014365862/article/details/79135767) 80 | 81 | 17. [机器学习-17:MachineLN之逻辑回归](http://blog.csdn.net/u014365862/article/details/79157777) 82 | 83 | 18. [机器学习-18:MachineLN之逻辑回归源码](http://blog.csdn.net/u014365862/article/details/79157841) 84 | 85 | 86 | ![image](http://upload-images.jianshu.io/upload_images/4618424-14fe247ce5f45412?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 87 | 88 | 版权声明:本文为博主原创文章,未经博主允许不得转载。有问题可以加微信:lp9628(注明CSDN)。 89 | -------------------------------------------------------------------------------- /MachinLN/机器学习-017:MachineLN之逻辑回归.md: -------------------------------------------------------------------------------- 1 | 2 | 我想说: 3 | 4 | 其实....整天其实,感觉没啥好说的了,好好GAN吧。 5 | 6 | 逻辑回归可以这样理解: 和感知机比较着来看或许更好,将感知机的表达式中的sign函数换成sigmoid就是逻辑回归的表达式,但是这一换不要紧,导致后边参数更新的方式完全不同,因为逻辑回顾的损失函数是参数连续可导的,还记得我们说过感知机的损失函数是参数连续不可导的吗? :[MachineLN之感知机](http://mp.weixin.qq.com/s?__biz=MzU3MTM3MTIxOQ==&mid=2247484156&idx=1&sn=5e3e5baab2701bda0c17ef0edb60bac0&chksm=fce07940cb97f056eae2cd8e52171092e893886d731f6bfaaec685ec67400ec82dd1288a04fa&scene=21#wechat_redirect) 7 | 8 | 还是一如既往: 9 | 10 | 说起逻辑回归,那么我的问题:(根据[MachineLN之三要素](http://mp.weixin.qq.com/s?__biz=MzU3MTM3MTIxOQ==&mid=2247483841&idx=2&sn=e4a3cff7b12c48af237c577c487ba3a1&chksm=fce07a7dcb97f36be5003c3018b3a391070bdc4e56839cb461d226113db4c5f24032e0bf5809&scene=21#wechat_redirect):模型、策略、算法) 11 | 12 | (1)什么是逻辑回归?(模型) 13 | 14 | (2)逻辑回归是如何学习的?(策略) 15 | 16 | (3)逻辑回归学习算法?(算法) 17 | 18 | 看到这里你的答案是什么?下面是我的答案: 19 | 20 | 1\. 什么是逻辑回归? 21 | 22 | 前面有提到,逻辑回归是来解决分类问题的,而不是回归问题,想想问什么呢?就是因为sigmoid。说起sigmoid应该很熟悉吧:[MachineLN之激活函数](http://mp.weixin.qq.com/s?__biz=MzU3MTM3MTIxOQ==&mid=2247483968&idx=1&sn=dc2e52c68cd8ea9037b114625c9b1a33&chksm=fce079fccb97f0ea4f3b8f8c74cb779613e06c54a718378c9d174651c16cabb28a1c283b9083&scene=21#wechat_redirect) 23 | 24 | 直接看一下二项逻辑回归表达式吧:可以理解为事件发生的概率和事件不发生的概率: 25 | 26 | ![image](http://upload-images.jianshu.io/upload_images/4618424-dc1f60f7bb7fa6ac?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 27 | 28 | 2. 逻辑回归是如何学习的? 29 | 30 | 逻辑回归可以通过极大似然估计(什么是极大似然估计,简单说利用已知的样本结果,反推有可能(最大概率)导致这样结果的参数值(模型已知,参数未知))来估计模型参数: 31 | 32 | 设: 33 | 34 | ![image](http://upload-images.jianshu.io/upload_images/4618424-d8e870e9e7ce4a6d?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 35 | 36 | 那么似然函数可表示为: 37 | 38 | ![image](http://upload-images.jianshu.io/upload_images/4618424-d98019b34167e75c?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 39 | 40 | 为了后面求导,这里取对数似然函数: 41 | 42 | 那么对数似然函数,也就是损失函数为: 43 | 44 | ![image](http://upload-images.jianshu.io/upload_images/4618424-8791408dcc55ac7b?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 45 | 46 | 接下来我们要求其最大值,其最大值的要用梯度上升法,如果想用梯度下降只需要加一个负号,利用梯度下降法求最小值。 47 | 48 | (3)逻辑回归学习算法? 49 | 50 | 还是用手撕一下吧: 51 | 52 | ![image](http://upload-images.jianshu.io/upload_images/4618424-54967a3d5f4f441d?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 53 | 54 | 下一节的源代码解析你会看到就是按照这个更新公式来做的,但是加了一些优化。 55 | 56 | 另外可以考虑一下:逻辑回归和softmax回归的关系? 多项逻辑回归是softmax吗? 答案是肯定的! 57 | 58 | 看下面逻辑回归表达式: 59 | 60 | ![image](http://upload-images.jianshu.io/upload_images/4618424-58200d8f6a2e2f3c?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 61 | 62 | 在看softmax表达式: 63 | 64 | ![image](http://upload-images.jianshu.io/upload_images/4618424-8c501f3b1d7a5cb9?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 65 | 66 | 有人说,啊,完全不一样,不要急化简一下看看: 67 | 68 | ![image](http://upload-images.jianshu.io/upload_images/4618424-973bd2a0b3da9856?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 69 | 70 | 推荐阅读: 71 | 72 | 1. [机器学习-1:MachineLN之三要素](http://blog.csdn.net/u014365862/article/details/78955063) 73 | 74 | 2. [机器学习-2:MachineLN之模型评估](http://blog.csdn.net/u014365862/article/details/78959353) 75 | 76 | 3. [机器学习-3:MachineLN之dl](http://blog.csdn.net/u014365862/article/details/78980142) 77 | 78 | 4. [机器学习-4:DeepLN之CNN解析](http://blog.csdn.net/u014365862/article/details/78986089) 79 | 80 | 5. [机器学习-5:DeepLN之CNN权重更新(笔记)](http://blog.csdn.net/u014365862/article/details/78959211) 81 | 82 | 6. [机器学习-6:DeepLN之CNN源码](http://blog.csdn.net/u014365862/article/details/79010248) 83 | 84 | 7. [机器学习-7:MachineLN之激活函数](http://blog.csdn.net/u014365862/article/details/79007801) 85 | 86 | 8. [机器学习-8:DeepLN之BN](http://blog.csdn.net/u014365862/article/details/79019518) 87 | 88 | 9. [机器学习-9:MachineLN之数据归一化](http://blog.csdn.net/u014365862/article/details/79031089) 89 | 90 | 10. [机器学习-10:MachineLN之样本不均衡](http://blog.csdn.net/u014365862/article/details/79040390) 91 | 92 | 11. [机器学习-11:MachineLN之过拟合](http://blog.csdn.net/u014365862/article/details/79057073) 93 | 94 | 12. [机器学习-12:MachineLN之优化算法](http://blog.csdn.net/u014365862/article/details/79070721) 95 | 96 | 13. [机器学习-13:MachineLN之kNN](http://blog.csdn.net/u014365862/article/details/79091913) 97 | 98 | 14. [机器学习-14:MachineLN之kNN源码](http://blog.csdn.net/u014365862/article/details/79101209) 99 | 100 | 15. [](http://mp.blog.csdn.net/postedit/79135612)[机器学习-15:MachineLN之感知机](http://blog.csdn.net/u014365862/article/details/79135612) 101 | 102 | 16. [机器学习-16:MachineLN之感知机源码](http://blog.csdn.net/u014365862/article/details/79135767) 103 | 104 | 17. [机器学习-17:MachineLN之逻辑回归](http://blog.csdn.net/u014365862/article/details/79157777) 105 | 106 | 18. [机器学习-18:MachineLN之逻辑回归源码](http://blog.csdn.net/u014365862/article/details/79157841) 107 | 108 | ![image](http://upload-images.jianshu.io/upload_images/4618424-1919cd11bc3dbb8f?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 109 | 110 | 111 | 版权声明:本文为博主原创文章,未经博主允许不得转载。有问题可以加微信:lp9628(注明CSDN)。 112 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Tensorflow- 2 | - [Tensorflow实战学习笔记](./tensorflow_in_action) 3 | - [机器学习进阶系列](./MachinLN) 4 | - [tensorflow实战代码](./Tensorflow) 5 | - [人脸检测系列](./face_detection) 6 | - [tensorflow api解读](./tf-API) 7 | - [机器学习实战代码注释](./ml_in_action) 8 | - [tensorflow2_tutorials_chinese](https://github.com/czy36mengfei/tensorflow2_tutorials_chinese) 9 | 10 | -------------------------------------------------------------------------------- /TensorFlow-Tutorials/00_multiply.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": { 7 | "collapsed": true 8 | }, 9 | "outputs": [], 10 | "source": [ 11 | "import tensorflow as tf" 12 | ] 13 | }, 14 | { 15 | "cell_type": "code", 16 | "execution_count": 2, 17 | "metadata": { 18 | "collapsed": true 19 | }, 20 | "outputs": [], 21 | "source": [ 22 | "a = tf.placeholder(\"float\") # Create a symbolic variable 'a'\n", 23 | "b = tf.placeholder(\"float\") # Create a symbolic variable 'b'\n", 24 | "\n", 25 | "y = tf.multiply(a, b) # multiply the symbolic variables" 26 | ] 27 | }, 28 | { 29 | "cell_type": "code", 30 | "execution_count": 3, 31 | "metadata": { 32 | "collapsed": false 33 | }, 34 | "outputs": [ 35 | { 36 | "name": "stdout", 37 | "output_type": "stream", 38 | "text": [ 39 | "2.000000 should equal 2.0\n", 40 | "9.000000 should equal 9.0\n" 41 | ] 42 | } 43 | ], 44 | "source": [ 45 | "with tf.Session() as sess: # create a session to evaluate the symbolic expressions\n", 46 | " print(\"%f should equal 2.0\" % sess.run(y, feed_dict={a: 1, b: 2})) # eval expressions with parameters for a and b\n", 47 | " print(\"%f should equal 9.0\" % sess.run(y, feed_dict={a: 3, b: 3}))" 48 | ] 49 | } 50 | ], 51 | "metadata": { 52 | "kernelspec": { 53 | "display_name": "Python 2", 54 | "language": "python", 55 | "name": "python2" 56 | }, 57 | "language_info": { 58 | "codemirror_mode": { 59 | "name": "ipython", 60 | "version": 2 61 | }, 62 | "file_extension": ".py", 63 | "mimetype": "text/x-python", 64 | "name": "python", 65 | "nbconvert_exporter": "python", 66 | "pygments_lexer": "ipython2", 67 | "version": "2.7.6" 68 | } 69 | }, 70 | "nbformat": 4, 71 | "nbformat_minor": 1 72 | } 73 | -------------------------------------------------------------------------------- /TensorFlow-Tutorials/00_multiply.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import tensorflow as tf 4 | 5 | a = tf.placeholder("float") # Create a symbolic variable 'a' 6 | b = tf.placeholder("float") # Create a symbolic variable 'b' 7 | 8 | y = tf.multiply(a, b) # multiply the symbolic variables 9 | 10 | with tf.Session() as sess: # create a session to evaluate the symbolic expressions 11 | print("%f should equal 2.0" % sess.run(y, feed_dict={a: 1, b: 2})) # eval expressions with parameters for a and b 12 | print("%f should equal 9.0" % sess.run(y, feed_dict={a: 3, b: 3})) 13 | -------------------------------------------------------------------------------- /TensorFlow-Tutorials/01_linear_regression.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": { 7 | "collapsed": false 8 | }, 9 | "outputs": [], 10 | "source": [ 11 | "import tensorflow as tf\n", 12 | "import numpy as np" 13 | ] 14 | }, 15 | { 16 | "cell_type": "code", 17 | "execution_count": 2, 18 | "metadata": { 19 | "collapsed": true 20 | }, 21 | "outputs": [], 22 | "source": [ 23 | "trX = np.linspace(-1, 1, 101)\n", 24 | "trY = 2 * trX + np.random.randn(*trX.shape) * 0.33 # create a y value which is approximately linear but with some random noise" 25 | ] 26 | }, 27 | { 28 | "cell_type": "code", 29 | "execution_count": 3, 30 | "metadata": { 31 | "collapsed": true 32 | }, 33 | "outputs": [], 34 | "source": [ 35 | "X = tf.placeholder(\"float\") # create symbolic variables\n", 36 | "Y = tf.placeholder(\"float\")\n", 37 | "\n", 38 | "def model(X, w):\n", 39 | " return tf.multiply(X, w) # lr is just X*w so this model line is pretty simple\n", 40 | "\n", 41 | "w = tf.Variable(0.0, name=\"weights\") # create a shared variable (like theano.shared) for the weight matrix\n", 42 | "y_model = model(X, w)\n", 43 | "\n", 44 | "cost = tf.square(Y - y_model) # use square error for cost function\n", 45 | "\n", 46 | "train_op = tf.train.GradientDescentOptimizer(0.01).minimize(cost) # construct an optimizer to minimize cost and fit line to my data" 47 | ] 48 | }, 49 | { 50 | "cell_type": "code", 51 | "execution_count": 5, 52 | "metadata": { 53 | "collapsed": false 54 | }, 55 | "outputs": [ 56 | { 57 | "name": "stdout", 58 | "output_type": "stream", 59 | "text": [ 60 | "2.00863\n" 61 | ] 62 | } 63 | ], 64 | "source": [ 65 | "# Launch the graph in a session\n", 66 | "with tf.Session() as sess:\n", 67 | " # you need to initialize variables (in this case just variable W)\n", 68 | " tf.global_variables_initializer().run()\n", 69 | "\n", 70 | " for i in range(100):\n", 71 | " for (x, y) in zip(trX, trY):\n", 72 | " sess.run(train_op, feed_dict={X: x, Y: y})\n", 73 | "\n", 74 | " print(sess.run(w)) # It should be something around 2" 75 | ] 76 | }, 77 | { 78 | "cell_type": "code", 79 | "execution_count": null, 80 | "metadata": { 81 | "collapsed": true 82 | }, 83 | "outputs": [], 84 | "source": [] 85 | } 86 | ], 87 | "metadata": { 88 | "kernelspec": { 89 | "display_name": "Python 2", 90 | "language": "python", 91 | "name": "python2" 92 | }, 93 | "language_info": { 94 | "codemirror_mode": { 95 | "name": "ipython", 96 | "version": 2 97 | }, 98 | "file_extension": ".py", 99 | "mimetype": "text/x-python", 100 | "name": "python", 101 | "nbconvert_exporter": "python", 102 | "pygments_lexer": "ipython2", 103 | "version": "2.7.13" 104 | } 105 | }, 106 | "nbformat": 4, 107 | "nbformat_minor": 0 108 | } 109 | -------------------------------------------------------------------------------- /TensorFlow-Tutorials/01_linear_regression.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import tensorflow as tf 4 | import numpy as np 5 | 6 | trX = np.linspace(-1, 1, 101) 7 | trY = 2 * trX + np.random.randn(*trX.shape) * 0.33 # create a y value which is approximately linear but with some random noise 8 | 9 | X = tf.placeholder("float") # create symbolic variables 10 | Y = tf.placeholder("float") 11 | 12 | 13 | def model(X, w): 14 | return tf.multiply(X, w) # lr is just X*w so this model line is pretty simple 15 | 16 | 17 | w = tf.Variable(0.0, name="weights") # create a shared variable (like theano.shared) for the weight matrix 18 | y_model = model(X, w) 19 | 20 | cost = tf.square(Y - y_model) # use square error for cost function 21 | 22 | train_op = tf.train.GradientDescentOptimizer(0.01).minimize(cost) # construct an optimizer to minimize cost and fit line to my data 23 | 24 | # Launch the graph in a session 25 | with tf.Session() as sess: 26 | # you need to initialize variables (in this case just variable W) 27 | tf.global_variables_initializer().run() 28 | 29 | for i in range(100): 30 | for (x, y) in zip(trX, trY): 31 | sess.run(train_op, feed_dict={X: x, Y: y}) 32 | 33 | print(sess.run(w)) # It should be something around 2 34 | -------------------------------------------------------------------------------- /TensorFlow-Tutorials/02_logistic_regression.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": { 7 | "collapsed": true 8 | }, 9 | "outputs": [], 10 | "source": [ 11 | "import tensorflow as tf\n", 12 | "import numpy as np\n", 13 | "from tensorflow.examples.tutorials.mnist import input_data" 14 | ] 15 | }, 16 | { 17 | "cell_type": "code", 18 | "execution_count": null, 19 | "metadata": { 20 | "collapsed": false 21 | }, 22 | "outputs": [], 23 | "source": [ 24 | "def init_weights(shape):\n", 25 | " return tf.Variable(tf.random_normal(shape, stddev=0.01))\n", 26 | "\n", 27 | "def model(X, w):\n", 28 | " return tf.matmul(X, w) # notice we use the same model as linear regression, this is because there is a baked in cost function which performs softmax and cross entropy\n", 29 | "\n", 30 | "mnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n", 31 | "trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels" 32 | ] 33 | }, 34 | { 35 | "cell_type": "code", 36 | "execution_count": 3, 37 | "metadata": { 38 | "collapsed": false 39 | }, 40 | "outputs": [], 41 | "source": [ 42 | "X = tf.placeholder(\"float\", [None, 784]) # create symbolic variables\n", 43 | "Y = tf.placeholder(\"float\", [None, 10])\n", 44 | "\n", 45 | "w = init_weights([784, 10]) # like in linear regression, we need a shared variable weight matrix for logistic regression\n", 46 | "\n", 47 | "py_x = model(X, w)\n", 48 | "\n", 49 | "cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=py_x, labels=Y)) # compute mean cross entropy (softmax is applied internally)\n", 50 | "train_op = tf.train.GradientDescentOptimizer(0.05).minimize(cost) # construct optimizer\n", 51 | "predict_op = tf.argmax(py_x, 1) # at predict time, evaluate the argmax of the logistic regression" 52 | ] 53 | }, 54 | { 55 | "cell_type": "code", 56 | "execution_count": null, 57 | "metadata": { 58 | "collapsed": false 59 | }, 60 | "outputs": [], 61 | "source": [ 62 | "# Launch the graph in a session\n", 63 | "with tf.Session() as sess:\n", 64 | " # you need to initialize all variables\n", 65 | " tf.global_variables_initializer().run()\n", 66 | "\n", 67 | " for i in range(100):\n", 68 | " for start, end in zip(range(0, len(trX), 128), range(128, len(trX)+1, 128)):\n", 69 | " sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end]})\n", 70 | " print(i, np.mean(np.argmax(teY, axis=1) ==\n", 71 | " sess.run(predict_op, feed_dict={X: teX})))" 72 | ] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "execution_count": null, 77 | "metadata": { 78 | "collapsed": true 79 | }, 80 | "outputs": [], 81 | "source": [] 82 | } 83 | ], 84 | "metadata": { 85 | "kernelspec": { 86 | "display_name": "Python 2", 87 | "language": "python", 88 | "name": "python2" 89 | }, 90 | "language_info": { 91 | "codemirror_mode": { 92 | "name": "ipython", 93 | "version": 2 94 | }, 95 | "file_extension": ".py", 96 | "mimetype": "text/x-python", 97 | "name": "python", 98 | "nbconvert_exporter": "python", 99 | "pygments_lexer": "ipython2", 100 | "version": "2.7.13" 101 | } 102 | }, 103 | "nbformat": 4, 104 | "nbformat_minor": 1 105 | } 106 | -------------------------------------------------------------------------------- /TensorFlow-Tutorials/02_logistic_regression.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import tensorflow as tf 4 | import numpy as np 5 | from tensorflow.examples.tutorials.mnist import input_data 6 | 7 | 8 | def init_weights(shape): 9 | return tf.Variable(tf.random_normal(shape, stddev=0.01)) 10 | 11 | 12 | def model(X, w): 13 | return tf.matmul(X, w) # notice we use the same model as linear regression, this is because there is a baked in cost function which performs softmax and cross entropy 14 | 15 | 16 | mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) 17 | trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels 18 | 19 | X = tf.placeholder("float", [None, 784]) # create symbolic variables 20 | Y = tf.placeholder("float", [None, 10]) 21 | 22 | w = init_weights([784, 10]) # like in linear regression, we need a shared variable weight matrix for logistic regression 23 | 24 | py_x = model(X, w) 25 | 26 | cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=py_x, labels=Y)) # compute mean cross entropy (softmax is applied internally) 27 | train_op = tf.train.GradientDescentOptimizer(0.05).minimize(cost) # construct optimizer 28 | predict_op = tf.argmax(py_x, 1) # at predict time, evaluate the argmax of the logistic regression 29 | 30 | # Launch the graph in a session 31 | with tf.Session() as sess: 32 | # you need to initialize all variables 33 | tf.global_variables_initializer().run() 34 | 35 | for i in range(100): 36 | for start, end in zip(range(0, len(trX), 128), range(128, len(trX)+1, 128)): 37 | sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end]}) 38 | print(i, np.mean(np.argmax(teY, axis=1) == 39 | sess.run(predict_op, feed_dict={X: teX}))) 40 | -------------------------------------------------------------------------------- /TensorFlow-Tutorials/03_net.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": { 7 | "collapsed": true 8 | }, 9 | "outputs": [], 10 | "source": [ 11 | "import tensorflow as tf\n", 12 | "import numpy as np\n", 13 | "from tensorflow.examples.tutorials.mnist import input_data" 14 | ] 15 | }, 16 | { 17 | "cell_type": "code", 18 | "execution_count": null, 19 | "metadata": { 20 | "collapsed": false 21 | }, 22 | "outputs": [], 23 | "source": [ 24 | "def init_weights(shape):\n", 25 | " return tf.Variable(tf.random_normal(shape, stddev=0.01))\n", 26 | "\n", 27 | "def model(X, w_h, w_o):\n", 28 | " h = tf.nn.sigmoid(tf.matmul(X, w_h)) # this is a basic mlp, think 2 stacked logistic regressions\n", 29 | " return tf.matmul(h, w_o) # note that we dont take the softmax at the end because our cost fn does that for us\n", 30 | "\n", 31 | "mnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n", 32 | "trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels" 33 | ] 34 | }, 35 | { 36 | "cell_type": "code", 37 | "execution_count": 5, 38 | "metadata": { 39 | "collapsed": false 40 | }, 41 | "outputs": [], 42 | "source": [ 43 | "X = tf.placeholder(\"float\", [None, 784])\n", 44 | "Y = tf.placeholder(\"float\", [None, 10])\n", 45 | "\n", 46 | "w_h = init_weights([784, 625]) # create symbolic variables\n", 47 | "w_o = init_weights([625, 10])\n", 48 | "\n", 49 | "py_x = model(X, w_h, w_o)\n", 50 | "\n", 51 | "cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=py_x, labels=Y)) # compute costs\n", 52 | "train_op = tf.train.GradientDescentOptimizer(0.05).minimize(cost) # construct an optimizer\n", 53 | "predict_op = tf.argmax(py_x, 1)" 54 | ] 55 | }, 56 | { 57 | "cell_type": "code", 58 | "execution_count": null, 59 | "metadata": { 60 | "collapsed": false 61 | }, 62 | "outputs": [], 63 | "source": [ 64 | "# Launch the graph in a session\n", 65 | "with tf.Session() as sess:\n", 66 | " # you need to initialize all variables\n", 67 | " tf.global_variables_initializer().run()\n", 68 | "\n", 69 | " for i in range(100):\n", 70 | " for start, end in zip(range(0, len(trX), 128), range(128, len(trX)+1, 128)):\n", 71 | " sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end]})\n", 72 | " print(i, np.mean(np.argmax(teY, axis=1) ==\n", 73 | " sess.run(predict_op, feed_dict={X: teX})))" 74 | ] 75 | }, 76 | { 77 | "cell_type": "code", 78 | "execution_count": null, 79 | "metadata": { 80 | "collapsed": true 81 | }, 82 | "outputs": [], 83 | "source": [] 84 | } 85 | ], 86 | "metadata": { 87 | "kernelspec": { 88 | "display_name": "Python 2", 89 | "language": "python", 90 | "name": "python2" 91 | }, 92 | "language_info": { 93 | "codemirror_mode": { 94 | "name": "ipython", 95 | "version": 2 96 | }, 97 | "file_extension": ".py", 98 | "mimetype": "text/x-python", 99 | "name": "python", 100 | "nbconvert_exporter": "python", 101 | "pygments_lexer": "ipython2", 102 | "version": "2.7.13" 103 | } 104 | }, 105 | "nbformat": 4, 106 | "nbformat_minor": 0 107 | } 108 | -------------------------------------------------------------------------------- /TensorFlow-Tutorials/03_net.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import tensorflow as tf 4 | import numpy as np 5 | from tensorflow.examples.tutorials.mnist import input_data 6 | 7 | 8 | def init_weights(shape): 9 | return tf.Variable(tf.random_normal(shape, stddev=0.01)) 10 | 11 | 12 | def model(X, w_h, w_o): 13 | h = tf.nn.sigmoid(tf.matmul(X, w_h)) # this is a basic mlp, think 2 stacked logistic regressions 14 | return tf.matmul(h, w_o) # note that we dont take the softmax at the end because our cost fn does that for us 15 | 16 | 17 | mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) 18 | trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels 19 | 20 | X = tf.placeholder("float", [None, 784]) 21 | Y = tf.placeholder("float", [None, 10]) 22 | 23 | w_h = init_weights([784, 625]) # create symbolic variables 24 | w_o = init_weights([625, 10]) 25 | 26 | py_x = model(X, w_h, w_o) 27 | 28 | cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=py_x, labels=Y)) # compute costs 29 | train_op = tf.train.GradientDescentOptimizer(0.05).minimize(cost) # construct an optimizer 30 | predict_op = tf.argmax(py_x, 1) 31 | 32 | # Launch the graph in a session 33 | with tf.Session() as sess: 34 | # you need to initialize all variables 35 | tf.global_variables_initializer().run() 36 | 37 | for i in range(100): 38 | for start, end in zip(range(0, len(trX), 128), range(128, len(trX)+1, 128)): 39 | sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end]}) 40 | print(i, np.mean(np.argmax(teY, axis=1) == 41 | sess.run(predict_op, feed_dict={X: teX}))) 42 | -------------------------------------------------------------------------------- /TensorFlow-Tutorials/04_modern_net.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": { 7 | "collapsed": true 8 | }, 9 | "outputs": [], 10 | "source": [ 11 | "import tensorflow as tf\n", 12 | "import numpy as np\n", 13 | "from tensorflow.examples.tutorials.mnist import input_data" 14 | ] 15 | }, 16 | { 17 | "cell_type": "code", 18 | "execution_count": null, 19 | "metadata": { 20 | "collapsed": false 21 | }, 22 | "outputs": [], 23 | "source": [ 24 | "def init_weights(shape):\n", 25 | " return tf.Variable(tf.random_normal(shape, stddev=0.01))\n", 26 | "\n", 27 | "def model(X, w_h, w_h2, w_o, p_keep_input, p_keep_hidden): # this network is the same as the previous one except with an extra hidden layer + dropout\n", 28 | " X = tf.nn.dropout(X, p_keep_input)\n", 29 | " h = tf.nn.relu(tf.matmul(X, w_h))\n", 30 | "\n", 31 | " h = tf.nn.dropout(h, p_keep_hidden)\n", 32 | " h2 = tf.nn.relu(tf.matmul(h, w_h2))\n", 33 | "\n", 34 | " h2 = tf.nn.dropout(h2, p_keep_hidden)\n", 35 | "\n", 36 | " return tf.matmul(h2, w_o)\n", 37 | "\n", 38 | "mnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n", 39 | "trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels" 40 | ] 41 | }, 42 | { 43 | "cell_type": "code", 44 | "execution_count": null, 45 | "metadata": { 46 | "collapsed": false 47 | }, 48 | "outputs": [], 49 | "source": [ 50 | "X = tf.placeholder(\"float\", [None, 784])\n", 51 | "Y = tf.placeholder(\"float\", [None, 10])\n", 52 | "\n", 53 | "w_h = init_weights([784, 625])\n", 54 | "w_h2 = init_weights([625, 625])\n", 55 | "w_o = init_weights([625, 10])\n", 56 | "\n", 57 | "p_keep_input = tf.placeholder(\"float\")\n", 58 | "p_keep_hidden = tf.placeholder(\"float\")\n", 59 | "py_x = model(X, w_h, w_h2, w_o, p_keep_input, p_keep_hidden)\n", 60 | "\n", 61 | "cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=py_x, labels=Y))\n", 62 | "train_op = tf.train.RMSPropOptimizer(0.001, 0.9).minimize(cost)\n", 63 | "predict_op = tf.argmax(py_x, 1)" 64 | ] 65 | }, 66 | { 67 | "cell_type": "code", 68 | "execution_count": null, 69 | "metadata": { 70 | "collapsed": false 71 | }, 72 | "outputs": [], 73 | "source": [ 74 | "# Launch the graph in a session\n", 75 | "with tf.Session() as sess:\n", 76 | " # you need to initialize all variables\n", 77 | " tf.global_variables_initializer().run()\n", 78 | "\n", 79 | " for i in range(100):\n", 80 | " for start, end in zip(range(0, len(trX), 128), range(128, len(trX)+1, 128)):\n", 81 | " sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end],\n", 82 | " p_keep_input: 0.8, p_keep_hidden: 0.5})\n", 83 | " print(i, np.mean(np.argmax(teY, axis=1) ==\n", 84 | " sess.run(predict_op, feed_dict={X: teX, Y: teY,\n", 85 | " p_keep_input: 1.0,\n", 86 | " p_keep_hidden: 1.0})))" 87 | ] 88 | }, 89 | { 90 | "cell_type": "code", 91 | "execution_count": null, 92 | "metadata": { 93 | "collapsed": true 94 | }, 95 | "outputs": [], 96 | "source": [] 97 | } 98 | ], 99 | "metadata": { 100 | "kernelspec": { 101 | "display_name": "Python 2", 102 | "language": "python", 103 | "name": "python2" 104 | }, 105 | "language_info": { 106 | "codemirror_mode": { 107 | "name": "ipython", 108 | "version": 2 109 | }, 110 | "file_extension": ".py", 111 | "mimetype": "text/x-python", 112 | "name": "python", 113 | "nbconvert_exporter": "python", 114 | "pygments_lexer": "ipython2", 115 | "version": "2.7.13" 116 | } 117 | }, 118 | "nbformat": 4, 119 | "nbformat_minor": 0 120 | } 121 | -------------------------------------------------------------------------------- /TensorFlow-Tutorials/04_modern_net.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import tensorflow as tf 4 | import numpy as np 5 | from tensorflow.examples.tutorials.mnist import input_data 6 | 7 | 8 | def init_weights(shape): 9 | return tf.Variable(tf.random_normal(shape, stddev=0.01)) 10 | 11 | 12 | def model(X, w_h, w_h2, w_o, p_keep_input, p_keep_hidden): # this network is the same as the previous one except with an extra hidden layer + dropout 13 | X = tf.nn.dropout(X, p_keep_input) 14 | h = tf.nn.relu(tf.matmul(X, w_h)) 15 | 16 | h = tf.nn.dropout(h, p_keep_hidden) 17 | h2 = tf.nn.relu(tf.matmul(h, w_h2)) 18 | 19 | h2 = tf.nn.dropout(h2, p_keep_hidden) 20 | 21 | return tf.matmul(h2, w_o) 22 | 23 | 24 | mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) 25 | trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels 26 | 27 | X = tf.placeholder("float", [None, 784]) 28 | Y = tf.placeholder("float", [None, 10]) 29 | 30 | w_h = init_weights([784, 625]) 31 | w_h2 = init_weights([625, 625]) 32 | w_o = init_weights([625, 10]) 33 | 34 | p_keep_input = tf.placeholder("float") 35 | p_keep_hidden = tf.placeholder("float") 36 | py_x = model(X, w_h, w_h2, w_o, p_keep_input, p_keep_hidden) 37 | 38 | cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=py_x, labels=Y)) 39 | train_op = tf.train.RMSPropOptimizer(0.001, 0.9).minimize(cost) 40 | predict_op = tf.argmax(py_x, 1) 41 | 42 | # Launch the graph in a session 43 | with tf.Session() as sess: 44 | # you need to initialize all variables 45 | tf.global_variables_initializer().run() 46 | 47 | for i in range(100): 48 | for start, end in zip(range(0, len(trX), 128), range(128, len(trX)+1, 128)): 49 | sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end], 50 | p_keep_input: 0.8, p_keep_hidden: 0.5}) 51 | print(i, np.mean(np.argmax(teY, axis=1) == 52 | sess.run(predict_op, feed_dict={X: teX, 53 | p_keep_input: 1.0, 54 | p_keep_hidden: 1.0}))) 55 | -------------------------------------------------------------------------------- /TensorFlow-Tutorials/05_convolutional_net.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import tensorflow as tf 4 | import numpy as np 5 | from tensorflow.examples.tutorials.mnist import input_data 6 | 7 | batch_size = 128 8 | test_size = 256 9 | 10 | def init_weights(shape): 11 | return tf.Variable(tf.random_normal(shape, stddev=0.01)) 12 | 13 | 14 | def model(X, w, w2, w3, w4, w_o, p_keep_conv, p_keep_hidden): 15 | l1a = tf.nn.relu(tf.nn.conv2d(X, w, # l1a shape=(?, 28, 28, 32) 16 | strides=[1, 1, 1, 1], padding='SAME')) 17 | l1 = tf.nn.max_pool(l1a, ksize=[1, 2, 2, 1], # l1 shape=(?, 14, 14, 32) 18 | strides=[1, 2, 2, 1], padding='SAME') 19 | l1 = tf.nn.dropout(l1, p_keep_conv) 20 | 21 | l2a = tf.nn.relu(tf.nn.conv2d(l1, w2, # l2a shape=(?, 14, 14, 64) 22 | strides=[1, 1, 1, 1], padding='SAME')) 23 | l2 = tf.nn.max_pool(l2a, ksize=[1, 2, 2, 1], # l2 shape=(?, 7, 7, 64) 24 | strides=[1, 2, 2, 1], padding='SAME') 25 | l2 = tf.nn.dropout(l2, p_keep_conv) 26 | 27 | l3a = tf.nn.relu(tf.nn.conv2d(l2, w3, # l3a shape=(?, 7, 7, 128) 28 | strides=[1, 1, 1, 1], padding='SAME')) 29 | l3 = tf.nn.max_pool(l3a, ksize=[1, 2, 2, 1], # l3 shape=(?, 4, 4, 128) 30 | strides=[1, 2, 2, 1], padding='SAME') 31 | l3 = tf.reshape(l3, [-1, w4.get_shape().as_list()[0]]) # reshape to (?, 2048) 32 | l3 = tf.nn.dropout(l3, p_keep_conv) 33 | 34 | l4 = tf.nn.relu(tf.matmul(l3, w4)) 35 | l4 = tf.nn.dropout(l4, p_keep_hidden) 36 | 37 | pyx = tf.matmul(l4, w_o) 38 | return pyx 39 | 40 | mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) 41 | trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels 42 | trX = trX.reshape(-1, 28, 28, 1) # 28x28x1 input img 43 | teX = teX.reshape(-1, 28, 28, 1) # 28x28x1 input img 44 | 45 | X = tf.placeholder("float", [None, 28, 28, 1]) 46 | Y = tf.placeholder("float", [None, 10]) 47 | 48 | w = init_weights([3, 3, 1, 32]) # 3x3x1 conv, 32 outputs 49 | w2 = init_weights([3, 3, 32, 64]) # 3x3x32 conv, 64 outputs 50 | w3 = init_weights([3, 3, 64, 128]) # 3x3x32 conv, 128 outputs 51 | w4 = init_weights([128 * 4 * 4, 625]) # FC 128 * 4 * 4 inputs, 625 outputs 52 | w_o = init_weights([625, 10]) # FC 625 inputs, 10 outputs (labels) 53 | 54 | p_keep_conv = tf.placeholder("float") 55 | p_keep_hidden = tf.placeholder("float") 56 | py_x = model(X, w, w2, w3, w4, w_o, p_keep_conv, p_keep_hidden) 57 | 58 | cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=py_x, labels=Y)) 59 | train_op = tf.train.RMSPropOptimizer(0.001, 0.9).minimize(cost) 60 | predict_op = tf.argmax(py_x, 1) 61 | 62 | # Launch the graph in a session 63 | with tf.Session() as sess: 64 | # you need to initialize all variables 65 | tf.global_variables_initializer().run() 66 | 67 | for i in range(100): 68 | training_batch = zip(range(0, len(trX), batch_size), 69 | range(batch_size, len(trX)+1, batch_size)) 70 | for start, end in training_batch: 71 | sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end], 72 | p_keep_conv: 0.8, p_keep_hidden: 0.5}) 73 | 74 | test_indices = np.arange(len(teX)) # Get A Test Batch 75 | np.random.shuffle(test_indices) 76 | test_indices = test_indices[0:test_size] 77 | 78 | print(i, np.mean(np.argmax(teY[test_indices], axis=1) == 79 | sess.run(predict_op, feed_dict={X: teX[test_indices], 80 | p_keep_conv: 1.0, 81 | p_keep_hidden: 1.0}))) 82 | -------------------------------------------------------------------------------- /TensorFlow-Tutorials/06_autoencoder.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | import numpy as np 3 | from tensorflow.examples.tutorials.mnist import input_data 4 | 5 | import matplotlib # to plot images 6 | # Force matplotlib to not use any X-server backend. 7 | matplotlib.use('Agg') 8 | import matplotlib.pyplot as plt 9 | import matplotlib.gridspec as gridspec 10 | 11 | ## Visualizing reconstructions 12 | def vis(images, save_name): 13 | dim = images.shape[0] 14 | n_image_rows = int(np.ceil(np.sqrt(dim))) 15 | n_image_cols = int(np.ceil(dim * 1.0/n_image_rows)) 16 | gs = gridspec.GridSpec(n_image_rows,n_image_cols,top=1., bottom=0., right=1., left=0., hspace=0., wspace=0.) 17 | for g,count in zip(gs,range(int(dim))): 18 | ax = plt.subplot(g) 19 | ax.imshow(images[count,:].reshape((28,28))) 20 | ax.set_xticks([]) 21 | ax.set_yticks([]) 22 | plt.savefig(save_name + '_vis.png') 23 | 24 | mnist_width = 28 25 | n_visible = mnist_width * mnist_width 26 | n_hidden = 500 27 | corruption_level = 0.3 28 | 29 | # create node for input data 30 | X = tf.placeholder("float", [None, n_visible], name='X') 31 | 32 | # create node for corruption mask 33 | mask = tf.placeholder("float", [None, n_visible], name='mask') 34 | 35 | # create nodes for hidden variables 36 | W_init_max = 4 * np.sqrt(6. / (n_visible + n_hidden)) 37 | W_init = tf.random_uniform(shape=[n_visible, n_hidden], 38 | minval=-W_init_max, 39 | maxval=W_init_max) 40 | 41 | W = tf.Variable(W_init, name='W') 42 | b = tf.Variable(tf.zeros([n_hidden]), name='b') 43 | 44 | W_prime = tf.transpose(W) # tied weights between encoder and decoder 45 | b_prime = tf.Variable(tf.zeros([n_visible]), name='b_prime') 46 | 47 | 48 | def model(X, mask, W, b, W_prime, b_prime): 49 | tilde_X = mask * X # corrupted X 50 | 51 | Y = tf.nn.sigmoid(tf.matmul(tilde_X, W) + b) # hidden state 52 | Z = tf.nn.sigmoid(tf.matmul(Y, W_prime) + b_prime) # reconstructed input 53 | return Z 54 | 55 | # build model graph 56 | Z = model(X, mask, W, b, W_prime, b_prime) 57 | 58 | # create cost function 59 | cost = tf.reduce_sum(tf.pow(X - Z, 2)) # minimize squared error 60 | train_op = tf.train.GradientDescentOptimizer(0.02).minimize(cost) # construct an optimizer 61 | predict_op = Z 62 | # load MNIST data 63 | mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) 64 | trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels 65 | 66 | # Launch the graph in a session 67 | with tf.Session() as sess: 68 | # you need to initialize all variables 69 | tf.global_variables_initializer().run() 70 | 71 | for i in range(100): 72 | for start, end in zip(range(0, len(trX), 128), range(128, len(trX)+1, 128)): 73 | input_ = trX[start:end] 74 | mask_np = np.random.binomial(1, 1 - corruption_level, input_.shape) 75 | sess.run(train_op, feed_dict={X: input_, mask: mask_np}) 76 | 77 | mask_np = np.random.binomial(1, 1 - corruption_level, teX.shape) 78 | print(i, sess.run(cost, feed_dict={X: teX, mask: mask_np})) 79 | # save the predictions for 100 images 80 | mask_np = np.random.binomial(1, 1 - corruption_level, teX[:100].shape) 81 | predicted_imgs = sess.run(predict_op, feed_dict={X: teX[:100], mask: mask_np}) 82 | input_imgs = teX[:100] 83 | # plot the reconstructed images 84 | vis(predicted_imgs,'pred') 85 | vis(input_imgs,'in') 86 | print('Done') -------------------------------------------------------------------------------- /TensorFlow-Tutorials/07_lstm.py: -------------------------------------------------------------------------------- 1 | #Inspired by https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3%20-%20Neural%20Networks/recurrent_network.py 2 | import tensorflow as tf 3 | from tensorflow.contrib import rnn 4 | 5 | import numpy as np 6 | from tensorflow.examples.tutorials.mnist import input_data 7 | 8 | # configuration 9 | # O * W + b -> 10 labels for each image, O[? 28], W[28 10], B[10] 10 | # ^ (O: output 28 vec from 28 vec input) 11 | # | 12 | # +-+ +-+ +--+ 13 | # |1|->|2|-> ... |28| time_step_size = 28 14 | # +-+ +-+ +--+ 15 | # ^ ^ ... ^ 16 | # | | | 17 | # img1:[28] [28] ... [28] 18 | # img2:[28] [28] ... [28] 19 | # img3:[28] [28] ... [28] 20 | # ... 21 | # img128 or img256 (batch_size or test_size 256) 22 | # each input size = input_vec_size=lstm_size=28 23 | 24 | # configuration variables 25 | input_vec_size = lstm_size = 28 26 | time_step_size = 28 27 | 28 | batch_size = 128 29 | test_size = 256 30 | 31 | def init_weights(shape): 32 | return tf.Variable(tf.random_normal(shape, stddev=0.01)) 33 | 34 | 35 | def model(X, W, B, lstm_size): 36 | # X, input shape: (batch_size, time_step_size, input_vec_size) 37 | XT = tf.transpose(X, [1, 0, 2]) # permute time_step_size and batch_size 38 | # XT shape: (time_step_size, batch_size, input_vec_size) 39 | XR = tf.reshape(XT, [-1, lstm_size]) # each row has input for each lstm cell (lstm_size=input_vec_size) 40 | # XR shape: (time_step_size * batch_size, input_vec_size) 41 | X_split = tf.split(XR, time_step_size, 0) # split them to time_step_size (28 arrays) 42 | # Each array shape: (batch_size, input_vec_size) 43 | 44 | # Make lstm with lstm_size (each input vector size) 45 | lstm = rnn.BasicLSTMCell(lstm_size, forget_bias=1.0, state_is_tuple=True) 46 | 47 | # Get lstm cell output, time_step_size (28) arrays with lstm_size output: (batch_size, lstm_size) 48 | outputs, _states = rnn.static_rnn(lstm, X_split, dtype=tf.float32) 49 | 50 | # Linear activation 51 | # Get the last output 52 | return tf.matmul(outputs[-1], W) + B, lstm.state_size # State size to initialize the stat 53 | 54 | mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) 55 | trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels 56 | trX = trX.reshape(-1, 28, 28) 57 | teX = teX.reshape(-1, 28, 28) 58 | 59 | X = tf.placeholder("float", [None, 28, 28]) 60 | Y = tf.placeholder("float", [None, 10]) 61 | 62 | # get lstm_size and output 10 labels 63 | W = init_weights([lstm_size, 10]) 64 | B = init_weights([10]) 65 | 66 | py_x, state_size = model(X, W, B, lstm_size) 67 | 68 | cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=py_x, labels=Y)) 69 | train_op = tf.train.RMSPropOptimizer(0.001, 0.9).minimize(cost) 70 | predict_op = tf.argmax(py_x, 1) 71 | 72 | session_conf = tf.ConfigProto() 73 | session_conf.gpu_options.allow_growth = True 74 | 75 | # Launch the graph in a session 76 | with tf.Session(config=session_conf) as sess: 77 | # you need to initialize all variables 78 | tf.global_variables_initializer().run() 79 | 80 | for i in range(100): 81 | for start, end in zip(range(0, len(trX), batch_size), range(batch_size, len(trX)+1, batch_size)): 82 | sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end]}) 83 | 84 | test_indices = np.arange(len(teX)) # Get A Test Batch 85 | np.random.shuffle(test_indices) 86 | test_indices = test_indices[0:test_size] 87 | 88 | print(i, np.mean(np.argmax(teY[test_indices], axis=1) == 89 | sess.run(predict_op, feed_dict={X: teX[test_indices]}))) 90 | -------------------------------------------------------------------------------- /TensorFlow-Tutorials/08_word2vec.py: -------------------------------------------------------------------------------- 1 | # Inspired by https://www.tensorflow.org/versions/r0.7/tutorials/word2vec/index.html 2 | import collections 3 | import numpy as np 4 | import tensorflow as tf 5 | import matplotlib 6 | matplotlib.use('Agg') 7 | import matplotlib.pyplot as plt 8 | 9 | # Configuration 10 | batch_size = 20 11 | # Dimension of the embedding vector. Two too small to get 12 | # any meaningful embeddings, but let's make it 2 for simple visualization 13 | embedding_size = 2 14 | num_sampled = 15 # Number of negative examples to sample. 15 | 16 | # Sample sentences 17 | sentences = ["the quick brown fox jumped over the lazy dog", 18 | "I love cats and dogs", 19 | "we all love cats and dogs", 20 | "cats and dogs are great", 21 | "sung likes cats", 22 | "she loves dogs", 23 | "cats can be very independent", 24 | "cats are great companions when they want to be", 25 | "cats are playful", 26 | "cats are natural hunters", 27 | "It's raining cats and dogs", 28 | "dogs and cats love sung"] 29 | 30 | # sentences to words and count 31 | words = " ".join(sentences).split() 32 | count = collections.Counter(words).most_common() 33 | print ("Word count", count[:5]) 34 | 35 | # Build dictionaries 36 | rdic = [i[0] for i in count] #reverse dic, idx -> word 37 | dic = {w: i for i, w in enumerate(rdic)} #dic, word -> id 38 | voc_size = len(dic) 39 | 40 | # Make indexed word data 41 | data = [dic[word] for word in words] 42 | print('Sample data', data[:10], [rdic[t] for t in data[:10]]) 43 | 44 | # Let's make a training data for window size 1 for simplicity 45 | # ([the, brown], quick), ([quick, fox], brown), ([brown, jumped], fox), ... 46 | cbow_pairs = []; 47 | for i in range(1, len(data)-1) : 48 | cbow_pairs.append([[data[i-1], data[i+1]], data[i]]); 49 | print('Context pairs', cbow_pairs[:10]) 50 | 51 | # Let's make skip-gram pairs 52 | # (quick, the), (quick, brown), (brown, quick), (brown, fox), ... 53 | skip_gram_pairs = []; 54 | for c in cbow_pairs: 55 | skip_gram_pairs.append([c[1], c[0][0]]) 56 | skip_gram_pairs.append([c[1], c[0][1]]) 57 | print('skip-gram pairs', skip_gram_pairs[:5]) 58 | 59 | def generate_batch(size): 60 | assert size < len(skip_gram_pairs) 61 | x_data=[] 62 | y_data = [] 63 | r = np.random.choice(range(len(skip_gram_pairs)), size, replace=False) 64 | for i in r: 65 | x_data.append(skip_gram_pairs[i][0]) # n dim 66 | y_data.append([skip_gram_pairs[i][1]]) # n, 1 dim 67 | return x_data, y_data 68 | 69 | # generate_batch test 70 | print ('Batches (x, y)', generate_batch(3)) 71 | 72 | # Input data 73 | train_inputs = tf.placeholder(tf.int32, shape=[batch_size]) 74 | # need to shape [batch_size, 1] for nn.nce_loss 75 | train_labels = tf.placeholder(tf.int32, shape=[batch_size, 1]) 76 | # Ops and variables pinned to the CPU because of missing GPU implementation 77 | with tf.device('/cpu:0'): 78 | # Look up embeddings for inputs. 79 | embeddings = tf.Variable( 80 | tf.random_uniform([voc_size, embedding_size], -1.0, 1.0)) 81 | embed = tf.nn.embedding_lookup(embeddings, train_inputs) # lookup table 82 | 83 | # Construct the variables for the NCE loss 84 | nce_weights = tf.Variable( 85 | tf.random_uniform([voc_size, embedding_size],-1.0, 1.0)) 86 | nce_biases = tf.Variable(tf.zeros([voc_size])) 87 | 88 | # Compute the average NCE loss for the batch. 89 | # This does the magic: 90 | # tf.nn.nce_loss(weights, biases, inputs, labels, num_sampled, num_classes ...) 91 | # It automatically draws negative samples when we evaluate the loss. 92 | loss = tf.reduce_mean(tf.nn.nce_loss(nce_weights, nce_biases, train_labels, embed, num_sampled, voc_size)) 93 | 94 | # Use the adam optimizer 95 | train_op = tf.train.AdamOptimizer(1e-1).minimize(loss) 96 | 97 | # Launch the graph in a session 98 | with tf.Session() as sess: 99 | # Initializing all variables 100 | tf.global_variables_initializer().run() 101 | 102 | for step in range(100): 103 | batch_inputs, batch_labels = generate_batch(batch_size) 104 | _, loss_val = sess.run([train_op, loss], 105 | feed_dict={train_inputs: batch_inputs, train_labels: batch_labels}) 106 | if step % 10 == 0: 107 | print("Loss at ", step, loss_val) # Report the loss 108 | 109 | # Final embeddings are ready for you to use. Need to normalize for practical use 110 | trained_embeddings = embeddings.eval() 111 | 112 | # Show word2vec if dim is 2 113 | if trained_embeddings.shape[1] == 2: 114 | labels = rdic[:10] # Show top 10 words 115 | for i, label in enumerate(labels): 116 | x, y = trained_embeddings[i,:] 117 | plt.scatter(x, y) 118 | plt.annotate(label, xy=(x, y), xytext=(5, 2), 119 | textcoords='offset points', ha='right', va='bottom') 120 | plt.savefig("word2vec.png") -------------------------------------------------------------------------------- /TensorFlow-Tutorials/09_tensorboard.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# TensorBoard" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "After Training the model, run \n", 15 | "\n", 16 | " tensorboard --logdir=path/to/log-directory\n", 17 | " \n", 18 | "Tensorboard provides a good visualization tool for all the variables you like and works on a browser." 19 | ] 20 | }, 21 | { 22 | "cell_type": "code", 23 | "execution_count": 1, 24 | "metadata": { 25 | "collapsed": true 26 | }, 27 | "outputs": [], 28 | "source": [ 29 | "import tensorflow as tf\n", 30 | "from tensorflow.examples.tutorials.mnist import input_data" 31 | ] 32 | }, 33 | { 34 | "cell_type": "code", 35 | "execution_count": null, 36 | "metadata": { 37 | "collapsed": false 38 | }, 39 | "outputs": [], 40 | "source": [ 41 | "def init_weights(shape, name):\n", 42 | " return tf.Variable(tf.random_normal(shape, stddev=0.01), name=name)\n", 43 | "\n", 44 | "# This network is the same as the previous one except with an extra hidden layer + dropout\n", 45 | "def model(X, w_h, w_h2, w_o, p_keep_input, p_keep_hidden):\n", 46 | " # Add layer name scopes for better graph visualization\n", 47 | " with tf.name_scope(\"layer1\"):\n", 48 | " X = tf.nn.dropout(X, p_keep_input)\n", 49 | " h = tf.nn.relu(tf.matmul(X, w_h))\n", 50 | " with tf.name_scope(\"layer2\"):\n", 51 | " h = tf.nn.dropout(h, p_keep_hidden)\n", 52 | " h2 = tf.nn.relu(tf.matmul(h, w_h2))\n", 53 | " with tf.name_scope(\"layer3\"):\n", 54 | " h2 = tf.nn.dropout(h2, p_keep_hidden)\n", 55 | " return tf.matmul(h2, w_o)\n", 56 | "\n", 57 | "mnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n", 58 | "trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels" 59 | ] 60 | }, 61 | { 62 | "cell_type": "code", 63 | "execution_count": 4, 64 | "metadata": { 65 | "collapsed": false 66 | }, 67 | "outputs": [], 68 | "source": [ 69 | "X = tf.placeholder(\"float\", [None, 784], name=\"X\")\n", 70 | "Y = tf.placeholder(\"float\", [None, 10], name=\"Y\")\n", 71 | "\n", 72 | "w_h = init_weights([784, 625], \"w_h\")\n", 73 | "w_h2 = init_weights([625, 625], \"w_h2\")\n", 74 | "w_o = init_weights([625, 10], \"w_o\")\n", 75 | "\n", 76 | "# Add histogram summaries for weights\n", 77 | "tf.summary.histogram(\"w_h_summ\", w_h)\n", 78 | "tf.summary.histogram(\"w_h2_summ\", w_h2)\n", 79 | "tf.summary.histogram(\"w_o_summ\", w_o)\n", 80 | "\n", 81 | "p_keep_input = tf.placeholder(\"float\", name=\"p_keep_input\")\n", 82 | "p_keep_hidden = tf.placeholder(\"float\", name=\"p_keep_hidden\")\n", 83 | "py_x = model(X, w_h, w_h2, w_o, p_keep_input, p_keep_hidden)\n", 84 | "\n", 85 | "with tf.name_scope(\"cost\"):\n", 86 | " cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=py_x, labels=Y))\n", 87 | " train_op = tf.train.RMSPropOptimizer(0.001, 0.9).minimize(cost)\n", 88 | " # Add scalar summary for cost\n", 89 | " tf.summary.scalar(\"cost\", cost)\n", 90 | "\n", 91 | "with tf.name_scope(\"accuracy\"):\n", 92 | " correct_pred = tf.equal(tf.argmax(Y, 1), tf.argmax(py_x, 1)) # Count correct predictions\n", 93 | " acc_op = tf.reduce_mean(tf.cast(correct_pred, \"float\")) # Cast boolean to float to average\n", 94 | " # Add scalar summary for accuracy\n", 95 | " tf.summary.scalar(\"accuracy\", acc_op)" 96 | ] 97 | }, 98 | { 99 | "cell_type": "code", 100 | "execution_count": null, 101 | "metadata": { 102 | "collapsed": false 103 | }, 104 | "outputs": [], 105 | "source": [ 106 | "with tf.Session() as sess:\n", 107 | " # create a log writer. run 'tensorboard --logdir=./logs/nn_logs'\n", 108 | " writer = tf.summary.FileWriter(\"./logs/nn_logs\", sess.graph) # for 1.0\n", 109 | " merged = tf.summary.merge_all()\n", 110 | "\n", 111 | " # you need to initialize all variables\n", 112 | " tf.global_variables_initializer().run()\n", 113 | "\n", 114 | " for i in range(100):\n", 115 | " for start, end in zip(range(0, len(trX), 128), range(128, len(trX)+1, 128)):\n", 116 | " sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end],\n", 117 | " p_keep_input: 0.8, p_keep_hidden: 0.5})\n", 118 | " summary, acc = sess.run([merged, acc_op], feed_dict={X: teX, Y: teY,\n", 119 | " p_keep_input: 1.0, p_keep_hidden: 1.0})\n", 120 | " writer.add_summary(summary, i) # Write summary\n", 121 | " print(i, acc) # Report the accuracy" 122 | ] 123 | }, 124 | { 125 | "cell_type": "code", 126 | "execution_count": null, 127 | "metadata": { 128 | "collapsed": true 129 | }, 130 | "outputs": [], 131 | "source": [] 132 | } 133 | ], 134 | "metadata": { 135 | "kernelspec": { 136 | "display_name": "Python 2", 137 | "language": "python", 138 | "name": "python2" 139 | }, 140 | "language_info": { 141 | "codemirror_mode": { 142 | "name": "ipython", 143 | "version": 2 144 | }, 145 | "file_extension": ".py", 146 | "mimetype": "text/x-python", 147 | "name": "python", 148 | "nbconvert_exporter": "python", 149 | "pygments_lexer": "ipython2", 150 | "version": "2.7.13" 151 | } 152 | }, 153 | "nbformat": 4, 154 | "nbformat_minor": 1 155 | } 156 | -------------------------------------------------------------------------------- /TensorFlow-Tutorials/09_tensorboard.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import tensorflow as tf 4 | from tensorflow.examples.tutorials.mnist import input_data 5 | 6 | def init_weights(shape, name): 7 | return tf.Variable(tf.random_normal(shape, stddev=0.01), name=name) 8 | 9 | # This network is the same as the previous one except with an extra hidden layer + dropout 10 | def model(X, w_h, w_h2, w_o, p_keep_input, p_keep_hidden): 11 | # Add layer name scopes for better graph visualization 12 | with tf.name_scope("layer1"): 13 | X = tf.nn.dropout(X, p_keep_input) 14 | h = tf.nn.relu(tf.matmul(X, w_h)) 15 | with tf.name_scope("layer2"): 16 | h = tf.nn.dropout(h, p_keep_hidden) 17 | h2 = tf.nn.relu(tf.matmul(h, w_h2)) 18 | with tf.name_scope("layer3"): 19 | h2 = tf.nn.dropout(h2, p_keep_hidden) 20 | return tf.matmul(h2, w_o) 21 | 22 | mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) 23 | trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels 24 | 25 | X = tf.placeholder("float", [None, 784], name="X") 26 | Y = tf.placeholder("float", [None, 10], name="Y") 27 | 28 | w_h = init_weights([784, 625], "w_h") 29 | w_h2 = init_weights([625, 625], "w_h2") 30 | w_o = init_weights([625, 10], "w_o") 31 | 32 | # Add histogram summaries for weights 33 | tf.summary.histogram("w_h_summ", w_h) 34 | tf.summary.histogram("w_h2_summ", w_h2) 35 | tf.summary.histogram("w_o_summ", w_o) 36 | 37 | p_keep_input = tf.placeholder("float", name="p_keep_input") 38 | p_keep_hidden = tf.placeholder("float", name="p_keep_hidden") 39 | py_x = model(X, w_h, w_h2, w_o, p_keep_input, p_keep_hidden) 40 | 41 | with tf.name_scope("cost"): 42 | cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=py_x, labels=Y)) 43 | train_op = tf.train.RMSPropOptimizer(0.001, 0.9).minimize(cost) 44 | # Add scalar summary for cost 45 | tf.summary.scalar("cost", cost) 46 | 47 | with tf.name_scope("accuracy"): 48 | correct_pred = tf.equal(tf.argmax(Y, 1), tf.argmax(py_x, 1)) # Count correct predictions 49 | acc_op = tf.reduce_mean(tf.cast(correct_pred, "float")) # Cast boolean to float to average 50 | # Add scalar summary for accuracy 51 | tf.summary.scalar("accuracy", acc_op) 52 | 53 | with tf.Session() as sess: 54 | # create a log writer. run 'tensorboard --logdir=./logs/nn_logs' 55 | writer = tf.summary.FileWriter("./logs/nn_logs", sess.graph) # for 1.0 56 | merged = tf.summary.merge_all() 57 | 58 | # you need to initialize all variables 59 | tf.global_variables_initializer().run() 60 | 61 | for i in range(100): 62 | for start, end in zip(range(0, len(trX), 128), range(128, len(trX)+1, 128)): 63 | sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end], 64 | p_keep_input: 0.8, p_keep_hidden: 0.5}) 65 | summary, acc = sess.run([merged, acc_op], feed_dict={X: teX, Y: teY, 66 | p_keep_input: 1.0, p_keep_hidden: 1.0}) 67 | writer.add_summary(summary, i) # Write summary 68 | print(i, acc) # Report the accuracy 69 | writer.close() -------------------------------------------------------------------------------- /TensorFlow-Tutorials/10_save_restore_net.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": { 7 | "collapsed": true 8 | }, 9 | "outputs": [], 10 | "source": [ 11 | "import tensorflow as tf\n", 12 | "import numpy as np\n", 13 | "from tensorflow.examples.tutorials.mnist import input_data\n", 14 | "import os" 15 | ] 16 | }, 17 | { 18 | "cell_type": "code", 19 | "execution_count": null, 20 | "metadata": { 21 | "collapsed": false 22 | }, 23 | "outputs": [], 24 | "source": [ 25 | "# This shows how to save/restore your model (trained variables).\n", 26 | "# To see how it works, please stop this program during training and resart.\n", 27 | "# This network is the same as 3_net.py\n", 28 | "\n", 29 | "def init_weights(shape):\n", 30 | " return tf.Variable(tf.random_normal(shape, stddev=0.01))\n", 31 | "\n", 32 | "def model(X, w_h, w_h2, w_o, p_keep_input, p_keep_hidden): # this network is the same as the previous one except with an extra hidden layer + dropout\n", 33 | " X = tf.nn.dropout(X, p_keep_input)\n", 34 | " h = tf.nn.relu(tf.matmul(X, w_h))\n", 35 | "\n", 36 | " h = tf.nn.dropout(h, p_keep_hidden)\n", 37 | " h2 = tf.nn.relu(tf.matmul(h, w_h2))\n", 38 | "\n", 39 | " h2 = tf.nn.dropout(h2, p_keep_hidden)\n", 40 | "\n", 41 | " return tf.matmul(h2, w_o)\n", 42 | "\n", 43 | "mnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n", 44 | "trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels" 45 | ] 46 | }, 47 | { 48 | "cell_type": "code", 49 | "execution_count": 3, 50 | "metadata": { 51 | "collapsed": true 52 | }, 53 | "outputs": [], 54 | "source": [ 55 | "X = tf.placeholder(\"float\", [None, 784])\n", 56 | "Y = tf.placeholder(\"float\", [None, 10])\n", 57 | "\n", 58 | "w_h = init_weights([784, 625])\n", 59 | "w_h2 = init_weights([625, 625])\n", 60 | "w_o = init_weights([625, 10])\n", 61 | "\n", 62 | "p_keep_input = tf.placeholder(\"float\")\n", 63 | "p_keep_hidden = tf.placeholder(\"float\")\n", 64 | "py_x = model(X, w_h, w_h2, w_o, p_keep_input, p_keep_hidden)\n", 65 | "\n", 66 | "cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=py_x, labels=Y))\n", 67 | "train_op = tf.train.RMSPropOptimizer(0.001, 0.9).minimize(cost)\n", 68 | "predict_op = tf.argmax(py_x, 1)\n", 69 | "\n", 70 | "ckpt_dir = \"./ckpt_dir\"\n", 71 | "if not os.path.exists(ckpt_dir):\n", 72 | " os.makedirs(ckpt_dir)\n", 73 | "\n", 74 | "global_step = tf.Variable(0, name='global_step', trainable=False)\n", 75 | "\n", 76 | "# Call this after declaring all tf.Variables.\n", 77 | "saver = tf.train.Saver()\n", 78 | "\n", 79 | "# This variable won't be stored, since it is declared after tf.train.Saver()\n", 80 | "non_storable_variable = tf.Variable(777)" 81 | ] 82 | }, 83 | { 84 | "cell_type": "code", 85 | "execution_count": null, 86 | "metadata": { 87 | "collapsed": false 88 | }, 89 | "outputs": [], 90 | "source": [ 91 | "# Launch the graph in a session\n", 92 | "with tf.Session() as sess:\n", 93 | " # you need to initialize all variables\n", 94 | " tf.global_variables_initializer().run()\n", 95 | "\n", 96 | " ckpt = tf.train.get_checkpoint_state(ckpt_dir)\n", 97 | " if ckpt and ckpt.model_checkpoint_path:\n", 98 | " print(ckpt.model_checkpoint_path)\n", 99 | " saver.restore(sess, ckpt.model_checkpoint_path) # restore all variables\n", 100 | "\n", 101 | " start = global_step.eval() # get last global_step\n", 102 | " print(\"Start from:\", start)\n", 103 | "\n", 104 | " for i in range(start, 100):\n", 105 | " for start, end in zip(range(0, len(trX), 128), range(128, len(trX)+1, 128)):\n", 106 | " sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end],\n", 107 | " p_keep_input: 0.8, p_keep_hidden: 0.5})\n", 108 | "\n", 109 | " global_step.assign(i).eval() # set and update(eval) global_step with index, i\n", 110 | " saver.save(sess, ckpt_dir + \"/model.ckpt\", global_step=global_step)\n", 111 | " print(i, np.mean(np.argmax(teY, axis=1) ==\n", 112 | " sess.run(predict_op, feed_dict={X: teX, Y: teY,\n", 113 | " p_keep_input: 1.0,\n", 114 | " p_keep_hidden: 1.0})))" 115 | ] 116 | }, 117 | { 118 | "cell_type": "code", 119 | "execution_count": null, 120 | "metadata": { 121 | "collapsed": true 122 | }, 123 | "outputs": [], 124 | "source": [] 125 | } 126 | ], 127 | "metadata": { 128 | "kernelspec": { 129 | "display_name": "Python 2", 130 | "language": "python", 131 | "name": "python2" 132 | }, 133 | "language_info": { 134 | "codemirror_mode": { 135 | "name": "ipython", 136 | "version": 2 137 | }, 138 | "file_extension": ".py", 139 | "mimetype": "text/x-python", 140 | "name": "python", 141 | "nbconvert_exporter": "python", 142 | "pygments_lexer": "ipython2", 143 | "version": "2.7.13" 144 | } 145 | }, 146 | "nbformat": 4, 147 | "nbformat_minor": 1 148 | } 149 | -------------------------------------------------------------------------------- /TensorFlow-Tutorials/10_save_restore_net.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import tensorflow as tf 4 | import numpy as np 5 | from tensorflow.examples.tutorials.mnist import input_data 6 | import os 7 | 8 | # This shows how to save/restore your model (trained variables). 9 | # To see how it works, please stop this program during training and resart. 10 | # This network is the same as 3_net.py 11 | 12 | def init_weights(shape): 13 | return tf.Variable(tf.random_normal(shape, stddev=0.01)) 14 | 15 | 16 | def model(X, w_h, w_h2, w_o, p_keep_input, p_keep_hidden): # this network is the same as the previous one except with an extra hidden layer + dropout 17 | X = tf.nn.dropout(X, p_keep_input) 18 | h = tf.nn.relu(tf.matmul(X, w_h)) 19 | 20 | h = tf.nn.dropout(h, p_keep_hidden) 21 | h2 = tf.nn.relu(tf.matmul(h, w_h2)) 22 | 23 | h2 = tf.nn.dropout(h2, p_keep_hidden) 24 | 25 | return tf.matmul(h2, w_o) 26 | 27 | 28 | mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) 29 | trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels 30 | 31 | X = tf.placeholder("float", [None, 784]) 32 | Y = tf.placeholder("float", [None, 10]) 33 | 34 | w_h = init_weights([784, 625]) 35 | w_h2 = init_weights([625, 625]) 36 | w_o = init_weights([625, 10]) 37 | 38 | p_keep_input = tf.placeholder("float") 39 | p_keep_hidden = tf.placeholder("float") 40 | py_x = model(X, w_h, w_h2, w_o, p_keep_input, p_keep_hidden) 41 | 42 | cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=py_x, labels=Y)) 43 | train_op = tf.train.RMSPropOptimizer(0.001, 0.9).minimize(cost) 44 | predict_op = tf.argmax(py_x, 1) 45 | 46 | 47 | ckpt_dir = "./ckpt_dir" 48 | if not os.path.exists(ckpt_dir): 49 | os.makedirs(ckpt_dir) 50 | 51 | global_step = tf.Variable(0, name='global_step', trainable=False) 52 | 53 | # Call this after declaring all tf.Variables. 54 | saver = tf.train.Saver() 55 | 56 | # This variable won't be stored, since it is declared after tf.train.Saver() 57 | non_storable_variable = tf.Variable(777) 58 | 59 | # Launch the graph in a session 60 | with tf.Session() as sess: 61 | # you need to initialize all variables 62 | tf.global_variables_initializer().run() 63 | 64 | ckpt = tf.train.get_checkpoint_state(ckpt_dir) 65 | if ckpt and ckpt.model_checkpoint_path: 66 | print(ckpt.model_checkpoint_path) 67 | saver.restore(sess, ckpt.model_checkpoint_path) # restore all variables 68 | 69 | start = global_step.eval() # get last global_step 70 | print("Start from:", start) 71 | 72 | for i in range(start, 100): 73 | for start, end in zip(range(0, len(trX), 128), range(128, len(trX)+1, 128)): 74 | sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end], 75 | p_keep_input: 0.8, p_keep_hidden: 0.5}) 76 | 77 | global_step.assign(i).eval() # set and update(eval) global_step with index, i 78 | saver.save(sess, ckpt_dir + "/model.ckpt", global_step=global_step) 79 | print(i, np.mean(np.argmax(teY, axis=1) == 80 | sess.run(predict_op, feed_dict={X: teX, 81 | p_keep_input: 1.0, 82 | p_keep_hidden: 1.0}))) 83 | -------------------------------------------------------------------------------- /TensorFlow-Tutorials/11_gan.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | import numpy as np 3 | from tensorflow.examples.tutorials.mnist import input_data 4 | #from PIL import Image 5 | 6 | mnist = input_data.read_data_sets("MNIST_data/") 7 | images = mnist.train.images 8 | 9 | def xavier_initializer(shape): 10 | return tf.random_normal(shape=shape, stddev=1.0/shape[0]) 11 | 12 | # Generator 13 | z_size = 100 # maybe larger 14 | g_w1_size = 400 15 | g_out_size = 28 * 28 16 | 17 | # Discriminator 18 | x_size = 28 * 28 19 | d_w1_size = 400 20 | d_out_size = 1 21 | 22 | z = tf.placeholder('float', shape=(None, z_size)) 23 | X = tf.placeholder('float', shape=(None, x_size)) 24 | 25 | # use dict to share variables 26 | g_weights = { 27 | 'w1': tf.Variable(xavier_initializer(shape=(z_size, g_w1_size))), 28 | 'b1': tf.Variable(tf.zeros(shape=[g_w1_size])), 29 | 'out': tf.Variable(xavier_initializer(shape=(g_w1_size, g_out_size))), 30 | 'b2': tf.Variable(tf.zeros(shape=[g_out_size])), 31 | } 32 | 33 | d_weights ={ 34 | 'w1': tf.Variable(xavier_initializer(shape=(x_size, d_w1_size))), 35 | 'b1': tf.Variable(tf.zeros(shape=[d_w1_size])), 36 | 'out': tf.Variable(xavier_initializer(shape=(d_w1_size, d_out_size))), 37 | 'b2': tf.Variable(tf.zeros(shape=[d_out_size])), 38 | } 39 | 40 | def G(z, w=g_weights): 41 | # here tanh is better than relu 42 | h1 = tf.tanh(tf.matmul(z, w['w1']) + w['b1']) 43 | # pixel output is in range [0, 255] 44 | return tf.sigmoid(tf.matmul(h1, w['out']) + w['b2']) * 255 45 | 46 | def D(x, w=d_weights): 47 | # here tanh is better than relu 48 | h1 = tf.tanh(tf.matmul(x, w['w1']) + w['b1']) 49 | h2 = tf.matmul(h1, w['out']) + w['b2'] 50 | return h2 # use h2 to calculate logits loss 51 | 52 | def generate_z(n=1): 53 | return np.random.normal(size=(n, z_size)) 54 | 55 | sample = G(z) 56 | 57 | 58 | dout_real = D(X) 59 | dout_fake = D(G(z)) 60 | 61 | G_obj = tf.reduce_mean( 62 | tf.nn.sigmoid_cross_entropy_with_logits(logits=dout_fake, labels=tf.ones_like(dout_fake))) 63 | D_obj_real = tf.reduce_mean( # use single side smoothing 64 | tf.nn.sigmoid_cross_entropy_with_logits(logits=dout_real, labels=(tf.ones_like(dout_real)-0.1))) 65 | D_obj_fake = tf.reduce_mean( 66 | tf.nn.sigmoid_cross_entropy_with_logits(logits=dout_fake, labels=tf.zeros_like(dout_fake))) 67 | D_obj = D_obj_real + D_obj_fake 68 | 69 | G_opt = tf.train.AdamOptimizer().minimize(G_obj, var_list=g_weights.values()) 70 | D_opt = tf.train.AdamOptimizer().minimize(D_obj, var_list=d_weights.values()) 71 | 72 | ## Training 73 | batch_size = 128 74 | 75 | with tf.Session() as sess: 76 | sess.run(tf.global_variables_initializer()) 77 | 78 | for i in range(200): 79 | sess.run(D_opt, feed_dict={ 80 | X: images[np.random.choice(range(len(images)), batch_size)].reshape(batch_size, x_size), 81 | z: generate_z(batch_size), 82 | }) 83 | # run two phases of generator 84 | sess.run(G_opt, feed_dict={ 85 | z: generate_z(batch_size) 86 | }) 87 | sess.run(G_opt, feed_dict={ 88 | z: generate_z(batch_size) 89 | }) 90 | 91 | g_cost = sess.run(G_obj, feed_dict={z: generate_z(batch_size)}) 92 | d_cost = sess.run(D_obj, feed_dict={ 93 | X: images[np.random.choice(range(len(images)), batch_size)].reshape(batch_size, x_size), 94 | z: generate_z(batch_size), 95 | }) 96 | image = sess.run(G(z), feed_dict={z:generate_z()}) 97 | df = sess.run(tf.sigmoid(dout_fake), feed_dict={z:generate_z()}) 98 | # print i, G cost, D cost, image max pixel, D output of fake 99 | print (i, g_cost, d_cost, image.max(), df[0][0]) 100 | 101 | # You may wish to save or plot the image generated 102 | # to see how it looks like 103 | image = sess.run(G(z), feed_dict={z:generate_z()}) 104 | image1 = image[0].reshape([28, 28]) 105 | #print image1 106 | #im = Image.fromarray(image1) 107 | #im.show() 108 | 109 | -------------------------------------------------------------------------------- /TensorFlow-Tutorials/README.md: -------------------------------------------------------------------------------- 1 | Introduction to deep learning based on Google's TensorFlow framework. 2 | -------------------------------------------------------------------------------- /Tensorflow-estimator-classification/00_mnist.py: -------------------------------------------------------------------------------- 1 | # Taken from https://www.tensorflow.org/tutorials/layers 2 | 3 | from __future__ import absolute_import 4 | from __future__ import division 5 | from __future__ import print_function 6 | 7 | # Imports 8 | import numpy as np 9 | import tensorflow as tf 10 | from pprint import pprint 11 | import matplotlib.pyplot as plt 12 | 13 | tf.logging.set_verbosity(tf.logging.INFO) 14 | tf.device("/gpu:0") 15 | 16 | def cnn_model_fn(features, labels, mode): 17 | """Model function for CNN.""" 18 | 19 | # Input Layer 20 | input_layer = tf.reshape(features["x"], [-1, 28, 28, 1]) 21 | 22 | # Convolutional Layer #1 23 | conv1 = tf.layers.conv2d( 24 | inputs=input_layer, 25 | filters=32, 26 | kernel_size=[5, 5], 27 | padding="same", 28 | activation=tf.nn.relu) 29 | 30 | # Pooling Layer #1 31 | pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2) 32 | 33 | # Convolutional Layer #2 and Pooling Layer #2 34 | conv2 = tf.layers.conv2d( 35 | inputs=pool1, 36 | filters=64, 37 | kernel_size=[5, 5], 38 | padding="same", 39 | activation=tf.nn.relu) 40 | 41 | # Pooling Layer #2 42 | pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2) 43 | 44 | # Dense Layer 45 | pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64]) 46 | dense = tf.layers.dense(inputs=pool2_flat, units=1024, 47 | activation=tf.nn.relu) 48 | dropout = tf.layers.dropout( 49 | inputs=dense, rate=0.4, training=mode == tf.estimator.ModeKeys.TRAIN) 50 | 51 | # Logits Layer 52 | logits = tf.layers.dense(inputs=dropout, units=10) 53 | 54 | predictions = { 55 | # Generate predictions (for PREDICT and EVAL mode) 56 | "classes": tf.argmax(input=logits, axis=1), 57 | # Add `softmax_tensor` to the graph. It is used for PREDICT and by the 58 | # `logging_hook`. 59 | "probabilities": tf.nn.softmax(logits, name="softmax_tensor") 60 | } 61 | 62 | if mode == tf.estimator.ModeKeys.PREDICT: 63 | return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions) 64 | 65 | # Calculate Loss (for both TRAIN and EVAL modes) 66 | onehot_labels = tf.one_hot(indices=tf.cast(labels, tf.int32), depth=10) 67 | loss = tf.identity(tf.losses.softmax_cross_entropy( 68 | onehot_labels=onehot_labels, logits=logits), name='loss') 69 | 70 | # Configure the Training Op (for TRAIN mode) 71 | if mode == tf.estimator.ModeKeys.TRAIN: 72 | optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001) 73 | train_op = optimizer.minimize( 74 | loss=loss, 75 | global_step=tf.train.get_global_step()) 76 | return tf.estimator.EstimatorSpec( 77 | mode=mode, loss=loss, train_op=train_op) 78 | 79 | # Add evaluation metrics (for EVAL mode) 80 | eval_metric_ops = { 81 | "accuracy": tf.metrics.accuracy( 82 | labels=labels, predictions=predictions["classes"])} 83 | return tf.estimator.EstimatorSpec( 84 | mode=mode, loss=loss, eval_metric_ops=eval_metric_ops) 85 | 86 | 87 | def main(unused_argv): 88 | 89 | if_plot = False 90 | 91 | # Load training and eval data 92 | mnist = tf.contrib.learn.datasets.load_dataset("mnist") 93 | train_data = mnist.train.images # Returns np.array 94 | train_labels = np.asarray(mnist.train.labels, dtype=np.int32) 95 | eval_data = mnist.test.images # Returns np.array 96 | eval_labels = np.asarray(mnist.test.labels, dtype=np.int32) 97 | 98 | # Initialize array to store loss and accuracy 99 | losses = np.zeros((100,1), dtype='float') 100 | accus = np.zeros((100,1), dtype='float') 101 | 102 | # Create the Estimator 103 | mnist_classifier = tf.estimator.Estimator(model_fn=cnn_model_fn, model_dir="./mnist_models/") 104 | tensors_to_log = {"loss": "loss"} 105 | logging_hook = tf.train.LoggingTensorHook(tensors=tensors_to_log, at_end=True) 106 | 107 | # Train data loader 108 | train_input_fn = tf.estimator.inputs.numpy_input_fn( 109 | x={"x": train_data}, 110 | y=train_labels, 111 | batch_size=100, 112 | num_epochs=None, 113 | shuffle=True) 114 | 115 | eval_input_fn = tf.estimator.inputs.numpy_input_fn( 116 | x={"x": eval_data}, 117 | y=eval_labels, 118 | num_epochs=1, 119 | shuffle=False) 120 | 121 | for given_iter in range(1,100): 122 | # Train for some number of iters 123 | mnist_classifier.train( 124 | input_fn=train_input_fn, 125 | steps=200, 126 | hooks=[logging_hook]) 127 | 128 | eval_results = mnist_classifier.evaluate(input_fn=eval_input_fn) 129 | losses[given_iter] = eval_results['loss'] 130 | accus[given_iter] = eval_results['accuracy'] 131 | 132 | if if_plot == True: 133 | xx = range(1,100) 134 | plt.plot(xx, losses, 'r--', accus, 'g^') 135 | plt.show() 136 | 137 | print(losses) 138 | print(accus) 139 | if __name__ == "__main__": 140 | tf.app.run() 141 | -------------------------------------------------------------------------------- /Tensorflow-estimator-classification/01_map.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MachineLP/Tensorflow-/4d94c4d012293a018f3b9b80f05562a80447670b/Tensorflow-estimator-classification/01_map.png -------------------------------------------------------------------------------- /Tensorflow-estimator-classification/MNIST-data/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Tensorflow-estimator-classification/MNIST-data/t10k-images-idx3-ubyte.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MachineLP/Tensorflow-/4d94c4d012293a018f3b9b80f05562a80447670b/Tensorflow-estimator-classification/MNIST-data/t10k-images-idx3-ubyte.gz -------------------------------------------------------------------------------- /Tensorflow-estimator-classification/MNIST-data/t10k-labels-idx1-ubyte.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MachineLP/Tensorflow-/4d94c4d012293a018f3b9b80f05562a80447670b/Tensorflow-estimator-classification/MNIST-data/t10k-labels-idx1-ubyte.gz -------------------------------------------------------------------------------- /Tensorflow-estimator-classification/MNIST-data/train-images-idx3-ubyte.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MachineLP/Tensorflow-/4d94c4d012293a018f3b9b80f05562a80447670b/Tensorflow-estimator-classification/MNIST-data/train-images-idx3-ubyte.gz -------------------------------------------------------------------------------- /Tensorflow-estimator-classification/MNIST-data/train-labels-idx1-ubyte.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MachineLP/Tensorflow-/4d94c4d012293a018f3b9b80f05562a80447670b/Tensorflow-estimator-classification/MNIST-data/train-labels-idx1-ubyte.gz -------------------------------------------------------------------------------- /Tensorflow-estimator-classification/README.md: -------------------------------------------------------------------------------- 1 | # Assignment-1 of Visual Learning and Representation course at CMU. Spring 2018. 2 | -------------------------------------------------------------------------------- /Tensorflow-estimator-classification/eval.py: -------------------------------------------------------------------------------- 1 | import sklearn.metrics 2 | 3 | 4 | def compute_map(gt, pred, valid, average=None): 5 | """ 6 | Compute the multi-label classification accuracy. 7 | gt (np.ndarray): Shape Nx20, 0 or 1, 1 if the object i is present in that 8 | image. 9 | pred (np.ndarray): Shape Nx20, probability of that object in the image 10 | (output probablitiy). 11 | valid (np.ndarray): Shape Nx20, 0 if you want to ignore that class for that 12 | image. Some objects are labeled as ambiguous. 13 | """ 14 | nclasses = gt.shape[1] 15 | all_ap = [] 16 | for cid in range(nclasses): 17 | gt_cls = gt[:, cid][valid[:, cid] > 0].astype('float32') 18 | pred_cls = pred[:, cid][valid[:, cid] > 0].astype('float32') 19 | # As per PhilK. code: 20 | # https://github.com/philkr/voc-classification/blob/master/src/train_cls.py 21 | pred_cls -= 1e-5 * gt_cls 22 | ap = sklearn.metrics.average_precision_score( 23 | gt_cls, pred_cls, average=average) 24 | all_ap.append(ap) 25 | return all_ap 26 | -------------------------------------------------------------------------------- /Tensorflow-estimator-classification/gpu_conf.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | export CUDA_HOME=/usr/local/cuda-8.0/ 4 | export LD_LIBRARY_PATH=/users/yash.p/cuda_version/cuda/lib64 5 | PATH=/users/yash.p/cuda_version/cuda/bin:${PATH} 6 | export PATH 7 | export CUDA_VISIBLE_DEVICES=3 8 | 9 | -------------------------------------------------------------------------------- /Tensorflow-estimator-classification/pascal_alexnet_mixup.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MachineLP/Tensorflow-/4d94c4d012293a018f3b9b80f05562a80447670b/Tensorflow-estimator-classification/pascal_alexnet_mixup.png -------------------------------------------------------------------------------- /Tensorflow-estimator-classification/pascal_vgg.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MachineLP/Tensorflow-/4d94c4d012293a018f3b9b80f05562a80447670b/Tensorflow-estimator-classification/pascal_vgg.png -------------------------------------------------------------------------------- /Tensorflow-estimator-classification/pascal_vgg_finetune.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MachineLP/Tensorflow-/4d94c4d012293a018f3b9b80f05562a80447670b/Tensorflow-estimator-classification/pascal_vgg_finetune.png -------------------------------------------------------------------------------- /Tensorflow/3_2_HelloWorld.py: -------------------------------------------------------------------------------- 1 | #%% 2 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # ============================================================================== 16 | from tensorflow.examples.tutorials.mnist import input_data 17 | mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) 18 | 19 | print(mnist.train.images.shape, mnist.train.labels.shape) 20 | print(mnist.test.images.shape, mnist.test.labels.shape) 21 | print(mnist.validation.images.shape, mnist.validation.labels.shape) 22 | 23 | import tensorflow as tf 24 | sess = tf.InteractiveSession() 25 | x = tf.placeholder(tf.float32, [None, 784]) 26 | 27 | W = tf.Variable(tf.zeros([784, 10])) 28 | b = tf.Variable(tf.zeros([10])) 29 | 30 | y = tf.nn.softmax(tf.matmul(x, W) + b) 31 | 32 | y_ = tf.placeholder(tf.float32, [None, 10]) 33 | cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) 34 | 35 | train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) 36 | 37 | tf.global_variables_initializer().run() 38 | 39 | for i in range(1000): 40 | batch_xs, batch_ys = mnist.train.next_batch(100) 41 | train_step.run({x: batch_xs, y_: batch_ys}) 42 | 43 | correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) 44 | 45 | accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 46 | 47 | print(accuracy.eval({x: mnist.test.images, y_: mnist.test.labels})) 48 | -------------------------------------------------------------------------------- /Tensorflow/4_4_MLP.py: -------------------------------------------------------------------------------- 1 | #%% 2 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # ============================================================================== 16 | 17 | # Create the model 18 | from tensorflow.examples.tutorials.mnist import input_data 19 | import tensorflow as tf 20 | mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) 21 | sess = tf.InteractiveSession() 22 | 23 | in_units = 784 24 | h1_units = 300 25 | W1 = tf.Variable(tf.truncated_normal([in_units, h1_units], stddev=0.1)) 26 | b1 = tf.Variable(tf.zeros([h1_units])) 27 | W2 = tf.Variable(tf.zeros([h1_units, 10])) 28 | b2 = tf.Variable(tf.zeros([10])) 29 | 30 | x = tf.placeholder(tf.float32, [None, in_units]) 31 | keep_prob = tf.placeholder(tf.float32) 32 | 33 | hidden1 = tf.nn.relu(tf.matmul(x, W1) + b1) 34 | hidden1_drop = tf.nn.dropout(hidden1, keep_prob) 35 | y = tf.nn.softmax(tf.matmul(hidden1_drop, W2) + b2) 36 | 37 | # Define loss and optimizer 38 | y_ = tf.placeholder(tf.float32, [None, 10]) 39 | cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) 40 | train_step = tf.train.AdagradOptimizer(0.3).minimize(cross_entropy) 41 | 42 | # Train 43 | tf.global_variables_initializer().run() 44 | for i in range(3000): 45 | batch_xs, batch_ys = mnist.train.next_batch(100) 46 | train_step.run({x: batch_xs, y_: batch_ys, keep_prob: 0.75}) 47 | 48 | # Test trained model 49 | correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) 50 | accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 51 | print(accuracy.eval({x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})) -------------------------------------------------------------------------------- /Tensorflow/5_2_CNN_MNIST.py: -------------------------------------------------------------------------------- 1 | #%% 2 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # ============================================================================== 16 | 17 | from tensorflow.examples.tutorials.mnist import input_data 18 | import tensorflow as tf 19 | mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) 20 | sess = tf.InteractiveSession() 21 | 22 | 23 | def weight_variable(shape): 24 | initial = tf.truncated_normal(shape, stddev=0.1) 25 | return tf.Variable(initial) 26 | 27 | def bias_variable(shape): 28 | initial = tf.constant(0.1, shape=shape) 29 | return tf.Variable(initial) 30 | 31 | def conv2d(x, W): 32 | return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') 33 | 34 | def max_pool_2x2(x): 35 | return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], 36 | strides=[1, 2, 2, 1], padding='SAME') 37 | 38 | x = tf.placeholder(tf.float32, [None, 784]) 39 | y_ = tf.placeholder(tf.float32, [None, 10]) 40 | x_image = tf.reshape(x, [-1,28,28,1]) 41 | 42 | W_conv1 = weight_variable([5, 5, 1, 32]) 43 | b_conv1 = bias_variable([32]) 44 | h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) 45 | h_pool1 = max_pool_2x2(h_conv1) 46 | 47 | W_conv2 = weight_variable([5, 5, 32, 64]) 48 | b_conv2 = bias_variable([64]) 49 | h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) 50 | h_pool2 = max_pool_2x2(h_conv2) 51 | 52 | W_fc1 = weight_variable([7 * 7 * 64, 1024]) 53 | b_fc1 = bias_variable([1024]) 54 | h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) 55 | h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) 56 | 57 | keep_prob = tf.placeholder(tf.float32) 58 | h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) 59 | 60 | W_fc2 = weight_variable([1024, 10]) 61 | b_fc2 = bias_variable([10]) 62 | y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) 63 | 64 | cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1])) 65 | train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) 66 | 67 | correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1)) 68 | accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 69 | tf.global_variables_initializer().run() 70 | for i in range(20000): 71 | batch = mnist.train.next_batch(50) 72 | if i%100 == 0: 73 | train_accuracy = accuracy.eval(feed_dict={ 74 | x:batch[0], y_: batch[1], keep_prob: 1.0}) 75 | print("step %d, training accuracy %g"%(i, train_accuracy)) 76 | train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5}) 77 | 78 | print("test accuracy %g"%accuracy.eval(feed_dict={ 79 | x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})) 80 | 81 | 82 | 83 | -------------------------------------------------------------------------------- /Tensorflow/7_3_BiRNN.py: -------------------------------------------------------------------------------- 1 | #%% 2 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # ============================================================================== 16 | import tensorflow as tf 17 | import numpy as np 18 | 19 | # Import MINST data 20 | from tensorflow.examples.tutorials.mnist import input_data 21 | mnist = input_data.read_data_sets("/tmp/data/", one_hot=True) 22 | 23 | 24 | 25 | # Parameters 26 | learning_rate = 0.01 27 | max_samples = 400000 28 | batch_size = 128 29 | display_step = 10 30 | 31 | # Network Parameters 32 | n_input = 28 # MNIST data input (img shape: 28*28) 33 | n_steps = 28 # timesteps 34 | n_hidden = 256 # hidden layer num of features 35 | n_classes = 10 # MNIST total classes (0-9 digits) 36 | 37 | # tf Graph input 38 | x = tf.placeholder("float", [None, n_steps, n_input]) 39 | y = tf.placeholder("float", [None, n_classes]) 40 | 41 | # Define weights 42 | weights = { 43 | # Hidden layer weights => 2*n_hidden because of foward + backward cells 44 | 'out': tf.Variable(tf.random_normal([2*n_hidden, n_classes])) 45 | } 46 | biases = { 47 | 'out': tf.Variable(tf.random_normal([n_classes])) 48 | } 49 | 50 | 51 | def BiRNN(x, weights, biases): 52 | 53 | # Prepare data shape to match `bidirectional_rnn` function requirements 54 | # Current data input shape: (batch_size, n_steps, n_input) 55 | # Required shape: 'n_steps' tensors list of shape (batch_size, n_input) 56 | 57 | # Permuting batch_size and n_steps 58 | x = tf.transpose(x, [1, 0, 2]) 59 | # Reshape to (n_steps*batch_size, n_input) 60 | x = tf.reshape(x, [-1, n_input]) 61 | # Split to get a list of 'n_steps' tensors of shape (batch_size, n_input) 62 | x = tf.split(x, n_steps) 63 | 64 | # Define lstm cells with tensorflow 65 | # Forward direction cell 66 | lstm_fw_cell = tf.contrib.rnn.BasicLSTMCell(n_hidden, forget_bias=1.0) 67 | # Backward direction cell 68 | lstm_bw_cell = tf.contrib.rnn.BasicLSTMCell(n_hidden, forget_bias=1.0) 69 | 70 | # Get lstm cell output 71 | # try: 72 | outputs, _, _ = tf.contrib.rnn.static_bidirectional_rnn(lstm_fw_cell, lstm_bw_cell, x, 73 | dtype=tf.float32) 74 | # except Exception: # Old TensorFlow version only returns outputs not states 75 | # outputs = rnn.bidirectional_rnn(lstm_fw_cell, lstm_bw_cell, x, 76 | # dtype=tf.float32) 77 | 78 | # Linear activation, using rnn inner loop last output 79 | return tf.matmul(outputs[-1], weights['out']) + biases['out'] 80 | 81 | 82 | pred = BiRNN(x, weights, biases) 83 | 84 | # Define loss and optimizer 85 | cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y)) 86 | optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) 87 | 88 | # Evaluate model 89 | correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1)) 90 | accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) 91 | 92 | # Initializing the variables 93 | init = tf.global_variables_initializer() 94 | 95 | 96 | 97 | # Launch the graph 98 | with tf.Session() as sess: 99 | sess.run(init) 100 | step = 1 101 | # Keep training until reach max iterations 102 | while step * batch_size < max_samples: 103 | batch_x, batch_y = mnist.train.next_batch(batch_size) 104 | # Reshape data to get 28 seq of 28 elements 105 | batch_x = batch_x.reshape((batch_size, n_steps, n_input)) 106 | # Run optimization op (backprop) 107 | sess.run(optimizer, feed_dict={x: batch_x, y: batch_y}) 108 | if step % display_step == 0: 109 | # Calculate batch accuracy 110 | acc = sess.run(accuracy, feed_dict={x: batch_x, y: batch_y}) 111 | # Calculate batch loss 112 | loss = sess.run(cost, feed_dict={x: batch_x, y: batch_y}) 113 | print("Iter " + str(step*batch_size) + ", Minibatch Loss= " + \ 114 | "{:.6f}".format(loss) + ", Training Accuracy= " + \ 115 | "{:.5f}".format(acc)) 116 | step += 1 117 | print("Optimization Finished!") 118 | 119 | # Calculate accuracy for 128 mnist test images 120 | test_len = 10000 121 | test_data = mnist.test.images[:test_len].reshape((-1, n_steps, n_input)) 122 | test_label = mnist.test.labels[:test_len] 123 | print("Testing Accuracy:", \ 124 | sess.run(accuracy, feed_dict={x: test_data, y: test_label})) 125 | 126 | 127 | -------------------------------------------------------------------------------- /Tensorflow/8_3_GridWorld.py: -------------------------------------------------------------------------------- 1 | #%% 2 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # ============================================================================== 16 | import numpy as np 17 | import random 18 | import itertools 19 | import scipy.misc 20 | import matplotlib.pyplot as plt 21 | 22 | 23 | class gameOb(): 24 | def __init__(self,coordinates,size,intensity,channel,reward,name): 25 | self.x = coordinates[0] 26 | self.y = coordinates[1] 27 | self.size = size 28 | self.intensity = intensity 29 | self.channel = channel 30 | self.reward = reward 31 | self.name = name 32 | 33 | class gameEnv(): 34 | def __init__(self,size): 35 | self.sizeX = size 36 | self.sizeY = size 37 | self.actions = 4 38 | self.objects = [] 39 | a = self.reset() 40 | plt.imshow(a,interpolation="nearest") 41 | 42 | 43 | def reset(self): 44 | self.objects = [] 45 | hero = gameOb(self.newPosition(),1,1,2,None,'hero') 46 | self.objects.append(hero) 47 | goal = gameOb(self.newPosition(),1,1,1,1,'goal') 48 | self.objects.append(goal) 49 | hole = gameOb(self.newPosition(),1,1,0,-1,'fire') 50 | self.objects.append(hole) 51 | goal2 = gameOb(self.newPosition(),1,1,1,1,'goal') 52 | self.objects.append(goal2) 53 | hole2 = gameOb(self.newPosition(),1,1,0,-1,'fire') 54 | self.objects.append(hole2) 55 | goal3 = gameOb(self.newPosition(),1,1,1,1,'goal') 56 | self.objects.append(goal3) 57 | goal4 = gameOb(self.newPosition(),1,1,1,1,'goal') 58 | self.objects.append(goal4) 59 | state = self.renderEnv() 60 | self.state = state 61 | return state 62 | 63 | def moveChar(self,direction): 64 | # 0 - up, 1 - down, 2 - left, 3 - right 65 | hero = self.objects[0] 66 | heroX = hero.x 67 | heroY = hero.y 68 | if direction == 0 and hero.y >= 1: 69 | hero.y -= 1 70 | if direction == 1 and hero.y <= self.sizeY-2: 71 | hero.y += 1 72 | if direction == 2 and hero.x >= 1: 73 | hero.x -= 1 74 | if direction == 3 and hero.x <= self.sizeX-2: 75 | hero.x += 1 76 | self.objects[0] = hero 77 | 78 | def newPosition(self): 79 | iterables = [ range(self.sizeX), range(self.sizeY)] 80 | points = [] 81 | for t in itertools.product(*iterables): 82 | points.append(t) 83 | currentPositions = [] 84 | for objectA in self.objects: 85 | if (objectA.x,objectA.y) not in currentPositions: 86 | currentPositions.append((objectA.x,objectA.y)) 87 | for pos in currentPositions: 88 | points.remove(pos) 89 | location = np.random.choice(range(len(points)),replace=False) 90 | return points[location] 91 | 92 | def checkGoal(self): 93 | others = [] 94 | for obj in self.objects: 95 | if obj.name == 'hero': 96 | hero = obj 97 | else: 98 | others.append(obj) 99 | for other in others: 100 | if hero.x == other.x and hero.y == other.y: 101 | self.objects.remove(other) 102 | if other.reward == 1: 103 | self.objects.append(gameOb(self.newPosition(),1,1,1,1,'goal')) 104 | else: 105 | self.objects.append(gameOb(self.newPosition(),1,1,0,-1,'fire')) 106 | return other.reward,False 107 | return 0.0,False 108 | 109 | def renderEnv(self): 110 | #a = np.zeros([self.sizeY,self.sizeX,3]) 111 | a = np.ones([self.sizeY+2,self.sizeX+2,3]) 112 | a[1:-1,1:-1,:] = 0 113 | for item in self.objects: 114 | a[item.y+1:item.y+item.size+1,item.x+1:item.x+item.size+1,item.channel] = item.intensity 115 | b = scipy.misc.imresize(a[:,:,0],[84,84,1],interp='nearest') 116 | c = scipy.misc.imresize(a[:,:,1],[84,84,1],interp='nearest') 117 | d = scipy.misc.imresize(a[:,:,2],[84,84,1],interp='nearest') 118 | a = np.stack([b,c,d],axis=2) 119 | return a 120 | 121 | def step(self,action): 122 | self.moveChar(action) 123 | reward,done = self.checkGoal() 124 | state = self.renderEnv() 125 | return state,reward,done -------------------------------------------------------------------------------- /Tensorflow/Tensorflow and Word2vec.txt: -------------------------------------------------------------------------------- 1 | 1. TensorFlow的NCE-Loss的实现和word2vec 2 | http://www.jianshu.com/p/fab82fa53e16 3 | 4 | 2. 通俗讲解TensorFlow的embedding_lookup -------------------------------------------------------------------------------- /face_detection/README.md: -------------------------------------------------------------------------------- 1 | 2 | # 人脸检测进阶系列 3 | -------------------------------------------------------------------------------- /face_detection/人脸检测——AFLW准备人脸.md: -------------------------------------------------------------------------------- 1 | 不多说了,直接代码吧: 2 | 3 | 生成AFLW_ann.txt的代码,其中包含图像名称 和 图像中人脸的位置(x,y,w,h); 4 | 5 | ** AFLW中含有aflw.aqlite文件。 6 | 7 | ``` 8 | 9 | importsqlite3 10 | 11 | list_annotation = list() 12 | 13 | # Format for saving: path x y w h 14 | 15 | ann_format ="{}/{} {} {} {} {}" 16 | 17 | conn = sqlite3.connect('aflw.sqlite') 18 | 19 | fidQuery ='SELECT face_id FROM Faces' 20 | 21 | faceIDs = conn.execute(fidQuery) 22 | 23 | foridxinfaceIDs: 24 | 25 | fidQuery ='SELECT file_id FROM Faces WHERE face_id = {}'.format(idx[0]) 26 | 27 | imgID = conn.execute(fidQuery) 28 | 29 | imgID = [idforidinimgID] 30 | 31 | imgDataQuery ="SELECT db_id,filepath,width,height FROM FaceImages WHERE file_id = '{}'".format(imgID[0][0]) 32 | 33 | fileID = conn.execute(imgDataQuery) 34 | 35 | fileID = [idforidinfileID] 36 | 37 | db_id = fileID[0][0] 38 | 39 | filepath = fileID[0][1] 40 | 41 | faceRectQuery ='SELECT x,y,w,h FROM FaceRect WHERE face_id = {}'.format(idx[0]) 42 | 43 | faceRect = conn.execute(faceRectQuery) 44 | 45 | faceRect = [idforidinfaceRect] 46 | 47 | iflen(faceRect)==0: 48 | 49 | continue 50 | 51 | x,y,w,h = faceRect[0] 52 | 53 | list_annotation.append(ann_format.format(db_id,filepath,x,y,w,h)) 54 | 55 | with open("AFLW_ann.txt",'w') as f: 56 | 57 | f.writelines("%s\n"% lineforlineinlist_annotation) 58 | 59 | ``` 60 | 61 | AFLW图片都整理到flickr文件下(含0,1,2三个文件),生成人脸的程序(并且对人脸进行了左右镜像): 62 | 63 | ``` 64 | 65 | importos 66 | 67 | fromPILimportImage 68 | 69 | fromPILimportImageFile 70 | 71 | # ImageFile.LOAD_TRUNCATED_IMAGES = True 72 | 73 | importcv2 74 | 75 | importnumpy as np 76 | 77 | with open('AFLW_ann.txt','r') as f: 78 | 79 | lines = f.readlines() 80 | 81 | save_dir1 ='data_prepare/net_positive' 82 | 83 | save_dir2 ='data_prepare/net_positive_flip' 84 | 85 | ifos.path.exists(save_dir1)==False: 86 | 87 | os.makedirs(save_dir1) 88 | 89 | ifos.path.exists(save_dir2)==False: 90 | 91 | os.makedirs(save_dir2) 92 | 93 | foridx, lineinenumerate(lines): 94 | 95 | s1 = line.strip().split(' ') 96 | 97 | image_path = s1[0] 98 | 99 | x = int(s1[1]) 100 | 101 | y = int(s1[2]) 102 | 103 | w = int(s1[3]) 104 | 105 | h = int(s1[4]) 106 | 107 | print(image_path) 108 | 109 | # image = Image.open(image_path) 110 | 111 | image = cv2.imread(image_path) 112 | 113 | ifimageisNone: 114 | 115 | continue 116 | 117 | ifx<=0andy<=0andw<=0andh<=0: 118 | 119 | continue 120 | 121 | box = (x, y, x+w, y+h) 122 | 123 | # patch = image.crop(box) 124 | 125 | patch = image[box[1]:box[3], box[0]:box[2], :] 126 | 127 | ifpatchisNone: 128 | 129 | continue 130 | 131 | patch1 = patch#.resize((51, 51)) 132 | 133 | # patch2 = patch1.transpose(Image.FLIP_LEFT_RIGHT) 134 | 135 | h = patch.shape[0] 136 | 137 | w = patch.shape[1] 138 | 139 | iLR = patch.copy() 140 | 141 | foriinrange(h): 142 | 143 | forjinrange(w): 144 | 145 | iLR[i,w-1-j] = patch[i,j] 146 | 147 | patch2 = iLR 148 | 149 | s2 = image_path.split('/') 150 | 151 | image_name = s2[-1] 152 | 153 | save_path1 = save_dir1+'/'+str(idx)+image_name +'.jpg' 154 | 155 | save_path2 = save_dir2+'/'+'l'+str(idx)+image_name +'.jpg' 156 | 157 | #patch1.save(save_path1, 'jpeg') 158 | 159 | #patch2.save(save_path2, 'jpeg') 160 | 161 | cv2.imwrite(save_path1, np.array(patch1)) 162 | 163 | cv2.imwrite(save_path2, np.array(patch2)) 164 | 165 | print(idx) 166 | 167 | ``` 168 | -------------------------------------------------------------------------------- /face_detection/人脸检测——准备非人脸.md: -------------------------------------------------------------------------------- 1 | 简单粗暴,不多说,直接代码吧: 2 | ``` 3 | import os 4 | import random 5 | from PIL import Image 6 | from PIL import ImageFile 7 | ImageFile.LOAD_TRUNCATED_IMAGES = True 8 | import cv2 9 | import numpy as np 10 | 11 | 12 | def random_crop(imagepath): 13 | 14 | # image = Image.open(imagepath) 15 | # len_rand = random.randint(0, min(image.size[0], image.size[1])-1) 16 | # x_rand = random.randint(0, image.size[0]-len_rand-1) 17 | # y_rand = random.randint(0, image.size[1]-len_rand-1) 18 | 19 | image = cv2.imread(imagepath) 20 | len_rand = random.randint(0, min(image.shape[1], image.shape[0])-1) 21 | x_rand = random.randint(0, image.shape[1]-len_rand-1) 22 | y_rand = random.randint(0, image.shape[0]-len_rand-1) 23 | 24 | box = (x_rand, y_rand, x_rand+len_rand, y_rand+len_rand) 25 | # return image.crop(box) 26 | return image[box[1]:box[3], box[0]:box[2], :] 27 | 28 | 29 | save_dir = 'data_prepare/net_negative' 30 | 31 | if os.path.exists(save_dir)==False: 32 | os.makedirs(save_dir) 33 | 34 | neg_img_dir = 'imagenet_selected' 35 | for file in os.walk(neg_img_dir): 36 | filenames = file[2] 37 | 38 | for idx, filename in enumerate(filenames): 39 | 40 | filepath = neg_img_dir + '/' + filename 41 | 42 | for i in range(33): 43 | 44 | image_crop = random_crop(filepath) 45 | 46 | savepath = save_dir + '/' + str(i) + filename 47 | 48 | # image_crop_12 = image_crop.resize((15,15)) 49 | if image_crop is None: 50 | continue 51 | if image_crop.shape[0]<10 and image_crop.shape[1]<10: 52 | continue 53 | image_crop = cv2.resize(image_crop, (12, 12)) 54 | 55 | # image_crop_12.save(savepath, 'jpeg') 56 | cv2.imwrite(savepath, np.array(image_crop)) 57 | 58 | print (idx) 59 | ``` 60 | -------------------------------------------------------------------------------- /face_detection/人脸检测——生成矫正人脸——cascade-cnn的思想,-但是mtcnn的效果貌似更赞.md: -------------------------------------------------------------------------------- 1 | 简单粗暴,不多说,直接代码吧:(这个代码实在上篇博客的基础上:[人脸检测——AFLW准备人脸](http://blog.csdn.net/u014365862/article/details/74682464)) 2 | 先要生成AFLW_ann.txt。 3 | ``` 4 | import os 5 | from PIL import Image 6 | from PIL import ImageFile 7 | ImageFile.LOAD_TRUNCATED_IMAGES = True 8 | import cv2 9 | import numpy as np 10 | 11 | 12 | def crop_for_cal(sn, xn, yn, n): 13 | 14 | with open('AFLW_ann.txt','r') as f: 15 | lines = f.readlines() 16 | 17 | save_dir1 = 'data_prepare/cal_positive_'+str(n)+'_12' 18 | save_dir2 = 'data_prepare/cal_positive_'+str(n)+'_24' 19 | save_dir3 = 'data_prepare/cal_positive_'+str(n)+'_48' 20 | 21 | if os.path.exists(save_dir1)==False: 22 | os.makedirs(save_dir1) 23 | if os.path.exists(save_dir2)==False: 24 | os.makedirs(save_dir2) 25 | if os.path.exists(save_dir3)==False: 26 | os.makedirs(save_dir3) 27 | 28 | for idx, line in enumerate(lines): 29 | spl1 = line.strip().split(' ') 30 | image_path = spl1[0] 31 | x = int(spl1[1]) 32 | y = int(spl1[2]) 33 | w = int(spl1[3]) 34 | h = int(spl1[4]) 35 | 36 | x = int(x-xn*w/sn) 37 | y = int(y-yn*h/sn) 38 | w = int(w/sn) 39 | h = int(h/sn) 40 | 41 | # image = Image.open(image_path) 42 | 43 | 44 | image = cv2.imread(image_path) 45 | if image is None: 46 | continue 47 | if x<=0 and y<=0 and w<=0 and h<=0: 48 | continue 49 | box = (x, y, x+w, y+h) 50 | 51 | # patch = image.crop(box) 52 | patch = image[box[1]:box[3], box[0]:box[2], :] 53 | if patch is None: 54 | continue 55 | if patch.shape[0]<10 and patch.shape[1]<10: 56 | continue 57 | 58 | #patch1 = patch.resize((12, 12)) 59 | #patch2 = patch.resize((24, 24)) 60 | #patch3 = patch.resize((48, 48)) 61 | patch1 = cv2.resize(patch, (12, 12)) 62 | patch2 = cv2.resize(patch, (24, 24)) 63 | patch3 = cv2.resize(patch, (48, 48)) 64 | 65 | 66 | spl2 = image_path.split('/') 67 | image_name = spl2[-1] 68 | 69 | save_path1 = save_dir1+'/'+str(idx)+image_name + '.jpg' 70 | save_path2 = save_dir2+'/'+str(idx)+image_name + '.jpg' 71 | save_path3 = save_dir3+'/'+str(idx)+image_name + '.jpg' 72 | 73 | #patch1.save(save_path1, 'jpeg') 74 | #patch2.save(save_path2, 'jpeg') 75 | #patch3.save(save_path3, 'jpeg') 76 | cv2.imwrite(save_path1, np.array(patch1)) 77 | cv2.imwrite(save_path2, np.array(patch2)) 78 | cv2.imwrite(save_path3, np.array(patch3)) 79 | 80 | 81 | if __name__ == '__main__': 82 | 83 | s_set = (0.83, 0.91, 1.0, 1.10, 1.21) 84 | x_set = (-0.17, 0, 0.17) 85 | y_set = (-0.17, 0, 0.17) 86 | n = 0 87 | for x in x_set: 88 | for y in y_set: 89 | for s in s_set: 90 | n = n + 1 91 | crop_for_cal(s, x, y, n) 92 | ``` 93 | -------------------------------------------------------------------------------- /face_detection/人脸检测——矫正人脸生成标签.md: -------------------------------------------------------------------------------- 1 | 直接代码: 2 | ``` 3 | import glob 4 | import random 5 | 6 | size_list = (12, 24, 48) 7 | 8 | for size in size_list: 9 | lines = [] 10 | for i in range(45): 11 | 12 | dir_path = 'data_prepare/cal_positive_' + str(i+1) + '_' + str(size) + '/*.jpg' 13 | 14 | filenames = glob.glob(dir_path) 15 | 16 | filelist = map(lambda x:x+' '+str(i)+'\n', filenames) 17 | lines = lines+filelist 18 | 19 | random.shuffle(lines) 20 | savename = 'cal_' + str(size) + '_list.txt' 21 | with open(savename,'w') as f: 22 | f.writelines(lines) 23 | ``` 24 | -------------------------------------------------------------------------------- /ml_in_action/Perceptron.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from numpy import * 3 | import operator 4 | import os 5 | 6 | 7 | # 原始形式感知机算法 8 | # 下面是一个简单的例子, 帮助理解感知机 9 | def createDataSet(): 10 | # 创建三组数据,及其对应的标签 11 | group = array([[3,3], [4,3], [1,1]]) 12 | labels = [1, 1, -1] # 共分为两类 13 | return group, labels 14 | 15 | # 下面是感知机参数的更新过程, 其实就是按照上一篇的原理实现的: 16 | def perceptronClassify(trainGroup,trainLabels): 17 | global w, b 18 | # 用来终止程序 和 保留最好的w, b; 19 | isFind = False 20 | # 计算样本数量, 用于参数训练更新; 21 | numSamples = trainGroup.shape[0] 22 | # 计算特征的维度, 用于初始化权重; 23 | mLenth = trainGroup.shape[1] 24 | # 开始将权重都初始化为0; 25 | w = [0]*mLenth 26 | b = 0 27 | # 用来标识是否样本都分类成正确,用停止 和 保存最好的权重; 28 | while(not isFind): 29 | # 去每一个样本, 进行判断, 预测模型时候是否将其错误分类; 30 | for i in range(numSamples): 31 | # 按照上一节,误分类点相乘 < 0 32 | if cal(trainGroup[i],trainLabels[i]) <= 0: 33 | print (w, b) 34 | # 更新参数, 这里要注意一下,每次有误分类点, 更新完以后,此for训练结束; 35 | # 重新进入while循环,表明一点发现误分类点后,更新模型,然后再从第一个点开始; 36 | # 这里就好比我们再学习数据结构算法时,各种时间和空间的优化,像动态规划自顶向下 和 被备忘的自底向上; 37 | # 还好比数组中连续累加和最大的序列,可以从O(n^2)优化到O(n); 38 | # 所以个人感觉无论你学什么,只要变成请好好学习数据结构和算法。 39 | update(trainGroup[i],trainLabels[i]) 40 | break #end for loop 41 | # 这地方更巧妙,判断最后一个点, 由上面的逻辑,最后一个点对了,前面的点肯定分对了; 42 | elif i == numSamples-1: 43 | print (w, b) 44 | isFind = True #end while loop 45 | 46 | # 用来判断是不是模型的误分类点的; 47 | def cal(row,trainLabel): 48 | # 设置为全局变量, 这里也可以都写到一类中; 49 | global w, b 50 | res = 0 51 | # 样本每个属性乘以权重 + 偏置, 计算预测值; 52 | # 这里可以理解用样本矩阵的每一行, 也就是样本中一个样本; 53 | for i in range(len(row)): 54 | res += row[i] * w[i] 55 | res += b 56 | # 预测值和真实值相乘, 看是大于0; 还是小于0, 用来判断是不是误分类点; 57 | res *= trainLabel 58 | return res 59 | # 如果是误分类点, 就更新权重; 60 | def update(row,trainLabel): 61 | global w, b 62 | # w[i] = w[i] + 一个样本中的每一个值 * 标签 * 学习率; 这地方学习率可以默认为1了 63 | for i in range(len(row)): 64 | w[i] += trainLabel * row[i] 65 | # 下面是偏置的更新 66 | b += trainLabel 67 | 68 | #import perceptron 69 | g,l = createDataSet() 70 | perceptronClassify(g,l) 71 | print("w, b", w, b) 72 | 73 | # 对上面的模型训练结果进行显示; 74 | import matplotlib.pyplot as plt 75 | from pylab import * 76 | import numpy as np 77 | 78 | group = array([[3,3], [4,3], [1,1]]) 79 | 80 | plt.figure(1) 81 | plt.subplot(111) 82 | x1 = [3, 4] 83 | y1 = [3, 3] 84 | x2 = [1] 85 | y2 = [1] 86 | plt.plot(x1, y1, 'bs') 87 | plt.plot(x2, y2, 'g^') 88 | x = np.arange(-5.0, 5.0, 0.02) 89 | y = - w[0]/w[1] * x - (b) 90 | plt.plot(x, y) 91 | plt.grid(True) 92 | plt.show() 93 | 94 | #################################################################################################### 95 | 96 | from numpy import * 97 | import operator 98 | import os 99 | 100 | # 对偶形式的感知机算法 101 | 102 | def createDataSet(): 103 | 104 | group = array([[3,3], [4,3], [1,1]]) 105 | labels = [1, 1, -1] 106 | return group, labels 107 | 108 | #classify using DualPerception 109 | def dualPerceptionClassify(trainGroup,trainLabels): 110 | global a,b 111 | isFind = False 112 | numSamples = trainGroup.shape[0] 113 | #mLenth = trainGroup.shape[1] 114 | a = [0]*numSamples 115 | b = 0 116 | gMatrix = cal_gram(trainGroup) 117 | while(not isFind): 118 | for i in range(numSamples): 119 | if cal(gMatrix,trainLabels,i) <= 0: 120 | cal_wb(trainGroup,trainLabels) 121 | update(i,trainLabels[i]) 122 | break 123 | elif i == numSamples-1: 124 | cal_wb(trainGroup,trainLabels) 125 | isFind = True 126 | 127 | 128 | # caculate the Gram matrix 129 | def cal_gram(group): 130 | # 样本数量 131 | mLenth = group.shape[0] 132 | gMatrix = zeros((mLenth,mLenth)) 133 | for i in range(mLenth): 134 | for j in range(mLenth): 135 | gMatrix[i][j] = dot(group[i],group[j]) 136 | return gMatrix 137 | 138 | def update(i,trainLabel): 139 | global a,b 140 | a[i] += 1 141 | b += trainLabel 142 | 143 | def cal(gMatrix,trainLabels,key): 144 | global a,b 145 | res = 0 146 | for i in range(len(trainLabels)): 147 | res += a[i]*trainLabels[i]*gMatrix[key][i] 148 | res = (res + b)*trainLabels[key] 149 | return res 150 | 151 | # 下面代码通过a计算出 权重(w)和偏置(b) 152 | def cal_wb(group,labels): 153 | global a,b 154 | w=[0]*(group.shape[1]) 155 | h = 0 156 | for i in range(len(labels)): 157 | h +=a[i]*labels[i] 158 | w +=a[i]*labels[i]*group[i] 159 | print (w,h) 160 | 161 | # import DualPerception 162 | g,l = createDataSet() 163 | dualPerceptionClassify(g,l) 164 | 165 | -------------------------------------------------------------------------------- /ml_in_action/README.md: -------------------------------------------------------------------------------- 1 | 2 | # 机器学习实战代码注释 3 | -------------------------------------------------------------------------------- /ml_in_action/treePlotter.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | ''' 3 | Created on Oct 14, 2010 4 | 5 | @author: Peter Harrington 6 | ''' 7 | import matplotlib.pyplot as plt 8 | 9 | decisionNode = dict(boxstyle="sawtooth", fc="0.8") 10 | leafNode = dict(boxstyle="round4", fc="0.8") 11 | arrow_args = dict(arrowstyle="<-") 12 | 13 | def getNumLeafs(myTree): 14 | numLeafs = 0 15 | firstStr = myTree.keys()[0] 16 | secondDict = myTree[firstStr] 17 | for key in secondDict.keys(): 18 | if type(secondDict[key]).__name__=='dict':#test to see if the nodes are dictonaires, if not they are leaf nodes 19 | numLeafs += getNumLeafs(secondDict[key]) 20 | else: numLeafs +=1 21 | return numLeafs 22 | 23 | def getTreeDepth(myTree): 24 | maxDepth = 0 25 | firstStr = myTree.keys()[0] 26 | secondDict = myTree[firstStr] 27 | for key in secondDict.keys(): 28 | if type(secondDict[key]).__name__=='dict':#test to see if the nodes are dictonaires, if not they are leaf nodes 29 | thisDepth = 1 + getTreeDepth(secondDict[key]) 30 | else: thisDepth = 1 31 | if thisDepth > maxDepth: maxDepth = thisDepth 32 | return maxDepth 33 | 34 | def plotNode(nodeTxt, centerPt, parentPt, nodeType): 35 | createPlot.ax1.annotate(nodeTxt, xy=parentPt, xycoords='axes fraction', 36 | xytext=centerPt, textcoords='axes fraction', 37 | va="center", ha="center", bbox=nodeType, arrowprops=arrow_args ) 38 | 39 | def plotMidText(cntrPt, parentPt, txtString): 40 | xMid = (parentPt[0]-cntrPt[0])/2.0 + cntrPt[0] 41 | yMid = (parentPt[1]-cntrPt[1])/2.0 + cntrPt[1] 42 | createPlot.ax1.text(xMid, yMid, txtString, va="center", ha="center", rotation=30) 43 | 44 | def plotTree(myTree, parentPt, nodeTxt):#if the first key tells you what feat was split on 45 | numLeafs = getNumLeafs(myTree) #this determines the x width of this tree 46 | depth = getTreeDepth(myTree) 47 | firstStr = myTree.keys()[0] #the text label for this node should be this 48 | cntrPt = (plotTree.xOff + (1.0 + float(numLeafs))/2.0/plotTree.totalW, plotTree.yOff) 49 | plotMidText(cntrPt, parentPt, nodeTxt) 50 | plotNode(firstStr, cntrPt, parentPt, decisionNode) 51 | secondDict = myTree[firstStr] 52 | plotTree.yOff = plotTree.yOff - 1.0/plotTree.totalD 53 | for key in secondDict.keys(): 54 | if type(secondDict[key]).__name__=='dict':#test to see if the nodes are dictonaires, if not they are leaf nodes 55 | plotTree(secondDict[key],cntrPt,str(key)) #recursion 56 | else: #it's a leaf node print the leaf node 57 | plotTree.xOff = plotTree.xOff + 1.0/plotTree.totalW 58 | plotNode(secondDict[key], (plotTree.xOff, plotTree.yOff), cntrPt, leafNode) 59 | plotMidText((plotTree.xOff, plotTree.yOff), cntrPt, str(key)) 60 | plotTree.yOff = plotTree.yOff + 1.0/plotTree.totalD 61 | #if you do get a dictonary you know it's a tree, and the first element will be another dict 62 | 63 | def createPlot(inTree): 64 | fig = plt.figure(1, facecolor='white') 65 | fig.clf() 66 | axprops = dict(xticks=[], yticks=[]) 67 | createPlot.ax1 = plt.subplot(111, frameon=False, **axprops) #no ticks 68 | #createPlot.ax1 = plt.subplot(111, frameon=False) #ticks for demo puropses 69 | plotTree.totalW = float(getNumLeafs(inTree)) 70 | plotTree.totalD = float(getTreeDepth(inTree)) 71 | plotTree.xOff = -0.5/plotTree.totalW; plotTree.yOff = 1.0; 72 | plotTree(inTree, (0.5,1.0), '') 73 | plt.show() 74 | 75 | #def createPlot(): 76 | # fig = plt.figure(1, facecolor='white') 77 | # fig.clf() 78 | # createPlot.ax1 = plt.subplot(111, frameon=False) #ticks for demo puropses 79 | # plotNode('a decision node', (0.5, 0.1), (0.1, 0.5), decisionNode) 80 | # plotNode('a leaf node', (0.8, 0.1), (0.3, 0.8), leafNode) 81 | # plt.show() 82 | 83 | def retrieveTree(i): 84 | listOfTrees =[{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}, 85 | {'no surfacing': {0: 'no', 1: {'flippers': {0: {'head': {0: 'no', 1: 'yes'}}, 1: 'no'}}}} 86 | ] 87 | return listOfTrees[i] 88 | 89 | #createPlot(thisTree) 90 | 91 | myTree = retrieveTree(0) 92 | leaf_num = getNumLeafs(myTree) 93 | print ('叶节点的数量:', leaf_num) 94 | 95 | createPlot(myTree) 96 | 97 | myTree['no surfacing'][3] = 'maybe' 98 | print ('myTree', myTree) 99 | createPlot(myTree) 100 | 101 | -------------------------------------------------------------------------------- /tensorflow_in_action/学习笔记TF002_ 怎么安装TensorFlow.md: -------------------------------------------------------------------------------- 1 | 公众号MachineLN,邀请您扫码关注: 2 | 3 | ![image](http://upload-images.jianshu.io/upload_images/4618424-3ef1722341ba72d2?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 4 | 5 | 官网: 6 | https://www.tensorflow.org/install/install_mac 7 | https://www.tensorflow.org/install/install_windows 8 | 9 | 考虑到软件依赖项,依赖冲突。单机建议用Virturalenv,分布式用Docker。解决依赖冲突有以下方式:代码库内部的软件包依赖,依赖库放到代码中,局部引用。重复占用空间,手工更改。用户无法修改。使用依赖环境,虚拟环境。Virturalenv、Anaconda。使用容器,软件、文件系统、运行时、依赖库打包轻量级方案。典型应用有Docker。 10 | 11 | TensorFlow需要用到两个经典库:Jupyter(iPython) Notebook、matplotlib。Jupyter Notebook可以交互式编写可视化结果文档,代码展示,Markdown单元,设计原型,代码写入逻辑块,方便调试脚本特定部分。matplotlib是绘图库,可以实现数据可视化,典型应用Seaborn。 12 | 13 | Virtualenv环境安装(看网络情况,我装了四小时,重试了无数次这两个命令,尤其是第二个) 14 | sudo easy_install pip 15 | sudo pip install --upgrade virtualenv 16 | 17 | 创建虚拟环境目录: 18 | sudo mkdir ~/env 19 | 20 | 创建虚拟环境: 21 | virtualenv --system-site-packages ~/env/tensorflow 22 | 23 | 激活虚拟环境: 24 | source ~/env/tensorflow/bin/activate 25 | 26 | 关闭虚拟环境: 27 | deactivate 28 | 29 | 安装TensorFlow(装了2小时,还是不行): 30 | Python 2.7: pip install --upgrade tensorflow 31 | Python 3.4: pip3 install --upgrade tensorflow 32 | 33 | 最后是把需要的whl下载下来,直接通过pip install 装本地的文件。 34 | 35 | 安装Jupyter、matplotlib(又是两小时。。。) 36 | sudo pip install jupyter 37 | sudo pip install matplotlib 38 | 39 | 其中widgetsnbextension没有办法下载下来装,因为下下来的是3.0.0的,需要的是2.0.0的。 40 | 41 | 装完之后,在Jupyter上跑一个。 42 | 43 | mkdir tf-notebooks 44 | 45 | cd tf-notebooks 46 | jupyter notebook 47 | 48 | 测试一下: 49 | 50 | import tensorflow as tf 51 | import numpy as np 52 | import matplotlib.pyplot as plt 53 | 54 | %matplotlib inline 55 | a = tf.random_normal([2,20]) 56 | sess = tf.Session() 57 | out = sess.run(a) 58 | x,y = out 59 | 60 | plt.scatter(x,y) 61 | plt.show() 62 | 63 | 参考资料: 64 | 《TensorFlow实战》 65 | 《面向机器智能的TensorFlow实践》 66 | 67 | 68 | -------------------------------------------------------------------------------- /tensorflow_in_action/学习笔记TF003_数据流图定义、执行、可视化.md: -------------------------------------------------------------------------------- 1 | 数据流图,有向图,定义计算结构。一组函数链接在一起。每个函数输出传递给级联链上其他函数。利用小数学函数构造数据复杂变换。 2 | 3 | 节点node,对数据所优质运算操作。边edge,向节点输入、输出的数据。指向节点的边为输入,从节点引出的边为输出。边是节点之间的连接,做信息传输。输入可能来自其他数据流图、文件读取、用户输入。 4 | 5 | 输入节点把单个输入传递给大量后继节点。不依赖其他节点信息的节点,互相独立。数据流图输入抽象,操控内部运算细节,客户只需了解输入信息种类。把整个节点序列视为一组输入输出的离散构件。级联运算组可视化更容易,无需关心部件内部具体细节。 6 | 7 | 造成循环依赖(circular dependency)的节点连接不被允许。节点输出是后继节点计算必须输入,节点是后继节点的依赖节点。输出不需要其他节点任何输入,互相独立。依赖关系具有传递性。依赖分为直接依赖和间接依赖。节点输出作为直接或间接依赖节点的输入,因都需要等待对方计算完成,形成循环依赖。设置节点初始值可以让数据流图工作起来,但也会陷入无限循环,程序无法终目,依赖节点无穷大无法追踪依赖信息,数据会导致溢出或使某些计算无意义。通过数据流图有限次复制,并排放置,原始输入传给所有副本,副本输出与输入串接,称为展开(unrolling)。 8 | 9 | 确保只对必要节点执行运算,维护节点的直接依赖节点列表。空栈开始,最终输出节点入栈,输出节点直接依赖节点全部入栈,继续追溯,直到所有依赖节点全部入栈,对栈中节点排序,保证上运行次序,追踪已经完成计算的节点,输出保存在内存,避免重复计算。 10 | 11 | TensorFlow工作流,定义数据流图,运行数据流图。节点被称为Operation(Op)。各Op接收零个或多个输入Tensor对象,输出零个或多个Tensor对象。调用Python构造方法创建Op。 12 | 13 | 确保TensorFlow环境处于活动状态。只有一个终端拥有活动状态的TensorFlow环境。jupyter notebook启动jupyter。新建项目,敲入以下代码: 14 | 15 | import tensorflow as tf #导入TensorFlow库,取别名tf 16 | a = tf.constant(5, name="input_a")#定义节点a,创建常量Op,接收单个张量值5,输出给连接节点,以 input_a标识。 17 | b = tf.constant(3, name="input_b")#定义节点b,创建常量Op,接收单个张量值3,输出给连接节点,以input_b标识。 18 | c = tf.multiply(a,b, name="mul_c")#定义节点c,创建乘法Op,接收两个输入,输出乘积,以mul_c标识。 19 | d = tf.add(a,b, name="add_d")#定义节点d,创建加法Op,接收两个输入,输出求和,以add_d标识。 20 | e = tf.add(c,d, name="add_e")#定义节点e,创建加法Op,接收两个输入,输出求和,以add_e标识。 21 | sess = tf.Session()#创建并启动TensorFlow Session对象。 22 | output = sess.run(e)#Session对象执行节点e,并保存输出结果 23 | writer = tf.summary.FileWriter('./my_graph', sess.graph)#创建并启动summary.FileWriter对象,接收两个参数,一是数据流图磁盘存放路径;二是Session对象graph属性。 24 | writer.close()#关闭summary.FileWriter对象 25 | sess.close()#关闭Session对象 26 | 27 | .constant创建常量Op,接收单个张量值,输出给连接节点,自动将标量值转换为Tensor对象,name参数标识节点。.multiply创建乘法Op,接收两个输入,输出乘积。.add创建加法Op,接收两个输入,输出求和。.sub创建减法Op。.div创建除法Op。.mod创建取模Op。无需定义边,TensofFlow自动绘制连接。TensorFlow Session负责运行时数据流图监督,运行数据流图。.Session()创建并启动TensorFlow Session对象。.run方法执行目标节点,运行必要运算,输出结果。.summary.FileWriter()创建并启动summary.FileWriter对象,接收两个参数,一是字符串输出目录,数据流图磁盘存放路径;二是Session对象graph属性,引用追踪数据流图。summary.FileWriter对象初始化后立即写入数据。 28 | 29 | 退出jupyter,tensorboard --logdir="my_graph"启动TensorBoard服务。在浏览器输入http://0.0.0.0:6006访问TensorBoard服务器。点击Graph标签,即可看到可视化的数据流图。 30 | 31 | ![](http://upload-images.jianshu.io/upload_images/80690-c3b745f5d1ac9ceb?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 32 | ![](http://upload-images.jianshu.io/upload_images/80690-925d8b2dc1aabcf5?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 33 | 34 | 参考资料: 35 | 《面向机器智能的TensorFlow实践》 36 | 37 | 38 | -------------------------------------------------------------------------------- /tensorflow_in_action/学习笔记TF004_张量表示、类型、形状、计算.md: -------------------------------------------------------------------------------- 1 | 张量是N维矩阵抽象。一维张量是向量。二维张量是矩阵,三维或以上称N维张量或N阶张量。 2 | 3 | 输入节点,从接收标量,改为接收向量。.reduce_prod()创建归约乘积Op。reduce_sum()创建归约求和Op。 4 | 5 | 6 | import tensorflow as tf 7 | a = tf.constant([[[1,2,3],[4,5,6]],[[7,8,9],[1,2,3]]], name="input_a") 8 | b = tf.reduce_prod(a, name="prod_b")#定义节点b,创建归约乘积Op,接收一个N维张量输入,输出张量所有分量(元素)的乘积,以prod_b标识。 9 | c = tf.reduce_sum(a, name="sum_c")#定义节点c,创建归约求和Op,接接收一个N维张量输入,输出张量所有分量(元素)的求和,以sum_c标识。 10 | d = tf.add(b,c, name="add_d") 11 | sess = tf.Session() 12 | out = sess.run(d) 13 | writer = tf.summary.FileWriter('./my_graph', sess.graph) 14 | writer.close() 15 | sess.close() 16 | 17 | 18 | 19 | TensorFlow可接收Python数值、布尔值、字符串、数组。单个数值转化为0阶张量(标量)。数值列表转化为1阶张量(向量)。由列表构成的列表转化为2阶张量(矩阵)。 20 | TensorFlow数据类型:float32、float64、int8、int16、int32、int64、uint8、string、bool、cpmples64(实部32位虚部32位的64位复数)、qint8(有符号用于量化Op)、qint32、quint8(无符号用于量化Op)。 21 | 22 | NumPy专为操作N维数组设计的科学计算软件包,是数据科学通用语言。TensorFlow数据类型基于NumPy。任何NumPy数组都可以传递给TensorFlow Op。指定所需数据类型代价最小。NumPy没有与tf.string字符串精确对应的数据类型。TensorFlow可以导入NumPy的字符串数组,但不能在NumPy中显式指定dtype属性。Session.run()方法返回的张量都是NumPy数组。不要用TensorFlow的数据类型初始化NumPy数组。推荐用NumPy手工指定Tensor对象。 23 | 张量Shape属性,表示张量的维(阶)数和每一维的长度。张量形状是包含有序整数集的列表(list)或元组(tuple)。元素数量即维数,元素数值即每一维的长度。.shape()创建获取张量形状Op。 24 | 25 | 26 | 27 | import tensorflow as tf 28 | #指定0阶张量(标量)形状 29 | s_0 = 1 30 | #指定1阶张量(向量)形状 31 | s_1_list = [1,2,3] 32 | s_1_tuple = (1,2,3) 33 | #指定2阶张量(矩阵)形状 34 | s_2 = [[2,3],[2,3]] 35 | #指定任意维数任意长度的张量形状 36 | s_any = None 37 | shape = tf.shape(s_2, name="mystery_shape")#创建获取张量形状Op,接收一个张量,输出张量形状,以mystery_shape标识。 38 | sess = tf.Session() 39 | sess.run(shape) 40 | 41 | 42 | Operation,Op,Tensor对象运算节点,返回张量。在Python中调用创建Op的构造方法,传入所需所有Tensor输入,以及正确创建Op所需属性,返回创建Op的输出(张量)句柄。name属性用描述性字符串指代Op。 43 | 44 | 运算符重载,为了使运算更加简洁。运算符有一个或多个操作对象为Tensor对象,TensorFlow Op被调用,添加到数据流图。-x,.neg(),x中每个元素的相反数。~x,.logical_not(),x中每个元素的逻辑非,只适用dtype为tf.bool的Tensor对象。abc(),.abs(),x中每个元素的绝对值。x+y,.add(),x、y逐元素相加。x-y,.sub(),x、y逐元素相减。x-y,.sub(),x、y逐元素相减。x*y,.multiply(),x、y逐元素相乘。x/y,.div(),x、y逐元素相除,整数张量执行整数除法,浮点数张量执行浮点数除法。x%y,.mod(),逐元素取模。x**y,.pow(),x逐元素为底,y逐元素为指数的幂。xy,.greater(),逐元素计算x>y真值。x>=y,.greater_equal(),逐元素计算x>=y真值。x&y,.logical_and(),逐元素计算x&y真值,元素dtype必须为tf.bool。x|y,.logical_or(),逐元素计算x|y真值,元素dtype必须为tf.bool。x^y,.logical_xor(),逐元素计算x^y真值,元素dtype必须为tf.bool。 45 | 运算符重载无法为Op指定name。==判断两个Tensor对象名是否引用同一个对象。.equal()和.not_equal()判断张量值是否相同。 46 | 47 | 48 | 参考资料: 49 | 《面向机器智能的TensorFlow实践》 50 | 51 | 52 | -------------------------------------------------------------------------------- /tensorflow_in_action/学习笔记TF005_Graph对象、Session对象、占位符.md: -------------------------------------------------------------------------------- 1 | 创建Graph对象,.Graph(),无需接收任何参数。.as_default()访问上下文管理器,添加Op。加载TensorFlow库时,自动创建一个Graph对象作为默认数据流图,Op、Tensor对象自动放置在默认数据流图。多个不依赖模型需要创建多个Graph对象,节点添加到正确的数据流图。不要将默认数据流图和用户创建数据流图混合使用,既存在自定义数据流图,又存在默认数据流图时,应把各自的Op写在with .as_default里。可以从其他TensorFlow脚本加载已定义模型,用Graph.as_graph_def()、tf.import_graph_def()赋给Graph对象。 2 | 3 | TensorFlow Session负责执行数据流图。.Session()构造方法有3个可选参数。target指定执行引擎,默认空字符串,分布式中用于连接不同tf.train.Server实例。graph加载Graph对象,默认None,默认当前数据流图,区分多个数据流图时的执行,不在with语句块内创建Session对象。config指定Session对象配置选项。 4 | .run()方法接收一个参数fetches指定执行对象,任意数据流图元素(Op 或Tensor对象),Tensor对象输出NumPy数组,Op对象输出None。fetches为列表,输出元素对应值列表。三个可选参数feed_dict、options、run_metadata。feed_dict覆盖数据流图Tensor对象值,输入Python字典对象,字典键为被覆盖Tensor对象句柄,值为数字、字符串、列表、NumPy数组,类型与键相同,用于虚构值测试或指定输入值。Session对象找到所需全部节点,顺序执行节点,输出。 5 | 最后需要调用.close()方法释放资源。Session对象作为上下文管理器,离开作用域自动关闭。.as_default()作为作为上下文管理器,作为with语句块默认Session对象,必须手工关闭Session对象。 6 | InteractiveSession运行时作为默认会话。尽量不要用。 7 | 8 | .placeholder Op创建占位符,利用占位节点添加输入,以便数据流图变换、数值复用。dtype参数为数据类型,必须指定。shape参数为张量维数长度,默认为None,可选。name参数为标识符,可选。Session.run()中feed_dict参数,占位符输出句柄为键,传入Tensor对象为值。必须在feed_dict为计算节点每个依赖占位符包含一个健值对。placeholder的值无法计算。 9 | 10 | import tensorflow as tf 11 | import numpy as np 12 | in_default_graph = tf.add(1, 2)#放置在默认数据流图 13 | g1 = tf.Graph()#创建数据流图 14 | g2 = tf.Graph() 15 | default_graph = tf.get_default_graph()#获取默认数据流图句柄 16 | with g1.as_default():#放置在g数据流图 17 | in_graph_g1 = tf.multiply(2, 3)#此Op将添加到Graph对象g1中 18 | with g2.as_default():#放置在g数据流图 19 | in_graph_g2 = tf.div(4, 2)#此Op将添加到Graph对象g2中 20 | with default_graph.as_default():#放置在默认数据流图 21 | also_in_default_graph1 = tf.subtract(5, 2)#此Op将添加到默认数据流图中 22 | also_in_default_graph2 = tf.multiply(also_in_default_graph1, 2)#此Op将添加到默认数据流图中 23 | replace_dict = {also_in_default_graph1: 15} 24 | also_in_default_graph3 = tf.placeholder(tf.int32, shape=[2], name="my_input")#创建指定长度、数据类型的占位tensor 25 | also_in_default_graph4 = tf.reduce_prod(also_in_default_graph3, name="prod_also_in_default_graph4")#占位tensor使用 26 | also_in_default_graph5 = tf.reduce_sum(also_in_default_graph3, name="sum_also_in_default_graph4")#占位tensor使用 27 | also_in_default_graph6 = tf.add(also_in_default_graph4,also_in_default_graph5, name="add_also_in_default_graph6")#占位tensor使用 28 | #with tf.Session(graph=g1) as sess:#离开作用域后自动关闭 29 | # sess.run(in_graph_g1) 30 | sess = tf.Session(graph=tf.get_default_graph())#以默认数据流图创建Session对象 31 | input_dict = {also_in_default_graph3: np.array([5, 3], dtype=np.int32)}#创建传给feed_dict的字典 32 | #sess.run([also_in_default_graph1, also_in_default_graph2], feed_dict=replace_dict)#执行Session对象,将replace_dict赋给feed_dict 33 | sess.run(also_in_default_graph6, feed_dict=input_dict)#将input_dict的值传给占符节点并执行 34 | #with sess.as_default(): 35 | # also_in_default_graph1.eval() 36 | #sess = tf.Session(graph=g1) 37 | #sess.run(in_graph_g1) 38 | #sess = tf.Session(graph=g2) 39 | #sess.run(in_graph_g2) 40 | writer = tf.summary.FileWriter('./my_graph', sess.graph) 41 | writer.close() 42 | sess.close()#关闭Session对象,释放资源 43 | 44 | 45 | ![graph?run=-3.png](http://upload-images.jianshu.io/upload_images/80690-749b3ead9a115510.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 46 | 参考资料: 47 | 《面向机器智能的TensorFlow实践》 48 | 49 | 50 | -------------------------------------------------------------------------------- /tensorflow_in_action/学习笔记TF006_Variable对象、名称作用域.md: -------------------------------------------------------------------------------- 1 | Tensor、Op对象不可变(immutable)。.Variable()构造方法创建Variable对象,包含Session.run()调用中可持久化的可变张量值。Variable对象初值通常为全0、全1或用随机数填充阶数较高张量,创建初值张量Op,.zeros()、.ones()、.random_normal()、.random_uniform(),接收shape参数。 2 | 3 | Graph管理Tensor对象,Session管理Variable对象。Variable对象必须在Session对象内初始化。初始化所有Variable对象,把.global_variables_initializer() Op传给Session.run()。初始化部分Variable对象,把.variables_initializer() Op传给Session.run()。Variable.assign()Op,修改Variable对象,必须在Session对象中运行。.assign_add()创建自增Op,.assign_sub()创建自减Op。不同Session对象独立维护在Graph对象定义的Variable对象值。Optimizer类自动训练机器学习模型,自动修改Variable对象值。创建Variable对象时trainable参数设False,只允许手工修改值。 4 | 5 | import tensorflow as tf 6 | 7 | my_var = tf.Variable(3, name="my_variable")#创建Variable对象 8 | add = tf.add(5, my_var) 9 | mul = tf.multiply(8, my_var) 10 | zeros = tf.zeros([2, 2])#零矩阵 11 | ones = tf.ones([6])#全1向量 12 | uniform = tf.random_uniform([3,3,3], minval=0, maxval=10)#三维张量,元素服从0~10均匀分布 13 | normal = tf.random_normal([3,3,3], mean=0.0, stddev=2.0)#三维张量,元素服从0均值,标准差为2正态分布 14 | trunc = tf.truncated_normal([2,2], mean=5.0, stddev=1.0)#不会返回小于3.0或大于7.0的张量 15 | radom_var = tf.Variable(tf.truncated_normal([2,2]))#默认值0,默认标准差1.0 16 | init_global = tf.global_variables_initializer()#所有Varialbe对象初始化 17 | sess = tf.Session() 18 | sess.run(init_global) 19 | sess.run(add) 20 | 21 | var1 = tf.Variable(1, name="initialize_me") 22 | var2 = tf.Variable(2, name="no_initialize") 23 | init_part = tf.variables_initializer([var1], name="initialize_var1") 24 | sess.run(init_part) 25 | 26 | var_assign = tf.Variable(1) 27 | var_assign_times_two = var_assign.assign(var_assign * 2)#创建赋值Op 28 | init_assign = tf.global_variables_initializer() 29 | sess = tf.Session() 30 | sess.run(init_assign) 31 | sess.run(var_assign_times_two)#2 32 | sess.run(var_assign_times_two)#4 33 | sess.run(var_assign_times_two)#8 34 | sess.run(var_assign.assign_add(1))#自增Op,8+1 35 | sess.run(var_assign.assign_sub(2))#自减Op,9-2 36 | var_idpt = tf.Variable(0)#0 37 | init_idpt = tf.global_variables_initializer() 38 | 39 | sess1 = tf.Session() 40 | sess2 = tf.Session() 41 | sess1.run(init_idpt) 42 | sess1.run(var_idpt.assign_add(5))#0+5 43 | sess2.run(init_idpt) 44 | sess2.run(var_idpt.assign_add(2))#0+2 45 | sess1.run(var_idpt.assign_add(10))#5+10 46 | sess2.run(var_idpt.assign_add(20))#2+20 47 | sess1.run(init_idpt)#0 48 | sess2.run(init_idpt)#0 49 | 50 | not_trainable = tf.Variable(0, trainable=False)#不可自动修改 51 | 52 | with tf.name_scpoe(),名称作用域(name scope)组织数据流图,将Op划分到较大有名称语句块。TensorBoard加载数据流图,名称作用域封装Op。可以把名称作用域嵌在其他名称作用域内。 53 | 54 | import tensorflow as tf 55 | with tf.name_scope("Scope_A"):#建立Scope_A作用域 56 |     a = tf.add(1, 2, name="A_add") 57 |     b = tf.multiply(a, 3, name="A_mul") 58 |      59 | with tf.name_scope("Scope_B"):#建立Scope_B作用域 60 |     c = tf.add(4, 5, name="B_add") 61 |     d = tf.multiply(c, 6, name="B_mul") 62 |      63 | e = tf.add(b, d, name="output") 64 | writer = tf.summary.FileWriter('./name_scope_1', graph=tf.get_default_graph()) 65 | writer.close() 66 | 67 | graph = tf.Graph() 68 | with graph.as_default(): 69 |     in_1 = tf.placeholder(tf.float32, shape=[], name="input_a") 70 |     in_2 = tf.placeholder(tf.float32, shape=[], name="input_b") 71 |     const = tf.constant(3, dtype=tf.float32, name="static_value") 72 |      73 |     with tf.name_scope("Transformation"): 74 |          75 |     with tf.name_scope("A"): 76 |           A_mul = tf.multiply(in_1, const) 77 |           A_out = tf.subtract(A_mul, in_1) 78 |              79 |       with tf.name_scope("B"): 80 |           B_mul = tf.multiply(in_2, const) 81 |           B_out = tf.subtract(B_mul, in_2) 82 |              83 |       with tf.name_scope("C"): 84 |           C_div = tf.div(A_out, B_out) 85 |           C_out = tf.add(C_div, const) 86 |              87 |       with tf.name_scope("D"): 88 |           D_div = tf.div(B_out, A_out) 89 |           D_out = tf.add(D_div, const) 90 |              91 |   out = tf.maximum(C_out, D_out) 92 |              93 | writer = tf.summary.FileWriter('./name_scope_2', graph=graph) 94 | writer.close()             95 | 96 | 97 | ![graph?run=-5.png](http://upload-images.jianshu.io/upload_images/80690-10966d4746599d82.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 98 | 99 | 100 | ![graph?run=-7.png](http://upload-images.jianshu.io/upload_images/80690-b4d79ce1ae7f429d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 101 | 102 | 参考资料: 103 | 《面向机器智能的TensorFlow实践》 104 | 105 | 106 | -------------------------------------------------------------------------------- /tensorflow_in_action/学习笔记TF007_Tensor、Graph、Op、Variable、占位符、Session、名称作用域、Board综合例子.md: -------------------------------------------------------------------------------- 1 | 输入采用占位符,模型接收任意长度向量,随时间计算数据流图所有输出总和,采用名称作用域合理划分数据流图,每次运行保存数据流图输出、累加、均值到磁盘。 2 | 3 | [None]代表任意长度向量,[]代表标量。update环节更新各Variable对象以及将数据传入TensorBoard汇总Op。与交换工作流分开,独立名称作用域包含Variable对象,存储输出累加和,记录数据流图运行次数。独立名称作用域包含TensorBoard汇总数据,tf.scalar_summary Op。汇总数据在Variable对象更新完成后才添加。 4 | 5 | 构建数据流图。 6 | 导入TensorFlow库。Graph类构造方法tf.Graph(),显式创建Graph对象。两个“全局”Variable对象,追踪模型运行次数,追踪模型所有输出累加和。与其他节点区分开,放入独立名称作用域。trainable=False设置明确指定Variable对象只能手工设置。 7 | 模型核心的变换计算,封装到名称作用域"transformation",又划分三个子名称作用域"input"、"intermediate_layer"、"output"。.multiply、.add只能接收标量参数,.reduce_prod、. reduce_sum可以接收向量参数。 8 | 在"update"名称作用域内更新Variable对象。.assign_add实现Variable对象递增。 9 | 在"summaries"名称作用域内汇总数据供TensorBoard用。.cast()做数据类型转换。.summary.scalar()做标量数据汇总。 10 | 在"global_ops"名称作用域创建全局Operation(Op)。初始化所有Variable对象。合并所有汇总数据。 11 | 12 | 运行数据流图。 13 | .Session()启动Session对象,graph属性加载Graph对象,.summary.FileWriter()启动FileWriter对象,保存汇总数据。 14 | 初始化Variable对象。 15 | 创建运行数据流图辅助函数,传入向量,运行数据流图,保存汇总数据。创建feed_dict参数字典,以input_tensor替换a句柄的tf.placeholder节点值。使用feed_dict运行output不关心存储,运行increment_step保存到step,运行merged_summaries Op保存到summary。添加汇总数据到FileWriter对象,global_step参数随时间图示折线图横轴。 16 | 变换向量长度多次调用运行数据流图辅助函数。.flush()把汇总数据写入磁盘。 17 | 18 | 查看数据流图。 19 | Graph标签,变换运算流入update方框,为summaries、variables提供输入,global_ops包含变换计算非关键运算。输入层、中间层、输出层分离。 20 | Scalars标签,summary.scalar对象标签查看不同时间点汇总数据变化。 21 | 22 | 23 | import tensorflow as tf#导入TensorFlow库 24 | #构建数据流图 25 | graph = tf.Graph()#显式创建Graph对象 26 | with graph.as_default():#设为默认Graph对象 27 | with tf.name_scope("variables"):#创建Variable对象名称作用域 28 | global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name="global_step")#记录数据流图运行次数的Variable对象,初值为0,数据类型为32位整型,不可自动修改,以global_step标识 29 | total_output = tf.Variable(0.0, dtype=tf.float32, trainable=False, name="total_output")#追踪模型所有输出累加和的Variable对象,初值为0.0,数据类型为32位浮点型,不可自动修改,以total_output标识 30 | with tf.name_scope("transformation"):#创建变换计算Op名称作用域 31 | with tf.name_scope("input"):#创建独立输入层名称作用域 32 | a = tf.placeholder(tf.float32, shape=[None], name="input_placeholder_a")#创建占位符,接收一个32位浮点型任意长度的向量作为输入,以input_placeholder_a标识 33 | with tf.name_scope("intermediate_layer"):#创建独立中间层名称作用域 34 | b = tf.reduce_prod(a, name="product_b")#创建创建归约乘积Op,接收张量输入,输出张量所有分量(元素)的乘积,以product_b标识 35 | c = tf.reduce_sum(a, name="sum_c")#创建创建归约求和Op,接收张量输入,输出张量所有分量(元素)的求和,以sum_c标识 36 | with tf.name_scope("output"):#创建独立输出层名称作用域 37 | output = tf.add(b, c, name="output")#创建创建求和Op,接收两个标量输入,输出标量求和,以output标识 38 | with tf.name_scope("update"): 39 | update_total = total_output.assign_add(output)#用最新的输出更新Variable对象total_output 40 | increment_step = global_step.assign_add(1)#增1更新Variable对象global_step,记录数据流图运行次数 41 | with tf.name_scope("summaries"):#创建数据汇总Op名称作用域 42 | avg = tf.div(update_total, tf.cast(increment_step, tf.float32), name="average")#计算平均值,输出累加和除以数据流图运行次数,把运行次数数据类型转换为32位浮点型,以average标识 43 | tf.summary.scalar(b'output_summary',output)#创建输出节点标量数据统计汇总,以output_summary标识 44 | tf.summary.scalar(b'total_summary',update_total)#创建输出累加求和标量数据统计汇总,以total_summary标识 45 | tf.summary.scalar(b'average_summary',avg)#创建平均值标量数据统计汇总,以average_summary标识 46 | with tf.name_scope("global_ops"):#创建全局Operation(Op)名称作用域 47 | init = tf.global_variables_initializer()#创建初始化所有Variable对象的Op 48 | merged_summaries = tf.summary.merge_all()#创建合并所有汇总数据的Op 49 | #运行数据流图 50 | sess = tf.Session(graph=graph)#用显式创建Graph对象启动Session会话对象 51 | writer = tf.summary.FileWriter('./improved_graph', graph)#启动FileWriter对象,保存汇总数据 52 | sess.run(init)#运行Variable对象初始化Op 53 | def run_graph(input_tensor):#定义数据注图运行辅助函数 54 | """ 55 | 辅助函数:用给定的输入张量运行数据流图, 56 | 并保存汇总数据 57 | """ 58 | feed_dict = {a: input_tensor}#创建feed_dict参数字典,以input_tensor替换a句柄的tf.placeholder节点值 59 | _, step, summary = sess.run([output, increment_step, merged_summaries], feed_dict=feed_dict)#使用feed_dict运行output不关心存储,运行increment_step保存到step,运行merged_summaries Op保存到summary 60 | writer.add_summary(summary, global_step=step)#添加汇总数据到FileWriter对象,global_step参数时间图示折线图横轴 61 | #用不同的输入用例运行数据流图 62 | run_graph([2,8]) 63 | run_graph([3,1,3,3]) 64 | run_graph([8]) 65 | run_graph([1,2,3]) 66 | run_graph([11,4]) 67 | run_graph([4,1]) 68 | run_graph([7,3,1]) 69 | run_graph([6,3]) 70 | run_graph([0,2]) 71 | run_graph([4,5,6]) 72 | writer.flush()#将汇总数据写入磁盘 73 | writer.close()#关闭FileWriter对象,释放资源 74 | sess.close()#关闭Session对象,释放资源 75 | 76 | 77 | ![WX20170513-142835@2x.png](http://upload-images.jianshu.io/upload_images/80690-e802d7684dae4f6e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 78 | ![graph?run=-8.png](http://upload-images.jianshu.io/upload_images/80690-86abeb9a29c9c27b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 79 | ![graph?run=-9.png](http://upload-images.jianshu.io/upload_images/80690-e9b752d7e8fdae77.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 80 | 81 | 参考资料: 82 | 《面向机器智能的TensorFlow实践》 83 | 84 | 85 | -------------------------------------------------------------------------------- /tensorflow_in_action/学习笔记TF008_机器学习基础 线性回归.md: -------------------------------------------------------------------------------- 1 | 有监督学习,带标注信息输入数据集,标注真实期望输出,训练推断模型,覆盖初始数据集,预测新样本输出。推断模型具体运算步骤代码设置。由给定问题解决模型确定。模型确定,运算固定。相关数据是模型参数,训练过程不断更新,模型学习,调整输出。 2 | 3 | 训练闭环一般结构:初始化模型参数(随机赋值或全0) -> 输入训练数据(样本及期望输出,随机打乱次序) ->训练数据执行推断模型(得到输出) -> 计算损失(输出与期望输出差距) ->调整模型参数(调整参数值,损失最小化,梯度下降算法)。依据学习速率、给定模型、输入数据,大量循环重复。 4 | 5 | 评估阶段,不同测试集(期望输出)模型推断,评估模型数据集损失,了解训练集外推广能力。原始数据集70%用于训练,30%用于评估。 6 | 7 | 初始化变量和模型参数,定义训练闭环运算。计算返回推断模型输出(数据X),计算损失(训练数据X及期望输出Y),读取或生成训练数据X及期望输出Y,训练或调整模型参数(计算总损失),评估训练模型。会话对象启动数据流图,搭建流程。 8 | 9 | 训练模型,多个训练周期更新参数(变量)。tf.train.Saver类保存变量到二进制文件。周期性保存所有变量,创建检查点(checkpoint)文件,从最近检查点恢复训练。启动会话对象前实例化Saver对象,每完成1000次训练迭代或训练结束,调用tf.train.Saver.save方法,创建遵循命名模板my-model{step}检查点文件,保存每个变量当前值,默认只保留最近5个文件,更早的自动删除。tf. train.get_checkpoint_state方法验证有无检查点文件。tf. trainSaver.restore方法恢复变量值。检查是否有检查点文件存在,在开始训练闭环前恢复变量值,根据检查点文件名称恢复全局迭代次数。 10 | 11 | 线性回归,给定数据点集合训练集,找到最吻合线性函数。2D数据线性函数是一条直线。点代表训练数据,线代表模型推断结果。线性回归模型基本原理,Y为待预测值。X为一组独立预测变量样本。W为模型从训练数据学到的参数,每个变量权值。b也是模型从训练数据学到的参数,线性函数常量,模型偏置(bias)。 12 | 13 | 计算损失,总平方误差,模型对训练样本预测值与期望输出之差平方总和。预测输出向量与期望向量之间欧氏距离平方。2D数据集,总平方误差对应数据点垂直方向到所预测回归直线距离平方总和。L2范数或L2损失函数。采用平方避免计算平方根,节省计算量。 14 | 15 | 模型训练运算,梯度下降算法优化模型参数。损失函数值随训练步数增加逐渐减小。 16 | 17 | 18 | import tensorflow as tf 19 | import os 20 | #初始化变量和模型参数,定义训练闭环运算 21 | W = tf.Variable(tf.zeros([2, 1]), name="weights")#变量权值 22 | b = tf.Variable(0., name="bias")#线性函数常量,模型偏置 23 | def inference(X):#计算返回推断模型输出(数据X) 24 | print "function: inference" 25 | return tf.matmul(X, W) + b 26 | def loss(X, Y):#计算损失(训练数据X及期望输出Y) 27 | print "function: loss" 28 | Y_predicted = inference(X) 29 | return tf.reduce_sum(tf.squared_difference(Y, Y_predicted)) 30 | def inputs():#读取或生成训练数据X及期望输出Y 31 | print "function: inputs" 32 | # Data from http://people.sc.fsu.edu/~jburkardt/datasets/regression/x09.txt 33 | weight_age = [[84, 46], [73, 20], [65, 52], [70, 30], [76, 57], [69, 25], [63, 28], [72, 36], [79, 57], [75, 44], [27, 24], [89, 31], [65, 52], [57, 23], [59, 60], [69, 48], [60, 34], [79, 51], [75, 50], [82, 34], [59, 46], [67, 23], [85, 37], [55, 40], [63, 30]] 34 | blood_fat_content = [354, 190, 405, 263, 451, 302, 288, 385, 402, 365, 209, 290, 346, 254, 395, 434, 220, 374, 308, 220, 311, 181, 274, 303, 244] 35 | return tf.to_float(weight_age), tf.to_float(blood_fat_content) 36 | def train(total_loss):#训练或调整模型参数(计算总损失) 37 | print "function: train" 38 | learning_rate = 0.0000001 39 | return tf.train.GradientDescentOptimizer(learning_rate).minimize(total_loss) 40 | def evaluate(sess, X, Y):#评估训练模型 41 | print "function: evaluate" 42 | print sess.run(inference([[80., 25.]]))# ~ 303 43 | print sess.run(inference([[65., 25.]]))# ~ 256 44 | saver = tf.train.Saver()#创建Saver对象 45 | #会话对象启动数据流图,搭建流程 46 | with tf.Session() as sess: 47 | print "Session: start" 48 | tf.global_variables_initializer().run() 49 | X, Y = inputs() 50 | total_loss = loss(X, Y) 51 | train_op = train(total_loss) 52 | coord = tf.train.Coordinator() 53 | threads = tf.train.start_queue_runners(sess=sess, coord=coord) 54 | training_steps = 1000#实际训练迭代次数 55 | initial_step = 0 56 | checkpoin_dir = "./" 57 | ckpt = tf.train.get_checkpoint_state(os.path.dirname(checkpoin_dir)) 58 | if ckpt and ckpt.model_checkpoint_path: 59 | print "checkpoint_path: " + ckpt.model_checkpoint_path 60 | saver.restore(sess, ckpt.model_checkpoint_path)#从检查点恢复模型参数 61 | initial_step = int(ckpt.model_checkpoint_path.rsplit('-', 1)[1]) 62 | for step in range(initial_step, training_steps):#实际训练闭环 63 | sess.run([train_op]) 64 | if step % 10 == 0:#查看训练过程损失递减 65 | print str(step)+ " loss: ", sess.run([total_loss]) 66 | save_file = saver.save(sess, 'my-model', global_step=step)#创建遵循命名模板my-model-{step}检查点文件 67 | print str(step) + " save_file: ", save_file 68 | evaluate(sess, X, Y)#模型评估 69 | coord.request_stop() 70 | coord.join(threads) 71 | saver.save(sess, 'my-model', global_step=training_steps) 72 | print str(training_steps) + " final loss: ", sess.run([total_loss]) 73 | sess.close() 74 | 75 | 76 | 参考资料: 77 | 《面向机器智能的TensorFlow实践》 78 | 79 | 80 | -------------------------------------------------------------------------------- /tensorflow_in_action/学习笔记TF009_对数几率回归.md: -------------------------------------------------------------------------------- 1 | logistic函数,也称sigmoid函数,概率分布函数。给定特定输入,计算输出"success"的概率,对回题回答"Yes"的概率。接受单个输入。多维数据或训练集样本特征,可以用线性回归模型表达式合并成单值。 2 | 3 | 损失函数可以使用平方误差。训练集"Yes"代表100%概率或输出值1的概率。损失刻画特定样本模型分配小于1值概率。"No"概率值0。损失是模型分配样本概率值并取平方。平方误差惩罚与损失同数量级情形。输出与期望相差太远,交叉熵(cross entropy)输出更大值(惩罚)。模型期望输出"Yes"样本预测概率接近0时,罚项值增长到接近无穷大。训练完,模型不可能做出这样的错误预测。TensorFlow提供单个优化步骤sigmoid输出计算交叉熵。 4 | 5 | 信息论,符号字符串每个字符出现概率已知,用香农熵估计字符串每个符号编码所需平均最小位数。符号编码,如果假设其他概率非真实概率,符号编码长度更大。交叉熵以次优编码方案计算同字符串编码平均最小位数。损失函数期望输出概率分布,实际值100%和0,将自定概率作为模型计算输出。sigmoid函数输出概率值。当真实概率等于自定概率,交叉熵值最小。交叉熵越接近熵,自定概率是真实概率更好逼近。模型输出与期望输出越接近,交叉熵越小。 6 | 7 | 从csv文件读取数据,加载解析,创建批次读取张量多行数据,提升推断计算效率。tf.decode_csv() Op将字符串(文本行)转换到指定默认值张量列元组,为每列设置数据类型。读取文件,加载张量batch_size行。属性数据(categorical data),推断模型需要把字符串特征转换为数值型特征。每个属性特征扩展为N维布尔型特征,每个可能取值对应一维。具备属性相应维度取值1。模型对每个可能取值独立加权。单个变量表示只可能两种值属性。所有特征排列矩阵,矩阵转置,每行一样本,每列一特征。输入,调用read_csv,转换读取数据,tf.equal方法检查属性值与常量值是否相等,tf.to_float方法将布尔值转换成数值。tf.stack方法打包所有布尔值进单个张量。 8 | 9 | 训练,度量准确率,正确预测样本总数占全部样本比例。样本输出大于0.5转换为正回答。tf.equal比较预测结果与实际值是否相等。tf.reduce_mean统计所有正确预测样本数,除以批次样本总数,得到正确预测百分比。 10 | 11 | 12 | import tensorflow as tf 13 | import os 14 | #参数变量初始化 15 | W = tf.Variable(tf.zeros([5, 1]), name="weights")#变量权值 16 | b = tf.Variable(0., name="bias")#线性函数常量,模型偏置 17 | def combine_inputs(X):#输入值合并 18 | print "function: combine_inputs" 19 | return tf.matmul(X, W) + b 20 | def inference(X):#计算返回推断模型输出(数据X) 21 | print "function: inference" 22 | return tf.sigmoid(combine_inputs(X))#调用概率分布函数 23 | def loss(X, Y):#计算损失(训练数据X及期望输出Y) 24 | print "function: loss" 25 | return tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=combine_inputs(X), labels=Y))#求平均值 26 | def read_csv(batch_size, file_name, record_defaults):#从csv文件读取数据,加载解析,创建批次读取张量多行数据 27 | filename_queue = tf.train.string_input_producer([os.path.join(os.getcwd(), file_name)]) 28 | reader = tf.TextLineReader(skip_header_lines=1) 29 | key, value = reader.read(filename_queue) 30 | decoded = tf.decode_csv(value, record_defaults=record_defaults)#字符串(文本行)转换到指定默认值张量列元组,为每列设置数据类型 31 | return tf.train.shuffle_batch(decoded, batch_size=batch_size, capacity=batch_size * 50, min_after_dequeue=batch_size)#读取文件,加载张量batch_size行 32 | def inputs():#读取或生成训练数据X及期望输出Y 33 | print "function: inputs" 34 | #数据来源:https://www.kaggle.com/c/titanic/data 35 | #模型依据乘客年龄、性别、船票等级推断是否能够幸存 36 | passenger_id, survived, pclass, name, sex, age, sibsp, parch, ticket, fare, cabin, embarked = \ 37 | read_csv(100, "train.csv", [[0.0], [0.0], [0], [""], [""], [0.0], [0.0], [0.0], [""], [0.0], [""], [""]]) 38 | #转换属性数据 39 | is_first_class = tf.to_float(tf.equal(pclass, [1]))#一等票 40 | is_second_class = tf.to_float(tf.equal(pclass, [2]))#二等票 41 | is_third_class = tf.to_float(tf.equal(pclass, [3]))#三等票 42 | gender = tf.to_float(tf.equal(sex, ["female"]))#性别,男性为0,女性为1 43 | 44 | features = tf.transpose(tf.stack([is_first_class, is_second_class, is_third_class, gender, age]))#所有特征排列矩阵,矩阵转置,每行一样本,每列一特征 45 | survived = tf.reshape(survived, [100, 1]) 46 | return features, survived 47 | def train(total_loss):#训练或调整模型参数(计算总损失) 48 | print "function: train" 49 | learning_rate = 0.01 50 | return tf.train.GradientDescentOptimizer(learning_rate).minimize(total_loss) 51 | def evaluate(sess, X, Y):#评估训练模型 52 | print "function: evaluate" 53 | predicted = tf.cast(inference(X) > 0.5, tf.float32)#样本输出大于0.5转换为正回答 54 | print sess.run(tf.reduce_mean(tf.cast(tf.equal(predicted, Y), tf.float32)))#统计所有正确预测样本数,除以批次样本总数,得到正确预测百分比 55 | #会话对象启动数据流图,搭建流程 56 | with tf.Session() as sess: 57 | print "Session: start" 58 | tf.global_variables_initializer().run() 59 | X, Y = inputs() 60 | total_loss = loss(X, Y) 61 | train_op = train(total_loss) 62 | coord = tf.train.Coordinator() 63 | threads = tf.train.start_queue_runners(sess=sess, coord=coord) 64 | training_steps = 1000#实际训练迭代次数 65 | for step in range(training_steps):#实际训练闭环 66 | sess.run([train_op]) 67 | if step % 10 == 0:#查看训练过程损失递减 68 | print str(step)+ " loss: ", sess.run([total_loss]) 69 | print str(training_steps) + " final loss: ", sess.run([total_loss]) 70 | evaluate(sess, X, Y)#模型评估 71 | import time 72 | time.sleep(5) 73 | coord.request_stop() 74 | coord.join(threads) 75 | sess.close() 76 | 77 | 78 | 参考资料: 79 | 《面向机器智能的TensorFlow实践》 80 | 81 | 82 | -------------------------------------------------------------------------------- /tensorflow_in_action/学习笔记TF010_softmax分类.md: -------------------------------------------------------------------------------- 1 | 公众号MachineLN,邀请您扫码关注: 2 | 3 | ![image](http://upload-images.jianshu.io/upload_images/4618424-3ef1722341ba72d2?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 4 | 5 | 回答多选项问题,使用softmax函数,对数几率回归在多个可能不同值上的推广。函数返回值是C个分量的概率向量,每个分量对应一个输出类别概率。分量为概率,C个分量和始终为1。每个样本必须属于某个输出类别,所有可能样本均被覆盖。分量和小于1,存在隐藏类别;分量和大于1,每个样本可能同时属于多个类别。类别数量为2,输出概率与对数几率回归模型输出相同。 6 | 7 | 变量初始化,需要C个不同权值组,每个组对应一个可能输出,使用权值矩阵。每行与输入特征对应,每列与输出类别对应。 8 | 9 | 鸢尾花数据集Iris,包含4个数据特征、3类可能输出,权值矩阵4X3。 10 | 11 | 训练样本每个输出类别损失相加。训练样本期望类别为1,其他为0。只有一个损失值被计入,度量模型为真实类别预测的概率可信度。每个训练样本损失相加,得到训练集总损失值。TensorFlow的softmax交叉熵函数,sparse_softmax_cross_entropy_with_logits版本针对训练集每个样本只对应单个类别优化,softmax_cross_entropy_with_logits版本可使用包含每个样本属于每个类别的概率信息的训练集。模型最终输出是单个类别值。 12 | 13 | 不需要每个类别都转换独立变量,需要把值转换为0~2整数(总类别数3)。tf.stack创建张量,tf.equal把文件输入与每个可能值比较。tf.argmax找到张量值为真的位置。 14 | 15 | 推断过程计算测试样本属于每个类别概率。tf. argmax函数选择预测输出值最大概率类别。tf.equal与期望类别比较。tf.reduce_meen计算准确率。 16 | 17 | 18 | import tensorflow as tf#导入TensorFlow库 19 | import os#导入OS库 20 | W = tf.Variable(tf.zeros([4, 3]), name="weights")#变量权值,矩阵,每个特征权值列对应一个输出类别 21 | b = tf.Variable(tf.zeros([3], name="bias"))#模型偏置,每个偏置对应一个输出类别 22 | def combine_inputs(X):#输入值合并 23 | print "function: combine_inputs" 24 | return tf.matmul(X, W) + b 25 | def inference(X):#计算返回推断模型输出(数据X) 26 | print "function: inference" 27 | return tf.nn.softmax(combine_inputs(X))#调用softmax分类函数 28 | def loss(X, Y):#计算损失(训练数据X及期望输出Y) 29 | print "function: loss" 30 | return tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=combine_inputs(X), labels=Y))#求平均值,针对每个样本只对应单个类别优化 31 | def read_csv(batch_size, file_name, record_defaults):#从csv文件读取数据,加载解析,创建批次读取张量多行数据 32 | filename_queue = tf.train.string_input_producer([os.path.join(os.getcwd(), file_name)]) 33 | reader = tf.TextLineReader(skip_header_lines=1) 34 | key, value = reader.read(filename_queue) 35 | decoded = tf.decode_csv(value, record_defaults=record_defaults)#字符串(文本行)转换到指定默认值张量列元组,为每列设置数据类型 36 | return tf.train.shuffle_batch(decoded, batch_size=batch_size, capacity=batch_size * 50, min_after_dequeue=batch_size)#读取文件,加载张量batch_size行 37 | def inputs():#读取或生成训练数据X及期望输出Y 38 | print "function: inputs" 39 | #数据来源:https://archive.ics.uci.edu/ml/datasets/Iris 40 | #iris.data改为iris.csv,增加sepal_length, sepal_width, petal_length, petal_width, label字段行首行 41 | sepal_length, sepal_width, petal_length, petal_width, label =\ 42 | read_csv(100, "iris.csv", [[0.0], [0.0], [0.0], [0.0], [""]]) 43 | #转换属性数据 44 | label_number = tf.to_int32(tf.argmax(tf.to_int32(tf.stack([ 45 | tf.equal(label, ["Iris-setosa"]), 46 | tf.equal(label, ["Iris-versicolor"]), 47 | tf.equal(label, ["Iris-virginica"]) 48 | ])), 0))#将类名称转抽象为从0开始的类别索引 49 | features = tf.transpose(tf.stack([sepal_length, sepal_width, petal_length, petal_width]))#特征装入矩阵,转置,每行一样本,每列一特征 50 | return features, label_number 51 | def train(total_loss):#训练或调整模型参数(计算总损失) 52 | print "function: train" 53 | learning_rate = 0.01 54 | return tf.train.GradientDescentOptimizer(learning_rate).minimize(total_loss) 55 | def evaluate(sess, X, Y):#评估训练模型 56 | print "function: evaluate" 57 | predicted = tf.cast(tf.arg_max(inference(X), 1), tf.int32)#选择预测输出值最大概率类别 58 | print sess.run(tf.reduce_mean(tf.cast(tf.equal(predicted, Y), tf.float32)))#统计所有正确预测样本数,除以批次样本总数,得到正确预测百分比 59 | with tf.Session() as sess:#会话对象启动数据流图,搭建流程 60 | print "Session: start" 61 | tf.global_variables_initializer().run() 62 | X, Y = inputs() 63 | total_loss = loss(X, Y) 64 | train_op = train(total_loss) 65 | coord = tf.train.Coordinator() 66 | threads = tf.train.start_queue_runners(sess=sess, coord=coord) 67 | training_steps = 1000#实际训练迭代次数 68 | for step in range(training_steps):#实际训练闭环 69 | sess.run([train_op]) 70 | if step % 10 == 0:#查看训练过程损失递减 71 | print str(step)+ " loss: ", sess.run([total_loss]) 72 | print str(training_steps) + " final loss: ", sess.run([total_loss]) 73 | evaluate(sess, X, Y)#模型评估 74 | coord.request_stop() 75 | coord.join(threads) 76 | sess.close() 77 | 78 | 79 | 参考资料: 80 | 《面向机器智能的TensorFlow实践》 81 | 82 | 83 | -------------------------------------------------------------------------------- /tensorflow_in_action/学习笔记TF011_多层神经网络.md: -------------------------------------------------------------------------------- 1 | 线性回归、对数几率回归模型,本质上是单个神经元。计算输入特征加权和。偏置视为每个样本输入特征为1权重,计算特征线性组合。激活(传递)函数 计算输出。线性回归,恒等式(值不变)。对数几率回归,sigmoid。输入->权重->求和->传递->输出。softmax分类含C个神经元,每个神经元对应一个输出类别。 2 | 3 | XOR异或运算,无法通过线性模型解决。sigmoido类型神经元要求数据线性可分。2D数据存在直线,高维数据存在超平面,把不同类别样本分隔。 4 | 5 | 在神经网络输入和输出之间插入更多神经元,解决非线性可分问题。输入层->隐含层(hidden layer)->输出层->输出。隐含层使网络可以对输入数据提出更多问题。隐含层每个神经元对应一个问题,依据问题回答最终决定输出结果。隐含层在数据分布图允许神经网络绘制以一条以上分隔线。每条分隔线向输入数据划分提出问题,所有相等输出划分到单个区域。深度学习,添加更多隐含层,可采用不同类型连接,使用不同激活函数。 6 | 7 | 梯度下降法,找到函数极值点。学习,改进模型参数,大量训练,损失最小化。梯度下降法寻找损失函数极值点。梯度输出偏导数向量,每个分量对应函数对输入向量相应分量偏导。求偏导,当前变量外所有变量视为常数,用单变量求导法则。偏导数度量函数输出相对特定输入变量的变化率,当输入变量值变化,输出值的变化。损失函数输入变量指模型权值,不是实际数据集输入特征。相对于推断模型每个权值。 8 | 梯度输出向量表明每个位置损失函数增长最快方向,在函数每个位置向哪个方向移动函数值可增长。点表示权值当前值。梯度向右箭头表示为增加损失需向右移动,简头长度表示向右移动函数值增长量。反方向移动,损失函数值减少。直到梯度模为0,达到损失函数极小值点。 9 | 学习速率(learning rate)缩放梯度。梯度向量长度在损失函数单元中,缩放与权值相加。学习速率是超参数(hyperparameter),模型手工可配置设置,需指定正确值。太小,需要多轮迭代。太大,超调(overshooting),永远找不到极小值点。用tf.summary.scalar函数在TensorBoard查看损失函数值变化曲线。 10 | 局部极值点问题,通过权值随机初始化,增加靠近全局最优点附近开始下降机会。损失函数所有极值点接近等价。 11 | tf.gradients方法,符号计算推导指定流图步骤梯度以张量输出。梯度下降法取决输入数据形状及问题特点。 12 | 13 | 误差反向传播算法,计算损失函数相对网络权值偏导,每层导数都是后一层导数与前一层导输出积。前馈,从输入开始,逐一计算隐含层输出,直到输出层。计算导数,从输出层逐一反向传播。复用所有已完成计算元素。 14 | 15 | Sigmoid隐含层,softmax输出层以及带反向传播梯度下降,是最基础构件。 16 | 17 | 参考资料: 18 | 《面向机器智能的TensorFlow实践》 19 | 20 | 21 | -------------------------------------------------------------------------------- /tensorflow_in_action/学习笔记TF012_卷积网络简述.md: -------------------------------------------------------------------------------- 1 | ImageNet http://www.image-net.org ,图像标注信息数据库。每年举办大规模视觉识别挑战赛(ILSVRC)。基于ImageNet数据库构建完成目标自动检测分类任务系统。2012年,SuperVision提交卷积神经网络(CNN)。 2 | 3 | CNN可用于任意类型数据张量(各分量与相关分量有序排列在多维网格),当前主要用于计算机视觉。语音识别,输入按录音时间顺序排列声音频率单行网络张量。图像宽高次序排列网格像素分量张量。 4 | 5 | 训练CNN模型数据集Stanford's Gogs Dataset: http://vision.stanford.edu/aditya86/ImageNetDogs/ 。包含不同品种狗图像及品种标签。模型目标:给定一幅图像,预测狗品种。大量非训练集图像创建测试集。数据集:训练集、测试集、验证集。数据集中大部分构成训练集。测试集了解模型对未训练数据表现。交叉验证集比较客观,对图像预处理(对比度调整、栽剪)划分原始数据集,用完全相同输入流水线。 6 | 7 | 卷积神经网络至少包含一个层(tf.nn.conv2d)。计算输入f与一组可配置卷积核g的卷积,生成层输出。卷积核(滤波器)应用张量所有点,输入张量上滑动卷积核生成过滤波处理张量。图像每个元素应用特殊卷积核,输出刻画所有边缘新图像。输入张量是图像,张量每个点对应像素红、绿、蓝色值。卷积核遍历图像像素,边缘像素卷积输出值增大。神经元簇依据训练模式激活。训练,多个不同层级联,梯度下降法变体调节卷积核(滤波器)权值。 8 | 9 | CNN架构,卷积层(tf.nn.conv2d)、非线性变换层(tf.nn.relu)、池化层(tf.nn.max_pool)、全连接层(tf.nn.matmul)。突出重要信息,忽略噪声。批量加载图像,同时处理多幅图像。数据结构包含卷积运算整批图像全部信息。TensorFlow输入流水线(读取解码文件)针对整批数据多幅图像处理专门格式,图像所需信息([image_batch_size,image_height,image_width,image_channels])。 10 | 11 | 12 | import tensorflow as tf 13 | image_batch = tf.constant([ 14 | [#第1幅图像 15 | [[0, 255, 0], [0, 255, 0], [0, 255, 0]], 16 | [[0, 255, 0], [0, 255, 0], [0, 255, 0]] 17 | ], 18 | [#第2幅图像 19 | [[0, 0, 255], [0, 0, 255], [0, 0, 255]], 20 | [[0, 0, 255], [0, 0, 255], [0, 0, 255]] 21 | ] 22 | ]) 23 | image_batch.get_shape() 24 | sess = tf.Session() 25 | sess.run(image_batch)[0][0][0] 26 | 27 | 28 | 第1组维度图像数量。第2组维度图像高度。第3组维度图像宽度。第4组维度颜色通道数量。每个像素索引映射图像宽高维度。 29 | 30 | 参考资料: 31 | 《面向机器智能的TensorFlow实践》 32 | 33 | 34 | -------------------------------------------------------------------------------- /tensorflow_in_action/学习笔记TF014_卷积层、激活函数、池化层、归一化层、高级层.md: -------------------------------------------------------------------------------- 1 | CNN神经网络架构至少包含一个卷积层 (tf.nn.conv2d)。单层CNN检测边缘。图像识别分类,使用不同层类型支持卷积层,减少过拟合,加速训练过程,降低内存占用率。 2 | 3 | TensorFlow加速所有不同类弄卷积层卷积运算。tf.nn.depthwise_conv2d,一个卷积层输出边接到另一个卷积层输入,创建遵循Inception架构网络 Rethinking the Inception Architecture for Computer Vision 4 | https://arxiv.org/abs/1512.00567 。tf.nn.separable_conv2d,规模较大模型不牺牲准确率加速训练,规模小模型快速收敛但准确率低。tf.nn.conv2d_transpos,卷积核用于新特征图,每部分填充卷积核相同值,卷积核遍历新图像,重叠部分相加。斯坦福大学课程CS231n Winter 2016:Lecture 13。 5 | 6 | 激活函数与其他层输出生成特征图,对某些运算结果平滑(微分),为神经网络引入非线性(输入输出曲线关系),刻画输入复杂变化,训练复杂模型。激活函数主要因素,单调,输出随输入增长,可用梯度下降法找局部极值点;可微分,定义域内任意一点有导数,输出可用梯度下降法。 7 | tf.nn.relu,修正线性单元,斜坡函数。分段线性,输入非负输出相同,输入为负输出为0。不受“梯度消失”影响,取值范围[0, +∞]。较大学习速率时,易受饱和神经元影响。损失信息但性能突出。输入秩1张量(向量),小于0置0,其余分量不变。 8 | tf.sigmoid,只接收浮点数,返回区间[0.0, 1.0]内的值。输入值较大返回接近1.0,输入值较小返回接近0.0。适用于真实输出位于[0.0, 1.0]。输入接近饱和或变化剧烈,输出范围缩减成为问题。输入0,输出0.5,sigmoid函数值域中间点。 9 | tf.tanh,双曲正切函数,值域[-1.0, 1.0],有输出负值能力。值域中间点为0.0。网络下层期待输入为负值或0.0,会有问题。 10 | tf.nn.dropout,依据可配置概率输出设0.0。适合少量随机性有助于训练。keep_prob参数指定输出保持概率。每次执行,不同输出。丢弃输出设为0.0。 11 | 12 | 池化层减少过拟合,减小输入尺寸,提高性能。输入降采样,为后续层保留重要信息。池化层减小尺寸效率比tf.nn.conv2d高。 13 | tf.nn.max_pool,跳跃遍历张量,卷积核覆盖元素最大数值作卷积结果。适合输入数据灰度与图像重要性相关。输入为前一层输出,非直接图像。跨度strides使用image_height、image_width遍历输入。只保留输入张量最大元素。最大池化(max-pooling),利用接受域(卷积核)完成。2X2接受域,单个通路最小数量降采样。1X1接受域,输出输入相同。 14 | tf.nn.avg_pool,跳跃遍历张量,卷积核覆盖各深度值取平均。适合卷积核重要,实现值缩减。如输入张量宽度高度大,深度小。 15 | 16 | tf.nn.relu是无界函数,归一化识别高频特征。tf.nn.local_response_normalization(tf.nn.lrn),局部响应归一化,给定向量,每个分量被depth_radius覆盖输入加权和除。输入保持在可接受范围。考虑每个值重要性。归一化输出调整到区间[-1.0, 1.0]。 17 | 18 | 高级层减少代码冗余,遵循最佳实践。 19 | tf.contrib.layers.convolution2d。权值初始化、偏置初始化、可训练变量输出、偏置相加、添加激活函数。卷积核,可训练变量。权值初始化用于卷积核首次运行值填充(tf.truncated_normal)。简单元组形式表示卷积核高度和宽度。输入图像,tf.image.convert_image_dtype,调整各分量表示颜色值。TensorFlow要求浮点型描述图像颜色,分量在[0, 1]。 20 | tf.contrib.layers.fully_connected。全连接层,每个输入输出存在连接。CNN最后一层常是全连接层。TensorFlow全连接层格式,tf.matmul(features,weight)+bias。输入张量与输出层每个神经元连接。 21 | 22 | 原始输入需要传递给输入层。目标识别与分类输入层tf.nn.conv2d。 23 | 24 | 25 | import tensorflow as tf 26 | features = tf.range(-2, 3) 27 | print features 28 | sess = tf.Session() 29 | print sess.run([features, tf.nn.relu(features)]) 30 | features2 = tf.to_float(tf.range(-1, 3)) 31 | print features2 32 | print sess.run([features2, tf.sigmoid(features2)]) 33 | print sess.run([features2, tf.tanh(features2)]) 34 | features3 = tf.constant([-0.1, 0.0, 0.1, 0.2]) 35 | print features3 36 | print sess.run([features3, tf.nn.dropout(features3, keep_prob=0.5)]) 37 | batch_size = 1 38 | input_height = 3 39 | input_width = 3 40 | input_channels = 1 41 | layer_input = tf.constant([ 42 | [ 43 | [[1.0], [0.2], [1.5]], 44 | [[0.1], [1.2], [1.4]], 45 | [[1.1], [0.4], [0.4]] 46 | ] 47 | ]) 48 | print layer_input 49 | kernel = [batch_size, input_height, input_width, input_channels] 50 | print kernel 51 | max_pool = tf.nn.max_pool(layer_input, kernel, [1, 1, 1, 1], "VALID") 52 | print max_pool 53 | print sess.run(max_pool) 54 | layer_input2 = tf.constant([ 55 | [ 56 | [[1.0], [1.0], [1.0]], 57 | [[1.0], [0.5], [0.0]], 58 | [[0.0], [0.0], [0.0]] 59 | ] 60 | ]) 61 | print layer_input2 62 | avg_pool = tf.nn.avg_pool(layer_input2, kernel, [1, 1, 1, 1], "VALID") 63 | print avg_pool 64 | print sess.run(avg_pool) 65 | layer_input3 = tf.constant([ 66 | [ 67 | [[1.], [2.], [3.]] 68 | ] 69 | ]) 70 | print layer_input3 71 | lrn = tf.nn.local_response_normalization(layer_input3) 72 | print lrn 73 | print sess.run([layer_input3, lrn]) 74 | image_input = tf.constant([ 75 | [ 76 | [[0., 0., 0.], [255., 255., 255.], [254., 0., 0.]], 77 | [[0., 191., 0.], [3., 108., 233.], [0., 191., 0.]], 78 | [[254., 0., 0.], [255., 255., 255.], [0., 0., 0.]] 79 | ] 80 | ]) 81 | print image_input 82 | conv2d = tf.contrib.layers.convolution2d( 83 | image_input, 84 | num_outputs=4, 85 | kernel_size=(1,1), 86 | activation_fn=tf.nn.relu, 87 | stride=(1,1), 88 | trainable=True) 89 | print conv2d 90 | sess.run(tf.global_variables_initializer()) 91 | print sess.run(conv2d) 92 | features4 = tf.constant([ 93 | [[1.2], [3.4]] 94 | ]) 95 | print features4 96 | fc = tf.contrib.layers.fully_connected(features4, num_outputs=2) 97 | print fc 98 | sess.run(tf.global_variables_initializer()) 99 | print sess.run(fc) 100 | 101 | 102 | 参考资料: 103 | 《面向机器智能的TensorFlow实践》 104 | 105 | 106 | -------------------------------------------------------------------------------- /tensorflow_in_action/学习笔记TF017_自然语言处理、RNN、LSTM.md: -------------------------------------------------------------------------------- 1 | 自然语言处理 (NLP)问题都是序列化的。前馈神经网络,在单次前馈中对到来数据处理,假定所有输入独立,模式丢失。循环神经网络(recurrent neural network,RNN)对时间显式建模神经网络。RNN神经元可接收其他神经元加权输入。RNN神经元可与更高层建立连接,也可与更低层建立连接。隐含活性值在同一序列相邻输入间被记忆。2006年 LSTM。语音识别、语音合成、手写连体字识别、时间序列预测、图像标题生成、端到端机器翻译。 2 | 3 | RNN由神经元和连接权值构成任意有向图。输入神经元(input neuron)拥有“到来”连接,活性值由输入数据设置。输出神经元(output neuron)是数据流图一组可读取预测结果神经元。所有其他神经元为隐含神经元(hidden neuron)。每个时间步,通过设置输入神经元为网络提供输入序列下一帧。隐含活性值作为下一个时间步附加输入。RNN当前隐含活性值为状态。序列最开始设置值0空状态。RNN状态依赖当前输入和上一状态。状态与序列所有前输入都间接相关,工作记忆(woring memory)。RNN权值矩阵定义执行程序,决定隐含活性值输入,不同活性值整合新活性值输出。sigmoid激活函数 RNN 2006年被证明图录完备(Turing-complete)。给定正确权值,RNN可完成任意计算程序相同计算。不存在找到完美权值方法,可用梯度下降法得到次好结果。 4 | 5 | 优化RNN,沿时间输展开,用优化前馈网络相同方式优化。复制序列神经元,连接在副本传递,移除循环边接而不改计算语义。相邻时间步权值相同强度。随时间反向传播(Back-Propagation Through Time,BPTT),返回时间相关误差对权值(包括联结相邻副本权值)偏导。联结权值(tied weight)梯度相加。 6 | 7 | 循环神经网络常见映射:序列分类、序列生成、序列标注、序列翻译。序列标注(sequential labelling),序列作为输入,训练网络为每帧数据产生正确输出,一个序列到另一个序列等长映射。序列分类(sequential classification),每个序列输入对应一个类别标签,可仅选择上一帧输出训练RNN,更新权值时误差流经所有时间步收集集成有用信息。序列生成(sequential generation),给定一个类别标签,输出反馈给网络作为下一步输入,生成序列。单个向量视为信息稠密表示。序列翻译(sequential translation),域中序列编码,最后隐含活性值解码为另一个域中序列。输入输出概念层次有差异,两个不同RNN,第一个模型最后活性值初始化第二个模型。单个网络,序列后传入特殊符号输入,通知网络停止编码,开始解码。 8 | 9 | 带输出投影RNN网络结构,全连接隐含单元,映射输入输出。所有隐含单元都为输出,堆叠前馈层。隐含单元和输出单元不同激活函数。 10 | 11 | TensorFlow支持RNN各种变体,tf.nn.rnn_cell。tensor flow.models.rnn中tf.nn.dynamic_rnn实现RNN动力学。接收循环网络定义,输入序列批数据。所有序列等长。返回保存每个时间步输出和隐含状态两个张量。从tensor flow.models.rnn导入rnn_cell和rnn。输入数据维数为batch_size*sequence_length*frame_size。不希望限制批次大小,第1维尺寸可以设None。rnn_cell.BasicRNNCell 创建基础RNN。rnn.dynamic_rnn 定义sequence_length步模拟RNN运算。定义RNN,沿时间轴展开,加载数据,选择TensorFlow优化器训练网络,tf.train.RMSPropOptimizer、tf.train.AdamOptimizer。 12 | 13 | 长时依赖性,网络记住含有许多后续不相关帧的序列第一帧。长序列,基础RNN展开网络深度非常大,层数非常多,每一层反向传播算法将来自网络上一层误差乘以局部偏导。如果大多数局部偏导远小于1,梯度每层变小,指数衰减,最终消失。如果很多偏导大于1,梯度值急剧增大。误差项包含相乘项权值矩阵转置。RNN相邻时间步联结一起,权值局部偏导都小于1或大于1,RNN每个权值都向相同方向缩放,梯度消失、爆炸问题突出。数值优化,浮点精度对梯度值产生影响。长短时记忆网络(long-short term memory,LSTM)RNN架构解决方案。 14 | 15 | LSTM专门解决梯度消失、爆炸问题。学习长时依赖关系的RNN事实标准。将RNN普通神经元替换为内部拥有少量记忆LSTM单元(LSTM Cell)。联结一起,内部状态记忆时间步误差。LSTM内部状态有固定权值为1自连接,线性激活函数,局部偏导始终为1。反向传播,常量误差传输子(constant error carousel)在时间步携带误差不发生梯度消失或爆炸。内部状态随时间步传递误差,LSTM环绕门(surrounding gates)负责学习,非线性激活函数(sigmoid)。原始LSTM单元,一种门学习对到来活性值缩放,另一种门学习输出活性值缩放,学习包含或忽略新输入,学习给其他单元传递特征。单元输入送入不同权值门。可以把循环神经网络用为规模更大网络架构组成部分。 16 | LSTMCell类可替换BasicRNNCell类,一个完整的LSTM层。输入非线性->输入门->状态->输出非线性->输出门。 17 | 18 | LSTM流行变种,添加对内部循环连接比例缩放遗忘门(forget gate),网络学会遗忘,内部循环连接局部偏导变成遗忘门活性值,可取非1值。当上下文重要,遗忘门保持关闭状态。输入非线性->输入门->状态->遗忘门->输出非线性->输出门。 19 | 20 | 添加窥视孔连接(peephole connection),门能看到单元状态。当精确时间选择和间隔时有益。TensorFlow LSTM层传入use-peepholes=Trues标记激活窥视孔连接。 21 | 22 | 门限循环单元(Gated Recurrent Unit,GRU),架构简单,更少计算量,没有输出门,输入和遗忘门整合单独更新门(update gate)。更新门决定内部状态与候选活性值融合比例。重置门(reset gate)和新输入确定部分隐含状态计算得到候选活性值。TensorFlow GRU层对应GRUCell类。只需要单元数目参数。输入->候选活性值->更新门->重置门->状态。 23 | 24 | 全连接隐含单元RNN,训练期间把不需要权值置0。最常见做法,两层或多层全连接RNN相互堆叠,信息只能在两层之间向上流动,多层RNN权值数目少,学习到更多抽象特征。 25 | 26 | 27 | 参考资料: 28 | 《面向机器智能的TensorFlow实践》 29 | 30 | 31 | -------------------------------------------------------------------------------- /tensorflow_in_action/学习笔记TF024_TensorFlow实现Softmax Regression(回归)识别手写数字.md: -------------------------------------------------------------------------------- 1 | TensorFlow实现Softmax Regression(回归)识别手写数字。MNIST(Mixed National Institute of Standards and Technology database),简单机器视觉数据集,28X28像素手写数字,只有灰度值信息,空白部分为0,笔迹根据颜色深浅取[0, 1], 784维,丢弃二维空间信息,目标分0~9共10类。数据加载,data.read_data_sets, 55000个样本,测试集10000样本,验证集5000样本。样本标注信息,label,10维向量,10种类one-hot编码。训练集训练模型,验证集检验效果,测试集评测模型(准确率、召回率、F1-score)。 2 | 3 | 算法设计,Softmax Regression训练手写数字识别分类模型,估算类别概率,取概率最大数字作模型输出结果。类特征相加,判定类概率。模型学习训练调整权值。softmax,各类特征计算exp函数,标准化(所有类别输出概率值为1)。y = softmax(Wx+b)。 4 | 5 | NumPy使用C、fortran,调用openblas、mkl矩阵运算库。TensorFlow密集复杂运算在Python外执行。定义计算图,运算操作不需要每次把运算完的数据传回Python,全部在Python外面运行。 6 | 7 | import tensor flow as tf,载入TensorFlow库。less = tf.InteractiveSession(),创建InteractiveSession,注册为默认session。不同session的数据、运算,相互独立。x = tf.placeholder(tf.float32, [None,784]),创建Placeholder 接收输入数据,第一参数数据类型,第二参数代表tensor shape 数据尺寸。None不限条数输入,每条输入为784维向量。 8 | 9 | tensor存储数据,一旦使用掉就会消失。Variable在模型训练迭代中持久化,长期存在,每轮迭代更新。Softmax Regression模型的Variable对象weights、biases 初始化为0。模型训练自动学习合适值。复杂网络,初始化方法重要。w = tf.Variable(tf.zeros([784, 10])),784特征维数,10类。Label,one-hot编码后10维向量。 10 | 11 | Softmax Regression算法,y = tf.nn.softmax(tf.matmul(x, W) + b)。tf.nn包含大量神经网络组件。tf.matmul,矩阵乘法函数。TensorFlow将forward、backward内容自动实现,只要定义好loss,训练自动求导梯度下降,完成Softmax Regression模型参数自动学习。 12 | 13 | 定义loss function描述问题模型分类精度。Loss越小,模型分类结果与真实值越小,越精确。模型初始参数全零,产生初始loss。训练目标是减小loss,找到全局最优或局部最优解。cross-entropy,分类问题常用loss function。y预测概率分布,y'真实概率分布(Label one-hot编码),判断模型对真实概率分布预测准确度。cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))。定义placeholder,输入真实label。tf.reduce_sum求和,tf.reduce_mean每个batch数据结果求均值。 14 | 15 | 定义优化算法,随机梯度下降SGD(Stochastic Gradient Descent)。根据计算图自动求导,根据反向传播(Back Propagation)算法训练,每轮迭代更新参数减小loss。提供封装优化器,每轮迭代feed数据,TensorFlow在后台自动补充运算操作(Operation)实现反向传播和梯度下降。train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)。调用tf.train.GradientDescentOptimizer,设置学习速度0.5,设定优化目标cross-entropy,得到训练操作train_step。 16 | 17 | tf.global_variables_initializer().run()。TensorFlow全局参数初始化器tf.golbal_variables_initializer。 18 | 19 | batch_xs,batch_ys = mnist.train.next_batch(100)。训练操作train_step。每次随机从训练集抽取100条样本构成mini-batch,feed给 placeholder,调用train_step训练样本。使用小部分样本训练,随机梯度下降,收敛速度更快。每次训练全部样本,计算量大,不容易跳出局部最优。 20 | 21 | correct_prediction = tf.equal(tf.argmax(y,1), tf.argmzx(y_,1)),验证模型准确率。tf.argmax从tensor寻找最大值序号,tf.argmax(y,1)求预测数字概率最大,tf.argmax(y_,1)找样本真实数字类别。tf.equal判断预测数字类别是否正确,返回计算分类操作是否正确。 22 | 23 | accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32)),统计全部样本预测正确度。tf.cast转化correct_prediction输出值类型。 24 | 25 | print(accuracy.eval({x: mnist.test.images,y_: mnist.test.labels}))。测试数据特征、Label输入评测流程,计算模型测试集准确率。Softmax Regression MNIST数据分类识别,测试集平均准确率92%左右。 26 | 27 | TensorFlow 实现简单机器算法步骤: 28 | 1、定义算法公式,神经网络forward计算。 29 | 2、定义loss,选定优化器,指定优化器优化loss。 30 | 3、迭代训练数据。 31 | 4、测试集、验证集评测准确率。 32 | 33 | 定义公式只是Computation Graph,只有调用run方法,feed数据,计算才执行。 34 | 35 | from tensorflow.examples.tutorials.mnist import input_data 36 | mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) 37 | print(mnist.train.images.shape, mnist.train.labels.shape) 38 | print(mnist.test.images.shape, mnist.test.labels.shape) 39 | print(mnist.validation.images.shape, mnist.validation.labels.shape) 40 | import tensorflow as tf 41 | sess = tf.InteractiveSession() 42 | x = tf.placeholder(tf.float32, [None, 784]) 43 | W = tf.Variable(tf.zeros([784, 10])) 44 | b = tf.Variable(tf.zeros([10])) 45 | y = tf.nn.softmax(tf.matmul(x, W) + b) 46 | y_ = tf.placeholder(tf.float32, [None, 10]) 47 | cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) 48 | train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) 49 | tf.global_variables_initializer().run() 50 | for i in range(1000): 51 | batch_xs, batch_ys = mnist.train.next_batch(100) 52 | train_step.run({x: batch_xs, y_: batch_ys}) 53 | correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) 54 | accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 55 | print(accuracy.eval({x: mnist.test.images, y_: mnist.test.labels})) 56 | 57 | 58 | 参考资料: 59 | 《TensorFlow实战》 60 | 61 | 62 | -------------------------------------------------------------------------------- /tensorflow_in_action/学习笔记TF026_多层感知机.md: -------------------------------------------------------------------------------- 1 | 隐含层,指除输入、输出层外,的中间层。输入、输出层对外可见。隐含层对外不可见。理论上,只要隐含层节点足够多,只有一个隐含层,神经网络可以拟合任意函数。隐含层越多,越容易拟合复杂函数。拟合复杂函数,所需隐含节点数,随隐含层数量增多指数下降。 2 | 3 | 过拟合,模型预测准确率在训练集上升,在测试集下降。泛化性不好,模型记忆当前数据特征,不具备推广能力。参数太多。Hinton教授团队,Dropout。随便丢弃部分输出数据节点。创造新随机样本,增大样本量,减少特征数量,防止过拟合。bagging方法,对特征新种采样。 4 | 5 | SGD参数难调试,SGD设置不同学习速率,结果可能差异巨大。神经网络很多局部最优解可以达到比较好分类效果,全局最优反而容易过拟合。Adagrad、Adam、Adadelta自适应方法,减轻调试参数负担。SGD需要调试学习速率、Momentum、Nesterov参数。 6 | 7 | 梯度弥散(Gradient Vanishment)。Sigmoid函数具有限制性,输出数值在0〜1,最符合概率输出定义。非线性Sigmoid函数,信号特征空间映射,中央区信号增益大,两侧区信息增益小。中央区像神经元兴奋态,两侧区像神经元抑制态。训练时,重要特征放中央区,非重要特征放两侧区。Sigmoid比最初期线性激活函数y=x,阶梯激活函数y=-1(x<0)|y=1(x>=0)、y=0(x<0)|y=1(x>=0)好。Sigmoid函数反向传播梯度值在多层传递指级急剧减小,根据训练数据反馈更新神经网络参数非常缓慢,不起训练作用。 8 | 9 | ReLU,非线性函数y=max(0,x),坐标轴上折线,当x<=0,y=0,x>0,y=x。人脑阈值响应机制,信号超过某个阈值,神经元兴奋激活状态,平时抑制状态。ReLU很好传递梯度,多层反向传播,梯度不会大幅缩小,适合很深神经网络,不需要无监督逐层初始化权重。ReLU变化,单侧抑制,相对宽阁兴奋边界,稀疏激活性。神经元同时激活1~4%,选择性响应很少部分输入信号,屏蔽大量不相关信号,更高效提取重要特征。传统Sigmoid函数接近一半神经元被激活。Softplus,单侧抑制,没有稀疏激活性。ReLU及变种(EIU,PReLU,RReLU)为最注流激活函数。输出层一般用Sigmoid函数,最接近概率输出分布。 10 | 11 | 隐含层可以解决XOR问题,用曲线划分两类样本。隐含层越多,原有特征越抽象变换。是多层神经网络(多层感知机 MLP)功能。 12 | 13 | 网络神经加上隐含层,使用Dropout、自适应学习速率Adagrad,解决梯度弥散激活函数ReLU。 14 | 15 | 载入TensorFlow,加载MNIST数据集,创建Interactive Session。 16 | 17 | 隐含层参数设置Variable初始化。in_units输入节点数,h1_units隐含层输出节点数设300(200〜1000区别不大)。W1隐含层权重初始化截断正态分布标准差0.1,b1偏置设0。模型激活函数ReLU,正态分布给参数加噪声,打破完全对称避免0梯度。偏置赋小非零值避免dead neuron(死亡神经元)。最后输出层Softmax,权重W2偏置b2初始化0。Sigmoid,0附近最敏感,梯度最大。 18 | 19 | 训练和预测,Dropout比率keep_prob(保留节点概率)不同。训练小于1。预测等于1。Dropout比率为计算图输入,定义placeholder。 20 | 21 | 定义模型结构。tf.nn.relu(tf.matmul(x,W1+b1)),实现激活函数为ReLU的hidden1隐含层,y=relu(W1x+b1)。tf.nn.dropout实现Dropout,随机置0分部节点。keep_prob参数,保留数据不置为0比例,训练应小于1,制造随机性,防止过拟合,预测等于1,用全部特征预测样本类别。输出层Softmax。 22 | 23 | 定义算法公式,神经网络forward计算。定义损失函数(交叉信息熵)和选择优化器(自适应优化器Adagrad),优化loss,学习速率0.3,使用tf.train.AdagradOptimizer 。Adadelta、Adam优化器。 24 | 25 | 训练,keep_prob计算图输入,训练时设0.75,保留75%节点,其余25%置0。越复杂越大规模神经网络,Dropout效果越显著。隐含层,需要更多训练迭代优化模型参数。3000个bacth,每个bacth100条样本,30万样本。相当全数据集5轮epoch迭代。增大循环次数,准确率略有提高。 26 | 27 | 准确率评测,加入keep_prob输入,等于1。 28 | 29 | 没有隐含层Softmax Regression,直接从图像像素推断是哪个数字,没有特征抽象过程。多层神经网络隐含层,组合高阶特征或组件,再组合成数字,实现精准匹配分类。隐含层输出高阶特征组件可以复用,每一类判别、概率输出共享。 30 | 31 | 全连接神经网络(Fully Connected Network,FCN,MLP的另一种说法)局限,很深网络,很多隐藏节点,很大迭代轮数,也难达到99%以上准确率。 32 | 33 | # Create the model 34 | from tensorflow.examples.tutorials.mnist import input_data 35 | import tensorflow as tf 36 | mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) 37 | sess = tf.InteractiveSession() 38 | in_units = 784 39 | h1_units = 300 40 | W1 = tf.Variable(tf.truncated_normal([in_units, h1_units], stddev=0.1)) 41 | b1 = tf.Variable(tf.zeros([h1_units])) 42 | W2 = tf.Variable(tf.zeros([h1_units, 10])) 43 | b2 = tf.Variable(tf.zeros([10])) 44 | x = tf.placeholder(tf.float32, [None, in_units]) 45 | keep_prob = tf.placeholder(tf.float32) 46 | hidden1 = tf.nn.relu(tf.matmul(x, W1) + b1) 47 | hidden1_drop = tf.nn.dropout(hidden1, keep_prob) 48 | y = tf.nn.softmax(tf.matmul(hidden1_drop, W2) + b2) 49 | # Define loss and optimizer 50 | y_ = tf.placeholder(tf.float32, [None, 10]) 51 | cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) 52 | train_step = tf.train.AdagradOptimizer(0.3).minimize(cross_entropy) 53 | # Train 54 | tf.global_variables_initializer().run() 55 | for i in range(3000): 56 | batch_xs, batch_ys = mnist.train.next_batch(100) 57 | train_step.run({x: batch_xs, y_: batch_ys, keep_prob: 0.75}) 58 | # Test trained model 59 | correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) 60 | accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 61 | print(accuracy.eval({x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})) 62 | 63 | 64 | 参考资料: 65 | 《TensorFlow实战》 66 | 67 | 68 | -------------------------------------------------------------------------------- /tensorflow_in_action/学习笔记TF027_卷积神经网络.md: -------------------------------------------------------------------------------- 1 | 卷积神经网络(Convolutional Neural Network,CNN),可以解决图像识别、时间序列信息问题。深度学习之前,借助SIFT、HoG等算法提取特征,集合SVM等机器学习算法识别图像。 2 | 3 | SIFT,缩放、平移、旋转、视角转变、亮度调整畸变的一定程度内,具有不变性。有局限性,ImageNet ILSVRC比赛最好结果错误率在26%以上,常年难以突破。 4 | 5 | 卷积神经网络提取特征效果更好,分类训练时自动提取最有效特征。卷积神经网络CNN,降低图像数据预处理要求,避免复杂特征工程。CNN使用图像原始像素输入,对缩放、平移、旋转畸变具有不变性,强泛化性。CNN卷积权值共享结构,大幅减少神经网络参数量,防止过拟合,降低神经网络模型复杂度。延时神经网络TDNN,时间权值共享,降低学习时间序列信号复杂度。 6 | 7 | 感受野(Receptive Field),每个视觉神经元只会处理一小块区域视觉图像。神经认知机(Neocognitron),两类神经元,抽取特征S-cells对应主流卷积神经网络卷积核滤波操作,抗形变C-cells对应激活函数、最大池化(Max-Pooling)操作。LeCun LeNet CNN首个成功多层训练网络结构。卷积神经网络利用空间结构关系减少学习参数量,提高反向传播算法训练效率。 8 | 9 | 第一个卷积层,接受图像像素级输入,每个卷积操作只处理一小块图像。卷积变化后传到后面网络。每一层卷积(滤波器),提取数据最有效特征。提取图像最基础特征,组合抽像更高阶特征。 10 | 11 | 一般卷积神经网络多个卷积层构成。每个卷积层,图像多个不同卷积核滤波,加偏置(bias),提取局部特征,每个卷积核映射一个新2D图像,卷积核滤波输出结果,非线性激活函数处理(ReLU),激活函数结果池化操作(降采样),最大池化,保留最显著特征,提升模型畸变容忍能力。可以加LRN(Local Response Normalization 局部响应归一化层),Batch Normalizations。 12 | 13 | 卷积核权值共享,卷积层多个不同卷积核,卷积核对应滤波后映射新图像,同一新图像每个像素来自完全相同卷积核。降低模型复杂度,减轻过拟合,降低计算量。 14 | 15 | 图像空间有组织结构,每个像素点与空间周围像素点有紧密联系,与太遥远像素点少联系,即感受野。每个感受野只接受一小块区域信号。小块区域内像素互相关联,每个神经元不需要接收全部像素点信息,只接收局部像素点输入,再将所有神经元收到局部信息综合起来得到全局信息。将全连接模型改为局部连接,从隐含层每个隐含节点和全部像素相连,改为每个隐含节点连接局部像素节点。 16 | 17 | 局部连接方式卷积操作,默认每个隐含节点参数完全一样。不再担心隐含节点数量和图片大小,参数量只跟卷积核大小有关。权值共享。一个卷积核只能提取一种卷积核滤波结果,只能提取一种图片特征。每个卷积核滤波图像是一类特征映射,一个Feature Map。一般,第一个卷积层100个卷积核已经充足。 18 | 19 | 卷积,不管图片尺寸,训练权值只与卷积核大小、数量有关,可以用非常少参数量处理任意大小图片。每个卷积层提取特征,在后面层抽象组合更高阶特征,多层抽象卷积网络表达能力强,效率高。隐含节点数量没有下降,隐含节点数量只跟卷积步长有关。隐含节点数量=输入像素数量/(步长X步长)。 20 | 21 | 卷积神经网络,局部连接(Local Connection)、权值共享(Weight Sharing)、池化层(Pooling)降采样(Down-Sampling)。局部连接、权值共享降低参数量,训练复杂度下降,减轻过拟合。权值共享,卷积网络平移容忍性。池化层降低输出参数量,模型轻度形变容忍性,提高泛化能力。训练中自动完成特征提取抽象,同时模式分类,降低图像识别难度。 22 | 23 | LeNet5 始于1994年,深层卷积神经网络。Yann LeCun。可训练参数卷积层,用少量参数在图像多个位置提取相似特征。如果图像独立像素直接作输入,利用不到图像很强的空间相关性。每个卷积层包含卷积、池化、非线性激活函数。卷积提取空间特征。降采样(Subsample)平均池化层(Average Pooling)。双曲正切(Tanh)或S型(Sigmoid)激活函数。MLP最后分类器。层间稀疏连接减少计算复杂度。 24 | 25 | State-of-the-art。LeNet5奠定现代卷积神经网络基石。LeNet5,输入图像,三个卷积层,一个全连接层,一个高斯连接层。第一个卷积层C1有6个卷积核,卷积核尺寸为5x5,共(5x5+1)x6=156个参数。1个bias。2x2平均池化层S2降采样。Sigmoid激活函数非线性处理。第二个卷积层C3,卷积核尺寸5x5,16个卷积核,16个Feature Map。第二个池化层S4,2x2降采样。第三个卷积层C5,120个卷积核,卷积大小5x5,输入5x5,构成全连接,可以算全连接层。F6全连接层,84个隐含节点,激活函数Sigmoid。最后一层,欧式径向基函数(Euclidean Radial Basis Function)单元组成,输出最后分类结果。 26 | 27 | 参考资料: 28 | 《TensorFlow实战》 29 | 30 | -------------------------------------------------------------------------------- /tensorflow_in_action/学习笔记TF028_实现简单卷积网络.md: -------------------------------------------------------------------------------- 1 | 载入MNIST数据集。创建默认Interactive Session。 2 | 3 | 初始化函数,权重制造随机噪声打破完全对称。截断正态分布噪声,标准差设0.1。ReLU,偏置加小正值(0.1),避免死亡节点(dead neurons)。 4 | 5 | 卷积层函数,tf.nn.conv2d,TensorFlow 2 维卷积函数,参数x输入,W卷积参数,卷积核尺寸,channel个数,卷积核数量(卷积层提取特征数量)。Strides卷积模板移动步长,全1代表不遗漏划过图片每一个点。Padding代表边界处理方式,SAME边界加Padding,卷积输出、输入保持同样尺寸。 6 | 7 | 池化层函数,tf.nn.max_pool,TensorFlow 最大池化函数。2x2最大池化,2x2像素块降为1x1像素。最大池化保留原始像素块灰度值最高像素,保留最显著特征。strides设横竖方向2步长。 8 | 9 | 定义输入placeholder,x特征,y真实label。卷积神经网络空间结构信息,1D输入向量,转为2D图片结构。尺寸[-1,28,28,1]。-1代表样本数量不固定。1代表颜色通道数量。tf.reshape tensor变形函数。 10 | 11 | 第一个卷积层,卷积函数初始化,weights、bias。[5,5,1,32]代表卷积核尺寸5x5,1个颜色通道,32个不同卷积核。使用conv2d函数卷积操作,加偏置,使用ReLU激活函数非线性处理。使用最大池化函数max_pool_2x2池化操作卷积输出结果。 12 | 13 | 第二个卷积层,卷积核64个,提取64种特征。经历两次步长2x2最大池化,边长只有1/4,图片尺寸28x28变7x7.第二个卷积层卷积核数量64,输出tensor尺寸7x7x64。使用tf.reshape函数对第二个卷积层输出tensor变形,转成1D向量,连接一个全连接层,隐含节点1024,使用ReLU激活函数。 14 | 15 | 使用Dropout层减轻过拟合。Dropout,通过一个placeholder传入keep_prob比率控制。训练时,随机丢弃部分节点数据减轻过拟合,预测时保留全部数据追求最好预测性能。 16 | 17 | Dropout层输出连接Softmax层,得到最后概率输出。 18 | 19 | 定义损失函数cross_entropy。优化器使用Adam,给予较小学习速率1e-4。 20 | 21 | 定义评测准确率操作。 22 | 23 | 训练,初始化所有参数,设置训练时Dropout的keep_prob比率0.5.使用大小50的mini-batch,进行20000次训练迭代,样本数量100万。每100次训练,评测准确率,keep_prob设1,实时监测模型性能。 24 | 25 | 全部训练完成,测试集全面测试,得到整体分类准确率。 26 | 27 | 99.2%准确率,卷积网络对图像特征提取抽象,卷积核权值共享。 28 | 29 | from tensorflow.examples.tutorials.mnist import input_data 30 | import tensorflow as tf 31 | mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) 32 | sess = tf.InteractiveSession() 33 | def weight_variable(shape): 34 | initial = tf.truncated_normal(shape, stddev=0.1) 35 | return tf.Variable(initial) 36 | def bias_variable(shape): 37 | initial = tf.constant(0.1, shape=shape) 38 | return tf.Variable(initial) 39 | 40 | def conv2d(x, W): 41 | return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') 42 | def max_pool_2x2(x): 43 | return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], 44 | strides=[1, 2, 2, 1], padding='SAME') 45 | 46 | x = tf.placeholder(tf.float32, [None, 784]) 47 | y_ = tf.placeholder(tf.float32, [None, 10]) 48 | x_image = tf.reshape(x, [-1,28,28,1]) 49 | 50 | W_conv1 = weight_variable([5, 5, 1, 32]) 51 | b_conv1 = bias_variable([32]) 52 | h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) 53 | h_pool1 = max_pool_2x2(h_conv1) 54 | W_conv2 = weight_variable([5, 5, 32, 64]) 55 | b_conv2 = bias_variable([64]) 56 | h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) 57 | h_pool2 = max_pool_2x2(h_conv2) 58 | W_fc1 = weight_variable([7 * 7 * 64, 1024]) 59 | b_fc1 = bias_variable([1024]) 60 | h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) 61 | h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) 62 | keep_prob = tf.placeholder(tf.float32) 63 | h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) 64 | W_fc2 = weight_variable([1024, 10]) 65 | b_fc2 = bias_variable([10]) 66 | y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) 67 | cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1])) 68 | train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) 69 | correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1)) 70 | accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 71 | tf.global_variables_initializer().run() 72 | for i in range(20000): 73 | batch = mnist.train.next_batch(50) 74 | if i%100 == 0: 75 | train_accuracy = accuracy.eval(feed_dict={ 76 | x:batch[0], y_: batch[1], keep_prob: 1.0}) 77 | print("step %d, training accuracy %g"%(i, train_accuracy)) 78 | train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5}) 79 | print("test accuracy %g"%accuracy.eval(feed_dict={ 80 | x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})) 81 | 82 | 参考资料: 83 | 《TensorFlow实战》 84 | 85 | 86 | -------------------------------------------------------------------------------- /tensorflow_in_action/学习笔记TF042_TF.Learn、分布式Estimator、深度学习Estimator.md: -------------------------------------------------------------------------------- 1 | TF.Learn,TensorFlow重要模块,各种类型深度学习及流行机器学习算法。TensorFlow官方Scikit Flow项目迁移,谷歌员工Illia Polosukhin、唐源发起。Scikit-learn代码风格,帮助数据科学从业者更好、更快适应接受TensorFlow代码。囊括许多TensorFlow代码、设计模式,用户更快搭建机器学习模型实现应用。避免大量代码重复,把精力放在搭建更精确模型。与其他contrib模块无逢结合。 2 | 3 | 分布式Estimator。Estimator,各种各样机器学习、深度学习类。可以直接用这些高阶类,也可以根据实际应用需求快速创建子类。graph_actions模块,Estimator在训练、评估模型复杂分布式逻辑被实现、浓缩,不需要复杂Supervisor、Coordinator分布式训练具体实现细节、逻辑。 4 | 5 | Estimator接受自定义模型,函数答名(入参字段->返回字段):(1)(features,targets)->(predictions,loss,train_op)。(2)(features,targets,mode)->(predictions,loss,train_op)。(3)(features,targets,mode,params)->(predictions,loss,train_op)。 6 | 7 | 自定义模型接受两个参数:features和targets。features,数据特征。targets数据特征每行目标或分类标识。tf.one_hot对targets独热编码(One-hot Encoding)。layers.stack叠加多层layers.fully_connected完全连接深度神经网络,每层分别10、20、10个隐藏节点,不同层转换、训练,得到新数据特征。models.logistic_regression_zero_init加一层,0初始参数值逻辑回归模型,得到预测值、损失值。contrib.layers.optimize_loss函数优化损失值,根据需要选择不同优化函数和学习速率。optimize_loss训练算子(Training Operator),每次训练迭代优化模型参数和决定模型发展方向。返回预测值、预测概率,或其中一个。 8 | 9 | iris数据分类。Scikit-learn datasets引入数据,cross_validation数据分训练、评估。my_model放learn.Estimator,Scikit-learn风格fit、predict函数。快速定义自己的模型函数,直接利用Estimator各种功能,直接分布式模型训练,不用担心实现细节。 10 | 11 | 模式(Mode)定义函数,常用模式training、evaluation、prediction,可以在ModeKeys找到。加条件语句实现复杂逻辑。params调节参数,fit函数可以给更多参数。 12 | 13 | 建立机器学习Estimator。BaseEstimator最抽象最基本实现TensorFlow模型训练、评估类。fit()模型训练,partial_fit()线上训练,evaluate()评估模型,predict()使用模型预测新数据。graph_actions复杂逻辑模型训练、预测。SuperVisor、Coordinator、QueueRunner,分布式训练、预测。learn.DataFeeder、learn.DataFrame类自动识别、处理、迭代不同类型数据。estimators.tensor_signature对数据进行兼容性判断(稀疏张量Sparse Tensor),数据读入更方便、稳定。BaseEstimator对learn.monitors及模型存储进行初始化设置。learn.monitors监测模型训练。 14 | 15 | BaseEstimator,_get_train_ops()、_get_eval_ops()、_get_predict_ops()子类实现。 16 | 17 | Estimator,_get_train_ops()接受features、targets参数,自定义模型函数返回Operation、损失Tensor Tuple,在每个训练迭代优化模型参数。非监督学习模型Estimator,忽略targets。 18 | 19 | _get_eval_ops(),BaseEstimator子类自定义metrics评估每个模型训练迭代。contrib.metrics。自定义metrics函数返回一个Tensor对象Python字黄代表评估Operation,每次迭代用到。 20 | 21 | 自定义模型对新数据预测、计算损失值,ModeKeys EVAL表明函数只在评估用。contrib.metrics模块,streaming_mean对loss计算平均流,之前计算过平均值加这次迭代损失值再计算平均值。 22 | 23 | _get_predict_ops()实现自定义预测。对预测结果进一步处理。预测概率转换简单预测结果,概率平滑加工(Smooting)。函数返回Tensor对象Python字典代表预测Operation。Estimator predict()函数,Estimator分布式功能。非监督模型,类似Sckkit-learn transform()函数。 24 | 25 | 逻辑回归(LogisticRegressor),Estimator提供绝大部分实现,LogisticRegressor只需提供自己的metrics(AUC、accuracy、precision、recall,处理二分类问题),快速在LogiticRegressor基础写子类实现个性化二分类Estimator,不需要关心其他逻辑实现。 26 | 27 | TF.Learn 随机森林模型TensorForestEstimator许多细节实现在contrib.tensor_forest。只利用、暴露高阶需要用到成分到TensorForestEstimator。超参数通过contrib.tensor_forest.ForestHParams传到构造函数params,构造函数params.fill()建造随机森林TensorFlow图,tensor_forest.RandomForestGraphs。 28 | 29 | 实现复杂,需要高效率,细节用C++实现单独Kernel。_get_predict_ops()函数,tensor_forest内部C++实现data_ops.ParseDataTensorOrDict()函数检测、转换读入数据到可支持数据类型,RandomForestGraphs inference_graph函数得到预测Operation。 30 | 31 | _get_train_ops()、_get_eval_ops()函数分别调用RandomForestGraphs.trainning_loss()、RandomForestGraphs.onference_graph()函数,data_ops.ParseDataTensorOrDict、data_ops.ParseLabelTensorOrDict分别检测、转换features、targets到兼容数据类型。 32 | 33 | 调节RunConfig运行时参数。RunConfig,TF.Learn类,调节程序运行时参数。num_cores选择使用核数量,num_ps_replicas调节参数服务器数量,gpu_memory_fraction控制使用GPU存储百分比。 34 | 35 | RunConfig master参数,指定训练模型主服务器地址,task设置任务ID,每个任务ID控制一个训练模型参数服务器replica。 36 | 37 | 初始化一个RunConfig对象,传进Estimator。RunConfig参数默认值在本地运行简单模型,只用一个任务ID,80%GPU存储参数传进Estimator。运行时参数会自动运用,不用担心ConfigProto、GPUOptions细节。快速改变参数实现分布式模型训练、参数服务器使用。 38 | 39 | Experiment,简单易用建立模型实验类,建模所需所有信息,Estimator、训练数据、评估数据、平估指标、监督器、评估频率。可以选择当地运行,可以和RunConfig配合分布式试验。LearnRunner,方便做实验。 40 | 41 | tf.app.flags定义可以从命令行传入参数,数据、模型、输出文件路径、训练、评估步数。schedule试验类型。local_run()当地试验。run_std_server()标准服务器试验。master_grpc_url主要GRPC TensorFlow服务器。num_parameter_servers参数服务器数量。 42 | 43 | 建立Experiment对象函数,FLAGS建立RunConfig,机器学习模型Estimator,建立广度深度结合分类器(DNNLinearCombinedClassifier)。input_train_fn、input_test_fn,数据来源、提供训练、评估数据。 44 | 45 | create_experiment_fn()函数传入LearnRunner进行不同类型试验,当地、服务器试验。试验结果存储到不同路径。 46 | 47 | 深度学习Estimator。TF.Learn包含简单易用深度神经网络Estimator。分类问题DNNClassifier。_input_fn()建立数据,layers模块建立特征列。 48 | 49 | 特征列、每层隐藏神经单元数、标识类别数传入DNNClassifier,迅速建立深度神经网络模型。 50 | 51 | fit()、evaluate()方法模型训练、评估。 52 | 53 | 每行数据都有权重。DNNClassfier,指定一列为权重列,自动分配到训练过程。四行数据,每行不同权重。权重列、特征列放入features。 54 | 55 | DNNClassifier表明权重列列名 w,特征列列名x(x转换特征列)。 56 | 57 | 传入自定义metrics方程_my_metric_op(),操作predictions、targets进行metrics计算。只考虑二分类问题,tf.slice()剪切predictions第二列作预测值。 58 | 59 | tf.slice()传入输入矩阵input,剪切开始元素begin,剪切Tensor形状size,size[i]代表第i个维度想剪切矩阵shape。 60 | 61 | 根据需求任意在predictions、targets操作实现想要metrics计算,evaluate()传入metrics函数,TF.Learn根据metrics评估模型。 62 | 63 | evaluate()可以提供多个metrics,_my_metric_op自定义,tr.contrib自带。 64 | 65 | optimizer提供自定义函数,定义自己的优化函 ,包含指数递减学习率。 66 | 67 | tf.contrib.framework.get_or_create_global_step()得到目前模型训练到达全局步数。tf.train.exponential_decay()对学习率指数递减,避免爆炸梯度。 68 | 69 | 广度深度模型,DNNLinearCombinedClassifier。谷歌广泛用在各种机器学习应用,深度神经网络和逻辑回归结合,不同特征通过两种不同方式结合,更能体现应用意义和更有效推荐结果。类似Kaggle竞赛Ensemble。 70 | 71 | 更多参数,与DNNClassifier、LinearClassifier不同特征列选择。 72 | 73 | gender、education、relationship、workclass转换为FeatureColumn。分wide_columns、deep_columns。wide_columns用在LinearClassifier,deep_columns用在DNNClassifier。分别传入DNNLinearCombinedClassifier建立广度深度模型。具有线性特征,也具有深度神经网络特征。 74 | 75 | 参考资料: 76 | 《TensorFlow实战》 77 | 78 | 79 | -------------------------------------------------------------------------------- /tensorflow_in_action/学习笔记TF043_TF.Learn 机器学习Estimator、DataFrame、监督器Monitors.md: -------------------------------------------------------------------------------- 1 | 线性、逻辑回归。input_fn()建立简单两个特征列数据,用特证列API建立特征列。特征列传入LinearClassifier建立逻辑回归分类器,fit()、evaluate()函数,get_variable_names()得到所有模型变量名称。可以使用自定义优化函数,tf.train.FtrlOptimizer(),可以任意改动传到LinearClassifier。 2 | 3 | 随机森林。包含多个决策树分类器及回归算法。处理不平衡分类资料集,极大平衡误差。Kaggle数据科学竞赛,延伸版XGBoost。 4 | 5 | TensorForestEstimator,tensor_forest.ForestHParams设置随机森林参数,多少棵树、节点数目上限、特征类别数目。 6 | 7 | 传进TensorForestEstimator初始化随机森林Estimator。数据特征列、类别列转换成float32格式,保证TensorForestExtimator训练更快拟合。Scikit-learn风格fit()方法。 8 | 9 | 随机森林容易过拟合,常用防止过拟合方法是损失减少的速度变慢或完全停止减少,提前停止模型训练。Monitor模块。random_forest模块自带LossMonitor。设定每隔100步Monitor检查损失减少速度,连续100次迭代损失没有减少,Monitor停止整个模型训练。 10 | 11 | K均值聚类。多维空间每个点划分到K个聚类,每个点属于离它最近均值对应聚类。NumPy制造适合做聚类数据。make_random_centers函数随机生成num_dims个维度数据集聚类num_centers个中心点。make_random_points函数根据生成聚类中心点随便生成num_points个点。生成10000个点,6个随机聚类中心点。factorization模块KMeans初始化聚类方法,随机初始化RANDOM_INIT,传入RunConfig和、聚类中心数初始化KMeans Estimator对象,Scikit-learn风格fit()、predict()。KMeans clusters()函数看训练数据集每个点聚类分布。KMeans Estimator,predict()预测新数据点聚类,score()预测每个点和最近聚类距离总和,transform()计算每个点和模型判断聚类中心距离。 12 | 13 | 支持向量机。各种不同kernel或不同距离方程,针对不同特征数据建立不同线性及非线性模型。同时最小化经验误差与最大化几何边缘区,最大边缘区分类器。文本、图像分类。TF.Learn SVM Extimator API建立支持向量机模型。定义input_fn()建立有两个数据特征列、一个ID列、一个标识列模拟数据。contrib.layers FeatureColumn API 将feature1、feature2转换方便Estimator的FeatureColumn。特征列、ID列传入SVM初始化支持向量机,参数调节。l1_regularization、l2_regularization加正规化防止过度拟合问题(特征过多、例子不多,容易发生)。fit()、predict()。 14 | 15 | DataFrame。TF.Learn包括独立DataFrame模块。类似Pandas、Spark、R编程语言DataFrame。提供TF.Learn读入数据迭代,读入各种数据类型(pandas.DataFrame、tensorflow.Example、NumPy),FeedingQueueRunner数据分批读入,存在Queue,方便Estimator模型训练。NumPy eye()建简单对角矩阵,TensorFlowDataFrame.from_numpy()把NumPy矩阵转为TensorFlow DataFrame。可以像Pandas读入各种文件类型。 16 | 17 | 用TensorFlowDataFrame读入文件或数据类型后,run()制造数据批量(batch)生成器,Python yield生成generator,生成器维持数据列名和数据字典mapping。调节number_batches选择生成batch数量,选择性用自己的graph、session,数据batch存到session coordinator。batch()重新改变batch大小。数据洗一遍打乱顺序。split(),DataFrame分多个。select_rows()选择具体行数据。 18 | 19 | 监督器Monitors。TF.Learn自带Monitor,各种logging及监督控制训练过程。5个等级log,严重性最小到最大排列,DEBUG、INFO、WARN、ERROR、FATAL。选择只打印设置等级或更严重的log。TensorFlow默认log等级 WARN。模型训练log,设INFO。CaptureVariable 指定变量值存储到Collection。PrintTensor打印Tensor值。SummarySaver存储Summary协议缓冲(Protocol Buffer)。ValidationMonitor训练打印多个评估Metrics,监督模型训练,提前停止训练防止模型过度拟合。 20 | 21 | TF.Learn自带learn.datasets.base.load_csv()读入CSV数据文件。定义评估模型metrics字典,contrib.metrics模块streaming_accuracy、streaming_precision、streaming_recall评估模型准确度、精确度、召回率。validation_metrics建立validation_monitor,提供评估数据及目标。提供every_n_steps指示每50步实行ValidationMonitor。validation_metrics传入metrics。early_stopping_netric提前停止监测metric。early_stopping_metric_minimize=True表明最小化前提供early_stopping_metric。early_stopping_rounds表明超过200步训练损失不减少,ValidationMonitor停止Estimator训练。 22 | 23 | 建立深度神经网络分类器DNNClassifier,三层神经网络,每层10、15、10个隐藏单元。分类器fit()指定监督器validation_monitor,指定多个监督器实现不同功能监督,validation_monitor,debug_monitor,print_monitor。 24 | 25 | evaluate()、predict(),新数据评估模型准确度。 26 | 27 | TF.Learn生成log及checkpoint文件可以直接读入TensorBoard可视化。 28 | 29 | 参考资料: 30 | 《TensorFlow实战》 31 | 32 | 33 | -------------------------------------------------------------------------------- /tensorflow_in_action/学习笔记TF044_TF.Contrib组件、统计分布、Layer、性能分析器tfprof.md: -------------------------------------------------------------------------------- 1 | TF.Contrib,开源社区贡献,新功能,内外部测试,根据反馈意见改进性能,改善API友好度,API稳定后,移到TensorFlow核心模块。生产代码,以最新官方教程和API指南参考。 2 | 3 | 统计分布。TF.contrib.ditributions模块,Bernoulli、Beta、Binomial、Gamma、Ecponential、Normal、Poisson、Uniform等统计分布,统计研究、应用中常用,各种统计、机器学习模型基石,概率模型、图形模型依赖。 4 | 5 | 每个不同统计分布不同特征、函数,同样子类Distribution扩展。Distribution,建立和组织随机变量、统计分布基础类。is_continuous表明随机变量分布是否连续。allow_nan_states表示分布是否接受nan数据。sample()从分布取样。prob()计算随机变量密度函数。cdf()求累积分布函数。entropy()、mean()、std()、variance()得到统计分布平均值和方差等特征。自定义统计分布类要实现以上方程。 6 | 7 | Gamma分布。contrib.distributions导入Gamma分布,初始化alpha、beta tf.constant,建立Gamma分布。batch_shap().eval()得到每个样本形状,get_batch_shape(),tf.TensorShape()。log_pdf()函数,值log转换概率密度函数。建立多维Gamma分布,传入多维alpha、beta参数。 8 | 9 | Layer模块。Contrib.layer包含机器学习算法所需各种各样成份、部件,卷积层、批标准化层、机器学习指票、优化函数、初始器、特征列。 10 | 11 | 机器学习层。深度学习和计算机视觉二维平均池avg_pool2d。np.random.uniform建立宽高都是3几张图片,contrib.layers.avg_pool2d()对图片快速建立3x3二维平均池,outpu形状[5,1,1,3],对每个3x3区域取计算平均值。 12 | 13 | 建立卷积层,contrib.layers.convolution2d()建立32个3x3过滤器卷积层,改stride、padding、activation_fn参数建立不同架构卷积层,使用不同卷咱们层激活函数。contrib.layers自动建立op名字,output.op.name值'Conv/Relu',用了Conv层和ReLU激活函数。layer有自己对应op名字,每个op空间存储对应变量,contrib.framework.get_variables_by_name()得到对应op空间变量值。get_variables_by_name得到建立卷积层权重,权重形状是weights_shape值,[3,3,4,32]。 14 | 15 | contrib.framework arg_scope减少代码重复使用。layers.convolution2d及传入参数放到agr_scope,避免重复在多个地方传入。normalizer_fn和normalizer_params,标准化方程及参数。 16 | 17 | len(tf.contrib.framework.get_variables('Conv/BatchNorm'))得到第一个Conv/BatchNorm层长度。 18 | 19 | 完全连接神经网络层fully_connected()。建立输入矩阵,fully_connected()建立输出7个神经单元神经网络层。tf.name_scope截下来运算放name_scope。fully_connected()传入scope。"fe/fc"层别号。传入outputs_collections,直接得到层输出。 20 | 21 | repeat()重复用同样参数重复建立某个层。stack()用不同参数建立多个fully_connected()层。conv2d_transpose、conv2d_in_plane、separable_conv2d,参考官方文档。 22 | 23 | 损失函数。tf.contrib.losses模块,各种常用损失函数,二类分类、多类分类、回归模型等机器学习算法。 24 | 25 | 绝对差值。tf.constant建立predictions、targets数列。同样shape。选择性建立权重。losses.absolute_difference()计算预测损失值。 26 | 27 | 计算softmax交叉熵。多类分类机器学习模型。建立predictions、labels,多给。losses.softmax_cross_entropy()计算预测softmax交叉熵值。loss.eval()运行。loss.op.name得到TensorFlow自动赋值op名字,'softmax_cross_entropy_loss/value'。softmax_cross_entropy() label_smoothing平滑所有标识。 28 | 29 | 应用大部分分布稀疏,sparse_softmax_cross_entropy()提升计算效率。 30 | 31 | 特征列 Feature Column。tf.contrib.layers高阶特征列(Feature Column)API,和TF.Learn API结合使用,建立最适合自己数据的模型。 32 | 33 | 数据连续特征(continuous Feature)、类别特征(Categorical Feature)。连续数值特征称连续特征,可直接用在模型里。不连续类别特征,需要数值化,转换为一系列数值代表每个不同类别。learn.datasets API读入数据。 34 | 35 | layers.FeatureColumn API定义特征列。real_valued_column()定义连续特征。 36 | 37 | sparse_column_with_keys()处理类别特征,事先知道特征所有可能值。不知道所有可能值,用sparse_column_with_hash_bucket()转为特征列,哈希表。SparseColumn,直接在TF.Learn传入Estimator。 38 | 39 | 数据科学应用,连续特征可能需要被离散化,形成新类别特征,更好代表特征和目标分类类别之间关系。bucketized_column()将SparseColumn区间化。 40 | 41 | 部分应用,多个特征综合、交互与目标分类类别关系更紧密。多个特征相关,特征交互能建立更有效模型。crossed_column()建立交叉特征列。 42 | 43 | 特征列传入TF.Learn Estimator。fit()、predict()训练、评估模型。 44 | 45 | 取部分特征加权求和作新特征列,weighted_sum_from_feature_columns()实现。 46 | 47 | Embeddings,嵌入向量。稀疏、高维类别特征向量,转换低维、稠密实数值向量,和连续特征向量联合,一起输入神经网络模型训练和优化损失函数。大部分文本识别,先将文本转换成嵌入向量。 48 | 49 | contrib.layers模块 embedding_column()迅速把高维稀疏类别特征向量转为想要维数的嵌入向量。特征交互矩阵比较稀疏,级别比较高,转换后可以使模型更具有概括性更有效。传入TF.Learn Extimator进行模型建立、训练、评估。embedding_columns传入DNNLinearCombinedClassifier深度神经网络特征列。 50 | 51 | 许多实际稀疏高维数据,通常有空特征及无效ID,safe_enbedding_lookup_sparse()安全建立嵌入向量。tf.SparseTensor建立稀疏ID和稀疏权重。建立嵌入向量权重embedding_weights,取决词汇量大小、嵌入同量维数、shard数量。initializer.run()、eval()初始化嵌入向量权重。safe_embedding_lookup_sparse()将原来特征向量安全转换为低维、稠密特征向量。eval()收集到一个tuple。 52 | 53 | 性能分析器tfprof。分析模型架构、衡量系统性能。衡量模型参数、浮点运算、op执行时间、要求存储大小、探索模型结构。 54 | 55 | 命令安装tfprof命令行工具。bazel build -c opt tensorflow/contrib/trprof/...。 56 | 57 | 查询帮助文件。bazel-bin/tensorflow/contrib/tfprof/tools/tfprof/tfprof help。 58 | 59 | 执行互动模式,指定graph_path分析模型shape、参数。bazel-bin/tensorflow/contrib/tfprof/tools/tfprof/tfprof \--graph_path=graph.pbtxt。 60 | 61 | graph_path、checkpoint_path查看checkpoint Tensor数据和对应值。bazel-bin/tensorflow/contrib/tfprof/tools/tfprof/tfprof \--graph_path=graph.pbtxt \--checkpoint_path=model.ckpt。 62 | 63 | 提供run_meta_path查看不同op请求存储、计时。bazel-bin/tensorflow/contrib/tfprof/tools/tfprof/tfprof \--graph_path=graph.pbtxt \--fun_meta_path=run_meta \--checkpoint_path=model.ckpt。 64 | 65 | graph_path文件是GraphDef文本文件,用来在内存建立模型代表。tf.Supervisor写graph.pbtxt。tf.Graph.as_graph_def()或其他类似API存储模型定义到GraphDef文件。 66 | 67 | run_meta_path文件是tensorflow::RunMetadata结果。得到模型每个op所需存储和时间消耗。 68 | 69 | checkpoint_path是模型checkpoint包含所有checkpoint变量op类型、shape、值。 70 | 71 | op_log_path是tensorflow::tfprof::OpLog结果,包含额外op信息,op组类别名字。 72 | 73 | tfprof是CLI命令行工具,输入tfprof命令按回车,进入互动模式,再按回车看到命令行参数默认值。 74 | 75 | 调节参数,show_name_regexes查找符合正则式条件的scope名字。 76 | 77 | tfprof提供两种类型分析:scope、graph。graph,查看op在graph里所花内存、时间。 78 | 79 | 参考资料: 80 | 《TensorFlow实战》 81 | 82 | 83 | -------------------------------------------------------------------------------- /tensorflow_in_action/学习笔记TF045_人工智能、深度学习、TensorFlow、比赛、公司.md: -------------------------------------------------------------------------------- 1 | 人工智能,用计算机实现人类智能。机器通过大量训练数据训练,程序不断自我学习、修正训练模型。模型本质,一堆参数,描述业务特点。机器学习和深度学习(结合深度神经网络)。 2 | 3 | 传统计算机器下棋,贪婪算法,Alpha-Beta修剪法配合Min-Max算法。 4 | AlphaGo,蒙特卡洛树搜索法(Monte Carlo tree search,MCTS)和深度卷积神经网络(deep convolutional neural network,DCNN)。估值网络(value network,盘面评估函数),计算盘面分类。策略网络(policy network),计算每个棋概率、胜率。训练模型过程,分类方法得到直接策略,直接策略对历史棋局资料库进行神经网络学习(深度卷积神经网络)得到习得策略,强化学习自我对局(蒙特卡洛树状搜寻法)得到改良策略,回归整体统计得到估值网络。谷歌《Nature》论文,《Mastering the game of Go with deep neural networks and tree search》。 5 | 6 | 深度学习。前身 是人工神经网络(artificial neural network,ANN),模仿人脑神经元传递、处理信息模式。输入层(input layer)输入训练数据,输出层(output layer)输出计算结果,中间隐藏层(hidden layer)向前传播数据。 7 | 8 | 数据预处理,图片,图像居中、灰度调整、梯度锐化、去除噪声、倾斜度调整。输入神经网络第一层,第一层提取图像特征,有用向下传递,最后一层输出结果。前向传播(forword propagation)。分类概率向量,前5概率值。 9 | 10 | 深度学习,利用已知数据学习模型,在未知数据做出预测。神经元特性,激活函数(activation function),非线性函数,输入非线性变化,前向传播;成本函数(cost function),定量评估预测值和真实值差距,调整权重参数,减少损失,反向传播(backword propagation)。 11 | 12 | 神经网络算法核心,计算、连接、评估、纠错、训练。深度学习增加中间隐藏层数和神经元数,网络变深变宽,大量数据训练。 13 | 14 | 分类(classification)。输入训练数据特征(feature)、标记(label),找出特征和标记映射关系(mapping),标记纠正学习偏差,提高预测率。有标记学习为监督学习(supervised learning)。无监督学习(unsuperVised learning),数据只有特征没有标记。训练不指定明确分类,数据聚群结构,相似类型聚集一起。没有标记数据分组合,聚类(clustering);成功激励制度,强化学习(reinforcement learning,RL)。延迟奖赏与训练相关,激励函数获得状态行动映射,适合连续决策领域。半监督学习(semi-supervised learning),训练数据部分有标记,部分没有,数据分布必然不完全随机,结合有标记数据局部特征,大量无标记数据整体分布,得到较好分类结果。有监督学习(分类、回归)-半监督学习(分类、回归)-半监督聚类(标记不确定)-无监督学习(聚类)。 15 | 16 | 深度学习入门,算法知识、大量数据、计算机(最好GPU)。 17 | 学习数学知识,训练过程涉及过程抽象数学函数,定义网络结构,定义线性非线性函数,设定优化目标,定义损失函数(loss function),训练过程求解最优解次优解,基本概率统计、高等数学、线性代数,知道原理、过程,兴趣涉猎推导证明。 18 | 19 | 经典机器学习理论、基本算法,支持向量机、逻辑回归、决策树、朴素贝叶斯分类器、随机森林、聚类算法、协同过滤、关联性分析、人工神经网络、BP算法、PCA、过拟合、正则化。 20 | 21 | 编程工具(语言),Python解释型、面向对象、动态数据类型高级程序设计语言,线性代数库、矩阵操作,Numpy、Pandas第三方库,机器学习库sklearn,SVM、逻辑回归,MATLAB,R,C++,Java,Go。 22 | 23 | 经典论文,最新动态研究成果,手写数据字识别,LeNet,物体目标检测,MSCNN,博客、笔记、微信公众号、微博、新媒体资讯,新训练方法,新模型。 24 | 25 | 自己动手训练神经网络,选择开源深度学习框架,主要考虑用的人多,方向主要集中视觉、语音,初学最好从计算机视觉入手,用各种网络模型训练手写数字(MNIST)、图像分类(CIFAR)数据集。 26 | 27 | 学入兴趣工作领域,计算机视觉,自然语言处理,预测,图像分类、目标检测、视频目标检测,语音识别、语音合成、对话系统、机器翻译、文章摘要、情感分析,医学行业,医学影像识别,淘宝穿衣,衣服搭配,款式识别,保险、通信客服,对话机器人智能问答系统,智能家居,人机自然语言交互。 28 | 29 | 工作问题,准确率、坏案例(bad case)、识别速度,可能瓶颈,结合具体行业领域业务创新,最新科研成果,调整模型,更改模型参数,贴近业务需求。 30 | 31 | 传统基于规则,依赖知识。统计方法为核心机器学习,重要的是做特征工程(feature engineering),调参,根据领域经验提取特征,文字等抽象领域,特征相对容易提取,语音一维时域信号、图像二维空域信号等领域,提取特征困难。深度学习,神经网络每层自动学习特征。TensorFlow深度学习开源工具。 32 | 33 | TensorFlow支持异构设备分布式计算(heterogeneous distributed computing)。异构,包含不同成分,异构网络、异构数据库。异构设备,CPU、GPU核心协同合作。分布式架构调度分配计算资源、容错。TensorFlow支持卷积神经网络(convolutional neural network,CNN)、循环神经网络(recurrent neural network,RNN),长短期记忆网络(long short-term memory,LSTM,RNN特例)。 34 | 35 | 《The Unreasonable Effectiveness of Recurrent Neural Networks》。Tensor库对CPU/GPU透明,不同设备运行由框架实现,用户指定什么设置做什么运算。完全独立代码库,脚本语言(Python)操作Tensor,实现所有深度学习内容,前向传播、反向传播、图形计算。共享训练模型,TensorFlow slim模块。没有编译过程,更大更复杂网络,可解释性,有效日志调试。 36 | 37 | 研究人群。学者,深度学习理论研究,网络模型,修改参数方法和理论,产耱科研前沿,理论研究、模型实验,新技术新理论敏感。算法改进者,现有网络模型适配应用,达到更好立人日木,模型改进,新算法改进应用现有模型,为上层应用提供优良模型。工业研究者,掌握各种模型网络结构、算法实现,阅读优秀论文,复现成果,应用工业,主流人群。 38 | 39 | TensorFlow工业优势,基于服务端大数据服务(谷歌云平台、搜索),面向终端用户移动端(Android)和嵌入式。模型压缩、8位低精度数据存储。 40 | 41 | TensorFlow特性。高度灵活性(deep flexibility),数据流图(data flow graph)数值计算,只需要构建图,书写计算内部循环,自定义上层库。真正可移植性(true portability),CPU、GPU、台式机、服务器、移动端、云端服务器、Docker容器。产研结合(connect research and production),快速试验框架,新算法,训练模型。自动求微分(auto-differentiation),只需要定义预测模型结构、目标函数,添加数据。多语言支持(language options),Python、C++、Java接口,C++实现核心,Jupyter Notebook,特征映射(feature map),自定义其他语言接口。优化性能(maximize performance),线程、队列、分布式计算支持,TensorFlow数据流图不同计算元素分配不同设备,最大化利用硬件资源。 42 | 43 | 应用公司。谷歌、京东、小米、Uber、eBay、Dropbox、Airbnb。 44 | 45 | 2016.4,0.8版支持分布式、多GPU。2016.6,0.9版支持移动设备。2017.2,1.0版Java、Go实验API,专用编译器XLA、调试工具Debugger,tf.transform数据预处理,动态图计算TensorFlow Fold。 46 | 47 | 机器学习赛事。 48 | ImageNet ILSVRC(ImageNet Large Scale Visual Recognition Challenge,大规模视觉识别挑战赛),对象检测、图像识别算法。2010年开始,最大图像识别数据库,1500万张有标记高分辨率图像数据集,22000类别,比寒用1000类别各1000图像,120万训练图像,5万验证图像,15万测试图像。每年邀请知名IT公司测试图片分类系统。Top-1,预测输出概率最高类别错误率。Top-5,预测输出概率前五类别错误率。2016,CUImage目标检测第一,商汤科技、香港中文大学;CUvideo视频物体检测子项目第一,商汤科技、香港中文大学;SenseCUSceneParsing场景分析第一,商汤科技、香港中文大学;Trimps-Soushen目标定位第一,公安部三所NUIST视频物体探测两个子项目第一,南京信息工程大学;Hikvvision场景分类第一,海康威视; 49 | Kaggel,2010年成立,数据发掘、数据分析预测竞赛在线平台。公司出数据出钱,计算机科学家、数学家、数据科学家领取任务,提供解决方案。3万到25万美元奖励。 50 | 天池大数据竞赛,阿里,穿衣搭配、微博互动预测、用户重复购买行为预测,赛题攻略。 51 | 52 | 国内人工智能公司。腾讯优图、阿里云ET、百度无人驾驶,搜狗、云从科技、商汤科技、昆仑万维、格灵深瞳。 53 | 陌上花科技,衣+(dress+),图像识别、图像搜索、特体追踪检测是、图片自动化标记、图像视频智能分析、边看边买、人脸识别分析。旷视科技,Face++,人脸识别精度,美颜,支付。科大讯飞,语音识别、语音合成、语言云、分词、词性标注、命名实体识别、依存句法分析、语义角色标注。地平线,嵌入式。 54 | 55 | 参考资料: 56 | 《TensorFlow技术解析与实战》 57 | 58 | 59 | -------------------------------------------------------------------------------- /tensorflow_in_action/学习笔记TF046_TensoFlow开发环境,Mac、Ubuntu、Linux、Windows,CPU版本、GPU版本.md: -------------------------------------------------------------------------------- 1 | 下载TensorFlow https://github.com/tensorflow/tensorflow/tree/v1.1.0 。Tags选择版本,下载解压。 2 | 3 | pip安装。pip,Python包管理工具,PyPI(Python Packet Index) https://pypi.python.org/pypi 。 4 | 5 | Mac环境。 6 | 安装virtualenv。virtualenv,Python沙箱工具,创建独立Python环境。pip install virtralenv --upgrade 安装virtualenv。virtualenv --system-site-packages ~/tensorflow 创建tensorflow文件夹。cd ~/tensorflow 进入目录。source bin/activate 激活沙箱。pip install tensorflow==1.1.0 安装TensorFlow。 7 | 8 | Ubuntu/Linux环境。 9 | 先安装virtualenv沙盒环境,再用pip安装TensorFlow。CPU版 pip install tensorflow==1.1.0 。GPU版 pip install tensorflow-gpu==1.1.0 。 10 | 11 | Windows环境。 12 | Windows 7、Windows 10、Server 2016。PowerShell。64位Python3.5.x。 13 | 14 | Java安装。 15 | 下载JAR(Java ARchive)libtensorflow-1.1.0-rc2.jar。本地库,libtensorflow_jni-cpu-darwin-x86_64-1.1.0-rc2.tar.gz解压到jni目录。编译 javac -cpu libtensorflow-1.1.0-rc2.jar MyClass.java 。 16 | 17 | 源代码安装。 18 | Bazel编译工具,JDK 8,0.44。brew install bazel 。其他操作系统,apt-get。进入tensorflow-1.1.0源代码目录,运行./configure,Python路径、是否用HDFS、是否用Google Cloud Platform。bazel编译命令,加入--local_resources 2048,4,1.0限制内存大小。bazel build --local_resources 2048,4,1.0 -c opt //tensorflow/tools/pip_package:build_pip_package bazel-bin/tensorflow/tools/pip_package/build_pip_package /tem/tensorflow_pkg 。进入/tem/tensorflow_pkg,pip install /tmp/tensorflow_pkg/tensorflow-1.1.0-cp27-cp27m-macosx_10_12_intel.whl 。GPU版本需要配置选择使用CUDA、CUDA SDK版本。 19 | 20 | 依赖模块。 21 | numpy。存储、处理大型矩阵科学计算包。比Python嵌套列表结构(nested list structure)高效。强大N维数组对象Array。成熟函数库。整合C/C++、Fortran代码工具包。线性代数、傅里叶变换、随机数生成函数。pip install numpy --upgrade 。 22 | matplotlib。绘图库。一整套和MATLAB相似命令API。适合交互式制图。线图、散点图、等高线图、条形图、柱状图、3D图。绘图控件,嵌入GUI应用。可视化训练结果、特征映射。pip install matplotlib --upgrade 。 23 | jupyter notebook。Ipython升级版。浏览器创建、共享代码、方程、文档。基于Tornado框架Web应用,MQ消息管理。pip install jupyter --upgrade 。打开 jupyter notebook 。浏览器自动打开,启动成功。 24 | scikit-image。图像处理算法,过滤图片。pip install scikit-image --upgrade 。 25 | librosa。音频特征提取。pip install librosa --upgrade 。 26 | nltk。语料库。自然语言处理,分词、词性标注、命名实体识别(NER)、句法分析。pip install nltk --upgrade 。nltk.download()下载nltk数据源。 27 | keras。第一个TensorFlow核心高级别框架,默认API。pip install keras --upgrade 。 28 | tflearn。pip install git+https://github.com/tflearn/tflearn.git 。 29 | 30 | 参考资料: 31 | 《TensorFlow技术解析与实战》 32 | 33 | -------------------------------------------------------------------------------- /tensorflow_in_action/学习笔记TF047_PlayGround、TensorBoard.md: -------------------------------------------------------------------------------- 1 | PlayGround。http://playground.tensorflow.org 。教学目的简单神经网络在线演示、实验图形化平台。可视化神经网络训练过程。在浏览器训练神经网络。界面,数据(DATA)、特征(FEATURES)、神经网络隐藏层(HIDDEN LAYERS)、层中连接线、输出(OUTPUT)。 2 | 3 | 数据。二维平面,蓝色正值,黄色负值。数据形态,圆形、异或、高斯、螺旋。数据配置,调整噪声(noise)大小,改变训练、测试数据比例(ratio),调整入输入每批(batch)数据数量1-30。 4 | 5 | 特征。特征提取(feature extraction)。每个点有X1、X2两个特征。衍生其他特征,X1X1、X2X2、X1X2、sin(X1)、sin(X2)。X1左边黄色是负,右边蓝色是正,表示横坐标值。X2上边蓝色是正,下边黄色是负,表示纵坐标值。X1X1横坐标抛物线信息。X2X2纵坐标抛物线信息。X1X2双曲抛物面信息。sin(X1)横坐标正弦函数信息。sin(X2)纵坐标正弦函数信息。分类器(classifier)结合特征,画出线,把原始颜色数据分开。 6 | 7 | 隐藏层。设置隐藏层数量、每个隐藏层神经元数量。隐藏层间连接线表示权重(weight),蓝色表示神经元原始输出,浅色表示神经元负输出。连接线粗细、深浅表示权重绝对值大小。鼠标放线上可以看到具体值,修改值。修改值要考虑激活函数。Sigmoid,没有负向黄色区域,值域(0,1)。下层神经网络神经元对上层输出再组合。根据上次预测准确性,反向传播每个组合不同权重。组合连接线粗细深浅变化。越深越粗,权重越大。 8 | 9 | 输出。黄色点归于黄色背景,蓝色点归于蓝色背景。背景颜色深浅代表可能性强弱。选定螺旋形数据,7个特征全部输入,3个隐藏层,第一层8个神经元,第二层4个神经元,第三层2个神经元。训练2分钟,测试损失(test loss)和训练损失(training loss)不再下降。只输入最基本前4特征,6个隐藏层,前4层8个神经元,第五层6个神经元,第六层2个神经元。增加神经元个数和神经网络层数。 10 | 11 | TensorBoard。TensorFlow自带可视化工具,Web应用程序套件。7种可视化,SCALARS(训练过程准确率、损失值、权重/偏置变化)、IMAGES(训练过程记录图像)、AUDIO(训练过程记录音频)、GRAPHS(模型数据流图、各设备消耗内存时间)、DISTRIBUTIONS(训练过程记数据分布图)、HISTOGRAMS(训练过程记录数据柱状图)、EMBEDDINGS(展示词向量投影分布)。 12 | 13 | 运行本地服务器,监听6006端口。浏览器发出请求,分析训练记录数据,绘制训练过程图像。运行手写数字识别入门例子。python tensorflow-1.1.0/tensorflow/examples/tutorials/mnist/mnist/mnist_with_summaries.py 。打开TensorBoard面板。tensorboard -logdir=/tmp/mnist/logs/mnist_with_summaries 。浏览器找开网址,查看面板各项功能。 14 | 15 | SCALARS面板。左边,Split on undercores(用下划线分开显示)、Data downloadlinks(数据下载链接)、Smoothing(图像曲线平滑程度)、Horizontal Axis(水平轴)。水平轴3种,STEP迭代次数,RELATIVE训练集测试集相对值,WALL时间。右边,准确率、交叉熵损失函数值变化曲线(迭代次数1000次)。每层偏置(biases)、权重(weights)变化曲线,每次迭代最大值、最小值、平均值、标准差。 16 | 17 | IMAGES面板。训练数据集、测试集预处理后图片。 18 | 19 | AUDIO面板。训练过程处理音频数据。 20 | 21 | GRAPHS面板。数据流图。节点间连线为数据流,连线越粗,两个节点间流动张量(tensor)越多。左边,选择迭代步骤。不同Color(颜色)不同Structure(整个数据流图结构),不同Color不同Device(设备)。选择特定迭代step899,显示各个节点Compute time(计算时间)、Memory(内存消耗)。 22 | 23 | DISTRIBUTIONS面板。平面表示特定层激活前后、权重、偏置分布。 24 | 25 | HISTOGRAMS面板。立体表示特定层激活前后、权重、偏置分布。 26 | 27 | EMBEDDINGS面板。词嵌入投影。 28 | 29 | 词嵌入(word embedding),自然语言处理,推荐系统。Word2vec。TensorFlow Word2vec basic版、optimised版。 30 | 31 | 降维分析。代码 https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/word2vec/word2vec_basic.py 。Word2vec训练数据集text8 http://mattmahoney.net/dc/textdata 。只包含a~z字符和空格,27种字符。Skip-gram模型,根据目标词汇预测上下文。给定n个词围绕词w,w预测一个句子中一个缺漏词c,概率p(c|w)表示。生成t-SNE降给呈现词汇接近程度关系。 32 | 33 | word2vec_basic.py。 34 | 下载文件读取数据,read_data函数,读取输入数据。输出list,每项一词。 35 | 建立词汇字典,对应词、编码。dictionary存储词、编码。reverse_dictionary是反过来的dictionary 编码、词。data是词list对应词编码上一步词list转编码。count存词汇、词频,重复数量少于49999,用'UNK'表示稀有词。 36 | 产生一个批次(batch)训练数据。定义generate_batch函数,输入batch_size、num_skip、skip_window,batch_size是每个batch大小,num_skips样本源端考虑次数,skip_window左右考虑词数,skip_window*2=num_skips。返回batch、label。batch形状[batch_size],label形状[batch_size,1],一个中心词预测周边词。 37 | 构建、训练模型。Skip-gram模型。 38 | t-SNE降维呈现。Matplotlib绘制出图形。 39 | 40 | t-SNE。流形学习(manifold Learning)。假设数据均匀采样于一个高维空间低维流形。流形学习,找到高维空间低维流形,求相庆嵌入映射,实现维数约简或数据可视化。线性流形学习如主成份分析(PCA),非线性流形学习如特距特征映射(Isomap)、拉普拉斯特征映射(Laplacian eigenmaps,LE)、局部线性嵌入(Locally-linear embedding,LLE)。 41 | 42 | 嵌入投影。EMBEDDINGS面板,交互式可视化、分析高维数据。例子 https://github.com/tensorflow/models/blob/master/tutorials/embedding/word2vec_optimized.py 。 43 | 44 | 定义操作(operator,OP),SkipgramWord2vec、NegTrainWord2vec。操作先编译,执行。TF_INC=$(python -c 'import tensorflow as tf;print(tf.sysconfig.get_include())') 。g++ -std=c++11 -shared word2vec_ops.cc word2vec_kernels.cc -o word2vec_ops.so -fPIC -I $TF_INC -O2 -D_GLIBCXX_USE_CXX11_ABI=0 。当前目录下生成word2vec_ops.so文件,执行word2vec_optimized.py,生成模型、日志文件,位于/tmp/,执行tensorboard --logdir=/tmp/ 。访问浏览器。 45 | 46 | EMBEDDINGS面板左边工具栏,降维方式T-SNE、PCA、CUSTOM,二维、三维图像切换。t-SNE降维工具,手动调整Dimension(困惑度)、Learnign rate(学习率),生成10000个点分布。右边,正则表达式匹配词,词间余弦距离、欧式距离关系。任意选择一个点,选择“isolate 101 points”按钮,展示100个空间上最近被选择点词,词数量。 47 | 48 | 参考资料: 49 | 《TensorFlow技术解析与实战》 50 | 51 | 52 | -------------------------------------------------------------------------------- /tf-API/README.md: -------------------------------------------------------------------------------- 1 | 2 | # tensorflow API一点总结 3 | -------------------------------------------------------------------------------- /tf-API/tf-API-研读1:tf-nn,tf-layers,-tf-contrib概述.md: -------------------------------------------------------------------------------- 1 | 我们在使用tensorflow时,会发现tf.nn,tf.layers, tf.contrib模块有很多功能是重复的,尤其是卷积操作,在使用的时候,我们可以根据需要现在不同的模块。但有些时候可以一起混用。 2 | 下面是对三个模块的简述: 3 | (1)tf.nn :提供神经网络相关操作的支持,包括卷积操作(conv)、池化操作(pooling)、归一化、loss、分类操作、embedding、RNN、Evaluation。 4 | (2)tf.layers:主要提供的高层的神经网络,主要和卷积相关的,个人感觉是对tf.nn的进一步封装,tf.nn会更底层一些。 5 | (3)tf.contrib:tf.contrib.layers提供够将计算图中的 网络层、正则化、摘要操作、是构建计算图的高级操作,但是tf.contrib包含不稳定和实验代码,有可能以后API会改变。 6 | 7 | 以上三个模块的封装程度是逐个递进的。 8 | --------------------------------------------------------------------------------