keras基础实例(电影评价预测

#%%

import keras
from keras import layers
import matplotlib.pyplot as plt
%matplotlib inline

#%%

data = keras.datasets.imdb

#%%

max_word = 10000

#%%

(x_train, y_train), (x_test, y_test) = data.load_data(num_words=max_word)

#%%

x_train.shape, y_train.shape

#%%

x_train[0]

#%%

y_train

#%%

word_index = data.get_word_index()

#%%

index_word = dict((value, key) for key,value in word_index.items())

#%%

[index_word.get(index-3, '?') for index in x_train[0]]

#%%

[len(seq) for seq in x_train]

#%%

max([max(seq) for seq in x_train])

#%% md

文本的向量化

#%% md

one-hot

#%% md

k-hot

#%%

import numpy as np

#%%

def k_hot(seqs, dim=10000):
    result = np.zeros((len(seqs), dim))
    for i, seq in enumerate(seqs):
        result[i, seq] = 1
    return result

#%%

x_train = k_hot(x_train)

#%%

x_train.shape

#%%

x_train[0].shape

#%%

x_test = k_hot(x_test)

#%%

y_train

#%%

model = keras.Sequential()

#%%

model.add(layers.Dense(32, input_dim=10000, activation='relu'))
model.add(layers.Dense(32, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))

#%%

model.summary()

#%%

model.compile(optimizer='adam',
              loss='binary_crossentropy',
              metrics=['acc']
)

#%%

history = model.fit(x_train, y_train, epochs=15, batch_size=256, validation_data=(x_test, y_test))

#%%

plt.plot(history.epoch, history.history.get('loss'), c='r', label='loss')
plt.plot(history.epoch, history.history.get('val_loss'), c='b', label='val_loss')
plt.legend()

#%%

plt.plot(history.epoch, history.history.get('acc'), c='r', label='acc')
plt.plot(history.epoch, history.history.get('val_acc'), c='b', label='val_acc')
plt.legend()

#%%

keras.datasets.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值