zoukankan      html  css  js  c++  java
  • AI

    Hello world

     1 # coding=utf-8
     2 import tensorflow as tf
     3 import os
     4 
     5 os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
     6 
     7 try:
     8     tf.contrib.eager.enable_eager_execution()
     9     print("TF imported with eager execution!")
    10 except ValueError:
    11     print("TF already imported with eager execution!")
    12 
    13 tensor = tf.constant('Hello, world!')
    14 tensor_value = tensor.numpy()
    15 print(tensor_value)
    16 
    17 # ### Eager Execution
    18 # https://www.tensorflow.org/guide/eager?hl=zh-cn
    19 # https://www.tensorflow.org/api_docs/python/tf/enable_eager_execution
    20 # TensorFlow的“Eager Execution”是一个命令式、由运行定义的接口,一旦从 Python 被调用可立即执行操作;
    21 #   - 操作会返回具体的值,而不是构建以后再运行的计算图;
    22 #   - 能够轻松地开始使用TensorFlow和调试模型,并且还减少了样板代码;
    23 #   - 使得 TensorFlow 的入门变得更简单,也使得研发工作变得更直观;

    运行结果:

    TF imported with eager execution!
    b'Hello, world!'

    建造第一个神经网络

     1 # coding=utf-8
     2 import tensorflow as tf
     3 import numpy as np
     4 import matplotlib.pyplot as plt
     5 import os
     6 
     7 os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
     8 
     9 
    10 # ### 添加神经层
    11 
    12 
    13 def add_layer(inputs, in_size, out_size, activation_function=None):  # 构造添加神经层的函数,这里设定默认激励函数为None
    14     Weights = tf.Variable(tf.random_normal([in_size, out_size]))  # 定义weights:为一个in_size行, out_size列的随机变量矩阵
    15     biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)  # 定义biases:在机器学习中biases的推荐值不为0
    16     Wx_plus_b = tf.matmul(inputs, Weights) + biases  # 定义Wx_plus_b:神经网络未激活的值;tf.matmul()是矩阵的乘法
    17     if activation_function is None:  # 当激励函数为None时,输出当前的预测值Wx_plus_b
    18         outputs = Wx_plus_b
    19     else:  # 不为None时,将Wx_plus_b传到activation_function()函数得到输出
    20         outputs = activation_function(Wx_plus_b)
    21     return outputs  # 返回输出
    22 
    23 
    24 # ### 构建数据
    25 x_data = np.linspace(-1, 1, 300, dtype=np.float32)[:, np.newaxis]  # 构建数据x_data
    26 noise = np.random.normal(0, 0.05, x_data.shape).astype(np.float32)  # 构建噪声数据noise,模拟真实情况
    27 y_data = np.square(x_data) - 0.5 + noise  # 构建数据y_data
    28 
    29 # ### 搭建网络
    30 xs = tf.placeholder(tf.float32, [None, 1])  # 利用占位符定义神经网络的输入
    31 ys = tf.placeholder(tf.float32, [None, 1])  # None代表无论输入有多少都可以,1表示输入只有一个特征
    32 h1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)  # 定义隐藏层,10个神经元,激励函数使用TensorFlow自带的tf.nn.relu
    33 prediction = add_layer(h1, 10, 1, activation_function=None)  # 定义输出层(预测层),输出一个结果
    34 loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),
    35                                     reduction_indices=[1]))  # 计算预测值prediction和真实值的误差,对二者差的平方求和再取平均
    36 train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)  # 选择Optimizer来最小化误差loss,以0.1的效率
    37 init = tf.global_variables_initializer()  # 使用变量前,必须初始化
    38 sess = tf.Session()  # 定义Session
    39 sess.run(init)  # 执行init初始化步骤
    40 
    41 # ### 结果可视化
    42 fig = plt.figure()  # 创建图形实例
    43 ax = fig.add_subplot(1, 1, 1)  # 创建子图,作为1行1列图形矩阵中的第1个subplot
    44 ax.scatter(x_data, y_data)  # 绘制散点图
    45 plt.ion()  # 打开交互模式
    46 plt.show()  # 显示图形
    47 
    48 # ### 训练
    49 for i in range(1000):  # 学习次数1000
    50     sess.run(train_step, feed_dict={xs: x_data, ys: y_data})  # 学习内容是train_step
    51     if i % 50 == 0:  # 每隔50次训练输出机器学习的误差和刷新一次图形
    52         print("loss: {}".format(sess.run(loss, feed_dict={xs: x_data, ys: y_data})))
    53         try:
    54             ax.lines.remove(lines[0])
    55         except Exception:
    56             pass
    57         prediction_value = sess.run(prediction, feed_dict={xs: x_data})
    58         lines = ax.plot(x_data, prediction_value, 'r-', lw=5)  # 用红色、宽度为5的线来显示预测数据和输入之间的关系
    59         plt.pause(0.2)  # 暂停0.2秒
    60 
    61 # ### 添加神经层
    62 # 通过在TensorFlow中定义一个添加层的函数,可以添加神经层;
    63 # 神经层里常见的参数通常有weights、biases和激励函数等;
    64 # 添加神经层的函数def add_layer()有四个参数:输入值、输入的大小、输出的大小和激励函数;
    65 #
    66 # ### 构建数据
    67 # 模拟真实数据;
    68 #
    69 # ### 搭建网络
    70 # 神经网络(输入层1个、隐藏层10个、输出层1个);
    71 #
    72 # ### 训练
    73 # 机器学习的内容是train_step, 用Session来run每一次training的数据,逐步提升神经网络的预测准确性;
    74 # 注意:当运算要用到placeholder时,就需要feed_dict这个字典来指定输入;
    75 #
    76 # ### 可视化
    77 # 利用matplotlib模块绘制和显示图形;

    某一次的运行过程中的图形显示:

    某一次的命令行输出:

     1 loss: 0.05769985169172287
     2 loss: 0.007242309395223856
     3 loss: 0.004746056627482176
     4 loss: 0.004090217407792807
     5 loss: 0.0037425532937049866
     6 loss: 0.0035221632570028305
     7 loss: 0.003357301466166973
     8 loss: 0.0032187148462980986
     9 loss: 0.0031040285248309374
    10 loss: 0.0030171412508934736
    11 loss: 0.0029463612008839846
    12 loss: 0.002890094416216016
    13 loss: 0.0028497371822595596
    14 loss: 0.002820496214553714
    15 loss: 0.0027967311907559633
    16 loss: 0.002780070761218667
    17 loss: 0.0027664629742503166
    18 loss: 0.00275203469209373
    19 loss: 0.002737578935921192
    20 loss: 0.002723217708989978
  • 相关阅读:
    17. Letter Combinations of a Phone Number
    16. 3Sum Closest
    15. 3Sum
    14. Longest Common Prefix
    13. Roman to Integer
    12. Integer to Roman
    11. Container With Most Water
    10. Regular Expression Matching
    9. Palindrome Number
    8. String to Integer (atoi)
  • 原文地址:https://www.cnblogs.com/anliven/p/10029637.html
Copyright © 2011-2022 走看看