安装keras

keras与Tensorflow

keras是一个用于快速构建模型的API库,但是他不处理实际的计算,所以它需要一个更底层的“服务”,这个服务负责把keras构的模型具体的实现。常用的有 TensorFlow, CNTK 或者 Theano作为它的后端服务,但是从Tensorflow2开始,Tensorflow中集成了Keras。目前Keras也是推荐使用Tensorflow作为它的后端。

安装keras

在anaconda的体系下,安装keras,实际上,只需要安装了Tensorflow就自然的装上了。如何安装Tensorflow可以看前面的博文。当然,这是安装CPU版的,GPU版的与CPU的类似,只是多了CUDA的安装部分。

测试

在jupyter notebook中写入下面的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import keras
from keras import models
from keras import layers
from keras.datasets import imdb
import numpy as np

(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)

def vectorize_sequences(sequences, dimension=10000):
# Create an all-zero matrix of shape (len(sequences), dimension)
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

# Our vectorized training data
x_train = vectorize_sequences(train_data)
# Our vectorized test data
x_test = vectorize_sequences(test_data)
# Our vectorized labels
y_train = np.asarray(train_labels).astype('float32')
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=['acc'])

model.fit(x_train, y_train, epochs=4, batch_size=512)
result = model.evaluate(x_test, y_test)
print(result)

运行,如果过程中不报错,就表示都安好了。