python 下运行的tensor资料

[复制链接]
 楼主| 一路向北lm 发表于 2018-9-29 22:25 | 显示全部楼层 |阅读模式
  1. #两个张量相加
  2. #Tensor("add:0", shape=(2,), dtype=float32)

  3. #coding:utf-8
  4. import tensorflow as tf
  5. a=tf.constant([1.0,2.0])
  6. b=tf.constant([3.0,4.0])
  7. result=a+b
  8. print (result)


 楼主| 一路向北lm 发表于 2018-9-29 22:26 | 显示全部楼层
  1. 两个张量相乘
  2. import tensorflow as tf
  3. x = tf.constant([[1.0, 2.0]])
  4. w = tf.constant([[3.0], [4.0]])
  5. y=tf.matmul(x,w)
  6. print (y)
  7. with tf.Session() as sess:
  8.     print (sess.run(y))


 楼主| 一路向北lm 发表于 2018-9-29 22:26 | 显示全部楼层
  1. #coding:utf-8
  2. #两层简单神经网络(全连接)
  3. import tensorflow as tf

  4. #定义输入和参数
  5. x = tf.constant([[0.7, 0.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. #定义前向传播过程
  9. a = tf.matmul(x, w1)
  10. y = tf.matmul(a, w2)

  11. #用会话计算结果
  12. with tf.Session() as sess:
  13.     init_op = tf.global_variables_initializer()
  14.     sess.run(init_op)
  15.     print ("y in tf3_3.py is:\n",sess.run(y))

  16. '''
  17. y in tf3_3.py is :
  18. [[3.0904665]]
  19. '''


 楼主| 一路向北lm 发表于 2018-9-29 22:28 | 显示全部楼层
  1. #coding:utf-8
  2. #两层简单神经网络(全连接)

  3. import tensorflow as tf

  4. #定义输入和参数
  5. #用placeholder实现输入定义 (sess.run中喂一组数据)
  6. x = tf.placeholder(tf.float32, shape=(1, 2))
  7. w1= tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1))
  8. w2= tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1))


  9. #定义前向传播过程
  10. a = tf.matmul(x, w1)
  11. y = tf.matmul(a, w2)


  12. #用会话计算结果
  13. with tf.Session() as sess:
  14.     init_op = tf.global_variables_initializer()
  15.     sess.run(init_op)
  16.     print ("y in tf3_4.py is:\n",sess.run(y, feed_dict={x: [[0.7,0.5]]}))

  17. '''
  18. y in tf3_4.py is:
  19. [[3.0904665]]
  20. '''


 楼主| 一路向北lm 发表于 2018-9-29 22:29 | 显示全部楼层
  1. #coding:utf-8
  2. #两层简单神经网络(全连接)

  3. import tensorflow as tf

  4. #定义输入和参数
  5. #用placeholder定义输入(sess.run喂多组数据)
  6. x = tf.placeholder(tf.float32, shape=(None, 2))
  7. w1= tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1))
  8. w2= tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1))

  9. #定义前向传播过程
  10. a = tf.matmul(x, w1)
  11. y = tf.matmul(a, w2)

  12. #调用会话计算结果
  13. with tf.Session() as sess:
  14.     init_op = tf.global_variables_initializer()  
  15.     sess.run(init_op)
  16.     print( "the result of tf3_5.py is:\n",sess.run(y, feed_dict={x: [[0.7,0.5],[0.2,0.3],[0.3,0.4],[0.4,0.5]]}))
  17.     print ("w1:\n", sess.run(w1))
  18.     print ("w2:\n", sess.run(w2))

  19. '''
  20. the result of tf3_5.py is:
  21. [[ 3.0904665 ]
  22. [ 1.2236414 ]
  23. [ 1.72707319]
  24. [ 2.23050475]]
  25. w1:
  26. [[-0.81131822  1.48459876  0.06532937]
  27. [-2.4427042   0.0992484   0.59122431]]
  28. w2:
  29. [[-0.81131822]
  30. [ 1.48459876]
  31. [ 0.06532937]]

  32. '''



gaoyang9992006 发表于 2018-9-30 14:21 | 显示全部楼层
ensor是tensorflow基础的一个概念——张量。
Tensorflow用到了数据流图,数据流图包括数据(Data)、流(Flow)、图(Graph)。Tensorflow里的数据用到的都是tensor,所以谷歌起名为tensorflow。
 楼主| 一路向北lm 发表于 2018-9-30 15:12 | 显示全部楼层
gaoyang9992006 发表于 2018-9-30 14:21
ensor是tensorflow基础的一个概念——张量。
Tensorflow用到了数据流图,数据流图包括数据(Data)、流(F ...

是的,你也在学吗?
 楼主| 一路向北lm 发表于 2018-9-30 15:18 | 显示全部楼层
  1. #coding:utf-8
  2. #预测多或预测少的影响一样
  3. #0导入模块,生成数据集
  4. import tensorflow as tf
  5. import numpy as np
  6. BATCH_SIZE = 8
  7. SEED = 23455

  8. rdm = np.random.RandomState(SEED)
  9. X = rdm.rand(32,2)
  10. Y_ = [[x1+x2+(rdm.rand()/10.0-0.05)] for (x1, x2) in X]

  11. #1定义神经网络的输入、参数和输出,定义前向传播过程。
  12. x = tf.placeholder(tf.float32, shape=(None, 2))
  13. y_ = tf.placeholder(tf.float32, shape=(None, 1))
  14. w1= tf.Variable(tf.random_normal([2, 1], stddev=1, seed=1))
  15. y = tf.matmul(x, w1)

  16. #2定义损失函数及反向传播方法。
  17. #定义损失函数为MSE,反向传播方法为梯度下降。
  18. loss_mse = tf.reduce_mean(tf.square(y_ - y))
  19. train_step = tf.train.GradientDescentOptimizer(0.001).minimize(loss_mse)

  20. #3生成会话,训练STEPS轮
  21. with tf.Session() as sess:
  22.     init_op = tf.global_variables_initializer()
  23.     sess.run(init_op)
  24.     STEPS = 20000
  25.     for i in range(STEPS):
  26.         start = (i*BATCH_SIZE) % 32
  27.         end = (i*BATCH_SIZE) % 32 + BATCH_SIZE
  28.         sess.run(train_step, feed_dict={x: X[start:end], y_: Y_[start:end]})
  29.         if i % 500 == 0:
  30.             print ("After %d training steps, w1 is: " % (i))
  31.             print (sess.run(w1), "\n")
  32.     print ("Final w1 is: \n", sess.run(w1))



 楼主| 一路向北lm 发表于 2018-9-30 15:19 | 显示全部楼层
  1. #coding:utf-8
  2. #酸奶成本1元, 酸奶利润9元
  3. #预测少了损失大,故不要预测少,故生成的模型会多预测一些
  4. #0导入模块,生成数据集
  5. import tensorflow as tf
  6. import numpy as np
  7. BATCH_SIZE = 8
  8. SEED = 23455
  9. COST = 1
  10. PROFIT = 9

  11. rdm = np.random.RandomState(SEED)
  12. X = rdm.rand(32,2)
  13. Y = [[x1+x2+(rdm.rand()/10.0-0.05)] for (x1, x2) in X]

  14. #1定义神经网络的输入、参数和输出,定义前向传播过程。
  15. x = tf.placeholder(tf.float32, shape=(None, 2))
  16. y_ = tf.placeholder(tf.float32, shape=(None, 1))
  17. w1= tf.Variable(tf.random_normal([2, 1], stddev=1, seed=1))
  18. y = tf.matmul(x, w1)

  19. #2定义损失函数及反向传播方法。
  20. # 定义损失函数使得预测少了的损失大,于是模型应该偏向多的方向预测。
  21. loss = tf.reduce_sum(tf.where(tf.greater(y, y_), (y - y_)*COST, (y_ - y)*PROFIT))
  22. train_step = tf.train.GradientDescentOptimizer(0.001).minimize(loss)

  23. #3生成会话,训练STEPS轮。
  24. with tf.Session() as sess:
  25.     init_op = tf.global_variables_initializer()
  26.     sess.run(init_op)
  27.     STEPS = 3000
  28.     for i in range(STEPS):
  29.         start = (i*BATCH_SIZE) % 32
  30.         end = (i*BATCH_SIZE) % 32 + BATCH_SIZE
  31.         sess.run(train_step, feed_dict={x: X[start:end], y_: Y[start:end]})
  32.         if i % 500 == 0:
  33.             print ("After %d training steps, w1 is: " % (i))
  34.             print (sess.run(w1), "\n")
  35.     print ("Final w1 is: \n", sess.run(w1))


 楼主| 一路向北lm 发表于 2018-9-30 15:22 | 显示全部楼层
  1. #coding:utf-8
  2. #酸奶成本9元, 酸奶利润1元
  3. #预测多了损失大,故不要预测多,故生成的模型会少预测一些
  4. #0导入模块,生成数据集
  5. import tensorflow as tf
  6. import numpy as np
  7. BATCH_SIZE = 8
  8. SEED = 23455
  9. COST = 9
  10. PROFIT = 1

  11. rdm = np.random.RandomState(SEED)
  12. X = rdm.rand(32,2)
  13. Y = [[x1+x2+(rdm.rand()/10.0-0.05)] for (x1, x2) in X]

  14. #1定义神经网络的输入、参数和输出,定义前向传播过程。
  15. x = tf.placeholder(tf.float32, shape=(None, 2))
  16. y_ = tf.placeholder(tf.float32, shape=(None, 1))
  17. w1= tf.Variable(tf.random_normal([2, 1], stddev=1, seed=1))
  18. y = tf.matmul(x, w1)

  19. #2定义损失函数及反向传播方法。
  20. #重新定义损失函数,使得预测多了的损失大,于是模型应该偏向少的方向预测。
  21. loss = tf.reduce_sum(tf.where(tf.greater(y, y_), (y - y_)*COST, (y_ - y)*PROFIT))
  22. train_step = tf.train.GradientDescentOptimizer(0.001).minimize(loss)

  23. #3生成会话,训练STEPS轮。
  24. with tf.Session() as sess:
  25.     init_op = tf.global_variables_initializer()
  26.     sess.run(init_op)
  27.     STEPS = 3000
  28.     for i in range(STEPS):
  29.         start = (i*BATCH_SIZE) % 32
  30.         end = (i*BATCH_SIZE) % 32 + BATCH_SIZE
  31.         sess.run(train_step, feed_dict={x: X[start:end], y_: Y[start:end]})
  32.         if i % 500 == 0:
  33.             print ("After %d training steps, w1 is: " % (i))
  34.             print (sess.run(w1), "\n")
  35.     print ("Final w1 is: \n", sess.run(w1))


 楼主| 一路向北lm 发表于 2018-9-30 15:23 | 显示全部楼层
  1. #coding:utf-8
  2. #设损失函数 loss=(w+1)^2, 令w初值是常数5。反向传播就是求最优w,即求最小loss对应的w值
  3. import tensorflow as tf
  4. #定义待优化参数w初值赋5
  5. w = tf.Variable(tf.constant(5, dtype=tf.float32))
  6. #定义损失函数loss
  7. loss = tf.square(w+1)
  8. #定义反向传播方法
  9. train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)
  10. #生成会话,训练40轮
  11. with tf.Session() as sess:
  12.     init_op=tf.global_variables_initializer()
  13.     sess.run(init_op)
  14.     for i in range(40):
  15.         sess.run(train_step)
  16.         w_val = sess.run(w)
  17.         loss_val = sess.run(loss)
  18.         print ("After %s steps: w is %f,   loss is %f." % (i, w_val,loss_val))





 楼主| 一路向北lm 发表于 2018-9-30 17:52 | 显示全部楼层
  1. #coding:utf-8
  2. #设损失函数 loss=(w+1)^2, 令w初值是常数10。反向传播就是求最优w,即求最小loss对应的w值
  3. #使用指数衰减的学习率,在迭代初期得到较高的下降速度,可以在较小的训练轮数下取得更有收敛度。
  4. import tensorflow as tf

  5. LEARNING_RATE_BASE = 0.1 #最初学习率
  6. LEARNING_RATE_DECAY = 0.99 #学习率衰减率
  7. LEARNING_RATE_STEP = 1  #喂入多少轮BATCH_SIZE后,更新一次学习率,一般设为:总样本数/BATCH_SIZE

  8. #运行了几轮BATCH_SIZE的计数器,初值给0, 设为不被训练
  9. global_step = tf.Variable(0, trainable=False)
  10. #定义指数下降学习率
  11. learning_rate = tf.train.exponential_decay(LEARNING_RATE_BASE, global_step, LEARNING_RATE_STEP, LEARNING_RATE_DECAY, staircase=True)
  12. #定义待优化参数,初值给10
  13. w = tf.Variable(tf.constant(5, dtype=tf.float32))
  14. #定义损失函数loss
  15. loss = tf.square(w+1)
  16. #定义反向传播方法
  17. train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)
  18. #生成会话,训练40轮
  19. with tf.Session() as sess:
  20.     init_op=tf.global_variables_initializer()
  21.     sess.run(init_op)
  22.     for i in range(40):
  23.         sess.run(train_step)
  24.         learning_rate_val = sess.run(learning_rate)
  25.         global_step_val = sess.run(global_step)
  26.         w_val = sess.run(w)
  27.         loss_val = sess.run(loss)
  28.         print ("After %s steps: global_step is %f, w is %f, learning rate is %f, loss is %f" % (i, global_step_val, w_val, learning_rate_val, loss_val))


 楼主| 一路向北lm 发表于 2018-9-30 17:52 | 显示全部楼层
  1. #coding:utf-8
  2. import tensorflow as tf

  3. #1. 定义变量及滑动平均类
  4. #定义一个32位浮点变量,初始值为0.0  这个代码就是不断更新w1参数,优化w1参数,滑动平均做了个w1的影子
  5. w1 = tf.Variable(0, dtype=tf.float32)
  6. #定义num_updates(NN的迭代轮数),初始值为0,不可被优化(训练),这个参数不训练
  7. global_step = tf.Variable(0, trainable=False)
  8. #实例化滑动平均类,给衰减率为0.99,当前轮数global_step
  9. MOVING_AVERAGE_DECAY = 0.99
  10. ema = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)
  11. #ema.apply后的括号里是更新列表,每次运行sess.run(ema_op)时,对更新列表中的元素求滑动平均值。
  12. #在实际应用中会使用tf.trainable_variables()自动将所有待训练的参数汇总为列表
  13. #ema_op = ema.apply([w1])
  14. ema_op = ema.apply(tf.trainable_variables())

  15. #2. 查看不同迭代中变量取值的变化。
  16. with tf.Session() as sess:
  17.     # 初始化
  18.     init_op = tf.global_variables_initializer()
  19.     sess.run(init_op)
  20.         #用ema.average(w1)获取w1滑动平均值 (要运行多个节点,作为列表中的元素列出,写在sess.run中)
  21.         #打印出当前参数w1和w1滑动平均值
  22.     print ("current global_step:", sess.run(global_step))
  23.     print ("current w1", sess.run([w1, ema.average(w1)]))
  24.    
  25.     # 参数w1的值赋为1
  26.     sess.run(tf.assign(w1, 1))
  27.     sess.run(ema_op)
  28.     print ("current global_step:", sess.run(global_step))
  29.     print ("current w1", sess.run([w1, ema.average(w1)]))
  30.    
  31.     # 更新global_step和w1的值,模拟出轮数为100时,参数w1变为10, 以下代码global_step保持为100,每次执行滑动平均操作,影子值会更新
  32.     sess.run(tf.assign(global_step, 100))  
  33.     sess.run(tf.assign(w1, 10))
  34.     sess.run(ema_op)
  35.     print ("current global_step:", sess.run(global_step))
  36.     print ("current w1:", sess.run([w1, ema.average(w1)]))      
  37.    
  38.     # 每次sess.run会更新一次w1的滑动平均值
  39.     sess.run(ema_op)
  40.     print ("current global_step:" , sess.run(global_step))
  41.     print ("current w1:", sess.run([w1, ema.average(w1)]))

  42.     sess.run(ema_op)
  43.     print ("current global_step:" , sess.run(global_step))
  44.     print ("current w1:", sess.run([w1, ema.average(w1)]))

  45.     sess.run(ema_op)
  46.     print ("current global_step:" , sess.run(global_step))
  47.     print ("current w1:", sess.run([w1, ema.average(w1)]))

  48.     sess.run(ema_op)
  49.     print ("current global_step:" , sess.run(global_step))
  50.     print ("current w1:", sess.run([w1, ema.average(w1)]))

  51.     sess.run(ema_op)
  52.     print ("current global_step:" , sess.run(global_step))
  53.     print ("current w1:", sess.run([w1, ema.average(w1)]))

  54.     sess.run(ema_op)
  55.     print ("current global_step:" , sess.run(global_step))
  56.     print ("current w1:", sess.run([w1, ema.average(w1)]))

  57. #更改MOVING_AVERAGE_DECAY 为 0.1  看影子追随速度

  58. """

  59. current global_step: 0
  60. current w1 [0.0, 0.0]
  61. current global_step: 0
  62. current w1 [1.0, 0.9]
  63. current global_step: 100
  64. current w1: [10.0, 1.6445453]
  65. current global_step: 100
  66. current w1: [10.0, 2.3281732]
  67. current global_step: 100
  68. current w1: [10.0, 2.955868]
  69. current global_step: 100
  70. current w1: [10.0, 3.532206]
  71. current global_step: 100
  72. current w1: [10.0, 4.061389]
  73. current global_step: 100
  74. current w1: [10.0, 4.547275]
  75. current global_step: 100
  76. current w1: [10.0, 4.9934072]

  77. """


 楼主| 一路向北lm 发表于 2018-9-30 17:53 | 显示全部楼层
  1. #coding:utf-8
  2. #0导入模块 ,生成模拟数据集
  3. import tensorflow as tf
  4. import numpy as np
  5. import matplotlib.pyplot as plt
  6. BATCH_SIZE = 30
  7. seed = 2
  8. #基于seed产生随机数
  9. rdm = np.random.RandomState(seed)
  10. #随机数返回300行2列的矩阵,表示300组坐标点(x0,x1)作为输入数据集
  11. X = rdm.randn(300,2)
  12. #从X这个300行2列的矩阵中取出一行,判断如果两个坐标的平方和小于2,给Y赋值1,其余赋值0
  13. #作为输入数据集的标签(正确答案)
  14. Y_ = [int(x0*x0 + x1*x1 <2) for (x0,x1) in X]
  15. #遍历Y中的每个元素,1赋值'red'其余赋值'blue',这样可视化显示时人可以直观区分
  16. Y_c = [['red' if y else 'blue'] for y in Y_]
  17. #对数据集X和标签Y进行shape整理,第一个元素为-1表示,随第二个参数计算得到,第二个元素表示多少列,把X整理为n行2列,把Y整理为n行1列
  18. X = np.vstack(X).reshape(-1,2)
  19. Y_ = np.vstack(Y_).reshape(-1,1)
  20. print (X)
  21. print (Y_)
  22. print (Y_c)
  23. #用plt.scatter画出数据集X各行中第0列元素和第1列元素的点即各行的(x0,x1),用各行Y_c对应的值表示颜色(c是color的缩写)
  24. plt.scatter(X[:,0], X[:,1], c=np.squeeze(Y_c))
  25. plt.show()


  26. #定义神经网络的输入、参数和输出,定义前向传播过程
  27. def get_weight(shape, regularizer):
  28.         w = tf.Variable(tf.random_normal(shape), dtype=tf.float32)
  29.         tf.add_to_collection('losses', tf.contrib.layers.l2_regularizer(regularizer)(w))
  30.         return w

  31. def get_bias(shape):  
  32.     b = tf.Variable(tf.constant(0.01, shape=shape))
  33.     return b
  34.        
  35. x = tf.placeholder(tf.float32, shape=(None, 2))
  36. y_ = tf.placeholder(tf.float32, shape=(None, 1))

  37. w1 = get_weight([2,11], 0.01)       
  38. b1 = get_bias([11])
  39. y1 = tf.nn.relu(tf.matmul(x, w1)+b1)

  40. w2 = get_weight([11,1], 0.01)
  41. b2 = get_bias([1])
  42. y = tf.matmul(y1, w2)+b2


  43. #定义损失函数
  44. loss_mse = tf.reduce_mean(tf.square(y-y_))
  45. loss_total = loss_mse + tf.add_n(tf.get_collection('losses'))


  46. #定义反向传播方法:不含正则化
  47. train_step = tf.train.AdamOptimizer(0.0001).minimize(loss_mse)

  48. with tf.Session() as sess:
  49.         init_op = tf.global_variables_initializer()
  50.         sess.run(init_op)
  51.         STEPS = 40000
  52.         for i in range(STEPS):
  53.                 start = (i*BATCH_SIZE) % 300
  54.                 end = start + BATCH_SIZE
  55.                 sess.run(train_step, feed_dict={x:X[start:end], y_:Y_[start:end]})
  56.                 if i % 2000 == 0:
  57.                         loss_mse_v = sess.run(loss_mse, feed_dict={x:X, y_:Y_})
  58.                         print("After %d steps, loss is: %f" %(i, loss_mse_v))
  59.     #xx在-3到3之间以步长为0.01,yy在-3到3之间以步长0.01,生成二维网格坐标点
  60.         xx, yy = np.mgrid[-3:3:.01, -3:3:.01]
  61.         #将xx , yy拉直,并合并成一个2列的矩阵,得到一个网格坐标点的集合
  62.         grid = np.c_[xx.ravel(), yy.ravel()]
  63.         #将网格坐标点喂入神经网络 ,probs为输出
  64.         probs = sess.run(y, feed_dict={x:grid})
  65.         #probs的shape调整成xx的样子
  66.         probs = probs.reshape(xx.shape)
  67.         print ("w1:\n",sess.run(w1))
  68.         print ("b1:\n",sess.run(b1))
  69.         print ("w2:\n",sess.run(w2))       
  70.         print ("b2:\n",sess.run(b2))

  71. plt.scatter(X[:,0], X[:,1], c=np.squeeze(Y_c))
  72. plt.contour(xx, yy, probs, levels=[.5])
  73. plt.show()



  74. #定义反向传播方法:包含正则化
  75. train_step = tf.train.AdamOptimizer(0.0001).minimize(loss_total)

  76. with tf.Session() as sess:
  77.         init_op = tf.global_variables_initializer()
  78.         sess.run(init_op)
  79.         STEPS = 40000
  80.         for i in range(STEPS):
  81.                 start = (i*BATCH_SIZE) % 300
  82.                 end = start + BATCH_SIZE
  83.                 sess.run(train_step, feed_dict={x: X[start:end], y_:Y_[start:end]})
  84.                 if i % 2000 == 0:
  85.                         loss_v = sess.run(loss_total, feed_dict={x:X,y_:Y_})
  86.                         print("After %d steps, loss is: %f" %(i, loss_v))

  87.         xx, yy = np.mgrid[-3:3:.01, -3:3:.01]
  88.         grid = np.c_[xx.ravel(), yy.ravel()]
  89.         probs = sess.run(y, feed_dict={x:grid})
  90.         probs = probs.reshape(xx.shape)
  91.         print ("w1:\n",sess.run(w1))
  92.         print ("b1:\n",sess.run(b1))
  93.         print ("w2:\n",sess.run(w2))
  94.         print ("b2:\n",sess.run(b2))

  95. plt.scatter(X[:,0], X[:,1], c=np.squeeze(Y_c))
  96. plt.contour(xx, yy, probs, levels=[.5])
  97. plt.show()



gaoyang9992006 发表于 2018-9-30 20:06 | 显示全部楼层
一路向北lm 发表于 2018-9-30 15:12
是的,你也在学吗?

了解过这个概念。以前学过Python,不过后来接触了其他的语言,觉得Python缺点还是很多的。
柳铁钢 发表于 2018-10-1 12:31 | 显示全部楼层
再看,试试
 楼主| 一路向北lm 发表于 2018-10-2 08:28 | 显示全部楼层

电脑配置不行的话,还跑不动
您需要登录后才可以回帖 登录 | 注册

本版积分规则

293

主题

3837

帖子

81

粉丝
快速回复 在线客服 返回列表 返回顶部