TensorFlow-layers使用

TensorFlow-layers使用

硬件:NVIDIA-GTX1080

软件:Windows7、python3.6.5、tensorflow-gpu-1.4.0

一、基础知识

1、layers:可表示为对nn进行了一次封装,让layers更加易于操作

2、softmax_cross_entropy_with_logits = softmax + cross_entropy

二、代码展示以mnist为例

import tensorflow as tf
import tensorflow.examples.tutorials.mnist.input_data as input_data

mnist = input_data.read_data_sets('MNIST_data', one_hot = True)

xs = tf.placeholder(tf.float32, [None, 28*28])
ys = tf.placeholder(tf.float32, [None, 10])
keep_prob = tf.placeholder(tf.float32)

x_image = tf.reshape(xs, [-1, 28, 28, 1])

#conv1 (inputs, out_size, ksize, strides=(1, 1))
conv1_layer = tf.layers.conv2d(x_image, 32, 5, padding = 'SAME', activation = tf.nn.relu)

#pool1 (inputs, ksize, strides)
pool1_layer = tf.layers.max_pooling2d(conv1_layer, [2,2], [2,2], padding = 'SAME')

#conv2
conv2_layer = tf.layers.conv2d(pool1_layer, 64, 5, padding = 'SAME', activation = tf.nn.relu)

#pool2
pool2_layer = tf.layers.max_pooling2d(conv2_layer, [2,2], [2,2], padding = 'SAME')

#layer flat
flat_layer = tf.layers.flatten(pool2_layer)

#fc1 (inputs, out_size)
fc1_layer = tf.layers.dense(flat_layer, 128, activation=tf.nn.relu)

#dropout
dropout_layer = tf.layers.dropout(fc1_layer, keep_prob)

#fc2
fc2_layer = tf.layers.dense(dropout_layer, 10)

#loss(logits is not probability, labels is)
#softmax + cross_entropy
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = fc2_layer, labels = ys))
optimizer = tf.train.AdamOptimizer(0.001)
train_step = optimizer.minimize(cross_entropy)

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    for step in range(2000):
        batch_xs, batch_ys = mnist.train.next_batch(100)
        sess.run(train_step, feed_dict = {xs: batch_xs, ys: batch_ys, keep_prob: 0.5})
        if step % 100 == 0:
            v_xs = mnist.test.images
            v_ys = mnist.test.labels
            #prediction = tf.nn.softmax(fc2_layer)
            #fc2_layer or prediction is good
            bool_pred = tf.equal(tf.argmax(fc2_layer, 1), tf.argmax(v_ys, 1))
            acc = tf.reduce_mean(tf.cast(bool_pred, tf.float32))
            output = sess.run(acc, feed_dict = {xs: v_xs, keep_prob: 1})
            print(output)

三、结果展示

Extracting MNIST_data\train-images-idx3-ubyte.gz
Extracting MNIST_data\train-labels-idx1-ubyte.gz
Extracting MNIST_data\t10k-images-idx3-ubyte.gz
Extracting MNIST_data\t10k-labels-idx1-ubyte.gz
0.1531
0.9581
0.9702
0.9751
0.9824
0.9842
0.9869
0.9866
0.987
0.9885
0.9873
0.9898
0.9903
0.9916
0.987
0.9905
0.9902
0.9911
0.9916
0.99

 

任何问题请加唯一QQ2258205918(名称samylee)!

唯一VX:samylee_csdn

### 配置和使用 Tensorflow-CPU 与 TensorFlow-DirectML-Plugin 为了配置并使用 `tensorflow-cpu` 和 `TensorFlow-DirectML-Plugin` 来进行深度学习模型训练,需遵循特定的安装流程以及环境设置。 #### 安装依赖项 确保环境中已正确安装 Python 版本,并建议创建一个新的虚拟环境来管理项目所需的包。这有助于避免不同版本之间的冲突[^3]。 ```bash python -m venv directml_env source directml_env/bin/activate # Linux or macOS directml_env\Scripts\activate # Windows ``` #### 安装 TensorFlow CPU 及 DirectML 插件 按照官方指导文档中的说明,先安装兼容版本的 `tensorflow-cpu`,再安装 `tensorflow-directml-plugin`: ```bash pip install tensorflow-cpu==2.10 pip install tensorflow-directml-plugin ``` 上述命令会下载并安装指定版本的 TensorFlow CPU 库及其对应的 DirectML 加速插件。 #### 设置环境变量 (可选) 某些情况下可能需要调整系统的环境路径以支持 DirectML 的正常工作。具体操作取决于操作系统类型和个人偏好。通常来说,默认配置已经足够满足大多数需求[^2]。 #### 编写代码示例 下面是一个简单的例子展示如何加载数据集、定义模型结构并通过 GPU 或者集成显卡加速来进行训练过程: ```python import tensorflow as tf from tensorflow.keras import layers, models # 检查是否能够检测到 DirectML 设备 physical_devices = tf.config.experimental.list_physical_devices('DML') print("Detected DML devices:", physical_devices) # 构建简单卷积神经网络模型 model = models.Sequential([ layers.Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(28, 28, 1)), layers.MaxPooling2D(pool_size=(2, 2)), layers.Flatten(), layers.Dense(64, activation='relu'), layers.Dropout(0.5), layers.Dense(10, activation='softmax') ]) # 使用 MNIST 数据集作为测试样本 (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() x_train = x_train.reshape(-1, 28, 28, 1).astype('float32') / 255. x_test = x_test.reshape(-1, 28, 28, 1).astype('float32') / 255. # 编译模型 model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) # 开始训练 history = model.fit(x=x_train, y=y_train, epochs=5, validation_split=0.2) ``` 此脚本会在控制台输出可用的 DirectML 设备信息,并尝试通过这些设备执行计算任务。如果一切顺利,则可以观察到性能上的显著提升。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值