- Python Deep Learning Cookbook
- Indra den Bakker
- 295字
- 2021-07-02 15:43:12
How to do it...
- We start by installing Keras on our local Anaconda environment as follows:
conda install -c conda-forge keras
Make sure your deep learning environment is activated before executing this command.
- Next, we import keras library into our Python environment:
from keras.models import Sequential
from keras.layers import Dense
This command outputs the backend used by Keras. By default, the TensorFlow framework is used:

Figure 1.3: Keras prints the backend used
- To provide a dummy dataset, we will use numpy and the following code:
import numpy as np
x_input = np.array([[1,2,3,4,5]])
y_input = np.array([[10]])
- When using sequential mode, it's straightforward to stack multiple layers in Keras. In this example, we use one hidden layer with 32 units and an output layer with one unit:
model = Sequential()
model.add(Dense(units=32, input_dim=x_input.shape[1]))
model.add(Dense(units=1))
- Next, we need to compile our model. While compiling, we can set different settings such as loss function, optimizer, and metrics:
model.compile(loss='mse',
optimizer='sgd',
metrics=['accuracy'])
- In Keras, you can easily print a summary of your model. It will also show the number of parameters within the defined model:
model.summary()
In the following figure, you can see the model summary of our build model:

Figure 1.4: Example of a Keras model summary
- Training the model is straightforward with one command, while simultaneously saving the results to a variable called history:
history = model.fit(x_input, y_input, epochs=10, batch_size=32)
- For testing, the prediction function can be used after training:
pred = model.predict(x_input, batch_size=128)
In this short introduction to Keras, we have demonstrated how easy it is to implement a neural network in just a couple of lines of code. However, don't confuse simplicity with power. The Keras framework provides much more than we've just demonstrated here and one can adjust their model up to a granular level if needed.
推薦閱讀
- HTML5+CSS3王者歸來(lái)
- Learning ROS for Robotics Programming(Second Edition)
- 解構(gòu)產(chǎn)品經(jīng)理:互聯(lián)網(wǎng)產(chǎn)品策劃入門(mén)寶典
- Python Network Programming Cookbook(Second Edition)
- SharePoint Development with the SharePoint Framework
- iPhone應(yīng)用開(kāi)發(fā)從入門(mén)到精通
- Swift語(yǔ)言實(shí)戰(zhàn)晉級(jí)
- 跟戴銘學(xué)iOS編程:理順核心知識(shí)點(diǎn)
- Anaconda數(shù)據(jù)科學(xué)實(shí)戰(zhàn)
- 算法秘籍
- 信息學(xué)奧林匹克競(jìng)賽初賽精講精練
- HTML5 and CSS3:Building Responsive Websites
- C/C++語(yǔ)言程序開(kāi)發(fā)參考手冊(cè)
- CISSP in 21 Days(Second Edition)
- 多接入邊緣計(jì)算實(shí)戰(zhàn)