《TensorFlow 機器學習方案手冊》(附 pdf 和完整程式碼)

红色石头發表於2019-04-03

今天給大家推薦一本適合新手入門機器學習和 TensorFlow 的最佳教程:《TensorFlow Machine Learning Cookbook》,中文譯為《TensorFlow 機器學習方案手冊》。

書籍介紹

TensorFlow 是一個用於機器學習的開源軟體庫。本書將教你如何使用 TensorFlow 進行復雜的資料計算,並將讓你比以往更深入地挖掘並獲得更多的資料見解。您將學習有關構建模型、模型評估、情緒分析、迴歸分析、聚類分析、人工神經網路和深度學習等內容,每塊內容都使用 Google 的機器學習庫 TensorFlow。

這份指南從 TensorFlow 庫的基本原理開始,該庫包括變數、矩陣和各種資料來源。接下來,你將獲得使用 TensorFlow 的線性迴歸技術的實踐經驗。下一章將介紹重要的高階概念,如神經網路、CNN、RNN 和 NLP。

一旦你熟悉 TensorFlow 的生態系統,最後一章將向您展示如何將其投入生產。

章節目錄

《TensorFlow 機器學習方案手冊》共包含 11 章內容,基本覆蓋機器學習、神經網路、CNN、RNN 的核心知識點。具體目錄如下:

隨書程式碼

該書每一章節都配備了相應的專案,完整的程式碼作者已經放在了 GitHub 上,地址為:

https://github.com/PacktPublishing/TensorFlow-Machine-Learning-Cookbook

專案中的程式碼非常詳細,比如我們來看一個 lasso 和 ridge 迴歸的例子:

# Lasso and Ridge Regression
#----------------------------------
#
# This function shows how to use Tensorflow to
# solve lasso or ridge regression.
# y = Ax + b
#
# We will use the iris data, specifically:
# y = Sepal Length
# x = Petal Width

import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from sklearn import datasets
from tensorflow.python.framework import ops
ops.reset_default_graph()

# Create graph
sess = tf.Session()

# Load the data
# iris.data = [(Sepal Length, Sepal Width, Petal Length, Petal Width)]
iris = datasets.load_iris()
x_vals = np.array([x[3] for x in iris.data])
y_vals = np.array([y[0] for y in iris.data])

# Declare batch size
batch_size = 50

# Initialize placeholders
x_data = tf.placeholder(shape=[None, 1], dtype=tf.float32)
y_target = tf.placeholder(shape=[None, 1], dtype=tf.float32)

# Create variables for linear regression
A = tf.Variable(tf.random_normal(shape=[1,1]))
b = tf.Variable(tf.random_normal(shape=[1,1]))

# Declare model operations
model_output = tf.add(tf.matmul(x_data, A), b)

# Declare Lasso loss function
# Lasso Loss = L2_Loss + heavyside_step,
# Where heavyside_step ~ 0 if A < constant, otherwise ~ 99
#lasso_param = tf.constant(0.9)
#heavyside_step = tf.truediv(1., tf.add(1., tf.exp(tf.multiply(-100., tf.subtract(A, lasso_param)))))
#regularization_param = tf.multiply(heavyside_step, 99.)
#loss = tf.add(tf.reduce_mean(tf.square(y_target - model_output)), regularization_param)

# Declare the Ridge loss function
# Ridge loss = L2_loss + L2 norm of slope
ridge_param = tf.constant(1.)
ridge_loss = tf.reduce_mean(tf.square(A))
loss = tf.expand_dims(tf.add(tf.reduce_mean(tf.square(y_target - model_output)), tf.multiply(ridge_param, ridge_loss)), 0)

# Initialize variables
init = tf.global_variables_initializer()
sess.run(init)

# Declare optimizer
my_opt = tf.train.GradientDescentOptimizer(0.001)
train_step = my_opt.minimize(loss)

# Training loop
loss_vec = []
for i in range(1500):
rand_index = np.random.choice(len(x_vals), size=batch_size)
rand_x = np.transpose([x_vals[rand_index]])
rand_y = np.transpose([y_vals[rand_index]])
sess.run(train_step, feed_dict={x_data: rand_x, y_target: rand_y})
temp_loss = sess.run(loss, feed_dict={x_data: rand_x, y_target: rand_y})
loss_vec.append(temp_loss[0])
if (i+1)%300==0:
print('Step #' + str(i+1) + ' A = ' + str(sess.run(A)) + ' b = ' + str(sess.run(b)))
print('Loss = ' + str(temp_loss))

# Get the optimal coefficients
[slope] = sess.run(A)
[y_intercept] = sess.run(b)

# Get best fit line
best_fit = []
for i in x_vals:
best_fit.append(slope*i+y_intercept)

# Plot the result
plt.plot(x_vals, y_vals, 'o', label='Data Points')
plt.plot(x_vals, best_fit, 'r-', label='Best fit line', linewidth=3)
plt.legend(loc='upper left')
plt.title('Sepal Length vs Pedal Width')
plt.xlabel('Pedal Width')
plt.ylabel('Sepal Length')
plt.show()

# Plot loss over time
plt.plot(loss_vec, 'k-')
plt.title('L2 Loss per Generation')
plt.xlabel('Generation')
plt.ylabel('L2 Loss')
plt.show()

相關書籍

  1. 《Getting Started with TensorFlow》

https://www.packtpub.com/big-data-and-business-intelligence/getting-started-tensorflow?utm_source=github&utm_medium=repository&utm_content=9781786468574

  1. 《Deep Learning with TensorFlow [Video]》

https://www.packtpub.com/big-data-and-business-intelligence/deep-learning-tensorflow-video?utm_source=github&utm_medium=repository&utm_content=9781786464491

  1. 《Building Machine Learning Systems with TensorFlow [Video]》

https://www.packtpub.com/big-data-and-business-intelligence/building-machine-learning-systems-tensorflow-video?utm_source=github&utm_medium=repository&utm_content=9781787281806

資源下載

最後,本書的的電子版 pdf 和原始碼已經打包完畢,需要的可以按照以下方式獲取:

連結:https://pan.baidu.com/s/1iHokcIStqE1mI86-fqdkzA 提取碼:3yfk


相關文章