接上文。收藏!带你见证Python小白到大牛的代码成长之路(中级篇)
使用Python的高级项目
Python具有广泛的应用程序-从“ Hello World”一直到实现人工智能的一切。
您可以使用Python进行几乎无限的项目,但是如果您想深入了解Python的核心,可以考虑以下主要项目。
使用PyTorch,TensorFlow,Keras和 任何您喜欢的机器学习库进行机器学习。使用OpenCV和PIL的计算机视觉。使用测试和文档创建和发布自己的pip模块。
在所有这些中,最喜欢的绝对是从事机器学习和深度学习。来看一个非常好的例子,以深入学习Python。
在Python中使用TensorFlow实现CIFAR10
让我们 训练一个 网络 , 使用内置的TensorFlow卷积神经网络 对来自CIFAR10数据集的图像进行分类 。
考虑以下 流程图,以 了解 用例 的 工作原理:
让我们将此流程分解解说:
首先将图像加载到程序中这些图像存储在程序可以访问的位置需要Python来理解存在的信息,因此我们需要进行标准化过程我们定义了神经网络的基础定义损失函数以确保我们在数据集上获得最大的准确性训练实际模型以了解有关其在这期间看到的数据的一些信息测试模型以分析准确性并在训练过程中进行迭代以获得更好的准确性
该用例分为2个程序。一种是训练网络,另一种是测试网络。
首先训练网络。
训练神经网络:
import numpy as np import tensorflow as tf from time import time import math from include.data import get_data_set from include.model import model, lr train_x, train_y = get_data_set("train") test_x, test_y = get_data_set("test") tf.set_random_seed(21) x, y, output, y_pred_cls, global_step, learning_rate = model() global_accuracy = 0 epoch_start = 0 # PARAMS _BATCH_SIZE = 128 _EPOCH = 60 _SAVE_PATH = "./tensorboard/cifar-10-v1.0.0/" # LOSS AND OPTIMIZER loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=output, labels=y)) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=0.9, beta2=0.999, epsilon=1e-08).minimize(loss, global_step=global_step) # PREDICTION AND ACCURACY CALCULATION correct_prediction = tf.equal(y_pred_cls, tf.argmax(y, axis=1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # SAVER merged = tf.summary.merge_all() saver = tf.train.Saver() sess = tf.Session() train_writer = tf.summary.FileWriter(_SAVE_PATH, sess.graph) try: print("Trying to restore last checkpoint ...") last_chk_path = tf.train.latest_checkpoint(checkpoint_dir=_SAVE_PATH) saver.restore(sess, save_path=last_chk_path) print("Restored checkpoint from:", last_chk_path) except ValueError: print("Failed to restore checkpoint. Initializing variables instead.") sess.run(tf.global_variables_initializer()) def train(epoch): global epoch_start epoch_start = time() batch_size = int(math.ceil(len(train_x) / _BATCH_SIZE)) i_global = 0 for s in range(batch_size): batch_xs = train_x[s*_BATCH_SIZE: (s+1)*_BATCH_SIZE] batch_ys = train_y[s*_BATCH_SIZE: (s+1)*_BATCH_SIZE] start_time = time() i_global, _, batch_loss, batch_acc = sess.run( [global_step, optimizer, loss, accuracy], feed_dict={x: batch_xs, y: batch_ys, learning_rate: lr(epoch)}) duration = time() - start_time if s % 10 == 0: percentage = int(round((s/batch_size)*100)) bar_len = 29 filled_len = int((bar_len*int(percentage))/100) bar = '=' * filled_len + '>' + '-' * (bar_len - filled_len) msg = "Global step: {:>5} - [{}] {:>3}% - acc: {:.4f} - loss: {:.4f} - {:.1f} sample/sec" print(msg.format(i_global, bar, percentage, batch_acc, batch_loss, _BATCH_SIZE / duration)) test_and_save(i_global, epoch) def test_and_save(_global_step, epoch): global global_accuracy global epoch_start i = 0 predicted_class = np.zeros(shape=len(test_x), dtype=np.int) while i < len(test_x): j = min(i + _BATCH_SIZE, len(test_x)) batch_xs = test_x[i:j, :] batch_ys = test_y[i:j, :] predicted_class[i:j] = sess.run( y_pred_cls, feed_dict={x: batch_xs, y: batch_ys, learning_rate: lr(epoch)} ) i = j correct = (np.argmax(test_y, axis=1) == predicted_class) acc = correct.mean()*100 correct_numbers = correct.sum() hours, rem = divmod(time() - epoch_start, 3600) minutes, seconds = divmod(rem, 60) mes = " Epoch {} - accuracy: {:.2f}% ({}/{}) - time: {:0>2}:{:0>2}:{:05.2f}" print(mes.format((epoch+1), acc, correct_numbers, len(test_x), int(hours), int(minutes), seconds)) if global_accuracy != 0 and global_accuracy < acc: summary = tf.Summary(value=[ tf.Summary.Value(tag="Accuracy/test", simple_value=acc), ]) train_writer.add_summary(summary, _global_step) saver.save(sess, save_path=_SAVE_PATH, global_step=_global_step) mes = "This epoch receive better accuracy: {:.2f} > {:.2f}. Saving session..." print(mes.format(acc, global_accuracy)) global_accuracy = acc elif global_accuracy == 0: global_accuracy = acc print("###########################################################################################################") def main(): train_start = time() for i in range(_EPOCH): print("Epoch: {}/{}".format((i+1), _EPOCH)) train(i) hours, rem = divmod(time() - train_start, 3600) minutes, seconds = divmod(rem, 60) mes = "Best accuracy pre session: {:.2f}, time: {:0>2}:{:0>2}:{:05.2f}" print(mes.format(global_accuracy, int(hours), int(minutes), seconds)) if __name__ == "__main__": main() sess.close()
输出:
纪元:60/60全局步:23070-[ > -----------------------------] 0%-acc:0.9531-损失:1.5081-7045.4样本/秒全局步进:23080-[ > -----------------------------] 3%-acc:0.9453-损失:1.5159-7147.6样本/秒全局步:23090-[ => ----------------------------] 5%-累积:0.9844-损失:1.4764-7154.6样本/秒全局步:23100-[ ==> ---------------------------] 8%-acc:0.9297-损失:1.5307-7104.4样本/秒全局步:23110-[ ==> ---------------------------] 10%-acc:0.9141-损失:1.5462-7091.4样本/秒全局步:23120-[ ===> --------------------------] 13%-acc:0.9297-损失:1.5314-7162.9样本/秒全局步骤:23130-[ ====> -------------------------] 15%-acc:0.9297-损失:1.5307-7174.8样本/秒全局步:23140-[ =====> ------------------------] 18%-acc:0.9375-损失:1.5231-7140.0样本/秒全局步:23150-[ =====> ------------------------] 20%-acc:0.9297-损失:1.5301-7152.8样本/秒全局步:23160-[ ======> -----------------------] 23%-acc:0.9531-损失:1.5080-7112.3样本/秒全局步:23170-[ =======> ----------------------] 26%-acc:0.9609-损失:1.5000-7154.0样本/秒全局步长:23180-[ ========> ---------------------] 28%-acc:0.9531-损失:1.5074-6862.2样本/秒全局步骤:23190-[ ========> ---------------------] 31%-acc:0.9609-损失:1.4993-7134.5样本/秒全局步骤:23200-[ =========> --------------------] 33%-acc:0.9609-损失:1.4995-7166.0样本/秒全局步骤:23210-[ ========== -------------------] 36%-acc:0.9375-损失:1.5231-7116.7样本/秒全局步长:23220-[ =========== ------------------] 38%-acc:0.9453-损失:1.5153-7134.1样本/秒全局步骤:23230-[ =========== ------------------] 41%-acc:0.9375-损失:1.5233-7074.5样本/秒全局步骤:23240-[ ============> -----------------] 43%-acc:0.9219-损失:1.5387-7176.9样本/秒全局步:23250-[ ============> ------------------] 46%-acc:0.8828-损失:1.5769-7144.1样本/秒全局步骤:23260-[ =============> ---------------] 49%-acc:0.9219-损失:1.5383-7059.7样本/秒全局步骤:23270-[ =============> ---------------] 51%-acc:0.8984-损失:1.5618-6638.6样本/秒全局步骤:23280-[ ==============> --------------] 54%-acc:0.9453-损失:1.5151-7035.7样本/秒全局步骤:23290-[ ===============> -------------] 56%-acc:0.9609-损失:1.4996-7129.0样本/秒全局步:23300-[ ================> ------------] 59%-acc:0.9609-损失:1.4997-7075.4样本/秒全局步骤:23310-[ ================> ------------] 61%-acc:0.8750-损失:1.5842-7117.8样本/秒全局步骤:23320-[ =================> -----------] 64%-acc:0.9141-损失:1.5463-7157.2样本/秒全局步骤:23330-[ ==================> ----------] 66%-acc:0.9062-损失:1.5549-7169.3样本/秒全局步骤:23340-[ ===================> ---------] 69%-acc:0.9219-损失:1.5389-7164.4样本/秒全局步骤:23350-[ ==================> ---------] 72%-acc:0.9609-损失:1.5002-7135.4样本/秒全局步骤:23360-[ ===================> --------] 74%-acc:0.9766-损失:1.4842-7124.2样本/秒全局步骤:23370-[ ====================> -------] 77%-acc:0.9375-损失:1.5231-7168.5样本/秒整体步骤:23380-[ ====================> -------] 79%-acc:0.8906-损失:1.5695-7175.2样本/秒全局步骤:23390-[ =====================> ------] 82%-acc:0.9375-损失:1.5225-7132.1样本/秒全局步骤:23400-[ =======================> -----] 84%-acc:0.9844-损失:1.4768-7100.1样本/秒全局步骤:23410-[ ========================> ----] 87%-acc:0.9766-损失:1.4840-7172.0样本/秒总体步骤:23420-[ ========================== ---] 90%-acc:0.9062-损失:1.5542-7122.1样本/秒全局步骤:23430-[ ========================== ---] 92%-acc:0.9297-损失:1.5313-7145.3样本/秒全局步骤:23440-[ ==========================> -] 95%-acc:0.9297-损失:1.5301-7133.3样本/秒全局步骤:23450-[ ===========================> -] 97%-acc:0.9375-损失:1.5231-7135.7样本/秒全局步骤:23460-[ ============================> ] 100%-acc:0.9250-损失:1.5362-10297.5样本/秒时代60-准确性:78.81%(7881/10000)此时期的准确性更高:78.81 > 78.78。正在保存会话... ########################################### ############################################### ############
用测试数据集运行模型:
import numpy as np import tensorflow as tf from include.data import get_data_set from include.model import model test_x, test_y = get_data_set("test") x, y, output, y_pred_cls, global_step, learning_rate = model() _BATCH_SIZE = 128 _CLASS_SIZE = 10 _SAVE_PATH = "./tensorboard/cifar-10-v1.0.0/" saver = tf.train.Saver() sess = tf.Session() try: print("Trying to restore last checkpoint ...") last_chk_path = tf.train.latest_checkpoint(checkpoint_dir=_SAVE_PATH) saver.restore(sess, save_path=last_chk_path) print("Restored checkpoint from:", last_chk_path) except ValueError: print("Failed to restore checkpoint. Initializing variables instead.") sess.run(tf.global_variables_initializer()) def main(): i = 0 predicted_class = np.zeros(shape=len(test_x), dtype=np.int) while i < len(test_x): j = min(i + _BATCH_SIZE, len(test_x)) batch_xs = test_x[i:j, :] batch_ys = test_y[i:j, :] predicted_class[i:j] = sess.run(y_pred_cls, feed_dict={x: batch_xs, y: batch_ys}) i = j correct = (np.argmax(test_y, axis=1) == predicted_class) acc = correct.mean() * 100 correct_numbers = correct.sum() print() print("Accuracy on Test-Set: {0:.2f}% ({1} / {2})".format(acc, correct_numbers, len(test_x))) if __name__ == "__main__": main() sess.close()
简单输出:
尝试还原上一个检查点...从以下位置恢复检查点:./tensorboard/cifar-10-v1.0.0/-23460测试仪精度:78.81%(7881/10000)
那是一个非常有趣的用例,不是吗?通过本文,了解了机器学习的工作原理,并开发了一个基本程序来使用Python中的TensorFlow库来实现它。
结论
本文讨论的Python项目应该可以帮助您开始学习Python,它会让您沉迷并推动您实际学习更多有关Python的知识。 当您尝试考虑问题并使用Python提供解决方案时,这将非常方便。 Python会帮你解决多个现实生活的项目,以及和这些概念将让你达到速度如何就可以开始探索和了解项目的实际操作经验。
从今天开始,你不止是是个小白,或是熟手,大牛之路已经在你眼前缓缓展开。