TensorFlow入门教程系列(二):用神经网络拟合二次函数
通过TensorFlow用神经网络实现对二次函数的拟合。代码来自莫烦TensorFlow教程。
1 import tensorflow as tf 2 import numpy as np 3 4 def add_layer(inputs, in_size, out_size, activation_function=None): 5 Weights = tf.Variable(tf.random_normal([in_size, out_size])) 6 biases = tf.Variable(tf.zeros([1, out_size]) + 0.1) 7 Wx_plus_b = tf.matmul(inputs, Weights) + biases 8 if activation_function is None: 9 outputs = Wx_plus_b 10 else: 11 outputs = activation_function(Wx_plus_b) 12 return outputs 13 14 # Make up some real data 15 x_data = np.linspace(-1, 1, 300, dtype=np.float32)[:, np.newaxis] # np.newaxis的作用就是在它所在的位置增加一个一维 16 noise = np.random.normal(0, 0.05, x_data.shape).astype(np.float32) 17 y_data = np.square(x_data) - 0.5 + noise 18 19 # define placeholder for inputs to network 20 xs = tf.placeholder(tf.float32, [None, 1]) 21 ys = tf.placeholder(tf.float32, [None, 1]) 22 # add hidden layer 23 l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu) 24 # add output layer 25 prediction = add_layer(l1, 10, 1, activation_function=None) 26 27 # the error between prediction and real data 28 loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction), reduction_indices=[1])) 29 train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss) 30 # important step 31 sess = tf.Session() 32 init = tf.global_variables_initializer() 33 sess.run(init) 34 35 for i in range(500): 36 # training 37 sess.run(train_step, feed_dict={xs: x_data, ys: y_data}) 38 if i % 50 == 0: 39 # to see the step improvement 40 print(sess.run(loss, feed_dict={xs: x_data, ys: y_data}))
运行结果:
0.3695223 0.03633204 0.07279602 0.008672798 0.0063357423 0.0055126143 0.004952927 0.0045463713 0.0041970443 0.0038996863
分类:
TensorFlow
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通