Keras(三)backend 兼容 Regressor 回归 Classifier 分类 原理及实例
原文链接: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 分类 原理及实例的更多相关文章
- Keras(五)LSTM 长短期记忆模型 原理及实例
LSTM 是 long-short term memory 的简称, 中文叫做 长短期记忆. 是当下最流行的 RNN 形式之一 RNN 的弊端 RNN没有长久的记忆,比如一个句子太长时开头部分可能会忘 ...
- Factorization Machines 学习笔记(三)回归和分类
近期学习了一种叫做 Factorization Machines(简称 FM)的算法,它可对随意的实值向量进行预測.其主要长处包含: 1) 可用于高度稀疏数据场景:2) 具有线性的计算复杂度.本文 ...
- Keras官方中文文档:keras后端Backend
所属分类:Keras Keras后端 什么是"后端" Keras是一个模型级的库,提供了快速构建深度学习网络的模块.Keras并不处理如张量乘法.卷积等底层操作.这些操作依赖于某种 ...
- 02-15 Logistic回归(鸢尾花分类)
目录 Logistic回归(鸢尾花分类) 一.导入模块 二.获取数据 三.构建决策边界 四.训练模型 4.1 C参数与权重系数的关系 五.可视化 更新.更全的<机器学习>的更新网站,更有p ...
- Sklearn中的回归和分类算法
一.sklearn中自带的回归算法 1. 算法 来自:https://my.oschina.net/kilosnow/blog/1619605 另外,skilearn中自带保存模型的方法,可以把训练完 ...
- matlab-逻辑回归二分类(Logistic Regression)
逻辑回归二分类 今天尝试写了一下逻辑回归分类,把代码分享给大家,至于原理的的话请戳这里 https://blog.csdn.net/laobai1015/article/details/7811321 ...
- 《转》Logistic回归 多分类问题的推广算法--Softmax回归
转自http://ufldl.stanford.edu/wiki/index.php/Softmax%E5%9B%9E%E5%BD%92 简介 在本节中,我们介绍Softmax回归模型,该模型是log ...
- keras实现简单性别识别(二分类问题)
keras实现简单性别识别(二分类问题) 第一步:准备好需要的库 tensorflow 1.4.0 h5py 2.7.0 hdf5 1.8.15.1 Keras 2.0.8 opencv-p ...
- 基于CART的回归和分类任务
CART 是 classification and regression tree 的缩写,即分类与回归树. 博主之前学习的时候有用过决策树来做预测的小例子:机器学习之决策树预测--泰坦尼克号乘客数据 ...
随机推荐
- springboot的邮件服务
作者:纯洁的微笑出处:http://www.ityouknow.com/ 版权归作者所有,转载请注明出处 springboot仍然在狂速发展,才五个多月没有关注,现在看官网已经到1.5.3.RELEA ...
- Linux零拷贝技术,看完这篇文章就懂了
本文首发于我的公众号 Linux云计算网络(id: cloud_dev),专注于干货分享,号内有 10T 书籍和视频资源,后台回复 「1024」 即可领取,欢迎大家关注,二维码文末可以扫. 本文讲解 ...
- codeforces 322 B Ciel and Flowers
题目链接 有红绿蓝三种颜色的画,每种拿三朵可以组成一束花,或者各拿一朵组成花束,告诉你每种花的数目,求出可能组成最多的花束. 如果你的代码过不了,考虑一下 8 8 9这种组合. 因为数据量很大,我的 ...
- Ubuntu中修改默认开机项
1首先,按住Ctrl+Alt+t打开终端 2输入cd /etc/default 3输入sudo sudo nano grub 并按照提示输入密码 4在我们开机的时候,可以看到自己想要默认的开机项是多少 ...
- 设计模式:与SpringMVC底层息息相关的适配器模式
目录 前言 适配器模式 1.定义 2.UML类图 3.实战例子 4.总结 SpringMVC底层的适配器模式 参考 前言 适配器模式是最为普遍的设计模式之一,它不仅广泛应用于代码开发,在日常生活里也很 ...
- codeforces679A_Bear and Prime 100 交互题
传送门 第一道交互题 题意: 电脑事先想好了一个数[,] 你会每次问电脑一个数是否是它想的那个数的因数 电脑会告诉你yes或no 至多询问20次 最后要输出它想的数是质数还是合数 思路: 枚举< ...
- 3PHP如何用PDO的连接方式方式导出mysql数据
首先连接mysql,具体看上一篇 接下来在try{}中加入以下代码 $query="select * from 你的数据表名称" //$query的内容给个SQL ...
- Spring系列(二):Spring IoC应用
一.Spring IoC的核心概念 IoC(Inversion of Control 控制反转),详细的概念见Spring系列(一):Spring核心概念 二.Spring IoC的应用 1.定义B ...
- django报错信息解决方法
You have 17 unapplied migration(s). Your project may not work properly until you apply the migration ...
- 面试java后端面经_3
小姐姐说:你一点都不懂表达,一点都不懂爱情,一点也不爱我! 你答:你知道吗,我听说过一个这样的故事,讲的就是有一个小女孩和一个男孩在一起,小男孩呢很不幸是位聋哑人,虽然如此,但是他们的日子过得特别的美 ...