Tensorflow:Android调用Tensorflow Mobile版本API(1)-训练一个网络

在这里,我们训练一个网络来拟合 y=x^2+1
代码如下:

# y = x^2 + 1

import tensorflow as tf
import numpy as np
import random

def get_batch(size=128):
    xs = []
    ys = []
    for i in range(size):
        x = random.random() * 2
        y = x * x + 1
        xs.append(x)
        ys.append(y)
    return np.array(xs), np.array(ys)




X = tf.placeholder(tf.float32, [None,1], name='input')
Y = tf.placeholder(tf.float32, [None,1])
def my_dnn():
    x = tf.reshape(X, shape=[-1, 1])
    w1 = tf.Variable(tf.random_normal(shape=[1,256], mean=0.0,
                                      stddev=1))
    b1 = tf.Variable(tf.random_normal([256]))
    out1 = tf.nn.bias_add(tf.matmul(x,w1),b1)
    out1 = tf.nn.relu(out1)
    w2= tf.Variable(tf.random_normal(shape=[256,256]))
    b2 = tf.Variable(tf.random_normal([256]))
    out2= tf.nn.bias_add(tf.matmul(out1, w2),b2)
    out2 = tf.nn.relu(out2)
    w3 = tf.Variable(tf.random_normal(shape=[256, 256]))
    b3 = tf.Variable(tf.random_normal([256]))
    out3 = tf.nn.bias_add(tf.matmul(out2, w3),b3)
    out3 = tf.nn.relu(out3)
    w4 = tf.Variable(tf.random_normal(shape=[256, 1]))
    b4 = tf.Variable(tf.random_normal([1]))
    out4 = tf.nn.bias_add(tf.matmul(out3, w4), b4, name='output')


    return out4
def train():
    out = my_dnn()
    loss = tf.reduce_mean(tf.square(Y - out))
    optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)

    saver = tf.train.Saver()
    with tf.Session() as sess:
        sess.run(tf.initialize_all_variables())
        step = 0
        while True:
            batch_x, batch_y = get_batch(64)
            batch_x = batch_x.reshape([-1, 1])
            batch_y = batch_y.reshape([-1, 1])
            _, loss_ = sess.run([optimizer, loss], feed_dict={X:batch_x, Y:batch_y})
            print(loss_)
            if loss_ < 0.0001:
                saver.save(sess, "./1.model", global_step=step)
                break
            step += 1


# train()

def eval():
    out = my_dnn()
    saver = tf.train.Saver()
    with tf.Session() as sess:
        saver.restore(sess, tf.train.latest_checkpoint('.'))
        for i in range(100):
            x = random.random() * 2
            x = np.array([x]).reshape([-1,1])
            y = sess.run(out, feed_dict={X:x})
            print("x=%.5f 正确的y=%.5f 预测的 y=%.5f" % (x, x*x + 1, y))


if __name__ == '__main__':
    # 训练
    # train()

    # 评估
    # eval()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值