tensorflow keras入門,深度學習跑起來

keras官方中文文檔

說實話安裝tensorflow的cuda支持版本的時候還是看英文的官方教程比較好,中文的太久了,安裝不成功,而且似乎只能通過源碼安裝,需要安裝java,bazel等工具,然後是cuda的驅動和cudnn,官網英文鏈接,按這個裝纔沒有錯,然後就是安裝keras,這個可以按照中文文檔來 keras中文文檔,安裝過程每臺電腦也不一樣,自己谷歌解決把,。然後我安裝完了之後還是有一個dot_parser庫沒有安裝成功,不過運行沒有影響,還有老師的泰坦x跑起來是真的快,速度親測比至強的cpu快百倍。。。。深度學習爽的不行

下面是跑自己的數據集和測試,網上都沒有,官網也只有fit,沒有預測的代碼

下面是訓練的代碼,安裝中文網站的貓狗分類寫的,用於測試自己的前車識別圖片

'''This script goes along the blog post
"Building powerful image classification models using very little data"
from blog.keras.io.
It uses data that can be downloaded at:
https://www.kaggle.com/c/dogs-vs-cats/data
In our setup, we:
- created a data/ folder
- created train/ and validation/ subfolders inside data/
- created cats/ and dogs/ subfolders inside train/ and validation/
- put the cat pictures index 0-999 in data/train/cats
- put the cat pictures index 1000-1400 in data/validation/cats
- put the dogs pictures index 12500-13499 in data/train/dogs
- put the dog pictures index 13500-13900 in data/validation/dogs
So that we have 1000 training examples for each class, and 400 validation examples for each class.
In summary, this is our directory structure:
```
data/
    train/
        veh/
            1.jpg
            2.jpg
            ...
        noveh/
            1.jpg
            2.jpg
            ...
    validation/
        veh/
            1.jpg
            2.jpg
            ...
        noveh/
            1.jpg
            2.jpg
            ...
```
'''



from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K
import h5py

# dimensions of our images.
img_width, img_height = 64, 64

train_data_dir = 'data/train'
validation_data_dir = 'data/validation'
nb_train_samples = 2000
nb_validation_samples = 1000
epochs = 30
batch_size = 32

if K.image_data_format() == 'channels_first':
    input_shape = (3, img_width, img_height)
else:
    input_shape = (img_width, img_height, 3)

#################################################################################
model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))

model.compile(loss='binary_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])
#################################################################################



##################################################################################
# from keras.optimizers import SGD
# model = Sequential()
# # input: 100x100 images with 3 channels -> (100, 100, 3) tensors.
# # this applies 32 convolution filters of size 3x3 each.
# model.add(Conv2D(32, (3, 3), activation='relu', input_shape=input_shape))
# model.add(Conv2D(32, (3, 3), activation='relu'))
# model.add(MaxPooling2D(pool_size=(2, 2)))
# model.add(Dropout(0.25))

# model.add(Conv2D(64, (3, 3), activation='relu'))
# model.add(Conv2D(64, (3, 3), activation='relu'))
# model.add(MaxPooling2D(pool_size=(2, 2)))
# model.add(Dropout(0.25))

# model.add(Flatten())
# model.add(Dense(256, activation='relu'))
# model.add(Dropout(0.5))
# model.add(Dense(1, activation='softmax'))

# sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
# model.compile(loss='binary_crossentropy', optimizer=sgd)
##################################################################################



#########################################################################
# model = Sequential()
# model.add(Dense(64, input_dim=20, activation='relu'))
# model.add(Dropout(0.5))
# model.add(Dense(64, activation='relu'))
# model.add(Dropout(0.5))
# model.add(Dense(1, activation='sigmoid'))

# model.compile(loss='binary_crossentropy',
#               optimizer='rmsprop',
#               metrics=['accuracy'])
#########################################################################



# this is the augmentation configuration we will use for training
train_datagen = ImageDataGenerator(
    rescale=1. / 255,
    shear_range=0.1,
    zoom_range=0.1,
    horizontal_flip=True)


# this is the augmentation configuration we will use for testing:
# only rescaling
test_datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = train_datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='binary')

validation_generator = test_datagen.flow_from_directory(
    validation_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='binary')

model.fit_generator(
    train_generator,
    steps_per_epoch=nb_train_samples // batch_size,
    epochs=epochs,
    validation_data=validation_generator,
    validation_steps=nb_validation_samples // batch_size)

#model.save_weights('first_try.h5')
model.save('first_try.h5')


注意最後可以只save_weight,但是在用的時候需要加載模型的框架,然後自己再載入模型weight,不方便,不如直接全部保留下來,然後是使用訓練好的模型預測

也可以通過下面的方式保存模型

import h5py from keras.models import model_from_json  
json_string = model.to_json()  
open('my_model_architecture.json','w').write(json_string)  
model.save_weights('my_model_weights.h5')  
加載模型

model = model_from_json(open('my_model_architecture.json').read())  
model.load_weights('my_model_weights.h5')  


然後是加載模型進行預測

import keras
from keras.models import load_model
from keras.models import Sequential

from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
from keras import backend as K
import cv2
import numpy as np 
import h5py
import os

#model = Sequential()
model = load_model('first_try.h5')

num_test=1000
img = load_img('pic/0.png')  # this is a PIL image
xx = img_to_array(img)  # this is a Numpy array with shape (3, 150, 150)
#print xx
#x = x.reshape((1,) + x.shape)  # this is a Numpy array with shape (1, 3, 64, 64)
# print xx.shape
# print K.image_data_format()
batch_x = np.zeros((num_test,) + xx.shape, dtype=K.floatx())



for i in range(num_test):
    #path='pic/'+str(i)+'.png';
    path='/home/cx/Desktop/tensorflow_test/the_first_keras/data/train/no_veh/'+str(i)+'.png'
    #print path
    img = load_img(path)  # this is a PIL image
    x = img_to_array(img)  # this is a Numpy array with shape (3, 150, 150)
    #img2=array_to_img(img)
    # cv2.imshow('test',x)
    # cv2.waitKey(0)
    batch_x[i] = x

# for i in range(num_test):
#     img = array_to_img(batch_x[i], scale=True)
#     fname = '{prefix}_{index}_{hash}.{format}'.format(prefix='test',
#                                                     index= i,
#                                                     hash=np.random.randint(1e4),
#                                                     format='png')
#     img.save(os.path.join('pic2', fname))


#classes = model.predict_proba(batch_x)
classes = model.predict_classes(batch_x)
count=0
print '\n'
for i in classes:
    if (i==[1]):
        count+=1
print count
#print classes


不出意外的話效果是不好的,,畢竟這個多層神經網絡很簡單,並不能很好的分類,下一篇我們用預訓練的高級網絡再來跑自己的數據集

發佈了93 篇原創文章 · 獲贊 45 · 訪問量 23萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章