keras实战(一)——线性回归

导入需要的模块,Sequential为序贯模型,是keras主要的模型之一,其作用是将一系列网络层堆成栈,也就是“一条路走到黑”。

import numpy as np
np.random.seed(1337)  # for reproducibility
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt # 可视化模块

创建数据,并可视化数据。

# create some data
X = np.linspace(-1, 1, 200)
np.random.shuffle(X)    # randomize the data
Y = 0.5 * X + 2 + np.random.normal(0, 0.05, (200, ))
# plot data
plt.scatter(X, Y)
plt.show()

X_train, Y_train = X[:160], Y[:160]     # train 前 160 data points
X_test, Y_test = X[160:], Y[160:]       # test 后 40 data points

创建序贯模型,添加全连接层。

model = Sequential()
model.add(Dense(output_dim = 1,input_dim = 1))

定义损失函数及优化方式,mse为平方损失函数,sgd为随机梯度下降。

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

训练,打印损失值(model.train_on_batch()返回损失值)。

for step in range(1001):
    cost = model.train_on_batch(X_train,Y_train)
    if step % 20 == 10:
        print ('cost is',cost)
cost is 0.0263342
cost is 0.0206481
cost is 0.0163268
cost is 0.013042
cost is 0.0105447
cost is 0.00864601
cost is 0.00720236
cost is 0.00610468
cost is 0.00527003
cost is 0.00463538
cost is 0.00415281
cost is 0.00378587
cost is 0.00350685
cost is 0.00329469
cost is 0.00313337
cost is 0.0030107
cost is 0.00291743
cost is 0.0028465
cost is 0.00279257
cost is 0.00275156
cost is 0.00272038
cost is 0.00269667
cost is 0.00267864
cost is 0.00266493
cost is 0.00265451
cost is 0.00264658
cost is 0.00264055
cost is 0.00263597
cost is 0.00263249
cost is 0.00262984
cost is 0.00262782
cost is 0.00262629
cost is 0.00262513
cost is 0.00262424
cost is 0.00262357
cost is 0.00262305
cost is 0.00262266
cost is 0.00262237
cost is 0.00262214
cost is 0.00262197
cost is 0.00262184
cost is 0.00262174
cost is 0.00262167
cost is 0.00262161
cost is 0.00262157
cost is 0.00262153
cost is 0.00262151
cost is 0.00262149
cost is 0.00262147
cost is 0.00262146

得到测试集的损失值,其中model.evaluate()返回的是损失值。

cost = model.evaluate(X_test,Y_test,batch_size = 40)
40/40 [==============================] - 0s 625us/step
打印测试集的损失值
print ('test cost is ',cost)
test cost is  0.00324514508247

打印Weight和bias

W,b = model.layers[0].get_weights()
print('Weight = ',W,'bias = ',b)
Weight =  [[ 0.49106082]] bias =  [ 2.00404763]

容易观察到,Weight与bias已经非常接近5和2了。

最后,将测试集和预测函数画出。

Y_pred = model.predict(X_test)
plt.scatter(X_test, Y_test)
plt.plot(X_test, Y_pred)
plt.show()

搞定!!!第一个keras案例到此结束,如果有疑问,私信博主或者参考keras中文文档





  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值