【Tool】Keras 基礎(chǔ)學(xué)習(xí) VI 二分類

先看一個基礎(chǔ)的二分類問題询件。使用keras實現(xiàn)感知機算法桑阶。keras提供了一些官方數(shù)據(jù)集分別對于二分類,多分類港华,回歸問題道川。其中IMDB評論數(shù)據(jù)集是二分類問題,Reuters數(shù)據(jù)集是多分類問題, house prices是回歸問題冒萄。
train_data是單詞在評論中出現(xiàn)的下標臊岸, test_label是用戶對電影的喜好,0: negative, 1: positive尊流。
分別查看下positive 和 negative 評論:

(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)
word_index = imdb.get_word_index()
reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])
good_review = ' '.join([reverse_word_index.get(i-3,'?') for i in train_data[0]])
# 輸出
"? this film was just brilliant casting location scenery story direction everyone's really suited the part they played and you could just imagine being there robert redford's is an amazing actor and now the same being director norman's father came from the same scottish island as myself so i loved the fact there was a real connection with this film the witty remarks throughout the film were great it was just brilliant so much that i bought the film as soon as it was released for retail and would recommend it to everyone to watch and the fly fishing was amazing really cried at the end it was so sad and you know what they say if you cry at a film it must have been good and this definitely was also congratulations to the two little boy's that played the part's of norman and paul they were just brilliant children are often left out of the praising list i think because the stars that play them all grown up are such a big profile for the whole film but these children are amazing and should be praised for what they have done don't you think the whole story was so lovely because it was true and was someone's life after all that was shared with us all"
bad_review = ' '.join([reverse_word_index.get(i-3,'?') for i in train_data[0]])
# 輸出
"? big hair big boobs bad music and a giant safety pin these are the words to best describe this terrible movie i love cheesy horror movies and i've seen hundreds but this had got to be on of the worst ever made the plot is paper thin and ridiculous the acting is an abomination the script is completely laughable the best is the end showdown with the cop and how he worked out who the killer is it's just so damn terribly written the clothes are sickening and funny in equal measures the hair is big lots of boobs bounce men wear those cut tee shirts that show off their stomachs sickening that men actually wore them and the music is just synthesiser trash that plays over and over again in almost every scene there is trashy music boobs and paramedics taking away bodies and the gym still doesn't close for bereavement all joking aside this is a truly bad film whose only charm is to look back on the disaster that was the 80's and have a good old laugh at how bad everything was back then"

構(gòu)建兩層感知機算法帅戒, 進行分類,分類之前我們對數(shù)據(jù)進行預(yù)處理崖技,進行one_hot encoding蜘澜。 只考慮出現(xiàn)頻率前1000的數(shù)據(jù),在樣本中出現(xiàn)為1响疚, 不出現(xiàn)為0, 每個樣本數(shù)據(jù)為1000 維向量。然后將處理后數(shù)據(jù)輸入感知機算法當(dāng)中瞪醋。

import os
import numpy as np
from keras.models import Sequential, Model
from keras import layers
from keras.preprocessing.image import ImageDataGenerator
from keras import optimizers
from keras.applications.vgg16 import VGG16
from keras.utils.np_utils import to_categorical
from scipy.misc import imread, imresize
import matplotlib.pyplot as plt
from keras.datasets import imdb

(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)
word_index = imdb.get_word_index()
reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])
decoded_review = ' '.join([reverse_word_index.get(i-3,'?') for i in train_data[0]])
def vectorize_sequences(sequences, dimension=10000):
    results = np.zeros((len(sequences), dimension))
    for i, sequence in enumerate(sequences):
        results[i, sequence] = 1. # set specific indices of results[i] to 1s
    return results
x_train = vectorize_sequences(train_data)
x_test = vectorize_sequences(test_data)
y_train = np.asarray(train_labels).astype('float32')
y_test = np.asarray(test_labels).astype('float32')


# define the model
model = Sequential()
model.add(layers.Dense(10, activation='relu', input_shape=(10000,)))
model.add(layers.Dense(10, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))

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

x_val = x_train[:10000]
partial_x_train = x_train[10000:]
y_val = y_train[:10000]
partial_y_train = y_train[10000:]

history = model.fit(partial_x_train, partial_y_train, epochs=10, batch_size=512, validation_data=(x_val, y_val))

metrics = model.evaluate(x_test, y_test)
print(model.metrics_names)
print(metrics)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末忿晕,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子银受,更是在濱河造成了極大的恐慌践盼,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,331評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件宾巍,死亡現(xiàn)場離奇詭異咕幻,居然都是意外死亡,警方通過查閱死者的電腦和手機顶霞,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,372評論 3 398
  • 文/潘曉璐 我一進店門肄程,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人选浑,你說我怎么就攤上這事蓝厌。” “怎么了古徒?”我有些...
    開封第一講書人閱讀 167,755評論 0 360
  • 文/不壞的土叔 我叫張陵拓提,是天一觀的道長。 經(jīng)常有香客問我隧膘,道長代态,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,528評論 1 296
  • 正文 為了忘掉前任疹吃,我火速辦了婚禮蹦疑,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘萨驶。我一直安慰自己必尼,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 68,526評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著判莉,像睡著了一般豆挽。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上券盅,一...
    開封第一講書人閱讀 52,166評論 1 308
  • 那天帮哈,我揣著相機與錄音,去河邊找鬼锰镀。 笑死娘侍,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的泳炉。 我是一名探鬼主播憾筏,決...
    沈念sama閱讀 40,768評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼花鹅!你這毒婦竟也來了氧腰?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,664評論 0 276
  • 序言:老撾萬榮一對情侶失蹤刨肃,失蹤者是張志新(化名)和其女友劉穎古拴,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體真友,經(jīng)...
    沈念sama閱讀 46,205評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡黄痪,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,290評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了盔然。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片桅打。...
    茶點故事閱讀 40,435評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖愈案,靈堂內(nèi)的尸體忽然破棺而出油额,到底是詐尸還是另有隱情,我是刑警寧澤刻帚,帶...
    沈念sama閱讀 36,126評論 5 349
  • 正文 年R本政府宣布潦嘶,位于F島的核電站,受9級特大地震影響崇众,放射性物質(zhì)發(fā)生泄漏掂僵。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,804評論 3 333
  • 文/蒙蒙 一顷歌、第九天 我趴在偏房一處隱蔽的房頂上張望锰蓬。 院中可真熱鬧,春花似錦眯漩、人聲如沸芹扭。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,276評論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽舱卡。三九已至辅肾,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間轮锥,已是汗流浹背矫钓。 一陣腳步聲響...
    開封第一講書人閱讀 33,393評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留舍杜,地道東北人新娜。 一個月前我還...
    沈念sama閱讀 48,818評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像既绩,于是被迫代替她去往敵國和親概龄。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,442評論 2 359

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