当前位置:   article > 正文

使用torch以及tensorflow训练一个最简单网络的基本步骤_torch tensorflow

torch tensorflow

torch: 

  1. import torch
  2. import torch.nn.functional as F
  3. import matplotlib.pyplot as plt
  4. x = torch.Tensor.unsqueeze(torch.Tensor.linspace(-1, 1, 100), dim=1) # x data (tensor), shape=(100, 1)
  5. y = x.pow(2) + 0.2 * torch.rand()
  6. class Net(torch.nn.Module):
  7. def __init__(self, n_feature, n_hidden, n_output):
  8. super(Net, self).__init__() #继承init
  9. #定义每层的形式
  10. self.hidden = torch.nn.Linear(n_feature, n_hidden)
  11. self.predict = torch.nn.Linear(n_hidden, n_output)
  12. def forward(self, x):
  13. #正向传播输入值,神经网络分析出输出值
  14. x = F.relu(self.hidden(x)) #激励函数(隐藏层的线性值)
  15. x = self.predict(x) #输出值
  16. return x
  17. net = Net(n_feature=1, n_hidden=10, n_output=1)
  18. print(net)
  19. optimizer = torch.optim.SGD(net.parameters(), lr=0.2) #传入net的所有参数,学习率
  20. loss_func = torch.nn.MSELoss() #预测值和真实值的误差计算公式(均方差)
  21. for t in range(100):
  22. prediction = net(x)
  23. loss = loss_func(prediction, y)

 

 

tensorflow:

  1. #--coding:utf-8--
  2. import tensorflow as tf
  3. from numpy.random import RandomState
  4. batch_size = 8
  5. #定义神经网络参数
  6. w1 = tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1))
  7. w2 = tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1))
  8. x = tf.placeholder(tf.float32, shape=(None, 2), name='x-input')
  9. y_ = tf.placeholder(tf.float32, shape=(None, 1), name='y-input')
  10. #前向传播过程
  11. a = tf.matmul(x, w1)
  12. y = tf.matmul(a, w2)
  13. #定义损失函数和反向传播算法
  14. y = tf.sigmoid(y)
  15. cross_entropy = -tf.reduce_mean(
  16. y_ * tf.log(tf.clip_by_value(y, 1e-10, 1.0)) + (1 - y) * tf.log(tf.clip_by_value(1 - y, 1e-10, 1.0))
  17. )
  18. train_step = tf.train.AdamOptimizer(0.001).minimize(cross_entropy)
  19. rdm = RandomState(1)
  20. dataset_size = 128
  21. X = rdm.rand(dataset_size, 2)
  22. Y = [[int(x1 + x2 < 1)] for (x1, x2) in X]
  23. with tf.Session() as sess:
  24. init_op = tf.global_variables_initializer()
  25. sess.run(init_op)
  26. print(sess.run(w1))
  27. print(sess.run(w2))
  28. #开始训练
  29. STEPS = 5000
  30. for i in range(STEPS):
  31. start = (i * batch_size) % dataset_size
  32. end = min(start + batch_size, dataset_size)
  33. sess.run(train_step,
  34. feed_dict={x: X[start:end], y_: Y[start:end]})
  35. if i % 1000 == 0:
  36. total_cross_entropy = sess.run(
  37. cross_entropy, feed_dict={x: X, y_: Y})
  38. print("After %d training steps, cross entropy on all data is %g" % (i, total_cross_entropy))
  39. print(sess.run(w1))
  40. print(sess.run(w2))

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/729912
推荐阅读
相关标签
  

闽ICP备14008679号