这是我参与8月更文挑战的第16天,活动详情查看:8月更文挑战
Session 会议控制
Session 是 TensorFlow 为了控制和输出文件的执行语句,运行 Session.run() 可以获得你想要的运算结果
import tensorflow as tf
# session 会议控制
tf.compat.v1.disable_eager_execution() # 保证sess.run()能够正常运行
matrix1 = tf.constant([[3, 3]]) # 建立两个矩阵
matrix2 = tf.constant([[2], [2]])
product = tf.matmul(matrix1, matrix2) # 矩阵乘法-->np.dot(m1,m2)
# 方法一
sess = tf.compat.v1.Session()
result = sess.run(product)
print(result) # 12 矩阵相乘的结果
sess.close()
# 方法二
# with tf.compat.v1.Session() as session: # 自动关上的
# result = session.run(product)
# print(result)
复制代码
Variable 变量定义
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
state = tf.Variable(0,name='counter') # Variable 变量
# print(state.name) # result=counter:0
one = tf.constant(1) # 加上常量
new_value = tf.add(state,one)
update = tf.compat.v1.assign(state, new_value) # 更新这个变量的值
init = tf.compat.v1.global_variables_initializer() # 更新过了之后就会这么一个函数的进行,初始化所有变量才能激活这些变量
with tf.compat.v1.Session() as sess:
sess.run(init)
for _ in range(3):
sess.run(update) # 每一次都更新这个函数里面的值
print(sess.run(state)) # 这样才会有这个state的出现,不然打印不出来的,要必须先在这个里面变成
# 1
# 2
# 3
复制代码
Placeholder 控制输入
import tensorflow as tf
# input1 = tf.compat.v1.placeholder(tf.float32,[2,2]) # [2,2] 输入两行两列的数据
tf.compat.v1.disable_eager_execution()
input1 = tf.compat.v1.placeholder(tf.float32)
input2 = tf.compat.v1.placeholder(tf.float32)
output = tf.compat.v1.multiply(input1, input2) # 相乘
with tf.compat.v1.Session() as sess:
print(sess.run(output, feed_dict={input1: [7.], input2: [2.]})) # 14
复制代码
Activation_Function 激活函数
Activation_Function 激活函数是用来加入非线性因素的,解决线性模型所不能解决的问题
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
tf.compat.v1.disable_eager_execution()
def add_layer(inputs, in_size, out_size,n_layer, activation_function):
# 添加隐藏层 即使添加神经层数 以达到不断迭代的过程
layer_name = 'layer%s'% n_layer
with tf.name_scope(layer_name):
with tf.name_scope('weights'):
Weights = tf.Variable(tf.random.normal([in_size, out_size]), name='W') # 定义一个矩阵,随机定义参数,初始值
tf.summary.histogram(layer_name+'/weights',Weights)
with tf.name_scope('biases'):
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name='b') # biases 的初始值是推荐不要为零,所以现在就是要加上0.1
tf.summary.histogram(layer_name+'/biases',biases)
with tf.name_scope('Wx_plus_b'):
Wx_plus_b = tf.compat.v1.matmul(inputs, Weights,name='wb') + biases # input*Weights + biases 这是预测的值 还没激活
if activation_function is None:
outputs = Wx_plus_b # 这个是线性方程,所以就不需要加上非线性的激活函数
else:
outputs = activation_function(Wx_plus_b)
tf.summary.histogram(layer_name+'/outputs',outputs)
return outputs
x_data = np.linspace(-1, 1, 300)[:, np.newaxis].astype(np.float32) # 建立一个-1 1 的等差数列 最后加上一个维度,变成有维度的矩阵形式
# 现在是[300,1] 的矩阵 输入层 300行1列的矩阵
# x_data=tf.cast(tf.float32,x_data)
noise = np.random.normal(0, 0.05, x_data.shape) # 手动添加噪点 方差0.05
# noise=tf.cast(tf.float32,noise)
y_data = np.square(x_data) - 0.5 + noise
# y_data=tf.cast(tf.float32,y_data)
with tf.name_scope('input'): # 输入层
xs = tf.compat.v1.placeholder(tf.float32, [None, 1], name='x_input') # 这里是传入数据用的,这里无论是传入多少个例子都是可以的
ys = tf.compat.v1.placeholder(tf.float32, [None, 1], name='y_input') # 这里是一个None来表达 ,但是是一个矩阵的形式:未知行1列
l1 = add_layer(xs, 1, 10, 1, tf.nn.relu)
# 这里是添加了第一层的隐藏层[1,10] 这里是1行10列的矩阵
predition = add_layer(l1, 10, 1, 2, None)
# 最后的输出层是一个[10,1] 是一个10行1列的矩阵
with tf.name_scope('loss'):
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - predition), axis=1)) # 平均的误差
tf.summary.scalar('loss', loss)
with tf.name_scope('train'):
train_step = tf.compat.v1.train.GradientDescentOptimizer(0.1).minimize(loss)
# 学习效率0.1 用这个优化器以0.1的效率对这个误差进行更正
init = tf.compat.v1.global_variables_initializer()
# 随机的梯度下降
fig = plt.figure() # 先生成一个框框
ax = fig.add_subplot(1, 1, 1)
ax.scatter(x_data, y_data) # 生成原来的图片
plt.ion()
plt.show()
with tf.compat.v1.Session() as sess:
writer = tf.compat.v1.summary.FileWriter("logs/", sess.graph)
sess.run(init)
for i in range(1000):
sess.run(train_step, feed_dict={xs: x_data, ys: y_data}) # 方便封装
if i % 50 == 0:
# print(sess.run(loss, feed_dict={xs: x_data, ys: y_data}))
try:
ax.lines.remove(lines[0]) # 显示之后要去除掉那条线
except Exception: # 第一次是没有的,
pass
predition_value = sess.run(predition, feed_dict={xs: x_data, ys: y_data})
lines = ax.plot(x_data, predition_value, 'r-', lw=5) # 将预测的这个值打上去
plt.pause(0.1)
# loss_function不断在减小,所以就会一直在学习,减少误差
# 1.9184123
# 0.053955305
# 0.03053456
# 0.017190851
# 0.010993273
# 0.008209449
# 0.0067526144
# 0.0058726957
# 0.005269445
# 0.00477808
# 0.0044394922
# 0.0041766805
# 0.0039696493
# 0.003815
# 0.0036952242
# 0.0036034652
# 0.0035240129
# 0.0034543637
# 0.0033897285
# 0.0033306282
# Tips:空间不足的时候,有可能会报错的
复制代码
TensorBorad
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
tf.compat.v1.disable_eager_execution()
def add_layer(inputs, in_size, out_size, n_layer, activation_function): # 添加隐藏层 即使添加神经层数 以达到不断迭代的过程吧
layer_name = 'layer%s' % n_layer
with tf.name_scope(layer_name):
with tf.name_scope('weights'):
Weights = tf.Variable(tf.random.normal([in_size, out_size]), name='W') # 定义一个矩阵,随机定义参数,初始值
tf.summary.histogram(layer_name + '/weights', Weights)
with tf.name_scope('biases'):
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name='b') # biases 的初始值是推荐不要为零,所以现在就是要加上0.1
tf.summary.histogram(layer_name + '/biases', biases)
with tf.name_scope('Wx_plus_b'):
Wx_plus_b = tf.compat.v1.matmul(inputs, Weights, name='wb') + biases # input*Weights + biases 这是预测的值 还没激活
if activation_function is None:
outputs = Wx_plus_b # 这个是线性方程,所以就不需要加上非线性的激活函数
else:
outputs = activation_function(Wx_plus_b)
tf.summary.histogram(layer_name + '/outputs', outputs)
return outputs
x_data = np.linspace(-1, 1, 300)[:, np.newaxis].astype(np.float32) # 建立一个-1 1 的等差数列 最后加上一个维度,变成有维度的矩阵形式
# 现在是[300,1] 的矩阵 输入层 300行1列的矩阵
# x_data=tf.cast(tf.float32,x_data)
noise = np.random.normal(0, 0.05, x_data.shape) # 手动添加噪点 方差0.05
# noise=tf.cast(tf.float32,noise)
y_data = np.square(x_data) - 0.5 + noise
# y_data=tf.cast(tf.float32,y_data)
with tf.name_scope('input'): # 输入层
xs = tf.compat.v1.placeholder(tf.float32, [None, 1], name='x_input') # 这里是传入数据用的,这里无论是传入多少个例子都是可以的
ys = tf.compat.v1.placeholder(tf.float32, [None, 1], name='y_input') # 这里是一个None来表达 ,但是是一个矩阵的形式:未知行1列
l1 = add_layer(xs, 1, 10, 1, tf.nn.relu)
# 这里是添加了第一层的隐藏层[1,10] 这里是1行10列的矩阵
predition = add_layer(l1, 10, 1, 2, None)
# 最后的输出层是一个[10,1] 是一个10行1列的矩阵
with tf.name_scope('loss'):
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - predition), axis=1)) # 平均的误差
tf.summary.scalar('loss', loss)
with tf.name_scope('train'):
train_step = tf.compat.v1.train.GradientDescentOptimizer(0.1).minimize(loss)
# 学习效率0.1 用这个优化器以0.1的效率对这个误差进行更正
init = tf.compat.v1.global_variables_initializer()
with tf.compat.v1.Session() as sess:
writer = tf.compat.v1.summary.FileWriter("logs/", sess.graph)
sess.run(init)
merged = tf.compat.v1.summary.merge_all()
for i in range(1000):
sess.run(train_step, feed_dict={xs: x_data, ys: y_data}) # 方便封装
if i % 50 == 0:
result = sess.run([merged,train_step], feed_dict={xs: x_data, ys: y_data})
writer.add_summary(result, i)
# Tips:空间不足的时候,有可能会报错的
复制代码
Classification 分类器
识别手写数字为例子
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist_data = input_data.read_data_sets("MNIST_data/", one_hot=True)
def add_layer(inputs, in_size, out_size, activation_function): # 添加隐藏层 即使添加神经层数 以达到不断迭代的过程吧
Weights = tf.Variable(tf.random.normal([in_size, out_size]), name='W') # 定义一个矩阵,随机定义参数,初始值
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name='b') # biases 的初始值是推荐不要为零,所以现在就是要加上0.1
Wx_plus_b = tf.compat.v1.matmul(inputs, Weights, name='wb') + biases
# input*Weights + biases 这是预测的值 还没激活
if activation_function is None:
outputs = Wx_plus_b # 这个是线性方程,所以就不需要加上非线性的激活函数
else:
outputs = activation_function(Wx_plus_b)
return outputs
def compute_accracy(v_xs, v_ys):
global prediction
y_pre = sess.run(prediction, feed_dict={xs: v_xs})
corrent_prediction = tf.equal(tf.argmax(y_pre, 1), tf.argmax(v_ys, 1)) # 生成预测值
accuracy = tf.reduce_mean(tf.cast(corrent_prediction, tf.float32))
result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys})
return result
tf.compat.v1.disable_eager_execution()
xs = tf.compat.v1.placeholder(tf.float32, [None, 784]) # 28*28
ys = tf.compat.v1.placeholder(tf.float32, [None, 10])
prediction = add_layer(xs, 784, 10, activation_function=tf.nn.softmax)
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.math.log(prediction), axis=1)) # 交叉熵损失函数
train_step = tf.compat.v1.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
sess = tf.compat.v1.Session()
sess.run(tf.compat.v1.initialize_all_variables())
for i in range(1000):
batch_xs, batch_ys = mnist_data.train.next_batch(100)
sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys}) # 进行学习1000次
if i % 50 == 0:
print(compute_accracy(mnist_data.test.images, mnist_data.test.labels))
sess.close()
复制代码
OverFitting 过拟合
在训练集当中表现优秀,但是在测试集当中表现好,举个例子:在自己圈子里很强,但是在放到别处就很水了。
解决过拟合
1.增加数据量,只要圈子足够大,就能减少过拟合的现象
2.使用正规化,y=w*x+b
L1正规化:
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
喜欢就支持一下吧
相关推荐