Tensorflow学习笔记:1-tensorflow-gpu部署 & keras简单使用-2023-2-12

遇到的问题:

  1. RTX3060 安装 tensorflow-gpu-2.3.0 无法使用–卸载、升级版本
  2. 导入了tensorflow显示找不到keras–import tensorflow.keras

要点:

  1. keras导入示例数据集、完成回归、二分类、多分类任务
  2. 使用sklearntf.keras.dataset示例数据集

tensorflow 2.6.0 GPU版本部署及测试

课程链接:https://edu.csdn.net/course/detail/36944
sklearn数据集使用说明:https://blog.csdn.net/rocling/article/details/85239441

0- 查看 NVIDIA 驱动版本

  • 需要450.80.02或更高版本
(base) C:\Users\ASUS>nvidia-smi
# Driver Version: 512.78

1- 安装

conda install tensorflow-gpu=2.6.0
# y
  • 如果下载很慢、可以更换国内源、创建.condarc文件、放在用户目录下
channels:
  - defaults
show_channel_urls: true
default_channels:
  - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
  - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/r
  - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/msys2
custom_channels:
  conda-forge: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  msys2: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  bioconda: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  menpo: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  pytorch: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  simpleitk: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  
================
# 查看下载源
conda config --show-source
  • 其他依赖包
pip install pandas matplotlib notebook -i https://pypi.tuna.tsinghua.edu.cn/simple
# pandas-1.3.5
# matplotlib-3.5.3
# scikit-learn-1.0.2

2- 测试

  • 运行jupyter notebook
jupyter notebook
  • 执行代码
import tensorflow as tf
print(f"版本号:{tf.__version__}")
# 版本号:2.3.0
tf.test.is_gpu_available()
# True

可以使用GPU加速了


3- 简单使用

  • 使用(0,1)的随机数、生成3行4列的tensor
tf.random.uniform((3,4))

4- tf.keras 概述

  • TF中的核心高级API

1、(单层)线性回归

1、导包 & 数据读取和观察
import tensorflow as tf
import tensorflow.keras
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

from sklearn import datasets
X, y = datasets.load_boston(return_X_y=True)
# X.shape (506, 13)
# 数据观察、散点图
plt.scatter(X[:,4], y)

# 读取csv文件
# df = pd.read_csv('./dataset/1.csv')
# 数据观察、散点图
# plt.scatter(df['x'], df['y'])
2、预测目标与损失函数
  • 损失函数和成本函数:找到使预测值和真实值整体误差最小的参数
  • 损失函数针对单样本、成本函数针对整体数据集
  • 使用均方误差(预测值和真实值差的平方取均值)作为成本函数
  • 使用梯度下降算法对损失函数进行优化
3、创建模型
# 模型初始化
model = tf.keras.Sequential()
# 添加一个隐藏层
# 添加输入维度input_shape为13
# input_shape=(13,) 维度为13、这里需要写元组形式
model.add(tf.keras.layers.Dense(1,input_shape=(13,)))
# 这里和shape的结果是反的 (特征数,样本数)

# 打印模型
model.summary()

# 输出结果如下
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense (Dense)                (None, 1)                 14        
=================================================================
Total params: 14
Trainable params: 14
Non-trainable params: 0
# Output Shape 样本数 (None, 1) None指的是样本数量 1指的是预测结果的维度
4、训练
# keras编译、自定义循环不需要这一步
model.compile(optimizer='adam', loss='mse')
# epochs 对所有数据的训练次数
history = model.fit(X, y, epochs=5000)
5、预测

predict 后面可以传Series、也可以传array

(样本数, 特征数)

# 使用原始数据
model.predict(X)

# 使用新数据、np.random.rand 生成0-1的随机数、维数要和原数据中的特征一样
model.predict(np.random.rand(1,13))

2、多层感知器

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

from sklearn import datasets
X, y = datasets.load_boston(return_X_y=True)

# 10层隐藏层
# activation 激活函数
model = tf.keras.Sequential([tf.keras.layers.Dense(10, input_shape=(13,), activation='relu'), tf.keras.layers.Dense(1)])

# 打印模型
model.summary()

# 输出结果如下
Model: "sequential_1"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense_1 (Dense)              (None, 10)                140       
_________________________________________________________________
dense_2 (Dense)              (None, 1)                 11        
=================================================================
Total params: 151
Trainable params: 151
Non-trainable params: 0
# Param 140 层数*(特征+1)=10*(13+1)

# keras编译、自定义循环不需要这一步
model.compile(optimizer='adam', loss='mse')
# epochs 对所有数据的训练次数
history = model.fit(X, y, epochs=100)

# 预测
model.predict(X)
model.predict(np.random.rand(1,13))

3、逻辑回归

1、sigmoid 函数
  • 概率分布函数:给定某个输入,输出为一个概率值
  • 线性回归是连续值、而逻辑回归是二分类
2、交叉熵损失函数
  • 衡量预测的概率分布和实际的概率分布的相似度
  • 比均方差算的值“大”
  • kerasbinary_crossentropy计算二元交叉熵
3、模型预测
import tensorflow as tf
import tensorflow.keras
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

from sklearn import datasets
X,y = datasets.load_breast_cancer(return_X_y=True)

model = tf.keras.Sequential([tf.keras.layers.Dense(4, input_shape=(30,), activation='relu'), tf.keras.layers.Dense(4, activation='relu'), tf.keras.layers.Dense(1, activation='sigmoid')])

# 打印模型
model.summary()

# 输出结果如下
Model: "sequential_2"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense_3 (Dense)              (None, 4)                 124       
_________________________________________________________________
dense_4 (Dense)              (None, 4)                 20        
_________________________________________________________________
dense_5 (Dense)              (None, 1)                 5         
=================================================================
Total params: 149
Trainable params: 149
Non-trainable params: 0
    
# keras编译、自定义循环不需要这一步
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc'])
# epochs 对所有数据的训练次数
history = model.fit(X, y, epochs=100)

# 预测
model.predict(X)
model.predict(np.random.rand(1,30))
4、画图看损失和准确率
plt.plot(history.epoch, history.history.get('loss'))
plt.plot(history.epoch, history.history.get('acc'))

4、多分类

  • softmax输出样本属于每个类别的概率
  • keras中对于多分类问题有categorical_crossentropysparse_categorical_crossentropy计算softmax交叉熵
  • 数据集:fasion mnist
import tensorflow as tf
import tensorflow.keras
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

(trainx, tariny), (testx, testy) = tf.keras.dataset.fasion_mnist.load

# 查看维度
trainx.shape,trainy.shape,testx.shape,testy.shape
# ((60000, 28, 28), (60000,), (10000, 28, 28), (10000,))

# 查看第一个图
plt.imshow(trainx[0])
trainy[0]
# 9 类别号

# 数据处理:缩小到0-1
trainx = trainx/255
testx = testx/255

# Flatten 数据打平为1维向量
model = tf.keras.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28,28)))  # 28*28的一维向量
model.add(tf.keras.layers.Dense(128,activation='relu'))
model.add(tf.keras.layers.Dense(10,activation='softmax'))

model.summary()
# 结果
Model: "sequential_3"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
flatten (Flatten)            (None, 784)               0         
_________________________________________________________________
dense_6 (Dense)              (None, 128)               100480    
_________________________________________________________________
dense_7 (Dense)              (None, 10)                1290      
=================================================================
Total params: 101,770
Trainable params: 101,770
Non-trainable params: 0
    
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['acc'])
history = model.fit(trainx, trainy, epochs=5)
# 第一行的acc: 0.8237 是训练完第一个epoch 优化之后 计算得到的准确率

# loss和acc
model.evaluate(testx,testy)
# 313/313 [==============================] - 1s 2ms/step - loss: 0.3604 - acc: 0.8691
# [0.36038756370544434, 0.8690999746322632]

# 10000,10 每个分类的概率
model.predict(testx)
# 预测的分类号  不是概率
list(map(lambda x:np.argmax(x),model.predict(testx)))

# 画图看损失和准确率
plt.plot(history.epoch, history.history.get('loss'))
plt.plot(history.epoch, history.history.get('acc'))

5- 问题

1、RTX3060 安装 tensorflow-gpu-2.3.0 无法使用

tf.test.is_gpu_available()
# False
  • 解决方案:安装2.6.0版本可以正常使用

2、使用 conda 再次安装出现提示

# 问题1:环境不一致
The environment is inconsistent, please check the package plan carefully
The following packages are causing the inconsistency:

# 问题2:需要的包已安装
All requested packages already installed
  • 原因:

    之前没有卸载干净(因为使用conda安装、但使用了pip卸载)

  • 解决方法:

    卸载提示中的包、如果还是不行、使用conda uninstall卸载(之前是用conda安装的)、再重新安装即可


3、命令行运行tf.test.is_gpu_available()出现提示

问题1
2023-02-12 18:17:54.229277: I tensorflow/core/platform/cpu_feature_guard.    cc:142] 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.
  • 原因

    遇到了这个问题,意思是你的 CPU 支持AVX AVX2 (可以加速CPU计算),但你安装的TensorFlow版本不支持

  • 解决方案

    可以忽略、如果需要处理、参考:https://blog.csdn.net/zhaohaibo_/article/details/80573676

问题2
WARNING:tensorflow:From C:\Users\ASUS\AppData\Local\Temp\ipykernel_26636\243930209.py:4: is_gpu_available (from tensorflow.python.framework.test_util) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.config.list_physical_devices('GPU')` instead.

原因:
is_gpu_available (From tensorflow.python.framework.test_util)已弃用,并将在未来版本中删除。

解决方法:改用

tf.config.list_physical_devices('GPU')
# [PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]

结果为[]说明不能使用GPU


4、导入了 tensorflow 显示找不到 keras

解决方法:导包时加入

import tensorflow.keras
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值