遇到的问题:
- RTX3060 安装 tensorflow-gpu-2.3.0 无法使用–卸载、升级版本
- 导入了tensorflow显示找不到keras–import tensorflow.keras
要点:
- keras导入示例数据集、完成回归、二分类、多分类任务
- 使用
sklearn
和tf.keras.dataset
示例数据集
课程链接:https://edu.csdn.net/course/detail/36944
sklearn数据集使用说明:https://blog.csdn.net/rocling/article/details/85239441
(base) C:\Users\ASUS>nvidia-smi
# Driver Version: 512.78
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
jupyter notebook
jupyter notebook
import tensorflow as tf
print(f"版本号:{tf.__version__}")
# 版本号:2.3.0
tf.test.is_gpu_available()
# True
可以使用GPU
加速了
(0,1)
的随机数、生成3行4列的tensor
tf.random.uniform((3,4))
TF
中的核心高级API
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'])
# 模型初始化
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指的是预测结果的维度
# keras编译、自定义循环不需要这一步
model.compile(optimizer='adam', loss='mse')
# epochs 对所有数据的训练次数
history = model.fit(X, y, epochs=5000)
predict
后面可以传Series、也可以传array(样本数, 特征数)
# 使用原始数据
model.predict(X)
# 使用新数据、np.random.rand 生成0-1的随机数、维数要和原数据中的特征一样
model.predict(np.random.rand(1,13))
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))
keras
中binary_crossentropy
计算二元交叉熵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))
plt.plot(history.epoch, history.history.get('loss'))
plt.plot(history.epoch, history.history.get('acc'))
softmax
输出样本属于每个类别的概率keras
中对于多分类问题有categorical_crossentropy
和sparse_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'))
tf.test.is_gpu_available()
# False
# 问题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
安装的)、再重新安装即可
tf.test.is_gpu_available()
出现提示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
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
解决方法:导包时加入
import tensorflow.keras