虽说闵老板不支持“调包侠”的行为,但y1s1,tensorflow作为工具使用来说,还是挺不错的。本文就基于tensorflow简单实现了一个神经网络的训练。
Tensorflow基础教学
同时在油管上也看了莫烦老师的视频,按着自己想法写了个不知道啥的神经网络,如下:
import tensorflow.compat.v1 as tf
import numpy as np
tf.disable_v2_behavior()
def add_layer(inputs, in_size, out_size, activation_function=None):
weights = tf.Variable(tf.random_normal([in_size, out_size]))
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
z = tf.matmul(tf.cast(inputs, tf.float32), weights) + biases
if activation_function is None:
outputs = z
else:
outputs = activation_function(z)
return outputs
x_data = np.random.rand(3, 5)
y_data = np.random.rand(3)
y_data = y_data[:, None]
l1_units = 4
l1 = add_layer(x_data, len(x_data[0]), l1_units, activation_function=tf.sigmoid)
l2 = add_layer(l1, l1_units, 1, activation_function=tf.sigmoid)
y=l2
loss = tf.reduce_mean(tf.reduce_sum(tf.abs(y_data-y), reduction_indices=[1]))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(loss)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for i in range(1001):
sess.run(optimizer)
if i % 50 == 0:
print(sess.run(loss))
print(sess.run(y))
print(y_data)
输出:
0.6259273
0.52464
0.17176615
0.14638905
0.14083363
0.13705803
0.13046668
0.124775015
0.11610514
0.10760417
0.098461725
0.08587402
0.073147416
0.058662564
0.046298873
0.038829297
0.034015466
0.022951135
0.016447445
0.020057917
0.017563215
[[0.659873 ]
[0.48339948]
[0.90430266]]
[[0.64303877]
[0.46659482]
[0.92335335]]
可以发现,在计算损失和实现梯度下降的时候,简单两句话就实现了,“调包侠”坐实了。
|