小白初学tensorflow入手教程——持续更新

这篇教程针对Windows用户和TensorFlow 2.0,记录了学习过程中遇到的挑战,如更新代码以适配新版本,错误修复以及弃用功能的替代方案。作者分享了在mnist数据集上训练模型的经验,包括解决tensorflow/example/tutorials不再支持的问题,并转向使用keras。尽管遇到升级后无法运行的问题,但最终成功运行了程序。
摘要由CSDN通过智能技术生成

看过很多视频和教程,适用与windows和tf2.0版本的教程很少。。决定从tensorflow中文社区重新开始学习。但是也会有很多报错,把诸多修改后的小代码如下所示。
变量:

# -*- coding: utf-8 -*-
"""
Created on Sat Nov  2 10:59:18 2019

@author: lsf81
"""

import tensorflow as tf
state=tf.Variable(0,name="counter")
one=tf.constant(1)
new_value=tf.add(state,one)
update=tf.compat.v1.assign(state,new_value)
init_op=tf.compat.v1.global_variables_initializer()
with tf.compat.v1.Session() as sess:
    sess.run(init_op)
    print(sess.run(state))
    for _ in range(3):
        sess.run(update)
        print(sess.run(state))

运行结果:在这里插入代码片
注意:原版update = tf.assign(state, new_value)都更新成了update=tf.compat.v1.assign(state,new_value)
Fetch:

import tensorflow as tf
input1 = tf.constant(3.0)
input2 = tf.constant(2.0)
input3 = tf.constant(5.0)
intermed = tf.compat.v1.add(input2, input3)
mul = tf.multiply(input1, intermed)

with tf.compat.v1.Session() as sess:
  result = sess.run([mul, intermed])
  print(result)

必须要注意,在现在版本中,mul调用方式变成了multiply,and sub 变成了subtract。
Feed:


```python
import tensorflow as tf
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.multiply(input1, input2)

with tf.compat.v1.Session() as sess:
  print(sess.run([output],feed_dict={
   input1:[7.],input2:[2.]}))

注意:官网上是input1 = tf.placeholder(tf.types.float32),其中types是多余的。

mnist详细版教程
https://blog.csdn.net/cqrtxwd/article/details/79028264

input_data.py下载地址
https://blog.csdn.net/weixin_43159628/article/details/83241345

搞了一下午:最新更新如下:
出现Please use alternatives such as official/mnist/dataset.py from tensorflow/models.的错误。原因是新版本不再支持tensorflow/example/tutorials函数库了,全部更新到keras里面了,具体代码如下

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

#mnist=input_data.read_data_sets('./MNIST_data/',one_hot=True)
#sess=tf.InteractiveSession()
#print('Training data size: ', mnist.train.num_examples)
mnist=tf.keras.datasets.mnist
(X_train, y_train), (X_test, y_test) = mnist.load_data()
print(X_train.shape) # out: (60000, 28, 28)
print(y_train.shape) # out: (60000,)

参考博文:https://blog.csdn.net/u011106767/article/details/93879120
后续问题遇到了keras中mnist分类的问题。见以下博文:
https://blog.csdn.net/Yumi_huang/article/details/82351173

参考上面的博文:

在这里插入代# -*- coding: utf-8 -*-
"""
Created on Sat Nov  2 18:56:47 2019

@author: lsf81
"""
import numpy as np
import matplotlib.pyplot as plt

path = r"F:\python\Anaconda\Lib\site-packages\keras_applications\examples\mnist.npz"
f = np.load(path)
x_train, y_train = f['x_train'], f['y_train']
x_test, y_test = f['x_test'], f['y_test']
f.close()
print(x_train.shape)
print(x_test.shape)
for i in range(9):
    plt.subplot(3,3,i+1)
    plt.imshow(x_train[i], cmap='gray', interpolation='none')
    plt.title("Class {}".format(y_train[i]))
plt.show()


from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Activation, Dropout
from keras.utils import np_utils
import numpy as np
import matplotlib.pyplot as plt
from keras.optimizers import RMSprop

path = r"F:\python\Anaconda\Lib\site-packages\keras_applications\examples\mnist.npz"
f = np.load(path)

x_train, y_train = f['x_train'], f['y_train']
x_test, y_test = f['x_test'], f['y_test']
f.close()
# print(x_train.shape)
# print(x_test.shape)
# for i in range(9):
#     plt.subplot(3,3,i+1)
#     plt.imshow(x_train[i], cmap='gray', interpolation='none')
#     plt.title("Class {}".format(y_train[i]))
# plt.show()

#将二维数据变为一维
X_train = x_train.reshape(len(x_train), -1)
X_test = x_test.reshape(len(x_test), -1)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
# Normalization.scaling it so that all values are in the [0, 1] interval. 
X_train = (X_train - 127) / 127
X_test = (X_test - 127) / 127

#one hot encoding
y_train = np_utils.to_categorical(y_train, num_classes=10)
y_test = np_utils.to_categorical(y_test, num_classes=10)
model = Sequential([
    Dense(512, input_dim=784),
    Activation('relu'),
    Dropout(0.2),
    # Dense(512),
    # Activation('relu'),
    # Dropout(0.2),
    Dense(10),
    Activation('softmax'),

])
rmsprop = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)

# We add metrics to get more results you want to see
model.compile(optimizer=rmsprop,
              loss='categorical_crossentropy',
              metrics=['accuracy'])

print('Training ------------')
# Another way to train the model
model.fit(X_train, y_train, epochs=20, batch_size=100)

print('\nTesting ------------')
# Evaluate the model with the metrics we defined earlier
loss, accuracy = model.evaluate(X_test, y_test)

print('test loss: ', loss)
print('test accuracy: ', accuracy)
码片

最后的结果为:

runfile('E:/Users/lsf81/Desktop/cnnmnist2.py', wdir='E:/Users/lsf81/Desktop')
(60000, 28, 28)
(10000, 28, 28)


Using TensorFlow backend.
WARNING:tensorflow:From F:\python\Anaconda\envs\tensorflow\lib\site-packages\keras\backend\tensorflow_backend.py:74: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead.

WARNING:tensorflow:From F:\python\Anaconda\envs\tensorflow\lib\site-pa
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值