学程序得从最基本的语法说起,虽然都说tensorflow的python编程比较简单,但是俺都是从头学起,一没有python编程基础,二没有tensorflow的基础,所以这两个东西加在一起学,还是有一定难度的(因为还不太分得清哪个是tensorflow的语法,哪些是python的东西)。例如以下的程序样本,输入编辑器进行编程测试:
import numpy as np
x_vals = np.array([1., 3., 5.,7.,9.]) #用于生成变量x_data = tf.placeholder(tf.float32)
m_const = tf.constant(3.)
my_product = tf.multiply(x_data,m_const)
for x_val in x_vals:
print(sess.run(my_product,feed_dict={x_data:x_val}))
会出现错误:
NameError: name 'tf' is not defined
所以必须加入
import tensorflow as tf
一行表示导入TF环境
加上这个,还会不会出现问题呢?答案是yes,因为没有定义sess是什么,所以还必须定义:
sess = tf.Session()
这样就可以得出如下结果:
runfile('D:/fs/coding/example1.py', wdir='D:/fs/coding')
3.0
9.0
15.0
21.0
27.0
对于这些代码,
import tensorflow as tf
import numpy as np
x_vals = np.array([1., 3., 5.,7.,9.])
x_data = tf.placeholder(tf.float32)
m_const = tf.constant(3.)
my_product = tf.multiply(x_data,m_const)
sess = tf.Session()
for x_val in x_vals:
print(sess.run(my_product,feed_dict={x_data:x_val}))
还有以下问题值得思考:
(1)能否改变x_vals定义的语句
x_vals = np.array([1., 3., 5.,7.,9.])
的顺序到x_data之后?
我的猜想应该是可以的,因为tensorflow是符号语言,数值带入占位符都是在会话中运行的,所以这个关系应该不大。
实际运行:运行如下代码
import tensorflow as tf
import numpy as np
x_data = tf.placeholder(tf.float32)
m_const = tf.constant(3.)
my_product = tf.multiply(x_data,m_const)
x_vals = np.array([1., 3., 5.,7.,9.])
sess = tf.Session()
for x_val in x_vals:
print(sess.run(my_product,feed_dict={x_data:x_val}))
结果一样!
(2)如果要将整个变量【1 3 5 7 9】跟常量相乘,应该怎么写?
建议:my_product = tf.matmul(x_vals,m_const)
实际:运行如下代码:
import tensorflow as tf
import numpy as np
x_vals = np.array([1., 3., 5.,7.,9.])
x_data = tf.placeholder(tf.float32)
m_const = tf.constant(3.)
my_product = tf.matmul(x_vals,m_const)
sess = tf.Session()
#for x_val in x_vals:
print(sess.run(my_product))
发生错误:TypeError: Input 'b' of 'MatMul' Op has type float32 that does not match type float64 of argument 'a'.
答案是直接相乘:my_product = x_vals*m_const
这个就是基本的python编程,需要进行实践才能掌握。