简述

Keras是在既有的NN框架之上的封装,可以以TF,CNTK,Theano等作为后端来运行。它的价值在于快速实验,能很方便将实验想法用Keras框架写成代码。

开发环境搭建

默认情况下Keras使用TF为后端。注意后面两个用pip安装,不然一直无法安装成功。这里为了学习方便直接安装了TF,如果有GPU可以去安装GPU版本的TF。

conda create -n krs python=3.6.5
conda activae krs
pip install tensorflow
pip install keras

安装好后在交互环境下测试一下:

>>> import keras
Using TensorFlow backend.

如果要更换后端,可以去用户目录/.keras/keras.json中修改。

使用Jupyter

在刚刚搭建的虚拟环境**的情况下:

conda install nb_conda

安装好后运行Jupyter,可以看到使用这个虚拟环境为Kernel了:
【Keras学习笔记】1:开发环境搭建,单变量线性回归
测试一下使用Keras:
【Keras学习笔记】1:开发环境搭建,单变量线性回归
这样Keras就配置好了,因为是新的虚拟环境,所以用conda再装一下matplotlib。

单变量线性回归

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
x = np.linspace(0,100,30) # 0~100取30个数
y = 3*x + 7 + np.random.randn(30)*6 # 加上30个~N(0,1)*6的随机数作为噪声
x
array([  0.        ,   3.44827586,   6.89655172,  10.34482759,
        13.79310345,  17.24137931,  20.68965517,  24.13793103,
        27.5862069 ,  31.03448276,  34.48275862,  37.93103448,
        41.37931034,  44.82758621,  48.27586207,  51.72413793,
        55.17241379,  58.62068966,  62.06896552,  65.51724138,
        68.96551724,  72.4137931 ,  75.86206897,  79.31034483,
        82.75862069,  86.20689655,  89.65517241,  93.10344828,
        96.55172414, 100.        ])
y
array([  9.61985034,   6.65902358,  27.65099404,  32.40425989,
        49.14349403,  51.59137817,  66.71080201,  77.52403701,
        83.64249992, 106.72422234,  98.75506834, 111.10188793,
       140.34920173, 138.65973915, 151.44733635, 163.7790927 ,
       170.96246611, 188.03953355, 198.75765628, 201.38912671,
       221.62011565, 215.62783703, 224.86768245, 241.135611  ,
       256.1511241 , 265.47398468, 271.02415446, 285.47453087,
       289.99888052, 305.56647148])
# 看一下分布情况
plt.scatter(x, y)
<matplotlib.collections.PathCollection at 0xe8edc88>

【Keras学习笔记】1:开发环境搭建,单变量线性回归

可以从分布图上看出是y = ax + b的关系,现在就是要求出参数a和b

import keras
Using TensorFlow backend.
# 建立一个Keras顺序模型,里面的模块都是顺序的一节一节的
model = keras.Sequential()
from keras import layers
# 为顺序模型中添加一个全连接层,输出是1维的,输入是1维的
model.add(layers.Dense(1, input_dim=1))
WARNING:tensorflow:From E:\MyProgram\Anaconda\envs\krs\lib\site-packages\tensorflow\python\framework\op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
# 显示一下模型的各个层,两个参数即一个w(这里是a)和一个b
model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense_1 (Dense)              (None, 1)                 2         
=================================================================
Total params: 2
Trainable params: 2
Non-trainable params: 0
_________________________________________________________________

编译模型,指明优化算法和优化目标(Loss)

model.compile(
    optimizer='adam',
    loss='mse'
)

训练模型,要把数据放进去

# 3000个epochs,这里verbose=0表示不在标准输出流输出训练日志
model.fit(x, y, epochs=3000, verbose=0)
WARNING:tensorflow:From E:\MyProgram\Anaconda\envs\krs\lib\site-packages\tensorflow\python\ops\math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.cast instead.





<keras.callbacks.History at 0x130dce10>

使用训练好的模型预测x的输出值y

model.predict(x)
array([[  1.9478713],
       [ 11.83144  ],
       [ 21.71501  ],
       [ 31.59858  ],
       [ 41.482147 ],
       [ 51.365715 ],
       [ 61.249287 ],
       [ 71.13285  ],
       [ 81.01642  ],
       [ 90.899994 ],
       [100.783554 ],
       [110.66713  ],
       [120.5507   ],
       [130.43428  ],
       [140.31784  ],
       [150.2014   ],
       [160.08498  ],
       [169.96855  ],
       [179.85213  ],
       [189.73569  ],
       [199.61925  ],
       [209.50284  ],
       [219.3864   ],
       [229.26997  ],
       [239.15353  ],
       [249.0371   ],
       [258.9207   ],
       [268.80423  ],
       [278.6878   ],
       [288.57138  ]], dtype=float32)

把实际输出和预测曲线绘制在一张图上看一下

plt.scatter(x, y)
# 因为训练得到的是a和b(而不是直接得到预测值),随意预测一定在一条直线上,这里绘制一条直线
plt.plot(x, model.predict(x), c='r')
[<matplotlib.lines.Line2D at 0x1356ac50>]

【Keras学习笔记】1:开发环境搭建,单变量线性回归

# 如果要预测单个值
model.predict([150])
array([[431.88312]], dtype=float32)