首页 >> 大全

基本使用

2023-08-24 大全 32 作者:考证青年

基本使用

以数据流图为表达形式,每一个节点会获得0个或多个(数据)

import tensorflow as tf
'''
"/cpu:0": 机器的 CPU.
"/gpu:0": 机器的第一个 GPU, 如果有的话.
"/gpu:1": 机器的第二个 GPU, 以此类推.
'''
tf.device("/cpu:0")
#创建一个节点matri1
matri1 = tf.constant([[3.,3.]]) #定义常量矩阵1*2
#创建一个节点matri2
matri2 = tf.constant([[2.],[2.]])#定义常量矩阵2*2
#创建矩阵乘法
prduct = tf.matmul(matri1,matri2)
#这里存在三个节点
#在一个会话中启动图
sess = tf.Session()
# 调用 sess 的 'run()' 方法来执行矩阵乘法 op, 传入 'product' 作为该方法的参数.
# 上面提到, 'product' 代表了矩阵乘法 op 的输出, 传入它是向方法表明, 我们希望取回
# 矩阵乘法 op 的输出.
# 整个执行过程是自动化的, 会话负责传递 op 所需的全部输入. op 通常是并发执行的.
# 函数调用 'run(product)' 触发了图中三个 op (两个常量 op 和一个矩阵乘法 op) 的执行.
# 返回值 'result' 是一个 numpy `ndarray` 对象.
result = sess.run(prduct)
print(result)
#任务完成,结束会话。
# sess.clase()
'''
可以使用with完成代码块激活
'''
with tf.Session() as sess: result = sess.run(prduct)print(result)

实现MNIST

是一个非常强大的用来做大规模数值计算的库。其所擅长的任务之一就是实现以及训练深度神经网络。

列表【】(# 列表(打了激素数组): 可以存储任意数据类型的集和。)

元组()(一旦定义了数值就没有办法修改!)

基本使用重量_pymysql的基本使用_

利于机器学习实现手写字体代码。

import tensorflow.examples.tutorials.mnist.input_data as input_data
mnist = input_data.read_data_sets("MNIST_data/",one_hot = True)import tensorflow as tf
'''
x不是一个特定的事,而是一个占位符。float32是tf最常用的数据格式。
定义个列表[]里面是数值是可以变化的量。
我们用2维的浮点数张量来表示这些图,这个张量的形状是[None,784 ]。
(这里的None表示此张量的第一个维度可以是任何长度的。)
'''
x = tf.placeholder(tf.float32,[None,784])
'''
一个Variable代表一个可修改的张量,
对于各种机器学习应用,一般都会有模型参数,可以用Variable表示。
tf.zeros创建一个初始化全为0的数值
w的维度是[784,10],一张图像输入28*28,总共10个分类,就会有{784*photo*10]个权重参数
B的维度是[10],每一个类别都会有1个偏置。
'''
W = tf.Variable(tf.zeros([784,10]))
B = tf.Variable(tf.zeros([10]))
'''
首先,我们用tf.matmul(​​X,W)表示x乘以W,对应之前等式里面的,这里x是一个2维张量拥有多个输入。
然后再加上b,把和输入到tf.nn.softmax函数里面。
经过Softmax之后(0.3,0.05,0.05,0.1,0.1.。。。。。。)10个数值
'''
y = tf.nn.softmax(tf.matmul(x,W)+B)
'''
训练模型:
定义指标来评估模型的好坏,指标一般是loss(损失)。最常见的函数是”交叉熵”cross_entropy
我们需要定义一个新的,正确的占位符来表示正确的输入。
'''
y_ = tf.placeholder(tf.float32,[None,10])
'''
计算交叉熵:
假设有一个三分类问题,某个样例的正确答案是(1,0,0)。
某模型经过softmax回归之后的预测答案是(0.5,0.4,0.1),
那么这个预测和正确答案之间的交叉熵为:正确答案((1,0,0),预测(0.5,0.4,0.1))= -(1*log0.5+0*log0.4+0*log0.1)≈0.3
用 tf.reduce_sum 计算张量的所有元素的总和。
(注意,这里的交叉熵不仅仅用来衡量单一的一对预测和真实值,
而是所有100幅图片的交叉熵的总和。对于100个数据点的预测表现比单一数据点的表现能更好地描述我们的模型的性能。
'''
cross_entropy = -tf.reduce_sum(y_ * tf.log(y)) #得出loss
'''
定义一个optimizer优化器(梯度下降算法),以0.01的学习率最小化交叉熵
'''
Optimizer = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
'''
定义完模型之后,运行之前需要对所有的变量进行初始化的操作。
'''
init = tf.global_variables_initializer() #最新版的定义全局初始化。
'''
在Session里面启动我们的模型
'''
sess = tf.Session()
sess.run(init)
'''
训练模型
mnist.train.next_batch 随机从mnist中抽取100张图片训练,
feed_dict:填充前面占位符的x和y
'''
for i in range(1000):batch_xs, batch_ys = mnist.train.next_batch(100)sess.run(Optimizer, feed_dict={x: batch_xs, y_: batch_ys})
'''
tf.argmax用途:返回最大的那个数值所在的下标(第一个参数是矩阵,第二个参数是0或者1。
0表示的是按列比较返回最大值的索引,1表示按行比较返回最大值的索引)。
tf.equal:判断真实和预测值是否相同。
例如真实值是[0,0,1],预测是[0.6,0.3,0.1],经过argmax之后返回3和1,经过equal判断后结果为False
下面一行代码只会输出True和False。
'''
correct_prrediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1))
'''
tf.cast()函数的作用是执行 tensorflow 中张量数据类型转换
tf.reduce_mean 函数用于计算张量tensor沿着指定的数轴(tensor的某一维度)上的的平均值,
主要用作降维或者计算tensor(图像)的平均值。
'''
accuracy = tf.reduce_mean(tf.cast(correct_prrediction,"float32"))
'''
我们计算所学习到的模型在测试数据集上面的正确率。
'''
print(sess.run(accuracy,feed_dict={x:mnist.test.images,y_: mnist.test.labels}))

#加载库
'''
如果某个版本中出现了某个新的功能特性,而且这个特性和当前版本中使用的不兼容,
也就是它在该版本中不是语言标准,那么我如果想要使用的话就需要从future模块导入。
'''
from __future__ import  print_function
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import  input_data
'''
建模顺序
导入库和数据
创建会话窗口
定义placehould变量,xs(图像) , ys(真实的lable) ,dropout
定义函数:权重,偏置,卷积,池化
执行,卷积池化,卷积池化,全连接,定义dropout,全连接softmax
定义交叉熵和优化器
全局变量初始化,激活图
训练
测试精确度
'''
#加载0~10的数据
mnist = input_data.read_data_sets( 'MNIST_data', one_hot=True )
'''
提前定义一个图
通过它,你可以更加灵活地构建你的代码。
它能让你在运行图的时候,插入一些计算图,这些计算图是由某些操作(operations)构成的。
'''
#定义运行变量
sess = tf.InteractiveSession()
'''
这里我们会应用多层的卷积网络来构建softmax回归模型。
虽然placeholder的shape参数是可选的,但有了它,TensorFlow能够自动捕捉因数据维度不一致导致的错误。
None表示其值大小不定,在这里作为第一个维度值,用以指代batch的大小
'''
#定义变量  开辟内存空间
xs = tf.placeholder( tf.float32, [None, 784] )/255. #28*28
ys = tf.placeholder( tf.float32, [None, 10 ])
dropout = tf.placeholder( tf.float32 )  #定义一个tensor
'''
函数的作用是将tensor变换为参数shape形式,其中的shape为一个列表形式,特殊的是列表可以实现逆序的遍历
即list(-1).-1所代表的含义是我们不用亲自去指定这一维的大小,函数会自动进行计算,但是列表中只能存在一个-1。
(如果存在多个-1,就是一个存在多解的方程) 只有reshape形式下才可以进行卷积池化???
'''
x_image = tf.reshape(xs, [-1, 28, 28, 1])  #输入reshape28*28  图片数量, 图片高度, 图片宽度, 图像通道数]#辅助函数 计算精度
def compute_accuracy( v_xs, v_ys ):global prediction  #Python中定义函数时,若想在函数内部对函数外的变量进行操作,就需要在函数内部声明其为global。y_pre = sess.run(prediction, feed_dict={ xs:v_xs, dropout:1 } )  #预测   #这里的run是为了执行外面global的函数correct_prediction = tf.equal( tf.argmax( y_pre, 1 ), tf.argmax(v_ys, 1 ) )   #比较预测和真实值accuracy = tf.reduce_mean( tf.cast( correct_prediction, tf.float32 ) )  #转换类型result = sess.run( accuracy, feed_dict={ xs:v_xs, ys:v_ys, dropout:1 } ) #这里的run是为了执行本函数return  result#**************************************  函数定义 *****************************************
#定义权重函数
'''
这里的weight相当于卷积核,将卷积核里面的参数初始化为正太分布的0.1。stddev(正太分布的标准差)
'''
def weight_variable(shape):initial = tf.truncated_normal(shape, stddev=0.1 )  #正态分布在0.1之间 #最后返回一个sizereturn tf.Variable(initial)#定义偏置函数
def bias_variable(shape):initial = tf.constant( 0.1, shape= shape )  #定义一个参数0.1作为最开始的偏置return tf.Variable(initial)#定义卷积函数
def conv2d(x,W):return tf.nn.conv2d( x,W, strides=[1,1,1,1] , padding='SAME')#定义最大池化函数
def max_pool_2x2(x):return tf.nn.max_pool( x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME' )  #ksize=[1,2,2,1]的前后两位都是1,因为我们不想在batch和channels上做池化,所以这两个维度设为了1#LeNet5 卷积+池化+卷积+池化+拉直+全连接层(隐层)+全连接层(输出层)
#**************************************  深度学习部分 *****************************************
#第1次:卷积+池化
W_conv1 = weight_variable( [5,5,1,32]   ) #卷积核大小5*5,输入通道数量1, 卷积核的数量32  [卷积核的高度,卷积核的宽度,图像通道数,卷积核个数]
b_conv1 = bias_variable( [32] )           #32个偏置,32个输出的神经元
h_conv1 = tf.nn.relu( conv2d( x_image,W_conv1) + b_conv1 ) #输入图像28*28, 输出通道32个
print('卷积',h_conv1)
h_pool1 = max_pool_2x2(h_conv1)           #池化后,输出图像14*14, 输出通道32个,输出特征图28*28
print(h_pool1)#第2次:卷积+池化
W_conv2 = weight_variable( [5,5,32,64] ) #卷积核大小5*5, 输入通道32个,卷积核数量64个
b_conv2 = bias_variable( [64] )          #偏置数量=该层神经元数量 = 64
h_conv2 = tf.nn.relu( conv2d( h_pool1, W_conv2) + b_conv2 ) #输入特征图14*14, 64个特征图 平面
print(h_conv2)
h_pool2 = max_pool_2x2( h_conv2 )        #池化后,输出特征图7*7, 64个特征图
print(h_pool2)#拉直
h_pool2_flat = tf.reshape(   h_pool2,  [-1, 7*7*64]  )#第1次:全连接层(隐层)
W_fc1 = weight_variable( [7*7*64,1024] ) #输入变量7*7*64,输出1024个变量
b_fc1 = bias_variable( [1024] )          #偏置数量= 该层神经元数量 = 1024
h_fc1 = tf.nn.relu( tf.matmul( h_pool2_flat, W_fc1 ) + b_fc1 ) # 输出神经元数量1024,一维向量 直线
'''
keep_prob: float类型,每个元素被保留下来的概率,设置神经元被选中的概率,在初始化时keep_prob是一个占位符, keep_prob = tf.placeholder(tf.float32) 。
tensorflow在run时设置keep_prob具体的值,例如keep_prob: 0.5
'''
h_fc1_drop = tf.nn.dropout( h_fc1, dropout )#第2次:全连接层(输出层)
W_fc2 = weight_variable( [1024,10] ) #输入1024变(神经元)量, 输出10个变量
b_fc2 = bias_variable( [10] )        #偏置数量 = 该层神经元数量 = 10
prediction = tf.nn.softmax( tf.matmul( h_fc1_drop , W_fc2 ) + b_fc2 )  #整个网络最后输出#误差:采用交叉熵,损失函数(评价标准=用于训练)
'''
交叉熵例子:正确答案((1,0,0),预测(0.5,0.4,0.1))= -(1*log0.5+0*log0.4+0*log0.1)≈0.3
tf.reduce_sum:计算总和
#reduction_indices[1] 会输出【1,2】这样的两个结果
tf.reduce_sum:计算张量的各个维度上的元素的平均值.:比如x = [[2,2,4],[2,2,4]] #(2+2+4)*2 /6  
'''
cross_entropy = tf.reduce_mean( -tf.reduce_sum( ys*tf.log(prediction), reduction_indices=[1] ) )
#训练
'''
设置优化器,定义优化交叉熵
'''
trian_step = tf.train.AdamOptimizer( 1e-4 ).minimize(cross_entropy)init = tf.global_variables_initializer()
sess.run(init)#训练300次
for i in range(1000):batch_xs, batch_ys = mnist.train.next_batch(100)sess.run(trian_step,  feed_dict={ xs:batch_xs, ys:batch_ys, dropout:0.5 } )if i % 50 == 0:print('训练loss:',sess.run(cross_entropy,feed_dict={xs:batch_xs,ys:batch_ys,dropout : 1}))if i % 50 == 0:print( "测试准确度:",i, compute_accuracy(mnist.test.images[:1000], mnist.test.labels[:1000]  ) )

利于Lenet做三分类任务

#coding=utf-8import os
#图像读取库
from PIL import Image
#矩阵运算库
import numpy as np
import tensorflow as tf# 数据文件夹
data_dir = "data"#_test
# 训练还是测试
train =False  # True#
# 模型文件路径
model_path = "model/image_model"data_test = 'data_test'
def read_test(x):global fpathtest = []for fname in os.listdir(x):fpath = os.path.join(x, fname)image = Image.open(fpath)fname = np.array(image) / 255.0test.append(fname)# test = np.append(test)return testdeta_test = read_test (data_test)# 从文件夹读取图片和标签到numpy数组中
# 标签信息在文件名中,例如1_40.jpg表示该图片的标签为1
'''
定义三个列表:图片,标签,图片文件
os.listdir(data_dir) 方法用于返回指定的文件夹包含的文件或文件夹的名字的列表。
s.path.join  。自动加上/    data/0_6.jpg
PIL.Image.open()专接图片路径,用来直接读取该路径指向的图片。要求路径必须指明到哪张图,不能只是所有图所在的文件夹;
'''
def read_data(data_dir):datas = []labels = []fpaths = []for fname in os.listdir(data_dir):fpath = os.path.join(data_dir, fname)    #data/0_6.jpgfpaths.append(fpath)   #拥有了data下所有的图片文件的位置image = Image.open(fpath)  #读取所有图片的位置,这里返回的是JPEG图像文件图像模式=RGB,大小=32x32data = np.array(image) / 255.0  #将图像矩阵32*32,转换为np的数据格式并做归一化label = int(fname.split("_")[0]) #从_中分割,0位置为图片的labeldatas.append(data)  #将矩阵图片添加进datas列表中labels.append(label)#加lable添加进labels列表走datas = np.array(datas)  #转换np格式labels = np.array(labels)#转换np格式print(r"shape aof dtas: {}\tshape of labels: {}".format(datas.shape, labels.shape))return fpaths, datas, labelsfpaths, datas, labels = read_data(data_dir)# 计算有多少类图片
num_classes = len(set(labels))# 定义Placeholder,存放输入和标签
datas_placeholder = tf.placeholder(tf.float32, [None, 32, 32, 3])
labels_placeholder = tf.placeholder(tf.int32, [None])# 存放DropOut参数的容器,训练时为0.25,测试时为0
dropout_placeholdr = tf.placeholder(tf.float32)'''
tf.layers.conv2d是tf.nn.conv2d更高级的api
这里只需要定义输入,卷积核通道数,卷积核大小,激活函数
'''
# 定义卷积层, 20个卷积核, 卷积核大小为5,用Relu激活
conv0 = tf.layers.conv2d(datas_placeholder, 20, 5, activation=tf.nn.relu)    #28*28*20
print(conv0)
# 定义max-pooling层,pooling窗口为2x2,步长为2x2
pool0 = tf.layers.max_pooling2d(conv0, [2, 2], [2, 2])      #14*14*20
print(pool0)
# 定义卷积层, 40个卷积核, 卷积核大小为4,用Relu激活
conv1 = tf.layers.conv2d(pool0, 40,5, activation=tf.nn.relu) #10*10*40
print(conv1)
# 定义max-pooling层,pooling窗口为2x2,步长为2x2
pool1 = tf.layers.max_pooling2d(conv1, [2, 2], [2, 2])  #5*5*40
print(pool1)
# 将3维特征转换为1维向量(扁平化)
flatten = tf.layers.flatten(pool1)# 全连接层,转换为长度为100的特征向量
fc = tf.layers.dense(flatten, 400, activation=tf.nn.relu)# 加上DropOut,防止过拟合
dropout_fc = tf.layers.dropout(fc, dropout_placeholdr)# 全连接层,转换为长度为nun_classes的特征向量,这一步不定义激活函数softmax的原因是:下面我们应用tf.nn.softmax_cross_entropy_with_logits函数。
logits = tf.layers.dense(dropout_fc, num_classes)predicted_labels = tf.arg_max(logits, 1)  #测试输出概率最大的一个类别
print(predicted_labels)
'''
tf.nn.softmax_cross_entropy_with_logits函数:
tf.one_hot:(热编码)函数,如果Yj为第一类那么其独热编码为: [1,0,0,0,0],如果是第二类那么独热编码为:[0,1,0,0,0],'''
# 利用交叉熵定义损失
losses = tf.nn.softmax_cross_entropy_with_logits(labels=tf.one_hot(labels_placeholder, num_classes), #真实label是分类的概率,比如说[0.2,0.3,0.5].我们设置了函数tf.one_hot之后就会输出[1,0],或者[0,1]logits=logits   #预测时的labels ,返回的是[0.2,0.3,0.5]概率值,加起来=1
)
# 平均损失
mean_loss = tf.reduce_mean(losses)  #将[0.2,0.3,0.5]相加之后除以数量求平均!这就是我们要缩小的loss值,越小越好。# 定义优化器,指定要优化的损失函数
optimizer = tf.train.AdamOptimizer(learning_rate=1e-2).minimize(losses)  #定义优化器缩小loss# 用于保存和载入模型
saver = tf.train.Saver()with tf.Session() as sess: #创建会话if train:   #假如多true则进行训练模式print("训练模式")# 如果是训练,初始化参数sess.run(tf.global_variables_initializer()) #全局变量初始化# sess.run:执行优化器和打印出loss。定义输入和Label以填充容器,训练时dropout为0.25for step in range(1500):_, mean_loss_val = sess.run([optimizer, mean_loss], feed_dict={datas_placeholder: datas,labels_placeholder: labels,dropout_placeholdr: 0.25})if step % 10 == 0: #每训练10次就打印出一次lossprint(r"step = {}\tmean loss = {}".format(step, mean_loss_val))saver.save(sess, model_path)  #保存模型文件#image_model.meta  保存模型#image_model.data  保存变量print("训练结束,保存模型到{}".format(model_path))else:print("测试模式")# 如果是测试,载入参数saver.restore(sess, model_path)  #saver.restore:载入数据,因为模型上面已经定义好了,所以只需要读书数据就好。需要读取模型就用tf.train.import_meta_graphprint("从{}载入模型".format(model_path))# label和名称的对照关系label_name_dict = {0: "飞机",1: "汽车",2: "鸟"}# 定义输入和Label以填充容器,测试时dropout为0predicted_labels_val = sess.run(predicted_labels, feed_dict={datas_placeholder: deta_test,dropout_placeholdr: 0})# print('鸟', predicted_labels_val)# 真实label与模型预测labelfor i in predicted_labels_val:if i == 1:print('汽车',)elif i == 0:print('飞机')else:print('鸟')

关于我们

最火推荐

小编推荐

联系我们


版权声明:本站内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 88@qq.com 举报,一经查实,本站将立刻删除。备案号:桂ICP备2021009421号
Powered By Z-BlogPHP.
复制成功
微信号:
我知道了