Deep Learning: Keras + IMDB

Classifying movie reviews: a binary classification example

# -*- coding: utf-8 -*-

"""
@Date: 2018/10/5

@Author: dreamhomes

@Summary:
"""
from keras.datasets import imdb
from keras import models
from keras import layers

import numpy as np
import matplotlib.pyplot as plt

# N 25000
(train_data, train_labels), (test_data,
                             test_labels) = imdb.load_data(num_words=10000)
# print(len(train_data))
# print(train_labels)
# print(max([max(sequence) for sequence in train_data]))

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]])
# print(decoded_review)


def vectorize_sequences(sequences, dimension=10000):
    """
    one hot encoding - Turn lists to vectors/tensors
    :param sequences:
    :param dimension:
    :return:
    """
    results = np.zeros((len(sequences), dimension))
    for i, sequence in enumerate(sequences):
        results[i, sequence] = 1.
    return results


x_train = vectorize_sequences(train_data)
x_test = vectorize_sequences(test_data)

# print(x_train[0])

y_train = np.asarray(train_labels).astype('float32')
# print(y_train)
y_test = np.asarray(test_labels).astype('float32')


model = models.Sequential()
model.add(layers.Dense(16, activation='relu', input_shape=(10000,)))
model.add(layers.Dense(16, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))

model.compile(
    optimizer='rmsprop',
    loss='binary_crossentropy',
    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=20,
    batch_size=512,
    validation_data=(
        x_val,
        y_val))


# Plotting the training and validation lose side by side
# history_dict = history.history
# loss_values = history_dict['loss']
# val_loss_values = history_dict['val_loss']
# acc_values = history_dict['acc']
# val_acc_values = history_dict['val_acc']
#
# epochs = range(1, len(history_dict['acc']) + 1)
#
# plt.figure()
# plt.plot(epochs, loss_values, 'bo', label='Training loss')
# plt.plot(epochs, val_loss_values, 'b', label='Validation loss')
# plt.title('Training and validation loss')
# plt.xlabel('Epochs')
# plt.ylabel('Loss')
# plt.legend()
#
# plt.figure()
# plt.plot(epochs, acc_values, 'bo', label='Training acc')
# plt.plot(epochs, val_acc_values, 'b', label='Validation acc')
# plt.title('Training and validation accuracy')
# plt.xlabel('Epochs')
# plt.ylabel('Accuracy')
# plt.legend()
# plt.show()

result = model.evaluate(x_test, y_test)
print(model.metrics_names)
print(result)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Deep Learning with Keras by Antonio Gulli English | 26 Apr. 2017 | ASIN: B06Y2YMRDW | 318 Pages | AZW3 | 10.56 MB Key Features Implement various deep-learning algorithms in Keras and see how deep-learning can be used in games See how various deep-learning models and practical use-cases can be implemented using Keras A practical, hands-on guide with real-world examples to give you a strong foundation in Keras Book Description This book starts by introducing you to supervised learning algorithms such as simple linear regression, the classical multilayer perceptron and more sophisticated deep convolutional networks. You will also explore image processing with recognition of hand written digit images, classification of images into different categories, and advanced objects recognition with related image annotations. An example of identification of salient points for face detection is also provided. Next you will be introduced to Recurrent Networks, which are optimized for processing sequence data such as text, audio or time series. Following that, you will learn about unsupervised learning algorithms such as Autoencoders and the very popular Generative Adversarial Networks (GAN). You will also explore non-traditional uses of neural networks as Style Transfer. Finally, you will look at Reinforcement Learning and its application to AI game playing, another popular direction of research and application of neural networks. What you will learn Optimize step-by-step functions on a large neural network using the Backpropagation Algorithm Fine-tune a neural network to improve the quality of results Use deep learning for image and audio processing Use Recursive Neural Tensor Networks (RNTNs) to outperform standard word embedding in special cases Identify problems for which Recurrent Neural Network (RNN) solutions are suitable Explore the process required to implement Autoencoders Evolve a deep neural network using reinforcement learning About the Author Antonio Gulli is a software executive and business leader with a passion for establishing and managing global technological talent, innovation, and execution. He is an expert in search engines, online services, machine learning, information retrieval, analytics, and cloud computing. So far, he has been lucky enough to gain professional experience in four different countries in Europe and managed people in six different countries in Europe and America. Antonio served as CEO, GM, CTO, VP, director, and site lead in multiple fields spanning from publishing (Elsevier) to consumer internet (Ask.com and Tiscali) and high-tech R&D (Microsoft and Google). Sujit Pal is a technology research director at Elsevier Labs, working on building intelligent systems around research content and metadata. His primary interests are information retrieval, ontologies, natural language processing, machine learning, and distributed processing. He is currently working on image classification and similarity using deep learning models. Prior to this, he worked in the consumer healthcare industry, where he helped build ontology-backed semantic search, contextual advertising, and EMR data processing platforms. He writes about technology on his blog at Salmon Run. Table of Contents Neural Networks Foundations Keras Installation and API Deep Learning with ConvNets Generative Adversarial Networks and WaveNet Word Embeddings Recurrent Neural Network — RNN Additional Deep Learning Models AI Game Playing Conclusion
图书可以从下面的链接下载 http://download.csdn.net/detail/u013003382/9832573 Deep Learning with Keras by Antonio Gulli English | 26 Apr. 2017 | ASIN: B06Y2YMRDW | 318 Pages | AZW3 | 10.56 MB Key Features Implement various deep-learning algorithms in Keras and see how deep-learning can be used in games See how various deep-learning models and practical use-cases can be implemented using Keras A practical, hands-on guide with real-world examples to give you a strong foundation in Keras Book Description This book starts by introducing you to supervised learning algorithms such as simple linear regression, the classical multilayer perceptron and more sophisticated deep convolutional networks. You will also explore image processing with recognition of hand written digit images, classification of images into different categories, and advanced objects recognition with related image annotations. An example of identification of salient points for face detection is also provided. Next you will be introduced to Recurrent Networks, which are optimized for processing sequence data such as text, audio or time series. Following that, you will learn about unsupervised learning algorithms such as Autoencoders and the very popular Generative Adversarial Networks (GAN). You will also explore non-traditional uses of neural networks as Style Transfer. Finally, you will look at Reinforcement Learning and its application to AI game playing, another popular direction of research and application of neural networks. What you will learn Optimize step-by-step functions on a large neural network using the Backpropagation Algorithm Fine-tune a neural network to improve the quality of results Use deep learning for image and audio processing Use Recursive Neural Tensor Networks (RNTNs) to outperform standard word embedding in special cases Identify problems for which Recurrent Neural Network (RNN) solutions are suitable Explore the process required to implement Autoencoders Evolve a deep neural network using reinforcement learning About the Author Antonio Gulli is a software executive and business leader with a passion for establishing and managing global technological talent, innovation, and execution. He is an expert in search engines, online services, machine learning, information retrieval, analytics, and cloud computing. So far, he has been lucky enough to gain professional experience in four different countries in Europe and managed people in six different countries in Europe and America. Antonio served as CEO, GM, CTO, VP, director, and site lead in multiple fields spanning from publishing (Elsevier) to consumer internet (Ask.com and Tiscali) and high-tech R&D (Microsoft and Google). Sujit Pal is a technology research director at Elsevier Labs, working on building intelligent systems around research content and metadata. His primary interests are information retrieval, ontologies, natural language processing, machine learning, and distributed processing. He is currently working on image classification and similarity using deep learning models. Prior to this, he worked in the consumer healthcare industry, where he helped build ontology-backed semantic search, contextual advertising, and EMR data processing platforms. He writes about technology on his blog at Salmon Run. Table of Contents Neural Networks Foundations Keras Installation and API Deep Learning with ConvNets Generative Adversarial Networks and WaveNet Word Embeddings Recurrent Neural Network — RNN Additional Deep Learning Models AI Game Playing Conclusion
Implement neural networks with Keras on Theano and TensorFlow The book presents more than 20 working deep neural networks coded in Python using Keras, a modular neural network library that runs on top of either Google's TensorFlow or Lisa Lab's Theano backends. The reader is introduced step by step to supervised learning algorithms such as simple linear regression, classical multilayer perceptron, and more sophisticated deep convolutional networks and generative adversarial networks. In addition, the book covers unsupervised learning algorithms such as autoencoders and generative networks. Recurrent networks and long short-term memory (LSTM) networks are also explained in detail. The book goes on to cover the Keras functional API and how to customize Keras in case the reader's use case is not covered by Keras's extensive functionality. It also looks at larger, more complex systems composed of the building blocks covered previously. The book concludes with an introduction to deep reinforcement learning and how it can be used to build game playing AIs. Practical applications include code for the classification of news articles into predefined categories, syntactic analysis of texts, sentiment analysis, synthetic generation of texts, and parts of speech annotation. Image processing is also explored, with recognition of handwritten digit images, classification of images into different categories, and advanced object recognition with related image annotations. An example of identification of salient points for face detection will be also provided. Sound analysis comprises recognition of discrete speeches from multiple speakers. Reinforcement learning is used to build a deep Q-learning network capable of playing games autonomously. Experiments are the essence of the book. Each net is augmented by multiple variants that progressively improve the learning performance by changing the input parameters, the shape of the network, loss functions, and algorithms used for optimizations. Several comparisons between training on CPUs and GPUs are also provided. 全书8章310页,主要聚焦于keras api的使用,推荐给炼丹的同学
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值