tensorflow 2.1.0 安装与实战教程(CASIA FACE v5)
作者:博二兔 发布时间:2022-06-12 08:41:23
1.0tensorflow的安装
1.1安装python
python下载 需要python3.x<=3.7
https://www.python.org/ftp/python/3.7.7/python-3.7.7-amd64.exe
安装时勾选Add Python 3.7 to PATH,把python添加到环境变量。
1.2安装tensorflow
打开命令行,执行
pip install tensorflow==2.1.0
pip 会安装tensorflow和一些其他的依赖
1.3安装vc++2015-2019redist…
tensorflow的另一个依赖(很多tensorflow安装失败的原因就是这个没安装)
https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads
1.4安装CUDA和CUDNN
cuda: https://developer.nvidia.com/cuda-downloads?target_os=Windows&target_arch=x86_64&target_version=10&target_type=exelocal
cudnn: https://developer.nvidia.com/rdp/cudnn-download(需要注册nvidia账号)
cudnn下载后是个压缩文件,要把他解压出来放在CUDA里,如下图
高版本CUDA缺失cudart64_101.dll,下载后放在C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.2\bin里
https://cn.dll-files.com/cudart64_101.dll.html
2.0CASIA实战
2.1CASIA数据集
可以从网上下载casia数据集,
这里以casia数据集为例,现实中可以使用自己需要的数据集。
2.2数据集的处理
建立data和test两个文件夹,把casia复制到里面
目录是这样的./data/000/000_0.bmp
data.py处理数据,其实就是遍历,匹配,删除
import os
data = './data'
dirs = os.listdir(data)
for dir in dirs:
for file in os.listdir(data + '/' + dir):
if file.endswith("4.bmp"):
os.remove(data + '/' + dir + '/' + file)
test = './test'
tdirs = os.listdir(test)
for dir in tdirs:
for file in os.listdir(test + '/' + dir):
if file.endswith("0.bmp"):
os.remove(test + '/' + dir + '/' + file)
if file.endswith("1.bmp"):
os.remove(test + '/' + dir + '/' + file)
if file.endswith("2.bmp"):
os.remove(test + '/' + dir + '/' + file)
if file.endswith("3.bmp"):
os.remove(test + '/' + dir + '/' + file)
2.3训练代码
casia.py
import os
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, Flatten, Dropout, MaxPooling2D
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import numpy as np
/*我直接建立了个0000,1111,...这样的数组作为标签*/
#data标签
arr = []
for i in range(100):
for j in range(4):
arr.append(i)
arr = np.array(arr)
#test标签
tarr = []
for i in range(100):
tarr.append(i)
tarr = np.array(tarr)
#训练集
pwd='./data'
dirs = os.listdir(pwd)
imgs = []
for dir in dirs:
for file in os.listdir(pwd + '/' + dir):
image = tf.io.read_file(pwd + '/' + dir + '/' + file)
img = tf.image.decode_bmp(image,channels=3)
imgs.append(img)
print("[*]训练集加载完毕")
print(imgs[0].shape)
#验证集(测试集)
tpwd='./test'
tdirs = os.listdir(tpwd)
timgs = []
for tdir in tdirs:
for tfile in os.listdir(tpwd + '/' + tdir):
timage = tf.io.read_file(tpwd + '/' + tdir + '/' + tfile)
timg = tf.image.decode_bmp(timage,channels=3)
timgs.append(timg)
print("[*]验证集加载完毕")
print(timgs[0].shape)
#神经网络模型
model = Sequential([
Conv2D(16, (3,3), padding='same', activation='relu',input_shape=(480,640,3)),
MaxPooling2D(),
Conv2D(64, (3,3), padding='same', activation='relu'),
MaxPooling2D(),
Conv2D(128, (3,3), padding='same', activation='relu'),
MaxPooling2D(),
Flatten(),
Dense(128, activation='relu'),
Dense(100, activation='softmax'),
])
model.summary()//打印神经网络模型
#优化器
model.compile(optimizer=tf.keras.optimizers.Adam(),
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
#训练
ds = tf.data.Dataset.from_tensor_slices((imgs,arr))
ds = ds.batch(16)
ds = ds.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
model.fit(ds,epochs=20)
tds = tf.data.Dataset.from_tensor_slices((timgs,tarr))
tds = ds.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
model.evaluate(tds, verbose=2)
#保存
tf.saved_model.save(model, "./tmp/")
2.4训练与验证
在命令行运行 python casia.py进行训练
predict.py
import os
import tensorflow as tf
import numpy as np
/*这里显卡内存不够了*/
from tensorflow.compat.v1 import ConfigProto
from tensorflow.compat.v1 import InteractiveSession
config = ConfigProto()
config.gpu_options.allow_growth = True
session = InteractiveSession(config=config)
/*显卡内存*/
model_path = './tmp' //加载模型
test_path = "./test/002/002_4.bmp"//这里就是个栗子
model = tf.keras.models.load_model(model_path, custom_objects=None, compile=True)
image = tf.io.read_file(test_path)
img = tf.image.decode_bmp(image,channels=3)
img = img[tf.newaxis, ...]
res = model.predict(
img, batch_size=None, verbose=0, steps=None, callbacks=None, max_queue_size=10,
workers=1, use_multiprocessing=False
)
pred = tf.argmax(res, axis=1)
print (pred[0])
print (res[0,pred[0]])
来源:https://blog.csdn.net/weixin_44753738/article/details/107032785
猜你喜欢
- 一、函数概述简单来说 函数 就是自己定义的一段 小程序 方便自己调取使用def 用来定义函数的关键字 也就是这个函数的名字函数运行到retu
- 本文通过问答的开式来解答在mysql在命名用过程中所遇到的常见问题。谁能连接,从那儿连接?你可以允许一个用户从特定的或一系列主机连接。有一个
- 如果用户查询时,使用Order BY排序语句指定按员工编号来排序,那么排序后产生的所有记录就是临时数据。对于这些临时数据,Oracle数据库
- 1 The syntax of the SQL statement is verified.SQL的语法检查2 The data dicti
- PHP将ppt转成图片查看PHP安装COM组件1、如php版本>5.3.15,需要保证ext文件夹下有php_com_dotnet.d
- 代码如下:SELECT [StartDate] FROM [dbo].[udf_Week](2012,2012) WHERE [
- 阅读上一篇:FrontPage2002简明教程一:安装与界面FrontPage中对于文字与图像的处理与Word很相似,用过Word的人对于F
- 我们进行CSS网页布局的时候,都知道它需要符合XHTML1.0规范。如果我们在进行CSS网页布局的时候,还在使用被W3C废弃的元素,那就失去
- 今天实习公司分配了一个数据处理的任务。在将列表中的字符串连接成一个长路径时,我遇到了如下问题:import ospath_list = [&
- 从这里开始我的博客,后台数据库是什么?没错,就是MySQL,服务器端使用的脚本就是PHP,整个框架使用的是WordPress。PHP和MyS
- 1. 复制表结构及其数据:create table table_name_new as select * from table_name_o
- 困扰我很久问题终于在昨天被解决了。其实问题很简单<% =now %>老是显示12小时制,总是出现上午、下午。这个问题虽然很小,但
- 问题:m = re.findall('[0-9]*4[0-9]*', '[4]') 可以匹配到4.m = r
- 此类技巧还有很多,欢迎继续分享解析 URL从 James Padolsey 的 Blog中看到的个小技巧,就是利用 a 标签的 DOM 属性
- 使用 Microsoft® SQL Server™ 2000,可以选择在一台计算机上安装 SQL Ser
- 本文实例为大家分享了python实现通讯录管理系统的具体代码,供大家参考,具体内容如下=====欢迎使用通讯录管理系统=====1.添加2.
- 曾经有许多创造性的logo设计案例,logo设计资源和logo设计指导张贴在互联网的各个角落。这些帮助会为你的logo设计创造一个功能强大的
- 每个浏览器都有自己的默认样式,这是一段预定义的CSS,用以简单地呈现网页。在Firefox中的地址栏中输入resource://gre/re
- 前天由于某些原因需要利用C++调用PyTorch,于是接触到了LibTorch,配了两天最终有了一定的效果,于是记录一下。环境PyTorch
- 1.Training: 如何训练模型一句话理解机器学习一般训练过程 :通过有标签样本来调整(学习)并确定所有权重Weights和偏差Bias