听说TensorFlow框架是人工智能的必学框架!给你五分钟能学会吗?

听说TensorFlow框架是人工智能的必学框架!给你五分钟能学会吗?

听说TensorFlow框架是人工智能的必学框架!给你五分钟能学会吗?

virtualenv1.sh hosted with ❤ by GitHub

听说TensorFlow框架是人工智能的必学框架!给你五分钟能学会吗?

进群:548377875  等即可获取大量的学习资料以及PDF哦!

sudo pip install --upgrade virtualenv

view raw

virtualenv2.sh hosted with ❤ by GitHub

听说TensorFlow框架是人工智能的必学框架!给你五分钟能学会吗?

virtualenv --system-site-packages tensorflow

view raw

virtualenv3.sh hosted with ❤ by GitHub

听说TensorFlow框架是人工智能的必学框架!给你五分钟能学会吗?

由于我的Python是2.7.10版本,并且没有支持GPU,因此执行:

pip install --upgrade tensorflow

view raw

virtualenv4.sh hosted with ❤ by GitHub

如果是其他情况的请参照官方教程

听说TensorFlow框架是人工智能的必学框架!给你五分钟能学会吗?

验证安装

官方地址: https://www.tensorflow.org/install/install_mac#ValidateYourInstallation

听说TensorFlow框架是人工智能的必学框架!给你五分钟能学会吗?

II. 训练模型案例

该案例来自官方的入门案例

import numpy as npimport tensorflow as tf

# 定义可训练模型变量W = tf.Variable([.3], tf.float32) #类型为tf.float32初始值为0.3的可训练模型变量Wb = tf.Variable([-.3], tf.float32) #类型为tf.float32初始值为-0.3的可训练模型变量b

# 定义模型的输入输出x = tf.placeholder(tf.float32) #定义类型为tf.float32的模型输入变量xlinear_model = W * x + b # 定义模型函数,已经模型输出值linear_model

# 定义输出目标变量y = tf.placeholder(tf.float32)

# 定义距离目标变量的距离loss = tf.reduce_sum(tf.square(linear_model - y)) # 每个输出值与对应目标值差平方的和

# 定义优化器optimizer = tf.train.GradientDescentOptimizer(0.01) # 通过以精度0.01的梯度下降train = optimizer.minimize(loss) # 通过优化器,让其距离目标值逐渐减小

# 准备训练用的数据x_train = [1,2,3,4] # 输入变量x的值序列y_train = [0,-1,-2,-3] # 需要能够对应输出的目标值序列

# 开始训练init = tf.global_variables_initializer() # 初始化可训练变量sess = tf.Session() # 创建一个sessionsess.run(init) # 复位训练模型for i in range(1000): # 喂训练数据 sess.run(train, {x:x_train, y:y_train})

# 输出训练结果curr_W, curr_b, curr_loss = sess.run([W, b, loss], {x:x_train, y:y_train})print("W: %s b: %s loss: %s"%(curr_W, curr_b, curr_loss))

# 最终结果当 W为-0.9999969、b为0.99999082,距离目标值(每个输出值与目标值差的平方和)为5.69997e-11# 输出: W: [-0.9999969] b: [0.99999082] loss: 5.69997e-11

view raw

tensorflow-low-level-sample1.py hosted with ❤ by GitHub

听说TensorFlow框架是人工智能的必学框架!给你五分钟能学会吗?

该次模型训练的性能决定因素是: 优化器选择、精度选择、训练数据

通过高级的接口快速的实现上面的模型训练

import tensorflow as tf# Numpy通常用于加载,维护与预处理数据import numpy as np# 需求队列(还有很多其他类型的column)features = [tf.contrib.layers.real_valued_column("x", dimension=1)]# estimator是一个前端调用用于训练与评估的接口,这里有非常多预定义的类型,如Linear Regression, Logistic Regression, Linear Classification, Logistic Classification 以及各种各样的Neural Network Classifiers 与 Regressors. 这里我们用的是Linear Regressionestimator = tf.contrib.learn.LinearRegressor(feature_columns=features)# TensorFlow有提供了许多工具方法来读写数据集,这里我们使用`numpy_input_fn`,我们不得不告诉方法一共有多少组(num_epochs),并且每组有多大(batch_size)x = np.array([1., 2., 3., 4.])y = np.array([0., -1., -2., -3.])input_fn = tf.contrib.learn.io.numpy_input_fn({"x":x}, y, batch_size=4, num_epochs=1000)# 我们可以通过传入训练所用的数据集调用1000次`fit`方法来一步步训练estimator.fit(input_fn=input_fn, steps=1000)# 评估目前模型训练的怎么样。实际运用中,我们需要一个独立的验证与测试数据集避免训练过渡(overfitting)estimator.evaluate(input_fn=input_fn)

view raw

tensorflow-high-level-sample1.py hosted with ❤ by GitHub

当然我们也可以通过tf.contrib.learn.Estimator这个高级接口,再使用低级接口来定制Linear Regressor算法模型(实际上内置的tf.contrib.learn.LinearRegressor也是继承自tf.contrib.learn.Estimator的)。当然我们不是通过继承,是通过提供model_fn来告诉他训练的步骤、如果评估等:

import numpy as npimport tensorflow as tf# 定义需求队列(这里我们只需要一个featurex)def model(features, labels, mode): # 构建线性模型 W = tf.get_variable("W", [1], dtype=tf.float64) b = tf.get_variable("b", [1], dtype=tf.float64) y = W*features['x'] + b # 定义距离目标变量的距离 loss = tf.reduce_sum(tf.square(y - labels)) # 训练子图 global_step = tf.train.get_global_step() optimizer = tf.train.GradientDescentOptimizer(0.01) train = tf.group(optimizer.minimize(loss), tf.assign_add(global_step, 1)) # ModelFnOps用于将各参数串起来 return tf.contrib.learn.ModelFnOps( mode=mode, predictions=y, loss=loss, train_op=train)

estimator = tf.contrib.learn.Estimator(model_fn=model)# 定义我们的训练用的数据集x = np.array([1., 2., 3., 4.])y = np.array([0., -1., -2., -3.])input_fn = tf.contrib.learn.io.numpy_input_fn({"x": x}, y, 4, num_epochs=1000)

# 训练estimator.fit(input_fn=input_fn, steps=1000)# 评估训练模型print(estimator.evaluate(input_fn=input_fn, steps=10))

view raw

tensorflow-high-level-sample2.py hosted with ❤ by GitHub

III. 常见的API

具体API可以参看官网文档

听说TensorFlow框架是人工智能的必学框架!给你五分钟能学会吗?

  • 定义常量: tf.constant(value, type),如tf.constant(3.0, tf.float32),当type没有给定的时候,会根据所给value定义
  • 定义变量: tf.placeholder(type), 如tf.placeholder(tf.float32)
  • 定义训练模型: tf.Variable([value], type], 如tf.Variable([.3], tf.float32)
  • 计算结果: 通过tf.Session()的run去计算
  • 初始化训练模型: tf.global_variables_initializer(),对其进行复位运行起对象即可,如Session对象是sees,初始化模型对象是init时: sess.run(init)
  • 对模型重新赋值: 如对W模型重新赋值: fixW = tf.assign(W, [-1.])
  • 求平方: tf.square(value)
  • 求和: tf.reduce_sum(value)

猜你喜欢

转载自blog.csdn.net/qq_42156420/article/details/83860188