用Keras搭建神经网络 简单模版(一)——Regressor 回归

本文详细介绍如何使用Keras和TensorFlow构建并训练一个简单的神经网络模型,通过预测线性关系的数据集,演示了从数据准备、模型搭建、训练到测试的完整流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先需要下载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)

​

输出结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蔡军帅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值