判断默认图
tensorboard展示
# -*- coding: UTF-8 -*-
# 引入tensorflow
import tensorflow as tf
# 构造图(Graph)的结构
# 用一个线性方程的例子 y = W * x + b
W = tf.Variable(2.0, dtype=tf.float32, name="Weight") # 权重
b = tf.Variable(1.0, dtype=tf.float32, name="Bias") # 偏差
x = tf.placeholder(dtype=tf.float32, name="Input") # 输入
with tf.name_scope("Output"): # 输出的命名空间
y = W * x + b # 输出
# const = tf.constant(2.0) # 不需要初始化
# 定义保存日志的路径
path = "./log"
# 创建用于初始化所有变量(Variable)的操作
# 如果定义了变量,但没有初始化的操作,会报错
init = tf.global_variables_initializer()
# 创建 Session(会话)
with tf.Session() as sess:
sess.run(init) # 初始化变量
writer = tf.summary.FileWriter(path, sess.graph)
result = sess.run(y, {x: 3.0}) # 为 x 赋值 3
print("y = W * x + b,值为 {}".format(result)) # 打印 y = W * x + b 的值,就是 7
np.linespace(-2,2,100)把区间均分为100个点
生成多张图
matplotply生成多张子图
matplotply输出碗状图形
梯度下降的动态演示
模拟线性回归
# -*- coding: UTF-8 -*-
"""
用梯度下降的优化方法来快速解决线性回归问题
"""
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
try:
xrange = xrange # Python 2
except:
xrange = range # Python 3
# 构建数据
points_num = 100
vectors = []
# 用 Numpy 的正态随机分布函数生成 100 个点
# 这些点的(x, y)坐标值对应线性方程 y = 0.1 * x + 0.2
# 权重(Weight)为 0.1,偏差(Bias)为 0.2
for i in xrange(points_num):
x1 = np.random.normal(0.0, 0.66)
y1 = 0.1 * x1 + 0.2 + np.random.normal(0.0, 0.04)
vectors.append([x1, y1])
x_data = [v[0] for v in vectors] # 真实的点的 x 坐标
y_data = [v[1] for v in vectors] # 真实的点的 y 坐标
# 图像 1 :展示 100 个随机数据点
plt.plot(x_data, y_data, 'r*', label="Original data") # 红色星形的点
plt.title("Linear Regression using Gradient Descent")
plt.legend()
plt.show()
# 构建线性回归模型
W = tf.Variable(tf.random_uniform([1], -1.0, 1.0)) # 初始化 Weight
b = tf.Variable(tf.zeros([1])) # 初始化 Bias
y = W * x_data + b # 模型计算出来的 y
# 定义 loss function(损失函数)或 cost function(代价函数)
# 对 Tensor 的所有维度计算 ((y - y_data) ^ 2) 之和 / N
loss = tf.reduce_mean(tf.square(y - y_data))
# 用梯度下降的优化器来最小化我们的 loss(损失)
optimizer = tf.train.GradientDescentOptimizer(0.5) # 设置学习率为 0.5
train = optimizer.minimize(loss)
# 创建会话
sess = tf.Session()
# 初始化数据流图中的所有变量
init = tf.global_variables_initializer()
sess.run(init)
# 训练 20 步
for step in xrange(20):
# 优化每一步
sess.run(train)
# 打印出每一步的损失,权重和偏差
print("第 {} 步的 损失={}, 权重={}, 偏差={}".format(step+1, sess.run(loss), sess.run(W), sess.run(b)))
# 图像 2 :绘制所有的点并且绘制出最佳拟合的直线
plt.plot(x_data, y_data, 'r*', label="Original data") # 红色星形的点
plt.title("Linear Regression using Gradient Descent") # 标题,表示 "梯度下降解决线性回归"
plt.plot(x_data, sess.run(W) * x_data + sess.run(b), label="Fitted line") # 拟合的线
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.show()
激活函数
# -*- coding: UTF-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
# 创建输入数据
x = np.linspace(-7, 7, 180) # (-7, 7) 之间等间隔的 180 个点
# 激活函数的原始实现
def sigmoid(inputs):
y = [1 / float(1 + np.exp(-x)) for x in inputs]
return y
def relu(inputs):
y = [x * (x > 0) for x in inputs]
return y
def tanh(inputs):
y = [(np.exp(x) - np.exp(-x)) / float(np.exp(x) - np.exp(-x)) for x in inputs]
return y
def softplus(inputs):
y = [np.log(1 + np.exp(x)) for x in inputs]
return y
# 经过 TensorFlow 的激活函数处理的各个 Y 值
y_sigmoid = tf.nn.sigmoid(x)
y_relu = tf.nn.relu(x)
y_tanh = tf.nn.tanh(x)
y_softplus = tf.nn.softplus(x)
# 创建会话
sess = tf.Session()
# 运行
y_sigmoid, y_relu, y_tanh, y_softplus = sess.run([y_sigmoid, y_relu, y_tanh, y_softplus])
# 创建各个激活函数的图像
plt.figure(1, figsize=(8, 6))
plt.subplot(221)
plt.plot(x, y_sigmoid, c='red', label='Sigmoid')
plt.ylim((-0.2, 1.2))
plt.legend(loc='best')
plt.subplot(222)
plt.plot(x, y_relu, c='red', label='Relu')
plt.ylim((-1, 6))
plt.legend(loc='best')
plt.subplot(223)
plt.plot(x, y_tanh, c='red', label='Tanh')
plt.ylim((-1.3, 1.3))
plt.legend(loc='best')
plt.subplot(224)
plt.plot(x, y_softplus, c='red', label='Softplus')
plt.ylim((-1, 6))
plt.legend(loc='best')
# 显示图像
plt.show()
# 关闭会话
sess.close()