0
点赞
收藏
分享

微信扫一扫

随想录(keras入门)



 

    深度学习基于神经网络而来,学习起来比较复杂。虽然google的tensorflow框架给我们提供了方便,但是使用上还是有很多不明白的地方。现在有了keras之后,大家应该就没有烦恼了。keras相当于在tensorflow上面封装了一层,大部分参数是用默认参数。使用起来得心应手。关于安装方法,我一般都是在ubuntu 16.04上面安装。比如先pip install tensorflow; pip install keras就可以完成安装了。一般来说,做到这几步就可以了,

 

1、构建sequential模型

from keras.models import Sequential

model = Sequential()

 

2、添加网络层

from keras.layers import Dense, Activation

model.add(Dense(units=64, input_dim=100))
model.add(Activation("relu"))
model.add(Dense(units=10))
model.add(Activation("softmax"))

 

3、编译模型,注意损失函数和优化函数两个变量

model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])

 

4、训练数据

model.fit(x_train, y_train, epochs=5, batch_size=32)

 

5、评估数据

loss_and_metrics = model.evaluate(x_test, y_test, batch_size=128)

 

6、如果不需要评估数据,可以直接预测数据

classes = model.predict(x_test, batch_size=128)

 

7、更多内容

    关于keras的内容,更多可以参考官方网站,或者它的中文网站​​https://keras-cn.readthedocs.io/en/latest/#30skeras​​。关于机器学习或者深度学习这块,个人觉人keras和sklearn、cv2这些开源库一样好用,建议大家多多练习。

import numpy as np
import keras

from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.optimizers import SGD

# Generate dummy data
x_train = np.random.random((100, 100, 100, 3))
y_train = keras.utils.to_categorical(np.random.randint(10, size=(100, 1)), num_classes=10)
x_test = np.random.random((20, 100, 100, 3))
y_test = keras.utils.to_categorical(np.random.randint(10, size=(20, 1)), num_classes=10)

model = Sequential()
# input: 100x100 images with 3 channels -> (100, 100, 3) tensors.
# this applies 32 convolution filters of size 3x3 each.
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(100, 100, 3)))
model.add(Conv2D(32, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(10, activation='softmax'))

sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy', optimizer=sgd)

model.fit(x_train, y_train, batch_size=32, epochs=10)
score = model.evaluate(x_test, y_test, batch_size=32)

 

ps:

    有兴趣的同学可以关注一下百度的paddlepaddle,即​​https://github.com/PaddlePaddle/Paddle​​。个人感觉也非常不错,和keras很像。此外,现在windows平台只有python3才可以安装tensorflow,所以keras也需要在python3上面运行。现在python27最晚在2020年一月份失去支持,大家也可以早点转到python3上面去。

 

 

 

举报

相关推荐

0 条评论