keras tensorboard的使用, 设置GPU使用的内存, 强制只使用cpu

2024-08-27 19:48

本文主要是介绍keras tensorboard的使用, 设置GPU使用的内存, 强制只使用cpu,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

强制只使用cpu:

import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"   # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"] = ""

keras2.0版本已经添加了一些贡献者的新建议,用keras调用tensorboard对训练过程进行跟踪观察非常方便了。

直接上例子:   (注意: 貌似调用tensorboard,训练速度好像被托慢了不少。其实可以记录model.fit的history对象,自己写几行代码显示 点击打开链接)

# coding: utf-8
import numpy as np
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.optimizers import SGD
from keras.utils import np_utils
import keras.callbacksimport os
import tensorflow as tf
import keras.backend.tensorflow_backend as KTF######################################
# TODO: set the gpu memory using fraction #
#####################################
def get_session(gpu_fraction=0.3):"""This function is to allocate GPU memory a specific fractionAssume that you have 6GB of GPU memory and want to allocate ~2GB"""num_threads = os.environ.get('OMP_NUM_THREADS')gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_fraction)if num_threads:return tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, intra_op_parallelism_threads=num_threads))else:return tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
KTF.set_session(get_session(0.6))  # using 60% of total GPU Memory
os.system("nvidia-smi")  # Execute the command (a string) in a subshell
raw_input("Press Enter to continue...")
######################batch_size = 128
nb_classes = 10
nb_epoch = 10
nb_data = 28 * 28
log_filepath = '/tmp/keras_log'# load data(X_train, y_train), (X_test, y_test) = mnist.load_data()# reshape
print X_train.shape
X_train = X_train.reshape(X_train.shape[0], X_train.shape[1] * X_train.shape[2])
X_test = X_test.reshape(X_test.shape[0], X_test.shape[1] * X_test.shape[2])
# rescaleX_train = X_train.astype(np.float32)
X_train /= 255X_test = X_test.astype(np.float32)
X_test /= 255
# convert class vectors to binary class matrices (one hot vectors)Y_train = np_utils.to_categorical(y_train, nb_classes)
Y_test = np_utils.to_categorical(y_test, nb_classes)model = Sequential()
model.add(Dense(512, input_shape=(nb_data,), init='normal', name='dense1')) # a sample is a row 28*28
model.add(Activation('relu', name='relu1'))
model.add(Dropout(0.2, name='dropout1'))
model.add(Dense(512, init='normal', name='dense2'))
model.add(Activation('relu', name='relu2'))
model.add(Dropout(0.2, name='dropout2'))
model.add(Dense(10, init='normal', name='dense3'))
model.add(Activation('softmax', name='softmax1'))
model.summary()model.compile(loss='categorical_crossentropy', optimizer=SGD(lr=0.001), metrics=['accuracy'])tb_cb = keras.callbacks.TensorBoard(log_dir=log_filepath, write_images=1, histogram_freq=1)
# 设置log的存储位置,将网络权值以图片格式保持在tensorboard中显示,设置每一个周期计算一次网络的
#权值,每层输出值的分布直方图
cbks = [tb_cb]
history = model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch, 
verbose=1, callbacks=cbks, validation_data=(X_test, Y_test))score = model.evaluate(X_test, Y_test, verbose=0)
print('Test score:', score[0])
print('Test accuracy;', score[1])
其实可以自己给每一层layer命名一个name, 也可以由keras根据自己的命名规则自动取名,自动命名的规则在Layer类中,代码如下:
name = kwargs.get('name')  
if not name:  prefix = self.__class__.__name__  name = _to_snake_case(prefix) + '_' + str(K.get_uid(prefix))  
self.name = name 
而在keras的call back模块中,tensorborad class类实现源码可以看出,keras默认将模型的所有层的所有weights, bias以及每一层输出的distribution, histogram等传送到tensorborad,方便在浏览器中观察网络的运行情况。实现源码如下:

def set_model(self, model):  self.model = model  self.sess = K.get_session()  if self.histogram_freq and self.merged is None:  for layer in self.model.layers:  for weight in layer.weights:  tf.summary.histogram(weight.name, weight)  if self.write_images:  w_img = tf.squeeze(weight)  shape = w_img.get_shape()  if len(shape) > 1 and shape[0] > shape[1]:  w_img = tf.transpose(w_img)  if len(shape) == 1:  w_img = tf.expand_dims(w_img, 0)  w_img = tf.expand_dims(tf.expand_dims(w_img, 0), -1)  tf.summary.image(weight.name, w_img)  if hasattr(layer, 'output'):  tf.summary.histogram('{}_out'.format(layer.name),  layer.output)  self.merged = tf.summary.merge_all() 

当然也可以指定输出某一些层的,通过tensorboard参数进行设定:

embeddings_freq: frequency (in epochs) at which selected embedding
    layers will be saved.
embeddings_layer_names: a list of names of layers to keep eye on. If
    None or empty list all the embedding layer will be watched.

现在运行最开始的例子,在terminal运行

tensorboard --logdir=/tmp/keras_log

在terminal打开浏览器地址,进入tensorboard可以随意浏览graph, distribution, histogram, 以及sclar列表中的loss, acc等等。


以下摘录自: 这里

TensorBoard will automatically include all runs logged within the sub-directories of the specifiedlog_dir, for example, if you logged another run using:

callback_tensorboard(log_dir = "logs/run_b")

Then the TensorBoard visualization would look like this:

You can use the unique_log_dir function if you want to record every training run in it’s own directory:

callback_tensorboard(log_dir = unique_log_dir())

Once again note that it’s not required to record every training run in it’s own directory. Using the default “logs” directory will work just fine, you’ll just only be able to visualize the most recent run using TensorBoard.



需要注意的是,tensorboard默认的slcar一栏只记录了训练集和验证集上的loss,如何想记录展示其他指标,在model.compile的metric中进行添加,例如:

    model.compile(  loss = 'mean_squared_error',  optimizer = 'sgd',  metrics= c('mae', 'acc')  # 可视化mae和acc  )  



这篇关于keras tensorboard的使用, 设置GPU使用的内存, 强制只使用cpu的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1112609

相关文章

Java内存分配与JVM参数详解(推荐)

《Java内存分配与JVM参数详解(推荐)》本文详解JVM内存结构与参数调整,涵盖堆分代、元空间、GC选择及优化策略,帮助开发者提升性能、避免内存泄漏,本文给大家介绍Java内存分配与JVM参数详解,... 目录引言JVM内存结构JVM参数概述堆内存分配年轻代与老年代调整堆内存大小调整年轻代与老年代比例元空

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

Go语言数据库编程GORM 的基本使用详解

《Go语言数据库编程GORM的基本使用详解》GORM是Go语言流行的ORM框架,封装database/sql,支持自动迁移、关联、事务等,提供CRUD、条件查询、钩子函数、日志等功能,简化数据库操作... 目录一、安装与初始化1. 安装 GORM 及数据库驱动2. 建立数据库连接二、定义模型结构体三、自动迁

ModelMapper基本使用和常见场景示例详解

《ModelMapper基本使用和常见场景示例详解》ModelMapper是Java对象映射库,支持自动映射、自定义规则、集合转换及高级配置(如匹配策略、转换器),可集成SpringBoot,减少样板... 目录1. 添加依赖2. 基本用法示例:简单对象映射3. 自定义映射规则4. 集合映射5. 高级配置匹

Spring 框架之Springfox使用详解

《Spring框架之Springfox使用详解》Springfox是Spring框架的API文档工具,集成Swagger规范,自动生成文档并支持多语言/版本,模块化设计便于扩展,但存在版本兼容性、性... 目录核心功能工作原理模块化设计使用示例注意事项优缺点优点缺点总结适用场景建议总结Springfox 是

嵌入式数据库SQLite 3配置使用讲解

《嵌入式数据库SQLite3配置使用讲解》本文强调嵌入式项目中SQLite3数据库的重要性,因其零配置、轻量级、跨平台及事务处理特性,可保障数据溯源与责任明确,详细讲解安装配置、基础语法及SQLit... 目录0、惨痛教训1、SQLite3环境配置(1)、下载安装SQLite库(2)、解压下载的文件(3)、

使用Python绘制3D堆叠条形图全解析

《使用Python绘制3D堆叠条形图全解析》在数据可视化的工具箱里,3D图表总能带来眼前一亮的效果,本文就来和大家聊聊如何使用Python实现绘制3D堆叠条形图,感兴趣的小伙伴可以了解下... 目录为什么选择 3D 堆叠条形图代码实现:从数据到 3D 世界的搭建核心代码逐行解析细节优化应用场景:3D 堆叠图

Springboot如何正确使用AOP问题

《Springboot如何正确使用AOP问题》:本文主要介绍Springboot如何正确使用AOP问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录​一、AOP概念二、切点表达式​execution表达式案例三、AOP通知四、springboot中使用AOP导出

Python中Tensorflow无法调用GPU问题的解决方法

《Python中Tensorflow无法调用GPU问题的解决方法》文章详解如何解决TensorFlow在Windows无法识别GPU的问题,需降级至2.10版本,安装匹配CUDA11.2和cuDNN... 当用以下代码查看GPU数量时,gpuspython返回的是一个空列表,说明tensorflow没有找到