用Keras搭建神经网络 简单模版(一)——Regressor 回归
2024-10-19 17:47:04
首先需要下载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)
输出结果
最新文章
- 2015 Autodesk 开发者日( DevDays)和 助力开发周火热报名中
- 前端小知识(转载http://www.cnblogs.com/Wayou/p/things_you_dont_know_about_frontend.html)
- 一维Poisson方程计算
- C# WinForm 单例模式(例:同一个窗体只创建一次实例)
- [Python爬虫] scrapy爬虫系列 <;一>;.安装及入门介绍
- 远程连接Windows2008R2时服务器报Terminal Services错误的解决办法
- Android SurfaceView实现静态于动态画图效果
- Windows phone 8 学习笔记(6) 多任务
- scala Weak Conformance
- 简单实用而不追求时髦的 Vim 配置
- 记录:C++类内存分布(虚继承与虚函数)
- Zabbix appliance One Stop
- 第一篇:你不一定了解的";推荐系统";
- 前端页面调用Spring boot接口发生的跨域问题
- SFTP编辑linux文件 ——mac sublime text2 sftp
- Python 读取文件中unicode编码转成中文显示问题
- 自己使用过比较好用的VSCode插件
- emacs之配置7,tabbar插件
- 改bug后 fix bug 时,一个不错的修复描述模板
- C++解析(1):C到C++的升级
热门文章
- 使用Setup安装Windows8 RTM方法
- L228 the complicated issue of equality: non-disabled actors play disabled roles
- 2019.1.11 EDVT
- juery 安全加固 集合
- CodeForces - 325E:The Red Button (哈密尔顿 转 欧拉回路)
- zookeeper 官方文档——综述
- Omar Loves Candies
- ubuntu 安装php 报错解决
- day33 python学习 多线程
- docker 方式运行drill