首先需要下载Keras,可以看到我用的是TensorFlow 的backend

自己构建虚拟数据,x是-1到1之间的数,y为0.5*x+2,可视化出来

# -*- coding: utf-8 -*-
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 #creat some data
X = np.linspace(-1,1,200) #200个x,-1到1之间
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]#160个
X_test,Y_test = X[160:], Y[160:]#40个

 

接下来搭建1层神经网络

#build a neural network from the 1st layer to the the last layer
model = Sequential()
model.add(Dense(output_dim=1,input_dim=1))#加一层 #choose loss function and optimizing method
#mse方差
model.compile(loss='mse',optimizer='sgd')

最后,训练测试,输出结果

#training
print("Training~~~~~~~~")
for step in range(301):
cost = model.train_on_batch(X_train,Y_train)#一批一批的数据,这里一批选择全部数据
if step %100==0:
print('train cost:',cost) #test
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) #plotting the prediction
Y_pred =model.predict(X_test)
plt.scatter(X_test,Y_test)
plt.plot(X_test,Y_pred)

输出结果

 

最新文章

  1. 2015 Autodesk 开发者日( DevDays)和 助力开发周火热报名中
  2. 前端小知识(转载http://www.cnblogs.com/Wayou/p/things_you_dont_know_about_frontend.html)
  3. 一维Poisson方程计算
  4. C# WinForm 单例模式(例:同一个窗体只创建一次实例)
  5. [Python爬虫] scrapy爬虫系列 <一>.安装及入门介绍
  6. 远程连接Windows2008R2时服务器报Terminal Services错误的解决办法
  7. Android SurfaceView实现静态于动态画图效果
  8. Windows phone 8 学习笔记(6) 多任务
  9. scala Weak Conformance
  10. 简单实用而不追求时髦的 Vim 配置
  11. 记录:C++类内存分布(虚继承与虚函数)
  12. Zabbix appliance One Stop
  13. 第一篇:你不一定了解的"推荐系统"
  14. 前端页面调用Spring boot接口发生的跨域问题
  15. SFTP编辑linux文件 ——mac sublime text2 sftp
  16. Python 读取文件中unicode编码转成中文显示问题
  17. 自己使用过比较好用的VSCode插件
  18. emacs之配置7,tabbar插件
  19. 改bug后 fix bug 时,一个不错的修复描述模板
  20. C++解析(1):C到C++的升级

热门文章

  1. 使用Setup安装Windows8 RTM方法
  2. L228 the complicated issue of equality: non-disabled actors play disabled roles
  3. 2019.1.11 EDVT
  4. juery 安全加固 集合
  5. CodeForces - 325E:The Red Button (哈密尔顿 转 欧拉回路)
  6. zookeeper 官方文档——综述
  7. Omar Loves Candies
  8. ubuntu 安装php 报错解决
  9. day33 python学习 多线程
  10. docker 方式运行drill