分享好友 人工智能首页 频道列表

(二) Keras 非线性回归

keras教程  2023-02-09 19:228240

视频学习来源

https://www.bilibili.com/video/av40787141?from=search&seid=17003307842787199553

笔记


Keras 非线性回归


import keras

import numpy as np

import matplotlib.pyplot as plt

#Sequential按序列构成的模型

from keras.models import Sequential

#Dense全连接层

from keras.layers import Dense



#使用numpy生成200个随机点

x_data=np.linspace(-0.5,0.5,200)  #均匀分布

noise=np.random.normal(0,0.02,x_data.shape)  #均值为0,方差为0.02

y_data=np.square(x_data)+noise

#显示随机点

plt.scatter(x_data,y_data)

plt.show()

clip_image002

#构建一个顺序模型
model=Sequential()
#在模型中添加一个全连接层
model.add(Dense(units=1,input_dim=1))

#sgd:stochastic gradient descent 随机梯度下降算法
#mse:mean square error 均方误差
model.compile(optimizer=\'sgd\',loss=\'mse\')

#训练3000次
for step in range(3000):
    #每次训练一个批次
    cost=model.train_on_batch(x_data,y_data)
    #每500个batch打印一次cost值
    if step%500==0:
        print(\'cost:\',cost)
        
#x_data输入网络中,得到预测值y_pred
y_pred=model.predict(x_data)

#显示随机点
plt.scatter(x_data,y_data)
#显示预测结果
plt.plot(x_data,y_pred,\'r-\',lw=3)
plt.show()


cost: 0.018438313

cost: 0.006655791

cost: 0.0058503654

cost: 0.0057009794

cost: 0.0056732716

cost: 0.005668133

clip_image004



加入隐藏层


#导入SGD,(后面要修改SGD的值)
from keras.optimizers import SGD
#构建一个顺序模型
model=Sequential()
#在模型中添加  1-10-1  ,一个输入,一个输出,中间10个隐藏层
model.add(Dense(units=10,input_dim=1))   #1-10部分
model.add(Dense(units=1)) #10-1部分 等效 model.add(Dense(units=1,input_dim=10))


#增大sgd算法的学习率,默认值为0.01,
#查看函数默认值可在jupyter中shift+Tab+Tab,前提是已经导入
sgd=SGD(lr=0.3)   #学习速率0.3


#sgd:stochastic gradient descent 随机梯度下降算法
#mse:mean square error 均方误差
model.compile(optimizer=sgd,loss=\'mse\')   #和上面不同的是没有引号

#训练3000次
for step in range(3000):
    #每次训练一个批次
    cost=model.train_on_batch(x_data,y_data)
    #每500个batch打印一次cost值
    if step%500==0:
        print(\'cost:\',cost)
        
#x_data输入网络中,得到预测值y_pred
y_pred=model.predict(x_data)

#显示随机点
plt.scatter(x_data,y_data)
#显示预测结果
plt.plot(x_data,y_pred,\'r-\',lw=3)
plt.show()

cost: 0.1012776
cost: 0.005666962
cost: 0.005666963
cost: 0.0056669624
cost: 0.005666963
cost: 0.005666963

clip_image006



设置激活函数


#设置激活函数,默认的激活函数为none也就是输入=输出,线性
from keras.layers import Dense,Activation




#设置激活函数方式1
#激活函数为tanh

#构建一个顺序模型
model=Sequential()
#在模型中添加  1-10-1  ,一个输入,一个输出,中间10个隐藏层
model.add(Dense(units=10,input_dim=1))   #1-10部分

model.add(Activation(\'tanh\'))  #双曲正切函数

model.add(Dense(units=1)) #10-1部分 等效 model.add(Dense(units=1,input_dim=10))

model.add(Activation(\'tanh\'))  #双曲正切函数

#增大sgd算法的学习率,默认值为0.01,
#查看函数默认值可在jupyter中shift+Tab+Tab,前提是已经导入
sgd=SGD(lr=0.3)   #学习速率0.3

#sgd:stochastic gradient descent 随机梯度下降算法
#mse:mean square error 均方误差
model.compile(optimizer=sgd,loss=\'mse\')   #和上面不同的是没有引号

#训练3000次
for step in range(3000):
    #每次训练一个批次
    cost=model.train_on_batch(x_data,y_data)
    #每500个batch打印一次cost值
    if step%500==0:
        print(\'cost:\',cost)
        
#x_data输入网络中,得到预测值y_pred
y_pred=model.predict(x_data)

#显示随机点
plt.scatter(x_data,y_data)
#显示预测结果
plt.plot(x_data,y_pred,\'r-\',lw=3)
plt.show()

cost: 0.049393196
cost: 0.003914159
cost: 0.0011130853
cost: 0.00090270495
cost: 0.00040989672
cost: 0.00045533947

clip_image008


#设置激活函数方式2
#激活函数为relu

#jupyter中 注释为 ctrl+/ 

#构建一个顺序模型
model=Sequential()
#在模型中添加  1-10-1  ,一个输入,一个输出,中间10个隐藏层
model.add(Dense(units=10,input_dim=1,activation=\'relu\'))   #1-10部分  

model.add(Dense(units=1,activation=\'relu\'))#10-1部分 等效 model.add(Dense(units=1,input_dim=10))

#增大sgd算法的学习率,默认值为0.01,
#查看函数默认值可在jupyter中shift+Tab+Tab,前提是已经导入
sgd=SGD(lr=0.3)   #学习速率0.3

#sgd:stochastic gradient descent 随机梯度下降算法
#mse:mean square error 均方误差
model.compile(optimizer=sgd,loss=\'mse\')   #和上面不同的是没有引号

#训练3000次
for step in range(3000):
    #每次训练一个批次
    cost=model.train_on_batch(x_data,y_data)
    #每500个batch打印一次cost值
    if step%500==0:
        print(\'cost:\',cost)
        
#x_data输入网络中,得到预测值y_pred
y_pred=model.predict(x_data)

#显示随机点
plt.scatter(x_data,y_data)
#显示预测结果
plt.plot(x_data,y_pred,\'r-\',lw=3)
plt.show()

cost: 0.0066929995
cost: 0.0004892901
cost: 0.00047061846
cost: 0.00046780292
cost: 0.00046706214
cost: 0.00046700903

clip_image010



shift+Tab+Tab 效果如下

clip_image012

查看更多关于【keras教程】的文章

展开全文
相关推荐
反对 0
举报 0
图文资讯
热门推荐
优选好物
更多热点专题
更多推荐文章
Keras2.2 predict和fit_generator的区别
查看keras文档中,predict函数原型:predict(self, x, batch_size=32, verbose=0)说明:只使用batch_size=32,也就是说每次将batch_size=32的数据通过PCI总线传到GPU,然后进行预测。在一些问题中,batch_size=32明显是非常小的。而通过PCI传数据是非常耗时的

0评论2023-02-09861

keras模块学习之-激活函数(activations)--笔记
本笔记由博客园-圆柱模板 博主整理笔记发布,转载需注明,谢谢合作!   每一个神经网络层都需要一个激活函数,例如一下样例代码:           from keras.layers.core import Activation, Densemodel.add(Dense(64))model.add(Activation('tanh'))或把

0评论2023-02-09550

keras: 在构建LSTM模型时,使用变长序列的方法
众所周知,LSTM的一大优势就是其能够处理变长序列。而在使用keras搭建模型时,如果直接使用LSTM层作为网络输入的第一层,需要指定输入的大小。如果需要使用变长序列,那么,只需要在LSTM层前加一个Masking层,或者embedding层即可。from keras.layers import

0评论2023-02-09679

keras channels_last、preprocess_input、全连接层Dense、SGD优化器、模型及编译
channels_last 和 channels_firstkeras中 channels_last 和 channels_first 用来设定数据的维度顺序(image_data_format)。对2D数据来说,"channels_last"假定维度顺序为 (rows,cols,channels), 而"channels_first"假定维度顺序为(channels, rows, cols)。

0评论2023-02-091012

将keras的h5模型转换为tensorflow的pb模型 keras 调用h5模型
h5_to_pb.pyfrom keras.models import load_modelimport tensorflow as tfimport os import os.path as ospfrom keras import backend as K#路径参数input_path = 'input path'weight_file = 'weight.h5'weight_file_path = osp.join(input_path,weight_file

0评论2023-02-09773

Keras MAE和MSE source code
def mean_squared_error(y_true, y_pred):if not K.is_tensor(y_pred):y_pred = K.constant(y_pred)y_true = K.cast(y_true, y_pred.dtype)return K.mean(K.square(y_pred - y_true), axis=-1)def mean_absolute_error(y_true, y_pred):if not K.is_tensor(y_

0评论2023-02-09801

Keras网络层之“关于Keras的层(Layer)” keras的embedding层
关于Keras的“层”(Layer)所有的Keras层对象都有如下方法:layer.get_weights():返回层的权重(numpy array)layer.set_weights(weights):从numpy array中将权重加载到该层中,要求numpy array的形状与layer.get_weights()的形状相同layer.get_config():返回

0评论2023-02-09888

Keras分类问题 keras 分类模型
#-*- coding: utf-8 -*-#使用神经网络算法预测销量高低import pandas as pd#参数初始化inputfile = 'data/sales_data.xls'data = pd.read_excel(inputfile, index_col = u'序号') #导入数据#数据是类别标签,要将它转换为数据#用1来表示“好”、“是”、“高

0评论2023-02-09923

tf.keras遇见的坑:Output tensors to a Model must be the output of a TensorFlow `Layer`
经过网上查找,找到了问题所在:在使用keras编程模式是,中间插入了tf.reshape()方法便遇到此问题。 解决办法:对于遇到相同问题的任何人,可以使用keras的Lambda层来包装张量流操作,这是我所做的:embed1 = keras.layers.Embedding(10000, 32)(inputs) # e

0评论2023-02-09963

更多推荐