原文链接:http://www.one2know.cn/keras4/

backend 兼容

  • backend,即基于什么来做运算

    Keras 可以基于两个Backend,一个是 Theano,一个是 Tensorflow
  • 查看当前backend

    import keras

    输出:

    Using Theano Backend.

    或者

    Using TensorFlow backend.
  • 修改backend

    找到~/.keras/keras.json文件,在文件内修改,每次import的时候,keras就会检查这个文件
{   # 后端为theano
"image_dim_ordering": "tf",
"epsilon": 1e-07,
"floatx": "float32",
"backend": "theano"
}
{ # 后端为tensorflow
"image_dim_ordering": "tf",
"epsilon": 1e-07,
"floatx": "float32",
"backend": "tensorflow"
}

但这样修改后,import的时候会出现错误信息,可以在terminal中直接输入临时环境变量执行:

KERAS_BACKEND=tensorflow python3 -c "from keras import backend"

最好是在python代码中import keras前加入一个环境变量修改的语句,这种方法仅在这个脚本生效:

import os

os.environ['KERAS_BACKEND']='theano' # os.environ['KERAS_BACKEND']='tensorflow'

Regressor 回归

  • 神经网络可以用来模拟回归问题,给出一组数据,用一条线来对数据进行拟合,并可以预测新输入 x 的输出值
  • 导入模块并创建数据

    models.Sequential 用来一层一层的去建立神经层

    layers.Dense 意思是这个神经层是全连接层
import numpy as np
np.random.seed(1)
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt # 创建一组数据
x = np.linspace(-1,1,200)
np.random.shuffle(x)
y = 0.5 * x + np.random.normal(0,0.05,(200,))
plt.scatter(x,y)
plt.show() x_train,y_train = x[:160],y[:160]
x_test,y_test = x[160:],y[160:]

输出:

  • 建立模型

    用 Sequential 建立 model,再用model.add添加神经层,添加的是Dense全连接神经层

    参数有两个,一个是输入数据和输出数据的维度,本代码的例子中 x 和 y 是一维的
model = Sequential()
model.add(Dense(input_dim=1,output_dim=1))
  • 激活模型

    参数中,误差函数loss用的是mse均方误差;优化器optimizer用的是sgd随机梯度下降法
model.compile(loss='mse', optimizer='sgd')
  • 训练模型

    训练的时候用 model.train_on_batch 一批一批的训练 x_train, y_train。默认的返回值是cost,每100步输出一下结果
print('Training -------------')
for step in range(301):
cost = model.train_on_batch(x_train,y_train) # 返回训练损失
if step % 100 == 0:
print('train cost',cost)

输出:

train cost 0.39069265
train cost 0.10105395
train cost 0.027371023
train cost 0.008624705
  • 检验模型

    用到的函数是 model.evaluate,输入测试集的x和y, 输出 cost,weights 和 biases。其中 weights 和 biases 是取在模型的第一层 model.layers[0] 学习到的参数(一共就一层)
print('\nTesting ------------')
cost = model.evaluate(x_test, y_test, batch_size=40)
print('test cost:', cost)
W, b = model.layers[0].get_weights()
print('Weights=', W, '\nbiases=', b)

输出:

Testing ------------
40/40 [==============================] - 0s 900us/step
test cost: 0.011580094695091248
Weights= [[0.64299107]]
biases= [0.00309446]
  • 可视化结果
y_pred = model.predict(x_test)
plt.scatter(x_test, y_test)
plt.plot(x_test, y_pred)
plt.show()

输出:

  • 整体代码
import numpy as np
np.random.seed(1)
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt # 创建一组数据
x = np.linspace(-1,1,200)
np.random.shuffle(x)
y = 0.5 * x + np.random.normal(0,0.05,(200,))
plt.scatter(x,y)
plt.show() x_train,y_train = x[:160],y[:160]
x_test,y_test = x[160:],y[160:] model = Sequential()
model.add(Dense(input_dim=1,output_dim=1)) model.compile(loss='mse', optimizer='sgd') # 分批训练模型
print('Training -------------')
for step in range(301):
cost = model.train_on_batch(x_train,y_train) # 返回训练损失
if step % 100 == 0:
print('train cost',cost) # 测速
print('\nTesting ------------')
cost = model.evaluate(x_test, y_test, batch_size=40)
print('test cost:', cost)
W, b = model.layers[0].get_weights()
print('Weights=', W, '\nbiases=', b) # 可视化
y_pred = model.predict(x_test)
plt.scatter(x_test, y_test)
plt.plot(x_test, y_pred)
plt.show()

Classifier 分类

  • 以数据集MNIST构建一个分类神经网路
  • 数据预处理

    Keras 自身就有 MNIST 这个数据包,再分成训练集和测试集。x 是一张张图片,y 是每张图片对应的标签,即它是哪个数字。

    输入的 x 变成 60,000×784(28x28的矩阵) 的数据,然后除以 255 进行标准化,因为每个像素都是在 0 到 255 之间的,标准化之后就变成了 0 到 1 之间。

    对于 y,要用到 Keras 改造的 numpy 的一个函数 np_utils.to_categorical,把 y 变成了 one-hot 的形式,即之前 y 是一个数值, 在 0-9 之间,现在是一个大小为 10 的向量,它属于哪个数字,就在哪个位置为 1,其他位置都是 0。
from keras.datasets import mnist
from keras.utils import np_utils
(x_train,y_train),(x_test,y_test) = mnist.load_data() x_train = x_train.reshape(x_train.shape[0],-1)/255 # 标准化
x_test = x_test.reshape(x_test.shape[0],-1)/255
y_train = np_utils.to_categorical(y_train,num_classes=10)
y_test = np_utils.to_categorical(y_test,num_classes=10) print(x_train[0].shape)
print(y_train[:3])

输出:

(784,)
[[0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
[1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]]
  • 建立神经网路

    相关的包:

    models.Sequential 用来一层一层一层的去建立神经层

    layers.Dense 意思是这个神经层是全连接层

    layers.Activation 激励函数

    optimizers.RMSprop 优化器采用 RMSprop,加速神经网络训练方法
  • 建立模型

    在回归网络中用到的是 model.add 一层一层添加神经层,今天的方法是直接在模型的里面加多个神经层。好比一个水管,一段一段的,数据是从上面一段掉到下面一段,再掉到下面一段

    第一段就是加入 Dense 神经层。32 是输出的维度,784 是输入的维度。 第一层传出的数据有 32 个 feature,传给激励单元,激励函数用到的是 relu 函数。 经过激励函数之后,就变成了非线性的数据。 然后再把这个数据传给下一个神经层,这个 Dense 我们定义它有 10 个输出的 feature。同样的,此处不需要再定义输入的维度,因为它接收的是上一层的输出。 接下来再输入给下面的 softmax 函数,用来分类

    接下来用 RMSprop 作为优化器,它的参数包括学习率等,可以通过修改这些参数来看一下模型的效果
import numpy as np
np.random.seed(1)
from keras.models import Sequential
from keras.layers import Dense,Activation
from keras.optimizers import RMSprop model = Sequential([
Dense(32,input_dim=784),
Activation('relu'),
Dense(10),
Activation('softmax')
]) # 优化器
rmsprop = RMSprop(lr=0.001,rho=0.9,epsilon=1e-08,decay=0.0) # 激活模型
model.compile(optimizer=rmsprop,loss='categorical_crossentropy',metrics=['accuracy'])
  • 训练网络

    这里用到的是 fit 函数,把训练集的 x 和 y 传入之后,nb_epoch 表示把整个数据训练多少次,batch_size 每批处理32个
print('Training --------------')
model.fit(x_train,y_train,epochs=2,batch_size=32)
  • 测试模型

    接下来就是用测试集来检验一下模型,方法和回归网络中是一样的,运行代码之后,可以输出 accuracy 和 loss。
print('\nTesting --------------')
loss,accuracy = model.evaluate(x_test,y_test)
print('test loss:',loss)
print('test accuracy:',accuracy)

输出:

test loss: 0.19889679334759713
test accuracy: 0.9396
  • 完整代码
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense,Activation
from keras.optimizers import RMSprop
(x_train,y_train),(x_test,y_test) = mnist.load_data() x_train = x_train.reshape(x_train.shape[0],-1)/255 # 标准化
x_test = x_test.reshape(x_test.shape[0],-1)/255
y_train = np_utils.to_categorical(y_train,num_classes=10)
y_test = np_utils.to_categorical(y_test,num_classes=10) print(x_train[0].shape)
print(y_train[:3]) # 创建模型
model = Sequential([
Dense(32,input_dim=784),Activation('relu'),
Dense(10),Activation('softmax'),
]) # 优化器
rmsprop = RMSprop(lr=0.001,rho=0.9,epsilon=1e-08,decay=0.0) # 激活模型
model.compile(optimizer=rmsprop,loss='categorical_crossentropy',metrics=['accuracy']) # 训练
print('Training --------------')
model.fit(x_train,y_train,epochs=2,batch_size=32) # 测试
print('\nTesting --------------')
loss,accuracy = model.evaluate(x_test,y_test)
print('test loss:',loss)
print('test accuracy:',accuracy)

Keras(三)backend 兼容 Regressor 回归 Classifier 分类 原理及实例的更多相关文章

  1. Keras(五)LSTM 长短期记忆模型 原理及实例

    LSTM 是 long-short term memory 的简称, 中文叫做 长短期记忆. 是当下最流行的 RNN 形式之一 RNN 的弊端 RNN没有长久的记忆,比如一个句子太长时开头部分可能会忘 ...

  2. Factorization Machines 学习笔记(三)回归和分类

      近期学习了一种叫做 Factorization Machines(简称 FM)的算法,它可对随意的实值向量进行预測.其主要长处包含: 1) 可用于高度稀疏数据场景:2) 具有线性的计算复杂度.本文 ...

  3. Keras官方中文文档:keras后端Backend

    所属分类:Keras Keras后端 什么是"后端" Keras是一个模型级的库,提供了快速构建深度学习网络的模块.Keras并不处理如张量乘法.卷积等底层操作.这些操作依赖于某种 ...

  4. 02-15 Logistic回归(鸢尾花分类)

    目录 Logistic回归(鸢尾花分类) 一.导入模块 二.获取数据 三.构建决策边界 四.训练模型 4.1 C参数与权重系数的关系 五.可视化 更新.更全的<机器学习>的更新网站,更有p ...

  5. Sklearn中的回归和分类算法

    一.sklearn中自带的回归算法 1. 算法 来自:https://my.oschina.net/kilosnow/blog/1619605 另外,skilearn中自带保存模型的方法,可以把训练完 ...

  6. matlab-逻辑回归二分类(Logistic Regression)

    逻辑回归二分类 今天尝试写了一下逻辑回归分类,把代码分享给大家,至于原理的的话请戳这里 https://blog.csdn.net/laobai1015/article/details/7811321 ...

  7. 《转》Logistic回归 多分类问题的推广算法--Softmax回归

    转自http://ufldl.stanford.edu/wiki/index.php/Softmax%E5%9B%9E%E5%BD%92 简介 在本节中,我们介绍Softmax回归模型,该模型是log ...

  8. keras实现简单性别识别(二分类问题)

    keras实现简单性别识别(二分类问题) 第一步:准备好需要的库 tensorflow  1.4.0 h5py 2.7.0 hdf5 1.8.15.1 Keras     2.0.8 opencv-p ...

  9. 基于CART的回归和分类任务

    CART 是 classification and regression tree 的缩写,即分类与回归树. 博主之前学习的时候有用过决策树来做预测的小例子:机器学习之决策树预测--泰坦尼克号乘客数据 ...

随机推荐

  1. 0 Spark完成WordCount操作

    先看下结果: pom.xml: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http ...

  2. 【iOS】UIAlertView 点击跳转事件

    iOS 开发中,UIAlertView 经常用到.这里记录下曾用到的点击跳转事件. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@& ...

  3. 认识 tomcat 被占用问题

    (1) Server 中的 port 该端口为tomcat使用jvm的端口,必须保证唯一性,否则tomcat启动不成功: (2) Connector 中的 port 该端口为tomcat中所有web应 ...

  4. 给最近正在找工作(iOS)的朋友一些建议/经验

    众所周知, iOS开发找工作越来越难, 企业要求越来越高,一方面是资本寒冬期+七八月是企业招人淡季, 另外一方面也是iOS市场饱和.最近有出去看新机会, 所以下面记录一下面试XimalayaFM的大概 ...

  5. java中System.out.println()打印输出结果

    疑点:syso()是打印输出语句,打印的是什么? syso()不同情况下打印输出的结果不一样: 1. package com.briup; public class Syso { public sta ...

  6. Unity经典游戏教程之:合金弹头

    版权声明: 本文原创发布于博客园"优梦创客"的博客空间(网址:http://www.cnblogs.com/raymondking123/)以及微信公众号"优梦创客&qu ...

  7. 【Java例题】4.1 级数求和1

    1. 计算级数之和: y=1-1/2+1/4-1/8+...+ (-1)^(n-1)/2^(n-1). 这里的"^"表示乘方. package chapter4; import j ...

  8. 【Java例题】1.2计算n的m次方

    package study; import java.util.*; import java.math.*; public class study { public static void main( ...

  9. java代码之美(13)--- Predicate详解

    java代码之美(13)--- Predicate详解 遇到Predicate是自己在自定义Mybatis拦截器的时候,在拦截器中我们是通过反射机制获取对象的所有属性,再查看这些属性上是否有我们自定义 ...

  10. spring cloud stream 经验总结

    ---恢复内容开始--- 基本概念 spring: cloud: stream: kafka: binder: brokers: cloudTest:19092 zk-nodes: cloudTest ...