anaconda、tensorflow使用

一、概述

https://tensorflow.google.cn/
1、教程
简单粗暴tensorflow2

tensorflow c++调用
简明tensorflow官方
tensorflow1.0使用
2、数据
CIFAR-10官网
Dataset之CIFAR-10

二、环境搭建

1、安装anaconda
anaconda官网下载:https://www.anaconda.com/products/individual
anaconda安装教程
(1)自己配置Anaconda环境变量:

此电脑——属性——高级系统设置——环境变量——path——编辑——新建

E:\Anaconda(Python需要)
E:\Anaconda\Scripts(conda自带脚本)
E:\Anaconda\Library\mingw-w64\bin(使用C with python的时候)
E:\Anaconda\Library\usr\bin
E:\Anaconda\Library\bin(jupyter notebook动态库)

(2)验证
A、在cmd中输入 :

conda --version,——查看是否有conda环境? (检验安装成功的标志)
conda info

B、运行Anaconda Navifator,出现界面(初次慢)
(3)添加清华镜像
在Anaconda prompt中操作:

conda config --add channels https:
conda config --add channels https:
conda config --set show_channel_urls yes
conda config --show channels

conda env list
conda create -n tf2 python=3.9
conda create --name tf2 python=3.9
conda remove --name tf2 --all
conda activate tf2
conda list
conda deactivate
conda remove -n tf2 --all

2、安装pycharm
pycharm官网下载
pycharm和谐教程
pycharm脚本之家和谐版
pycharm的破解和基本使用
3、安装tensorflow
Tensorflow2.x的安装教程
Anaconda3环境下安装Tensorflow2及pycharm环境配置详细教程
(1)查看电脑是否有GPU
查看自己电脑是否支持GPU方法:①任务栏点击右键打开任务管理器;②点击性能,并下拉;③左侧框如果有GPU,则代表自己电脑是由GPU的。
使用GPU需要安装cudatoolkit和cudnn实现GPU的加速。(Tensorflow2.x安装以后不再区分是否是GPU,检测到已经安装GPU和CUDA后,会自动调用GPU运行。)
(2)在anaconda prompt中输入:

conda create -n tf2 python=3.9
conda activate tf2

conda install cudatoolkit cudnn
pip install tensorflow

(3)检查是否安装成功

在conda tf2环境中:
输入 python
输入 import tensorflow as tf
输入 tf.__version__

在pycharm中:

    print(tf.__version__)

    print(tf.test.is_gpu_available())
    for i in tf.config.list_physical_devices():
        if 'GPU' in i[1]:
            print(i[1], '可用,GPU名称: ', i[0])
    结果显示:
    GPU 可用,GPU名称:  /physical_device:GPU:0

三、使用

1、session模块在2.0中已移除
由于tensorflow2.x和1.x版本有一些代码的区别,在使用tensorflow2.x的时候,在代码中添加compat.v1 能够解决大多数问题。


import tensorflow as tf
tf.Session() --> tf.compat.v1.Session()
    tf.compat.v1.disable_eager_execution()
    sess = tf.compat.v1.Session()
    a = tf.constant(1)
    b = tf.constant(2)
    print(sess.run(a + b))

2、问题

  • 2022-02-04 15:58:39.249679: I tensorflow/core/platform/cpu_feature_guard.cc:151] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX AVX2
    To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.

  • 2022-02-04 15:58:39.936572: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1525] Created device /job:localhost/replica:0/task:0/device:GPU:0 with 2805 MB memory: -> device: 0, name: GeForce MX150, pci bus id: 0000:01:00.0, compute capability: 6.1

该警告提示tensorflow可以以更快的速度运行。
原因是下载TensorFlow的版本不支持cpu的AVX2编译。可能是因为安装时使用的pip install tensorflow ,这样默认会下载X86_64的SIMD版本。
(1)把tensorflow的警告等级为2的警告忽略:

import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'

(2)重新安装
tensorflow 带vx2版本列表

pip uninstall tensorflow
pip install 具体版本

3、keras
线性回归:y=ax+b

import tensorflow as tf
import pandas as pd
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(1, input_shape=(1,)))
model.summary()  # ax+b
model.compile(optimizer='adam',loss='mse')
history = model.fit(x, y, epochs=5000)
model.predict(x)
model.predict(pd.Series([20]))

多层(隐含层):

x=data.iloc[:,1:-1]
y=data.iloc[:,-1]
model = tf.keras.Sequential([tf.keras.layers.Dense(10, input_shape=(3,),activation='relu',
                             tf.keras.layers.Dense(1)]
                           )
model.summary()
model.compile(optimizer='adam',loss='mse')
model.fit(x, y, epochs=100)
model.predict()

逻辑回归:二分类(sigmoid)

import tensorflow as tf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
data = pd.read_csv('dataset/credit_a.csv',header=None)
data.head()
x=data.iloc[:,:-1]
y=data.iloc[;,-1].replace(-1,0)  #用0替代-1
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(4, input_shape=(15,),activation='relu'))
model.add(tf.keras.layers.Dense(4, activation='relu'))
model.add(tf.keras.layers.Dense(1, activation='sigmoid'))
model.summary()
model.compile(optimizer='adam',
              loss='binary_crossentropy',
              metrics=['acc']
)
history = model.fit(x, y, epochs=100)
history.history.keys()
plt.plot(history.epoch, history.history.get('loss')
plt.plot(history.epoch, history.history.get('acc')
model.predict()

softmax: 多分类

anaconda、tensorflow使用

loss为sparse_categorical_crossentropy

import tensorflow as tf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

(train_image,train_lable),(test_image, test_lable) = tf.keras.datasets.fashion_mnist.load_data()
train_image = train_image/255
test_image = test_image/255
model = tf.keras.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28,28)))
model.add(tf.keras.layers.Dense(128,activation='relu'))
model.add(tf.keras.layers.Dense(10,activation='softmax'))
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['acc']
)
model.fit(train_image, train_lable, epochs=5)
model.evaluate(test_image, test_lable)

上面的转成独热码:loss为categorical_crossentropy

train_lable_onehot = tf.keras.utils.to_categorical(train_lable)
test_lable_onehot = tf.keras.utils.to_categorical(test_lable)
model = tf.keras.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28,28)))
model.add(tf.keras.layers.Dense(128,activation='relu'))
model.add(tf.keras.layers.Dense(10,activation='softmax'))
model.compile(optimizer='adam',
              loss='categorical_crossentropy',
              metrics=['acc']
)
model.fit(train_image, train_lable_onehot, epochs=5)
model.evaluate(test_image, test_lable_onehot)
predict = model.predict(test_image)

优化器:

SGD:     随机梯度下降优化器
RMSProp:
Adam:

model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.01),
              loss='categorical_crossentropy',
              metrics=['acc']
)

检查匹配:在训练数据上得分很高,在测试数据上得分很低

[En]

Checked the fit: scored high on training data and quite low on test data

长拟合:训练数据得分低,测试数据得分低,增加网络深度

[En]

Long fitting: low score on training data, low score on test data, increase network depth

history = model.fit(train_image, train_lable_onehot, epochs=10,
                    validation_data = (test_image, test_lable_onehot))
history.history.keys()
plt.plot(history.epoch, history.history.get(loss), label='loss')
plt.plot(history.epoch, history.history.get(val_loss), label='val_loss')
plt.legend()

plt.plot(history.epoch, history.history.get(acc), label='acc')
plt.plot(history.epoch, history.history.get(val_acc), label='val_acc')
plt.legend()

参数选择原则:
首先,开发一个过拟合模型(1,多层;2,每层更大;3,训练更多轮)

[En]

First, develop an over-fitting model (1, more layers; 2, each layer is larger; 3, train more rounds)

而后抑制过拟合(1、dropout;2、正则化;3、图像增强;4、增强训练数据)
再次调整超级参数(学习率、隐含层单元数、训练轮次)

[En]

Adjust the super parameters again (learning rate, number of units in the hidden layer, training rounds)

model = tf.keras.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28,28)))
model.add(tf.keras.layers.Dense(128,activation='relu'))
model.add(tf.keras.layers.Dropout(0.5))
model.add(tf.keras.layers.Dense(128,activation='relu'))
model.add(tf.keras.layers.Dropout(0.5))
model.add(tf.keras.layers.Dense(128,activation='relu'))
model.add(tf.keras.layers.Dropout(0.5))
model.add(tf.keras.layers.Dense(10,activation='softmax'))

函数式api:可实现多输入

from tensorflow import keras
input = keras.Input(shape=(28, 28))
x = keras.layers.Flatten()(input)
x = keras.layers.Dense(32, activation='relu')(x)
x = keras.layers.Dropout(0.5)(x)
x = keras.layers.Dense(64, activation='relu')(x)
output = keras.layers.Dense(10, activation='softmax')(x)
model = keras.Model(inputs=input, outputs=output)
model.summary()

tf.sata 输入模块
计算机视觉 卷积神经网络
tf.keras高阶API实例
Eager模式与自定义训练
Tensorboard可视化
定制培训、全面的示例和图片增强

[En]

Custom training comprehensive examples and picture enhancement

使用预培训网络(迁移学习)

[En]

Use pre-training network (transfer learning)

多输出模型实例
模型的保存与恢复
图像定位
自动图运算与GPU使用策略
图像语义分割
RNN循环神经网络
RNN序列预测实例-空气污染预测
使用免费GPU加速训练

Original: https://blog.csdn.net/pzs0221/article/details/122770733
Author: pzs0221
Title: anaconda、tensorflow使用

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/511342/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球