深度學習 keras_Keras深度學習教程

 2023-11-19 阅读 15 评论 0

摘要:深度學習 keras 什么是Keras? (What is Keras?) Keras is a high-level neural networks API. It is written in Python and can run on top of Theano, TensorFlow or CNTK. It was developed with the idea of: Keras是高級神經網絡API。 它是用Python編寫的,

深度學習 keras

什么是Keras? (What is Keras?)

Keras is a high-level neural networks API. It is written in Python and can run on top of Theano, TensorFlow or CNTK. It was developed with the idea of:

Keras是高級神經網絡API。 它是用Python編寫的,可以在Theano,TensorFlow或CNTK之上運行。 它的開發思想是:

Being able to go from idea to result with the least possible delay is key to doing good research.
能夠以盡可能少的延遲將想法付諸實踐是進行良好研究的關鍵。

Keras is a user-friendly, extensible and modular library which makes prototyping easy and fast. It supports convolutional networks, recurrent networks and even the combination of both.

Keras是一個用戶友好,可擴展的模塊化庫,可輕松快速地制作原型。 它支持卷積網絡,循環網絡,甚至兩者的組合。

Initial development of Keras was a part of the research of project ONEIROS (Open-ended Neuro-Electronic Intelligent Robot Operating System).

Keras的最初開發是ONEIROS(開放式神經電子智能機器人操作系統)項目研究的一部分。

為什么選擇Keras? (Why Keras?)

There are countless deep-learning frameworks available today, but there are some of the areas in which Keras proved better than other alternatives.

當今有無數的深度學習框架可用,但是Keras在某些領域被證明比其他選擇要好。

Keras focuses on minimal user action requirement when common use cases are concerned also if the user makes an error, clear and actionable feedback is provided. This makes keras easy to learn and use.

當涉及到常見用例時,如果用戶犯了錯誤,提供了清晰且可行的反饋,Keras專注于最小化用戶操作要求。 這使喀拉拉邦易于學習和使用

When you want to put your Keras models to use into some application, you need to deploy it on other platforms which is comparatively easy if you are using keras. It also supports multiple backends and also allows portability across backends i.e. you can train using one backend and load it with another.

當您想將Keras模型用于某些應用程序時,您需要將其部署在其他平臺上,如果您使用的是keras,這相對容易。 它還支持多個后端,并且還允許跨后端進行可移植性,即,您可以使用一個后端進行培訓,然后將其加載到另一個后端。

It has got a strong back with built-in multiple GPU support, it also supports distributed training.

憑借內置的多個GPU支持獲得了強大的支持,它還支持分布式培訓。

Keras教程 (Keras Tutorial)

安裝Keras (Installing Keras)

We need to install one of the backend engines before we actually get to installing Keras. Let’s go and install any of TensorFlow or Theano or CNTK modules.

在實際安裝Keras之前,我們需要安裝一個后端引擎。 我們去安裝任何TensorFlow或Theano或CNTK模塊。

Now, we are ready to install keras. We can either use pip installation or clone the repository from git. To install using pip, open the terminal and run the following command:

現在,我們準備安裝keras。 我們可以使用pip安裝或從git克隆存儲庫。 要使用pip進行安裝,請打開終端并運行以下命令:

pip install keras

In case pip installation doesn’t work or you want another method, you can clone the git repository using

如果無法安裝pip或需要其他方法,則可以使用以下命令克隆git存儲庫

git clone https://github.com/keras-team/keras.git

Once cloned, move to the cloned directory and run:

克隆后,移至克隆目錄并運行:

sudo python setup.py install

使用Keras (Using Keras)

To use Keras in any of your python scripts we simply need to import it using:

要在您的任何python腳本中使用Keras,我們只需要使用以下命令導入即可:

import keras

密集連接的網絡 (Densely Connected Network)

A Sequential model is probably a better choice to create such network, but we are just getting started so it’s a better choice to start with something really simple:

順序模型可能是創建此類網絡的更好選擇,但是我們才剛剛開始,因此從一個非常簡單的東西開始是一個更好的選擇:

from keras.layers import Input, Dense
from keras.models import Model
# This returns a tensor
inputs = Input(shape=(784,))# a layer instance is callable on a tensor, and returns a tensor
x = Dense(64, activation='relu')(inputs)
x = Dense(64, activation='relu')(x)
predictions = Dense(10, activation='softmax')(x)
# This creates a model that includes
# the Input layer and three Dense layers
model = Model(inputs=inputs, outputs=predictions)
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

Now that you have seen how to create a simple Densely Connected Network model you can train it with your training data and may use it in your deep learning module.

既然您已經了解了如何創建簡單的密集連接網絡模型,則可以將其與訓練數據一起訓練,并可以在深度學習模塊中使用它。

順序模型 (Sequential Model)

Model is core data structure of Keras. The simplest type of model is a linear stack of layers, we call it Sequential Model. Let’s put our hands in code and try to build one:

模型是Keras的核心數據結構。 模型的最簡單類型是層的線性堆棧,我們稱之為順序模型。 讓我們動手編寫代碼,嘗試構建一個:

# import required modules
from keras.models import Sequential
from keras.layers import Dense
import numpy as np
# Create a model
model= Sequential()
# Stack Layers
model.add(Dense(units=64, activation='relu', input_dim=100))
model.add(Dense(units=10, activation='softmax'))
# Configure learning
model.compile(loss='categorical_crossentropy', optimizer='sgd',metrics=['accuracy'])
# Create Numpy arrays with random values, use your training or test data here
x_train = np.random.random((64,100))
y_train = np.random.random((64,10))
x_test = np.random.random((64,100))
y_test = np.random.random((64,10))
# Train using numpy arrays
model.fit(x_train, y_train, epochs=5, batch_size=32)
# evaluate on existing data
loss_and_metrics = model.evaluate(x_test, y_test, batch_size=128)
# Generate predictions on new data
classes = model.predict(x_test, batch_size=128)

Let’s run the program to see the results:

keras tutorial, keras deep learning tutorial

讓我們運行程序以查看結果:

Let’s try a few more models and how to create them like, Residual Connection on a Convolution Layer:

讓我們嘗試其他一些模型,以及如何在卷積層上創建“殘留連接”,例如:

from keras.layers import Conv2D, Input# input tensor for a 3-channel 256x256 image
x = Input(shape=(256, 256, 3))
# 3x3 conv with 3 output channels (same as input channels)
y = Conv2D(3, (3, 3), padding='same')(x)
# this returns x + y.
z = keras.layers.add([x, y])

共享視覺模型 (Shared Vision Model)

Shared Vision Model helps to classify whether two MNIST digits are the same digit or different digits by reusing the same image-processing module on two inputs. Let’s create one as shown below.

共享視覺模型通過在兩個輸入上重用相同的圖像處理模塊,有助于對兩個MNIST數字是相同數字還是不同數字進行分類。 讓我們創建一個如下所示。

from keras.layers import Conv2D, MaxPooling2D, Input, Dense, Flatten
from keras.models import Model
import keras
# First, define the vision modules
digit_input = Input(shape=(27, 27, 1))
x = Conv2D(64, (3, 3))(digit_input)
x = Conv2D(64, (3, 3))(x)
x = MaxPooling2D((2, 2))(x)
out = Flatten()(x)
vision_model = Model(digit_input, out)
# Then define the tell-digits-apart model
digit_a = Input(shape=(27, 27, 1))
digit_b = Input(shape=(27, 27, 1))
# The vision model will be shared, weights and all
out_a = vision_model(digit_a)
out_b = vision_model(digit_b)
concatenated = keras.layers.concatenate([out_a, out_b])
out = Dense(1, activation='sigmoid')(concatenated)
classification_model = Model([digit_a, digit_b], out)

視覺問答模型 (Visual Question Answering Model)

Let’s create a model which can choose the correct one-word answer to a natural-language question about a picture.

讓我們創建一個模型,該模型可以為有關圖片的自然語言問題選擇正確的單字答案。

It can be done by encoding the question and image into two separate vectors, concatenating both of them and training on top a logistic regression over some vocabulary of potential answers. Let’s try the model:

可以通過將問題和圖像編碼為兩個單獨的向量,并將它們連接在一起,并在一些潛在答案的詞匯表上進行邏輯回歸來訓練來完成。 讓我們嘗試一下模型:

from keras.layers import Conv2D, MaxPooling2D, Flatten
from keras.layers import Input, LSTM, Embedding, Dense
from keras.models import Model, Sequential
import keras# First, let's define a vision model using a Sequential model.
# This model will encode an image into a vector.
vision_model = Sequential()
vision_model.add(Conv2D(64, (3, 3), activation='relu', padding='same', input_shape=(224, 224, 3)))
vision_model.add(Conv2D(64, (3, 3), activation='relu'))
vision_model.add(MaxPooling2D((2, 2)))
vision_model.add(Conv2D(128, (3, 3), activation='relu', padding='same'))
vision_model.add(Conv2D(128, (3, 3), activation='relu'))
vision_model.add(MaxPooling2D((2, 2)))
vision_model.add(Conv2D(256, (3, 3), activation='relu', padding='same'))
vision_model.add(Conv2D(256, (3, 3), activation='relu'))
vision_model.add(Conv2D(256, (3, 3), activation='relu'))
vision_model.add(MaxPooling2D((2, 2)))
vision_model.add(Flatten())# Now let's get a tensor with the output of our vision model:
image_input = Input(shape=(224, 224, 3))
encoded_image = vision_model(image_input)# Next, let's define a language model to encode the question into a vector.
# Each question will be at most 100 word long,
# and we will index words as integers from 1 to 9999.
question_input = Input(shape=(100,), dtype='int32')
embedded_question = Embedding(input_dim=10000, output_dim=256, input_length=100)(question_input)
encoded_question = LSTM(256)(embedded_question)# Let's concatenate the question vector and the image vector:
merged = keras.layers.concatenate([encoded_question, encoded_image])# And let's train a logistic regression over 1000 words on top:
output = Dense(1000, activation='softmax')(merged)# This is our final model:
vqa_model = Model(inputs=[image_input, question_input], outputs=output)# The next stage would be training this model on actual data.

If you want to learn more about Visual Question Answering (VQA), check out this beginner’s guide to VQA.

如果您想了解有關視覺問答(VQA)的更多信息,請查閱此VQA初學者指南 。

訓練神經網絡 (Training Neural Network)

Now that we have seen how to build different models using Keras, let’s put things together and work on a complete example. The following example trains a Neural Network on MNIST data set:

既然我們已經了解了如何使用Keras構建不同的模型,那么讓我們將它們放在一起并研究一個完整的示例。 以下示例在MNIST數據集上訓練神經網絡:

import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.optimizers import RMSpropbatch_size = 128
num_classes = 10
epochs = 20# the data, shuffled and split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()x_train = x_train.reshape(60000, 784)
x_test = x_test.reshape(10000, 784)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)model = Sequential()
model.add(Dense(512, activation='relu', input_shape=(784,)))
model.add(Dropout(0.2))
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(num_classes, activation='softmax'))model.summary()
# Compile model
model.compile(loss='categorical_crossentropy',optimizer=RMSprop(),metrics=['accuracy'])history = model.fit(x_train, y_train,batch_size=batch_size,epochs=epochs,verbose=1,validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
# Print the results
print('Test loss:', score[0])
print('Test accuracy:', score[1])

Let’s run this example and wait for results:

keras example, keras neural network tutorial

The output shows only the final part, it might take a few minutes for the program to finish execution depending on machine

讓我們運行此示例并等待結果:

輸出僅顯示最后一部分,根據機器的不同,程序可能需要幾分鐘才能完成執行

結論 (Conclusion)

In this tutorial, we discovered that Keras is a powerful framework and makes it easy for the user to create prototypes and that too very quickly. We have also seen how different models can be created using keras. These models can be used for feature extraction, fine-tuning and prediction. We have also seen how to train a neural network using keras.

在本教程中,我們發現Keras是一個功能強大的框架,它使用戶易于創建原型,而且開發起來太快了。 我們還看到了如何使用keras創建不同的模型。 這些模型可用于特征提取,微調和預測。 我們還看到了如何使用keras訓練神經網絡。

Keras has grown popular with other frameworks and it is one of the most popular frameworks on Kaggle.

Keras在其他框架中變得越來越流行,它是Kaggle上最受歡迎的框架之一。

翻譯自: https://www.journaldev.com/18314/keras-deep-learning-tutorial

深度學習 keras

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/5/183187.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息