在学习深度学习的时候,需要用到tensorflow框架,如何搭建环境,有很多可以参考:
windows下用pycharm安装tensorflow简易教程
其实,如果你已经安装了pycharm,本文以MAC 系统为例,加上图例进行说明。
- 按照示意图顺序,最终点加号,进入下一个图
- 点到➕以后,在搜索框中搜索tensorflow,选择版本,选1开头的,2.0版本的和1有明显区别。step3时选择1.13.1版本,选择安装好会有提示,在上一图中会显示有tensorflow模块
这么做的好处是什么呢?最大的好处就是省时省事,你不必重新搭建一个tensorflow环境,然后再重复导入sklearn等各种包,在现有的环境当中直接导入即可。
装成功没呢?下文给出一段测试数据;
- 数据部分1,用于导包
# -*- coding:UTF-8 -*-
import tensorflow as tf
import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.preprocessing import StandardScaler
# 全局取消证书验证
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
数据部分2,不懂的可以参考机器学习实战9-运行Tensorflow(california_housing数据集)
n_epochs = 36500
learning_rate = 0.001
housing = fetch_california_housing(data_home="./scikit_learn_data", download_if_missing=True)
m, n = housing.data.shape
print(m, n)
housing_data_plus_bias = np.c_[np.ones((m, 1)), housing.data]
# 可以使用TensorFlow或者Numpy或者sklearn的StandardScaler去进行归一化
# StandardScaler默认就做了方差归一化,和均值归一化,这两个归一化的目的都是为了更快的进行梯度下降
# 你如何构建你的训练集,你训练除了的模型,就具备什么样的功能!
scaler = StandardScaler().fit(housing_data_plus_bias)
scaled_housing_data_plus_bias = scaler.transform(housing_data_plus_bias)
X = tf.constant(scaled_housing_data_plus_bias, dtype=tf.float32, name='X')
y = tf.constant(housing.target.reshape(-1, 1), dtype=tf.float32, name='y')
# random_uniform函数创建图里一个节点包含随机数值,给定它的形状和取值范围,就像numpy里面rand()函数
theta = tf.Variable(tf.random_uniform([n + 1, 1], -1.0, 1.0), name='theta')
y_pred = tf.matmul(X, theta, name="predictions")
error = y_pred - y
rmse = tf.sqrt(tf.reduce_mean(tf.square(error), name="rmse"))
# 梯度的公式:(y_pred - y) * xj
gradients = 2/m * tf.matmul(tf.transpose(X), error)
# 赋值函数对于BGD来说就是 theta_new = theta - (learning_rate * gradients)
training_op = tf.assign(theta, theta - learning_rate * gradients)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for epoch in range(n_epochs):
if epoch % 100 == 0:
print("Epoch", epoch, "RMSE = ", rmse.eval())
sess.run(training_op)
best_theta = theta.eval()
print(best_theta)
测试的结果:
/Users/cody/PycharmProjects/ml/venv/bin/python /Applications/PyCharm.app/Contents/helpers/pydev/pydevconsole.py --mode=client --port=55904
import sys; print('Python %s on %s' % (sys.version, sys.platform))
sys.path.extend(['/Users/cody/PycharmProjects/ml'])
Python 3.7.2 (v3.7.2:9a3ffc0492, Dec 24 2018, 02:59:38)
Type "copyright", "credits" or "license" for more information.
IPython 5.0.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
PyDev console: using IPython 5.0.0
Python 3.7.2 (v3.7.2:9a3ffc0492, Dec 24 2018, 02:59:38)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
runfile('/Users/cody/PycharmProjects/ml/tensorf/test.py', wdir='/Users/cody/PycharmProjects/ml/tensorf')
20640 8
WARNING:tensorflow:From /Users/cody/PycharmProjects/ml/venv/lib/python3.7/site-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
2019-05-03 20:13:11.787149: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
Epoch 0 RMSE = 2.854933
Epoch 100 RMSE = 2.5693479
#-------省略若干行
Epoch 25900 RMSE = 2.1917095
Epoch 26000 RMSE = 2.1917078
Epoch 26100 RMSE = 2.1917067
#-------省略若干行
Epoch 36200 RMSE = 2.1916444
Epoch 36300 RMSE = 2.1916444
Epoch 36400 RMSE = 2.191644
[[-0.22428417]
[ 0.83755594]
[ 0.1202107 ]
[-0.2805653 ]
[ 0.31815496]
[-0.00407523]
[-0.0396193 ]
[-0.8818057 ]
[-0.85338384]]