Tensorflow的基本运行方式--demo程序

本篇博客通过一个具体的实例,详细介绍了如何使用TensorFlow进行数据拟合,优化二次函数模型。从数据生成、模型搭建到训练过程,逐步展示了TensorFlow的基本操作流程。

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

1. Tensorflow的运行流程如下

  • 加载数据及定义超参数
  • 构建网络
  • 训练模型
  • 评估模型和进行预测

2. Tensorflow demo实现

demo如下:优化目标为:y=x2−0.5

# -*- coding: utf-8 -*-
"""
Created on Wed Apr 18 20:30:10 2018

@author: spfhy

discription: tensorflow 的运行方式示例
"""

import tensorflow as tf
import numpy as np

#1. 生成输入数据,学习方程为:y = x^2 - 0.5,构造满足这个方程的一堆x,y,同时加入噪点
x_data = np.linspace(-1,1,30)[:,np.newaxis] #300*1的二维数组作为输入

noise = np.random.normal(0,0.05,x_data.shape)

y_data = np.square(x_data) - 0.5 +noise

#定义 x,y的占位符

xs = tf.placeholder(tf.float32,[None,1])
ys = tf.placeholder(tf.float32,[None,1])

def add_layer(inputs,in_size,out_size,activation_function =None):
    #构建权重:in_size*out_size大小的矩阵
    weights = tf.Variable(tf.random_normal([in_size,out_size]))
    #构建偏置:1*out_size的矩阵
    biases = tf.Variable(tf.zeros([1,out_size])+0.1)
    #矩阵相乘
    Wx_plus_b = tf.matmul(inputs,weights)+ biases
    if activation_function is None:
        outputs = Wx_plus_b
    else:
        outputs = activation_function(Wx_plus_b)
    return outputs

#构建隐匿层,假设隐匿层有20个神经元
h1 = add_layer(xs,1,20,activation_function=tf.nn.relu)
#构建输出层,假设输出层和输入层一样,有1个神经元
prediction = add_layer(h1,20,1,activation_function=None)

#构建损失函数:计算输出层的预测值和真实值间的误差,对二者差的方求和再取平均,得到损失
#函数,运用梯度下降法,以0.1的学习速率最小化损失:

loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys -prediction),
                                    reduction_indices=[1]))
#实现梯度下降算法的优化器
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

for i in range(1000):
    sess.run(train_step,feed_dict={xs:x_data,ys:y_data})
    if i%50 == 0:
        print(sess.run(loss,feed_dict={xs:x_data,ys:y_data}))

本文时学习《TensorFlow 技术解析与实践》的学习笔记,代码摘抄自该书;

参考文献:李嘉璇《TensorFlow 技术解析与实践》

原文:https://blog.youkuaiyun.com/u010177286/article/details/79998193

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值