nb.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #%%
  2. import tensorflow as tf
  3. from tensorflow import keras
  4. from tensorflow.keras import datasets, layers
  5. import os
  6. #%%
  7. a = tf.random.normal([4,35,8]) # 模拟成绩册A
  8. b = tf.random.normal([6,35,8]) # 模拟成绩册B
  9. tf.concat([a,b],axis=0) # 合并成绩册
  10. #%%
  11. x = tf.random.normal([2,784])
  12. w1 = tf.Variable(tf.random.truncated_normal([784, 256], stddev=0.1))
  13. b1 = tf.Variable(tf.zeros([256]))
  14. o1 = tf.matmul(x,w1) + b1 #
  15. o1 = tf.nn.relu(o1)
  16. o1
  17. #%%
  18. x = tf.random.normal([4,28*28])
  19. # 创建全连接层,指定输出节点数和激活函数
  20. fc = layers.Dense(512, activation=tf.nn.relu)
  21. h1 = fc(x) # 通过fc类完成一次全连接层的计算
  22. #%%
  23. vars(fc)
  24. #%%
  25. x = tf.random.normal([4,4])
  26. # 创建全连接层,指定输出节点数和激活函数
  27. fc = layers.Dense(3, activation=tf.nn.relu)
  28. h1 = fc(x) # 通过fc类完成一次全连接层的计算
  29. #%%
  30. fc.non_trainable_variables
  31. #%%
  32. embedding = layers.Embedding(10000, 100)
  33. #%%
  34. x = tf.ones([25000,80])
  35. #%%
  36. embedding(x)
  37. #%%
  38. z = tf.random.normal([2,10]) # 构造输出层的输出
  39. y_onehot = tf.constant([1,3]) # 构造真实值
  40. y_onehot = tf.one_hot(y_onehot, depth=10) # one-hot编码
  41. # 输出层未使用Softmax函数,故from_logits设置为True
  42. loss = keras.losses.categorical_crossentropy(y_onehot,z,from_logits=True)
  43. loss = tf.reduce_mean(loss) # 计算平均交叉熵损失
  44. loss
  45. #%%
  46. criteon = keras.losses.CategoricalCrossentropy(from_logits=True)
  47. loss = criteon(y_onehot,z) # 计算损失
  48. loss
  49. #%%