《TensorFlow 机器学习方案手册》(附 pdf 和完整代码)

今天给大家推荐一本适合新手入门机器学习和 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


未经允许不得转载:红色石头的个人博客 » 《TensorFlow 机器学习方案手册》(附 pdf 和完整代码)

赞 (5) 打赏

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏