1、安装anaconda 参考https://blog.csdn.net/lwplwf/article/details/79162470
2、使用anaconda创建一个虚拟环境
conda create -n <环境名称> python=3.5(python版本)
3、激活上一步骤创建的虚拟环境
#
# To activate this environment, use:
# > source activate tf1.4
#
# To deactivate this environment, use:
# > source deactivate tf1.4
#
4、用anaconda安装最新的TensorFlow版本
参考https://blog.csdn.net/qq_35203425/article/details/79965389
https://blog.csdn.net/u013550000/article/details/80042471
5、激活环境之后测试
import tensorflow as tf
>>> tf.__version__
'1.4.1'
6、测试
import tensorflow as tf
hello = tf.constant('hello,tensorflow')
sess = tf.Session()
print(sess.run(hello))
测试时候的一些警告:
>>> sess = tf.Session()
2019-09-02 11:27:36.323811: I tensorflow/core/platform/cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX AVX2 FMA
原因:安装的是cpu版本(后续还会安装GPU版本)
解决:在代码中加入以下代码,忽略警告
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
参考:https://blog.csdn.net/hq86937375/article/details/79696023
7、测试结果
(tf1.4) s@s:~$ python
Python 3.5.4 |Continuum Analytics, Inc.| (default, Aug 14 2017, 13:26:58)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow as tf
>>> import os
>>> os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
>>> hello = tf.constant('hello,tensorflow')
>>> sess = tf.Session()
>>> print(sess.run(hello))
b'hello,tensorflow'
>>>
ps:新建一个py文件
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
hello = tf.constant('hello,tensorflow')
sess = tf.Session()
print(sess.run(hello))
'''
import tensorflow as tf
import numpy as np
#去除cpu版本的警告
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
#creat data
x_data = np.random.rand(100).astype(np.float32) ##输入值[0,1)之间的随机数
y_data = x_data * 0.1 + 0.3 ##预测值
###creat tensorflow structure strat###
# 构造要拟合的线性模型
Weights = tf.Variable(tf.random_uniform([1],-1.0,1.0))
biases = tf.Variable(tf.zeros([1]))
y = Weights * x_data + biases
# 定义损失函数和训练方法
loss = tf.reduce_mean(tf.square(y-y_data)) ##最小化方差
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
# 初始化变量
'''
init = tf.initialize_all_variables()
'''
init = tf.global_variables_initializer()
###creat tensorflow structure end###
# 启动
sess = tf.Session()
sess.run(init)
# 训练拟合,每一步训练队Weights和biases进行更新
count = 1
for step in range(201):
sess.run(train)
if step % 20 == 0:
print(step,sess.run(Weights),sess.run(biases))
# 得到最优拟合结果 W接近于0.1,b接近于0.3
在conda空间tf1.4中直接运行./test1.py,迭代200次后的结果如下
s@s:~$ source activate tf1.4
(tf1.4) s@s:~$ cd TF_study/
(tf1.4) s@s:~/TF_study$ ./test1.py
0 [0.36548096] [0.21200436]
20 [0.15784316] [0.2683353]
40 [0.11386405] [0.2924105]
60 [0.10332299] [0.29818094]
80 [0.10079648] [0.299564]
100 [0.10019091] [0.2998955]
120 [0.10004577] [0.29997495]
140 [0.10001099] [0.299994]
160 [0.10000264] [0.29999858]
180 [0.10000062] [0.29999968]
200 [0.10000015] [0.29999992]