以双精度运行Keras失败

时间:2018-01-31 22:29:22

标签: tensorflow keras

我正在尝试使用双精度在Keras上运行LeNet,但它失败并出现错误:TypeError: Input 'filter' of 'Conv2D' Op has type float64 that does not match type float32 of argument 'input'.。我使用的代码如下:

import numpy as np
from sklearn.utils import shuffle
import keras
from keras.models import Sequential
from keras.layers import Input, Dense, Conv2D, MaxPooling2D, Dropout,Flatten
from keras import backend as K
from keras.models import Model
from keras.utils import np_utils
import time
import tensorflow as tf
K.set_floatx('float64') # Note: the code works if we comment this line, i.e., with single precision
from mlxtend.data import mnist_data
X, y = mnist_data()
X = X.astype(np.float64)
X, y =  shuffle(X, y)
keras_model = Sequential()
keras_model.add(Conv2D(32, kernel_size=(5, 5), activation='relu', input_shape=(28,28,1), padding='same'))
keras_model.add(MaxPooling2D(pool_size=(2, 2)))
keras_model.add(Conv2D(64, (5, 5), activation='relu', padding='same'))
keras_model.add(MaxPooling2D(pool_size=(2, 2)))
keras_model.add(Flatten())
keras_model.add(Dense(512, activation='relu'))
keras_model.add(Dropout(0.5))
keras_model.add(Dense(10, activation='softmax'))
keras_model.compile(loss='categorical_crossentropy', optimizer=keras.optimizers.SGD(lr=0.01, momentum=0.95, decay=5e-4, nesterov=True))
keras_model.fit(X.reshape((-1, 28,28, 1)), np_utils.to_categorical(y, 10), epochs=1, batch_size=64)

非常感谢任何建议:)

1 个答案:

答案 0 :(得分:1)

你有一款游戏NVIDIA GPU。 您只能使用float32int32,全部 它是TensorFlow的默认值 由于Nvidia支持CUDA的GPU的限制,Tensorflow引入了此默认设置。 Best explanation I found here.因此,优质特斯拉GPU在float16float64上运行良好,但游戏GPU仅适用于float32并且对float16执行效果非常差float64
我想我们都在关注那些价格更高的AMD GPU支持的OpenCL。不幸的是,截至目前,TensorFlow不支持OpenCL。

建议#1: 你被float32困住了。在拥有硬件的同时忘记更改它。

建议#2: 一旦你获得GPU好用float16改变那个。机器学习并不需要高精度。