我是用Anaconda安装的,具体安装Anaconda的链接在这里:
Anaconda超详细安装教程(Windows环境下)_菜鸟1号!!的博客-CSDN博客_windows安装anaconda
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --user tensorflow==1.15
我把这个放在前面,因为我习惯安装的时候会把TensorFlow安装,这个是在线下载的方式安装,还有离线安装 https://pypi.org/ ,需要什么可以自己下载
可能会遇到各种问题,百度应该都能搜到,我举个例子:

报错信息:protobuf requires Python '>=3.7' but the running Python is 3.6.5
解决方法:更新pip后重新安装tensorflow。
更新命令:python -m pip install --upgrade pip
安装各个包的方法,上面的镜像是清华大学的, --user不加有时候会报错
使用:===============
使用tensorflow来进行拟合
- import tensorflow as tf
- import numpy as np
-
- tf.compat.v1.disable_eager_execution()
- #使用numpy生成100个点
- x_data = np.random.rand(100)
- #相当于一条线目标的k为0.1 目标b为0.2 相当于样本
- y_data = x_data*0.1 + 0.2
-
- #构造一个线性模型,b和k为小数 优化b和k使创建的模型接近于样本
- b = tf.Variable(0.)
- k = tf.Variable(0.)
- y = k*x_data + b
-
- #二次代价函数 reduce_mean:平均值
- loss = tf.reduce_mean(tf.square(y_data-y))
- #定义一个梯度下降法来训练的优化器 使用梯度下降法学习率为0.2
- optimizer = tf.train.GradientDescentOptimizer(0.2)
- #最小化代价函数
- train = optimizer.minimize(loss)
- #初始化变量
- init = tf.global_variables_initializer()
- with tf.Session() as sess:
- sess.run(init)
- for step in range(201):#200次
- sess.run(train)
- if step%20 == 0:#每20次打印k和b的值
- print(step,sess.run([k,b]))
最后的输出结果为:
- 0 [0.05454114, 0.10042667]
- 20 [0.10407049, 0.19777988]
- 40 [0.10242963, 0.19867489]
- 60 [0.1014502, 0.19920906]
- 80 [0.10086558, 0.19952792]
- 100 [0.100516655, 0.19971822]
- 120 [0.10030838, 0.19983181]
- 140 [0.10018406, 0.19989961]
- 160 [0.10010986, 0.19994009]
- 180 [0.10006558, 0.19996424]
- 200 [0.10003916, 0.19997863]
下面写一个简单的线性回归,以二次的为例:
- import tensorflow as tf
- import numpy as np
- import matplotlib.pyplot as plt
- tf.compat.v1.disable_eager_execution()
- #使用numpy生成200个随机点 [:np.newaxis]:加一个维度200行1列
- x_data = np.linspace(-0.5,0.5,200)[:,np.newaxis]
- #生成噪音,形状和x_data一样
- noise = np.random.normal(0,0.02,x_data.shape)
- y_data = np.square(x_data)+noise
-
- #定义两个placeholder
- x = tf.placeholder(tf.float32,[None,1])
- y = tf.placeholder(tf.float32,[None,1])
-
- #定义神经网络中间层
- Weight_L1 = tf.Variable(tf.random_normal([1,10]))
- biases_L1 = tf.Variable(tf.zeros([1,10]))
- Wx_plus_b_L1 = tf.matmul(x,Weight_L1) + biases_L1
- #定义激活函数
- L1 = tf.nn.tanh(Wx_plus_b_L1)
-
- #定义输出层
- Weight_L2 = tf.Variable(tf.random_normal([10,1]))
- biases_L2 = tf.Variable(tf.random_normal([1,1]))
- Wx_plus_b_L2 = tf.matmul(L1,Weight_L2) + biases_L2
- prediction = tf.nn.tanh(Wx_plus_b_L2)
-
- #二次代价函数
- loss = tf.reduce_mean(tf.square(y-prediction))
- #梯度下降法
- train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
-
- #定义会话
- with tf.Session() as sess:
- #变量初始化
- sess.run(tf.global_variables_initializer())
- for _ in range(2000):
- sess.run(train_step,feed_dict={x:x_data,y:y_data})
- #查看训练结果 训练后的w和b值进行计算的
- prediction_value = sess.run(prediction,feed_dict={x:x_data})
- plt.figure()
- plt.scatter(x_data,y_data)
- plt.plot(x_data,prediction_value,'r-',lw=2)
- plt.show()
最后运行的结果为:
