前言:
{
这次也遇到了不少问题,最头疼的就是OOM(内存不够)。虽然要训练的东西很少,但在初始化时还是会出错,目前就先用CPU(禁用显存)做初步调试。
}
正文:
{
按照我原本的打算,损失是mean_squared_error;当某类的输出与标签的差不小于0.5时,则此类的预测正确,准确率为平均正确率。
此准确率的计算用到了二值张量。代码1是张量二值化的函数和评估步骤,其中输出张量input_tensor的类型需要与阈值threshold的一致。
#代码1
#the following function is to return a binary tensor by the argument input_tensor
#of which values less than the threshold will be converted into zeros or Falses.
def tensor_binaryzation(input_tensor, threshold):
y = tf.subtract(tf.cast(threshold, tf.float32), 1.0)
x = tf.cast(input_tensor, tf.float32)
output_tensor = tf.cast(tf.subtract(x, y), dtype=tf.uint64)
return tf.cast(output_tensor, dtype=tf.bool)
如果想改变trainable variables,可以把tf.GraphKeys.TRAINABLE_VARIABLES改成新的集合名。
我的计划是把图像预处理成500*500的大小,不过重点在于要保留图像的比例,即最大的边长被设置成500,另一个边长按比例缩放,剩余像素用0填充。函数如代码2。
#代码2
def preprocessing_for_training(image, unified_image_shape):
# standardization, which is divided into 2 parts, expansion and padding
image_shape = tf.shape(image)
shape_ratio1 = tf.div(unified_image_shape[0], image_shape[0])
shape_ratio2 = tf.div(unified_image_shape[1], image_shape[1])
shape_one = tf.cast(tf.multiply(image_shape[0:2], shape_ratio2), tf.int32)
shape_two = tf.cast(tf.multiply(image_shape[0:2], shape_ratio1), tf.int32)
image_as_float = tf.image.convert_image_dtype(image, dtype=tf.float32)
resized_image = tf.cond(shape_ratio1>shape_ratio2,
lambda:tf.image.resize_images(image_as_float, shape_one),
lambda:tf.image.resize_images(image_as_float, shape_two))
resized_image = tf.image.resize_image_with_crop_or_pad(resized_image, unified_image_shape[0], unified_image_shape[1])
return resized_image
代码2其实是我修改《TensorFlow实战Google深度学习框架(第2版)》中代码而得来的(基本面目全非),此函数输出的图像如图1。
}
结语:
{
放下训练速度先不说,内存真是一个大问题。我打算跑出结果后再公开全部代码,但虽然程序代码都已经写好,换到CPU上进行训练也还是会卡死(我还是第一次看到360内存球显示内存占用99%)。
对上述问题目前有两种方法,一是添加新的设备,不过我还没开始训练整个网络,就已经这样了,估计就算买显卡也是够呛。另一种方法是使用云设备,之后我会去看看有什么云GPU的供应商。
不知道各位观众有没有什么可推荐的硬件解决方案,我目前主要是个人学习调试用。
这次我写的这2段代码对应的方法都是我在百度没搜到,自己写的,如有更好的方法欢迎指出。
}