自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

TF Learn : 基于Scikit-learn和TensorFlow的深度學(xué)習(xí)利器

原創(chuàng)
人工智能 深度學(xué)習(xí) 后端
Scikit-learn 是最常用的 Python 機(jī)器學(xué)習(xí)框架,在各大互聯(lián)網(wǎng)公司做算法的工程師在實(shí)現(xiàn)單機(jī)版本的算法的時(shí)候或多或少都會用到 Scikit-learn 。TensorFlow 就更是大名鼎鼎,做深度學(xué)習(xí)的人都不可能不知道 TensorFlow。

【51CTO.com原創(chuàng)稿件】了解國外數(shù)據(jù)科學(xué)市場的人都知道,2017年海外數(shù)據(jù)科學(xué)最常用的三項(xiàng)技術(shù)是 Spark ,Python 和 MongoDB 。說到 Python ,做大數(shù)據(jù)的人都不會對 Scikit-learn 和 Pandas 感到陌生。

[[242642]]

Scikit-learn 是最常用的 Python 機(jī)器學(xué)習(xí)框架,在各大互聯(lián)網(wǎng)公司做算法的工程師在實(shí)現(xiàn)單機(jī)版本的算法的時(shí)候或多或少都會用到 Scikit-learn 。TensorFlow 就更是大名鼎鼎,做深度學(xué)習(xí)的人都不可能不知道 TensorFlow。

下面我們先來看一段樣例,這段樣例是傳統(tǒng)的機(jī)器學(xué)習(xí)算法邏輯回歸的實(shí)現(xiàn):

TF Learn : 基于Scikit-learn和TensorFlow的深度學(xué)習(xí)利器

可以看到,樣例中僅僅使用了 3 行代碼就完成了邏輯回歸的主要功能。下面我們來看一下如果用 TensorFlow 來實(shí)現(xiàn)同樣的代碼,需要多少行?下面的代碼來自 GitHub :

 

  1. '' 
  2. A logistic regression learning algorithm example using TensorFlow library.  
  3. This example is using the MNIST database of handwritten digits  
  4. (http://yann.lecun.com/exdb/mnist/)  
  5. Author: Aymeric Damien  
  6. Project: https://github.com/aymericdamien/TensorFlow-Examples/  
  7. '' 
  8. from __future__ import print_function  
  9. import tensorflow as tf  
  10. # Import MNIST data  
  11. from tensorflow.examples.tutorials.mnist import input_data  
  12. mnist = input_data.read_data_sets("/tmp/data/", one_hot=True 
  13.  
  14. # Parameters  
  15. learning_rate = 0.01  
  16. training_epochs = 25  
  17. batch_size = 100  
  18. display_step = 1  
  19.  
  20. # tf Graph Input  
  21. x = tf.placeholder(tf.float32, [None, 784]) # mnist data image of shape 28*28=784  
  22. y = tf.placeholder(tf.float32, [None, 10]) # 0-9 digits recognition => 10 classes  
  23.  
  24. Set model weights  
  25. W = tf.Variable(tf.zeros([784, 10]))  
  26. b = tf.Variable(tf.zeros([10]))  
  27.  
  28. # Construct model  
  29. pred = tf.nn.softmax(tf.matmul(x, W) + b) # Softmax  
  30.  
  31. # Minimize error using cross entropy  
  32. cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred), reduction_indices=1))  
  33. # Gradient Descent  
  34. optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)  
  35.  
  36. # Initialize the variables (i.e. assign their default value)  
  37. init = tf.global_variables_initializer()  
  38.  
  39. # Start training  
  40. with tf.Session() as sess:  
  41.     # Run the initializer  
  42.     sess.run(init)  
  43.     # Training cycle  
  44.     for epoch in range(training_epochs):  
  45.         avg_cost = 0.  
  46.         total_batch = int(mnist.train.num_examples/batch_size)  
  47.         # Loop over all batches  
  48.         for i in range(total_batch):  
  49.             batch_xs, batch_ys = mnist.train.next_batch(batch_size)  
  50.             # Run optimization op (backprop) and cost op (to get loss value)  
  51.             _, c = sess.run([optimizer, cost], feed_dict={x: batch_xs,  
  52.                                                           y: batch_ys})  
  53.             # Compute average loss  
  54.             avg_cost += c / total_batch  
  55.         # Display logs per epoch step  
  56.         if (epoch+1) % display_step == 0:  
  57.             print("Epoch:"'%04d' % (epoch+1), "cost=""{:.9f}".format(avg_cost))  
  58.  
  59.     print("Optimization Finished!" 
  60.  
  61.     # Test model  
  62.     correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))  
  63.     # Calculate accuracy  
  64.     accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))  
  65. print("Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels})) 

一個(gè)相對來說比較簡單的機(jī)器學(xué)習(xí)算法,用 Tensorflow 來實(shí)現(xiàn)卻花費(fèi)了大量的篇幅。然而 Scikit-learn 本身沒有 Tensorflow 那樣豐富的深度學(xué)習(xí)的功能。有沒有什么辦法,能夠在保證 Scikit-learn 的簡單易用性的前提下,能夠讓 Scikit-learn 像 Tensorflow 那樣支持深度學(xué)習(xí)呢?答案是有的,那就是 Scikit-Flow 開源項(xiàng)目。該項(xiàng)目后來被集成到了 Tensorflow 項(xiàng)目里,變成了現(xiàn)在的 TF Learn 模塊。

我們來看一個(gè) TF Learn 實(shí)現(xiàn)線性回歸的樣例:

 

  1. """ Linear Regression Example """ 
  2. from __future__ import absolute_import, division, print_function  
  3. import tflearn  
  4. # Regression data  
  5. X = [3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,7.042,10.791,5.313,7.997,5.654,9.27,3.1]  
  6. Y = [1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,2.827,3.465,1.65,2.904,2.42,2.94,1.3]  
  7. # Linear Regression graph  
  8. input_ = tflearn.input_data(shape=[None])  
  9. linear = tflearn.single_unit(input_)  
  10. regression = tflearn.regression(linear, optimizer='sgd', loss='mean_square' 
  11.                                 metric='R2', learning_rate=0.01)  
  12. m = tflearn.DNN(regression)  
  13. m.fit(X, Y, n_epoch=1000, show_metric=True, snapshot_epoch=False 
  14. print("\nRegression result:" 
  15. print("Y = " + str(m.get_weights(linear.W)) +  
  16.       "*X + " + str(m.get_weights(linear.b)))  
  17.  
  18. print("\nTest prediction for x = 3.2, 3.3, 3.4:" 
  19. print(m.predict([3.2, 3.3, 3.4])) 

我們可以看到,TF Learn 繼承了 Scikit-Learn 的簡潔編程風(fēng)格,在處理傳統(tǒng)的機(jī)器學(xué)習(xí)方法的時(shí)候非常的方便。下面我們看一段 TF Learn 實(shí)現(xiàn) CNN (MNIST數(shù)據(jù)集)的樣例:

 

  1. """ Convolutional Neural Network for MNIST dataset classification task.  
  2. References 
  3.     Y. LeCun, L. Bottou, Y. Bengio, and P. Haffner. "Gradient-based  
  4.     learning applied to document recognition." Proceedings of the IEEE,  
  5.     86(11):2278-2324, November 1998.  
  6. Links:  
  7.     [MNIST Dataset] http://yann.lecun.com/exdb/mnist/  
  8. "" 
  9.  
  10. from __future__ import division, print_function, absolute_import   
  11. import tflearn  
  12. from tflearn.layers.core import input_data, dropout, fully_connected  
  13. from tflearn.layers.conv import conv_2d, max_pool_2d  
  14. from tflearn.layers.normalization import local_response_normalization  
  15. from tflearn.layers.estimator import regression  
  16.  
  17. # Data loading and preprocessing  
  18. import tflearn.datasets.mnist as mnist  
  19. X, Y, testX, testY = mnist.load_data(one_hot=True 
  20. X = X.reshape([-1, 28, 28, 1])  
  21. testX = testX.reshape([-1, 28, 28, 1])  
  22. # Building convolutional network  
  23. network = input_data(shape=[None, 28, 28, 1], name='input' 
  24. network = conv_2d(network, 32, 3, activation='relu', regularizer="L2" 
  25. network = max_pool_2d(network, 2)  
  26. network = local_response_normalization(network)  
  27. network = conv_2d(network, 64, 3, activation='relu', regularizer="L2" 
  28. network = max_pool_2d(network, 2)  
  29. network = local_response_normalization(network)  
  30. network = fully_connected(network, 128, activation='tanh' 
  31. network = dropout(network, 0.8)  
  32. network = fully_connected(network, 256, activation='tanh' 
  33. network = dropout(network, 0.8)  
  34. network = fully_connected(network, 10, activation='softmax'
  35. network = regression(network, optimizer='adam', learning_rate=0.01,  
  36.                      loss='categorical_crossentropy'name='target' 
  37.  
  38. # Training  
  39. model = tflearn.DNN(network, tensorboard_verbose=0)  
  40. model.fit({'input': X}, {'target': Y}, n_epoch=20,  
  41.            validation_set=({'input': testX}, {'target': testY}),  
  42. snapshot_step=100, show_metric=True, run_id='convnet_mnist'

可以看到,基于 TF Learn 的深度學(xué)習(xí)代碼也是非常的簡潔。

TF Learn 是 TensorFlow 的高層次類 Scikit-Learn 封裝,提供了原生版 TensorFlow 和 Scikit-Learn 之外的又一種選擇。對于熟悉了 Scikit-Learn 和厭倦了 TensorFlow 冗長代碼的用戶來說,不啻為一種福音,也值得機(jī)器學(xué)習(xí)和數(shù)據(jù)挖掘的從業(yè)者認(rèn)真學(xué)習(xí)和掌握。

[[242643]]

汪昊,恒昌利通大數(shù)據(jù)部負(fù)責(zé)人/資深架構(gòu)師,美國猶他大學(xué)本科/碩士,對外經(jīng)貿(mào)大學(xué)在職MBA。曾在百度,新浪,網(wǎng)易,豆瓣等公司有多年的研發(fā)和技術(shù)管理經(jīng)驗(yàn),擅長機(jī)器學(xué)習(xí),大數(shù)據(jù),推薦系統(tǒng),社交網(wǎng)絡(luò)分析等技術(shù)。在 TVCG 和 ASONAM 等國際會議和期刊發(fā)表論文 8 篇。本科畢業(yè)論文獲國際會議 IEEE SMI 2008 ***論文獎。

【51CTO原創(chuàng)稿件,合作站點(diǎn)轉(zhuǎn)載請注明原文作者和出處為51CTO.com】

責(zé)任編輯:龐桂玉 來源: 51CTO
相關(guān)推薦

2015-07-22 16:16:47

PythonScikit-Lear機(jī)器學(xué)習(xí)

2023-05-26 12:45:22

predict?方法數(shù)據(jù)

2021-05-12 09:58:09

PythonXGBoostscikit-lear

2017-01-05 10:07:33

大數(shù)據(jù)TheanoCaffe

2017-11-03 12:57:06

機(jī)器學(xué)習(xí)文本數(shù)據(jù)Python

2018-10-15 09:10:09

Python編程語言數(shù)據(jù)科學(xué)

2023-02-13 15:00:13

機(jī)器學(xué)習(xí)scikit-leaPyTorch

2023-11-13 18:05:53

處理數(shù)據(jù)搭建模型

2017-04-21 09:59:11

開源機(jī)器學(xué)習(xí)框架

2022-04-15 10:11:03

機(jī)器學(xué)習(xí)scikit-lea

2018-04-06 05:10:04

K-NN數(shù)據(jù)集算法

2018-05-15 08:27:20

Scikit-lear機(jī)器學(xué)習(xí)Python

2017-07-20 10:23:20

pythonscikit-lear垃圾郵件過濾

2024-02-01 09:43:32

模型人工智能

2016-12-18 15:03:57

Python Scikit Lea數(shù)據(jù)

2016-12-20 16:07:13

Python數(shù)據(jù)預(yù)處理

2017-05-03 22:05:48

深度學(xué)習(xí)候選采樣深度學(xué)習(xí)庫

2017-08-16 10:57:52

深度學(xué)習(xí)TensorFlowNLP

2017-09-21 12:29:58

深度學(xué)習(xí)TensorFlow智能終端

2017-05-22 13:15:45

TensorFlow深度學(xué)習(xí)
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號