TF2.0實(shí)現(xiàn)Lenet_5網(wǎng)絡(luò)

# 小型CNN模型搭建和測(cè)試
import picture_read
import numpy as np
import tensorflow as tf
import time

def data_processing(train_document1,train_document2,test_document1,test_document2,    #(訓(xùn)練集數(shù)據(jù)1,訓(xùn)練集數(shù)據(jù)2苫纤,測(cè)試集數(shù)據(jù)1,測(cè)試集數(shù)據(jù)2)
                    pic_size,label1,label2,):    #(圖片縮放大小畴蒲,標(biāo)簽1沮焕,標(biāo)簽2)

    train_data_1,train_label_1 = picture_read.picture_document_deal(train_document1, pic_size, label1)   #sxs標(biāo)簽為0
    train_data_2,train_label_2 = picture_read.picture_document_deal(train_document2, pic_size, label2)   #xsx標(biāo)簽為1
    test_data_1,test_label_1 = picture_read.picture_document_deal(test_document1, pic_size, label1)   #sxs標(biāo)簽為0
    test_data_2,test_label_2 = picture_read.picture_document_deal(test_document2, pic_size, label2)   #xsx標(biāo)簽為1

    # numpy:vstack列上合并兩個(gè)矩陣,hstack在行上合并兩個(gè)矩陣
    train_data = np.vstack((train_data_1,train_data_2))
    train_labels = np.hstack((train_label_1,train_label_2))
    test_data = np.vstack((test_data_1,test_data_2))
    test_labels = np.hstack((test_label_1,test_label_2))
    print('train_data = ',train_data.shape)    #train_data,
    # print('train_labels = ', train_labels, train_labels.shape)

    # 二、 歸一化,將每個(gè)點(diǎn)的像素值歸一化到[0, 1]之間
    training_pics = train_data.reshape(train_data.shape[0], train_data.shape[1], train_data.shape[2], 1)
    test_pics = test_data.reshape(test_data.shape[0], test_data.shape[1], test_data.shape[2], 1)
    training_pics = training_pics / 255.0
    test_pics = test_pics / 255.0
    print('training_pics = ',training_pics.shape)      #training_pics,
    # print('test_pics = ',test_pics,test_pics.shape)

    print(training_pics.shape[1], training_pics.shape[2], training_pics.shape[3])
    print("training_pics = ", training_pics.shape)
    print("training_labels = ", train_labels.shape)

    return training_pics,test_pics,train_labels,test_labels


def model_structure(shape,classification ):   #(圖片的格式隧甚,最終分類的結(jié)果)
    print('shape = ',shape)
    # 第一種寫法
    # 定義模型车荔,按順序創(chuàng)建模型
    model_def = tf.keras.models.Sequential([
        tf.keras.layers.Conv2D(6, (3, 3), activation='relu', input_shape=(shape[1], shape[2], shape[3])),
        tf.keras.layers.MaxPooling2D(2, 2),
        tf.keras.layers.ReLU(),
        tf.keras.layers.Conv2D(16, (3, 3), activation='relu'),
        tf.keras.layers.MaxPooling2D(2, 2),
        tf.keras.layers.ReLU(),
        tf.keras.layers.Flatten(),
        tf.keras.layers.Dense(120, activation='relu'),
        tf.keras.layers.Dense(84, activation='relu'),
        tf.keras.layers.Dense(classification, activation='softmax')
    ])

    # # 第二種寫法
    # inputs = tf.keras.layers.Input(shape = shape[1:])
    # x = tf.keras.layers.Conv2D(filters=6, kernel_size=3, strides=1,
    #                                activation='relu', padding='same')(inputs)
    # x = tf.keras.layers.MaxPool2D(pool_size=2, strides=1, padding='same')(x)
    # x = tf.keras.layers.ReLU()(x)
    # x = tf.keras.layers.Conv2D(filters=16, kernel_size=3, strides=1,
    #                            activation='relu', padding='same')(x)
    # x = tf.keras.layers.MaxPool2D(pool_size=2, strides=1, padding='same')(x)
    # x = tf.keras.layers.ReLU()(x)
    # x = tf.keras.layers.Flatten()(x)
    # x = tf.keras.layers.Dense(120,activation='relu')(x)
    # x = tf.keras.layers.Dense(84,activation='relu')(x)
    # outputs = tf.keras.layers.Dense(classification,activation='softmax')(x)   # 二分類
    # model_def = tf.keras.Model(inputs = inputs, outputs=outputs)


    # 編譯模型,確定優(yōu)化方法戚扳,損失函數(shù)等
    model_def.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

    return model_def

def model_train_save(model,model_file):     #(模型保存文件的名稱)


    # 四忧便、訓(xùn)練模型,并將每輪訓(xùn)練的歷史信息保存在變量 history 中
    history = model.fit(x=training_images, y=train_label, batch_size = 32 ,
                        epochs = 20,validation_split=0.2)  # validation_split = 0.1   validation_data=(test_images, test_labels)
    # 計(jì)算損失
    test_loss = model.evaluate(test_images, test_label)
    # print('test_loss = ',test_loss)

    # 模型保存
    model.save(model_file)    # 保存全部

    # 刪除模型
    del model

def model_predict_labels(model_file,test_pic,test_labels):  #測(cè)試集有標(biāo)簽時(shí)使用
    # 四、恢復(fù)模型并預(yù)測(cè)
    # print("模型讀回")
    model = tf.keras.models.load_model(model_file)
    # 測(cè)試模型
    loss, acc = model.evaluate(test_pic, test_labels)

    # 五帽借、預(yù)測(cè)
    predict = model.predict(test_pic)
    # print('predict = ',predict)
    predict = np.array(tf.argmax(predict, 1))
    print('predict = ',predict)   #tf.argmax根據(jù)axis取值的不同返回每行或者每列最大值的索引,axis = 1時(shí)取每行最大值的索引位置
    print('test_labels = ', test_labels)

    print("Restored model, accuracy:{:5.2f}%".format(100 * acc))

    return predict

def model_predict_nolabels(model_file,test_pic):    #測(cè)試集無標(biāo)簽時(shí)使用
    # 四珠增、恢復(fù)模型
    # print("模型讀回")
    model = tf.keras.models.load_model(model_file)

    # 五、預(yù)測(cè)
    predict = model.predict(test_pic)
    # print('predict = ',predict)
    predict = np.array(tf.argmax(predict, 1))
    print('predict = ',predict)   #tf.argmax根據(jù)axis取值的不同返回每行或者每列最大值的索引,axis = 1時(shí)取每行最大值的索引位置

    return predict

if __name__ == '__main__':

    start_time = time.time()

    # 一砍艾、獲取數(shù)據(jù)并處理數(shù)據(jù)
    im_size = (28, 28)   #圖片放縮的大小
    train_document_1 = 'D:\\python_work\\model_project\\dataset\\train\\sxs'
    train_document_2 = 'D:\\python_work\\model_project\\dataset\\train\\xsx'
    test_document_1 = 'D:\\python_work\\model_project\\dataset\\test\\sxs'
    test_document_2 = 'D:\\python_work\\model_project\\dataset\\test\\xsx'

    training_images, test_images, train_label, test_label = data_processing(train_document_1,train_document_2,
                                                                            test_document_1,test_document_2,   #(訓(xùn)練集數(shù)據(jù)1蒂教,訓(xùn)練集數(shù)據(jù)2,測(cè)試集數(shù)據(jù)1辐董,測(cè)試集數(shù)據(jù)2)
                                                                            im_size,0,1,)
    # 二悴品、模型搭建:
    model_name = model_structure(training_images.shape,classification = 2)

    # 三禀综、訓(xùn)練神經(jīng)網(wǎng)絡(luò)模型進(jìn)行圖片分類:
    model_train_save(model_name,'my_model.h5')


    # 四简烘、模型讀回及預(yù)測(cè)(有對(duì)比標(biāo)簽)
    predict_labels = model_predict_labels('my_model.h5',test_images,test_label)

    # # 五、模型讀回及預(yù)測(cè)(無對(duì)比標(biāo)簽)
    # predict_labels = model_predict_nolabels('my_model.h5',test_images)


    end_time = time.time()
    print('程序運(yùn)行時(shí)間:',end_time-start_time)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
禁止轉(zhuǎn)載定枷,如需轉(zhuǎn)載請(qǐng)通過簡(jiǎn)信或評(píng)論聯(lián)系作者孤澎。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市欠窒,隨后出現(xiàn)的幾起案子覆旭,更是在濱河造成了極大的恐慌退子,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,496評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件型将,死亡現(xiàn)場(chǎng)離奇詭異寂祥,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)七兜,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,407評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門丸凭,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人腕铸,你說我怎么就攤上這事惜犀。” “怎么了狠裹?”我有些...
    開封第一講書人閱讀 162,632評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵虽界,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我涛菠,道長(zhǎng)莉御,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,180評(píng)論 1 292
  • 正文 為了忘掉前任俗冻,我火速辦了婚禮颈将,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘言疗。我一直安慰自己晴圾,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,198評(píng)論 6 388
  • 文/花漫 我一把揭開白布噪奄。 她就那樣靜靜地躺著死姚,像睡著了一般。 火紅的嫁衣襯著肌膚如雪勤篮。 梳的紋絲不亂的頭發(fā)上都毒,一...
    開封第一講書人閱讀 51,165評(píng)論 1 299
  • 那天,我揣著相機(jī)與錄音碰缔,去河邊找鬼账劲。 笑死,一個(gè)胖子當(dāng)著我的面吹牛金抡,可吹牛的內(nèi)容都是我干的瀑焦。 我是一名探鬼主播,決...
    沈念sama閱讀 40,052評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼梗肝,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼榛瓮!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起巫击,我...
    開封第一講書人閱讀 38,910評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤禀晓,失蹤者是張志新(化名)和其女友劉穎精续,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體粹懒,經(jīng)...
    沈念sama閱讀 45,324評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡重付,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,542評(píng)論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了凫乖。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片堪夭。...
    茶點(diǎn)故事閱讀 39,711評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖拣凹,靈堂內(nèi)的尸體忽然破棺而出森爽,到底是詐尸還是另有隱情,我是刑警寧澤嚣镜,帶...
    沈念sama閱讀 35,424評(píng)論 5 343
  • 正文 年R本政府宣布爬迟,位于F島的核電站,受9級(jí)特大地震影響菊匿,放射性物質(zhì)發(fā)生泄漏付呕。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,017評(píng)論 3 326
  • 文/蒙蒙 一跌捆、第九天 我趴在偏房一處隱蔽的房頂上張望徽职。 院中可真熱鬧,春花似錦佩厚、人聲如沸姆钉。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,668評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽潮瓶。三九已至,卻和暖如春钙姊,著一層夾襖步出監(jiān)牢的瞬間毯辅,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,823評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工煞额, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留思恐,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,722評(píng)論 2 368
  • 正文 我出身青樓膊毁,卻偏偏與公主長(zhǎng)得像胀莹,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子媚媒,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,611評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容