【Tensorflow】Python实现神经网络回归

本文通过使用TensorFlow构建了一个简单的神经网络模型来预测交通事故导致的直接财产损失。该模型基于过去四年中事故起数、死亡人数及受伤人数等数据进行训练。

环境

macOS,python3.6,tensorflow1.1.0

回归问题

年份事故起数死亡人数受伤人数直接财产损失(万元)
20038035011
20049087012.5
20051802012020
2006140169018
200712058015

说明:利用前四年的数据建立回归模型,并对第五年进行预测。

实现代码

import numpy as np
import tensorflow as tf

x = [[80,3,50],[90,8,70],[180,20,120],[140,16,90]]
y = [[11],[12.5],[20],[18]]
# y = [11,12.5,20,18]
x_pred = [[120,5,85]]

tf_x = tf.placeholder(tf.float32, [None,3])     # input x
tf_y = tf.placeholder(tf.float32, [None,1])     # input y

# neural network layers
l1 = tf.layers.dense(tf_x, 20, tf.nn.relu)          # hidden layer
output = tf.layers.dense(l1, 1)                     # output layer

loss = tf.losses.mean_squared_error(tf_y, output)   # compute cost
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1)
train_op = optimizer.minimize(loss)

sess = tf.Session()                                 # control training and others
sess.run(tf.global_variables_initializer())         # initialize var in graph


for step in range(150):
    # train and net output
    _, l, pred = sess.run([train_op, loss, output], {tf_x: x, tf_y: y})
    if step % 10 == 0:
        print('loss is: ' + str(l))
        # print('prediction is:' + str(pred))

output_pred = sess.run(output,{tf_x:x_pred})
print('input is:' + str(x_pred[0][:]))
print('output is:' + str(output_pred[0][0]))

运行结果

这里写图片描述

评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值