Keras安裝與測試遇到的坑

Keras是基於python的深度學習庫python

Keras是一個高層神經網絡API,Keras由純Python編寫而成並基TensorflowTheano以及CNTK後端。git

安裝步驟及遇到的坑:github

(1)安裝tensorflow:CMD命令行輸入pip install --upgrade tensorflow後端

(2)安裝Keras:pip install keras -U --pre網絡

(3)驗證tensorflow工具

  jupyter notebook或者spyder輸入如下代碼:學習

  import tensorflow as tf

  hello = tf.constant(「hello,tensorflow」)

  sess = tf.Session()

  print(sess.run(hello))

  能顯示「hello,tensorflow」則表示安裝成功測試

(4)驗證keras,lua

  使用Keras中mnist數據集測試 下載Keras開發包,命令行輸入如下命令url

  >>> conda install git   #安裝git工具

  >>> git clone https://github.com/fchollet/keras.git   #下載keras工程內容

  >>> cd keras/examples/    #進入測試代碼所在路徑

  >>> python mnist_mlp.py   #執行測試代碼

 

驗證keras時遇到兩個坑,問題描述及解決方案以下:

(1)conda更新失敗,安裝git工具遇到CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://repo.anaconda.com/pkgs/main/win-64/git-2問題,解決辦法是修改國內鏡像源,改成清華鏡像源便可

>>>conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
>>>conda config --set show_channel_urls yes #生成配置文件

  修改生成的配置文件 C:\Users\<你的用戶名>\.condarc

#修改前
channels: - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/ - default
ssl_verify: true show_channel_urls: true

#修改後
channels:
  - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
ssl_verify: true show_channel_urls: true

  >>>conda info命令查看配置信息,確認修改爲功後,>>>conda install git便可完成下載更新

(2)keras中的example案例中MNIST數據集沒法下載

  問題緣由:keras 源碼中下載MNIST的方式是 path = get_file(path, origin='https://s3.amazonaws.com/img-datasets/mnist.npz'),數據源是經過 url = https://s3.amazonaws.com/img-datasets/mnist.npz 進行下載的。訪問該 url 地址被牆了,致使 MNIST 相關的案例都

  卡在數據下載部分

  解決辦法:

  (a)下載好 mnist_npz 數據集,並將其放於 .\keras\examples 目錄下

  (b)修改mnist_mlp.py

'''Trains a simple deep NN on the MNIST dataset.

Gets to 98.40% test accuracy after 20 epochs
(there is *a lot* of margin for parameter tuning).
2 seconds per epoch on a K520 GPU.
'''

from __future__ import print_function

import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.optimizers import RMSprop

batch_size = 128
num_classes = 10
epochs = 20

#load data from local
import numpy as np
path = "./mnist.npz"
f = np.load(path)
x_train, y_train = f["x_train"], f["y_train"]
x_test, y_test = f["x_test"], f["y_test"]
f.close()

# the data, split between train and test sets
#(x_train, y_train), (x_test, y_test) = mnist.load_data()

x_train = x_train.reshape(60000, 784)
x_test = x_test.reshape(10000, 784)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

model = Sequential()
model.add(Dense(512, activation='relu', input_shape=(784,)))
model.add(Dropout(0.2))
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(num_classes, activation='softmax'))

model.summary()

model.compile(loss='categorical_crossentropy',
              optimizer=RMSprop(),
              metrics=['accuracy'])

history = model.fit(x_train, y_train,
                    batch_size=batch_size,
                    epochs=epochs,
                    verbose=1,
                    validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
相關文章
相關標籤/搜索