Skip to content

Commit 8b67fc7

Browse files
committed
update tf2.0
1 parent c7a9f04 commit 8b67fc7

15 files changed

Lines changed: 363 additions & 65 deletions

17tensorflow/tf2/__init__.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
@author:XuMing([email protected])
4+
@description:
5+
"""
6+

17tensorflow/tf2/base_demo.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
@author:XuMing([email protected])
4+
@description:
5+
"""
6+
7+
def test_grad():
8+
import tensorflow as tf
9+
10+
x = tf.Variable(initial_value=4.)
11+
with tf.GradientTape() as tape: # 在 tf.GradientTape() 的上下文内,所有计算步骤都会被记录以用于求导
12+
y = tf.square(x)
13+
y_grad = tape.gradient(y, x) # 计算y关于x的导数
14+
print([y, y_grad]) # 2*x = 2*4 = 8
15+
# y = 16, y_grad = 8
16+
17+
def test_linear():
18+
import tensorflow as tf
19+
20+
X = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
21+
y = tf.constant([[10.0], [20.0]])
22+
23+
24+
class Linear(tf.keras.Model):
25+
def __init__(self):
26+
super().__init__()
27+
self.dense = tf.keras.layers.Dense(
28+
units=1,
29+
activation=None,
30+
kernel_initializer=tf.zeros_initializer(),
31+
bias_initializer=tf.zeros_initializer()
32+
)
33+
34+
def call(self, input):
35+
output = self.dense(input)
36+
return output
37+
38+
39+
# 以下代码结构与前节类似
40+
model = Linear()
41+
optimizer = tf.keras.optimizers.SGD(learning_rate=0.01)
42+
for i in range(100):
43+
with tf.GradientTape() as tape:
44+
y_pred = model(X) # 调用模型 y_pred = model(X) 而不是显式写出 y_pred = a * X + b
45+
loss = tf.reduce_mean(tf.square(y_pred - y))
46+
grads = tape.gradient(loss, model.variables) # 使用 model.variables 这一属性直接获得模型中的所有变量
47+
optimizer.apply_gradients(grads_and_vars=zip(grads, model.variables))
48+
print(model.variables)
49+
50+
if __name__ == '__main__':
51+
test_grad()
52+
test_linear()
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
@author:XuMing([email protected])
4+
@description:
5+
"""
6+
import matplotlib.pyplot as plt
7+
import tensorflow.keras as keras
8+
9+
(train_data, train_label), (test_data, test_label) = keras.datasets.fashion_mnist.load_data()
10+
print(train_data.shape)
11+
print(train_label.shape)
12+
13+
print("#" * 42)
14+
15+
model = keras.Sequential()
16+
model.add(keras.layers.Flatten(input_shape=(28, 28)))
17+
model.add(keras.layers.Dense(128, activation='relu'))
18+
model.add(keras.layers.Dense(128, activation='relu'))
19+
model.add(keras.layers.Dense(128, activation='relu'))
20+
model.add(keras.layers.Dense(10, activation='softmax'))
21+
22+
model.summary()
23+
model.compile(optimizer='adam',
24+
loss='sparse_categorical_crossentropy',
25+
metrics=['acc'],
26+
)
27+
his = model.fit(train_data, train_label, epochs=20, validation_data=(test_data, test_label))
28+
print(his)
29+
30+
pred_y = model.evaluate(test_data, test_label)
31+
32+
plt.plot(his.epoch, his.history.get('loss'), label='loss')
33+
plt.plot(his.epoch, his.history.get('val_loss'), label='val_loss')
34+
plt.legend()
35+
plt.savefig('a1.png')
36+
plt.close()
37+
38+
plt.plot(his.epoch, his.history.get('acc'), label='acc')
39+
plt.plot(his.epoch, his.history.get('val_acc'), label='val_acc')
40+
plt.legend()
41+
plt.savefig('a2.png')
42+
plt.close()
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
@author:XuMing([email protected])
4+
@description:
5+
"""
6+
import matplotlib.pyplot as plt
7+
import tensorflow.keras as keras
8+
9+
(train_data, train_label), (test_data, test_label) = keras.datasets.fashion_mnist.load_data()
10+
print(train_data.shape)
11+
print(train_label.shape)
12+
print("#" * 42)
13+
14+
model = keras.Sequential()
15+
model.add(keras.layers.Flatten(input_shape=(28, 28)))
16+
model.add(keras.layers.Dense(128, activation='relu'))
17+
# model.add(keras.layers.Dropout(0.5))
18+
model.add(keras.layers.Dense(128, activation='relu'))
19+
# model.add(keras.layers.Dropout(0.5))
20+
model.add(keras.layers.Dense(128, activation='relu'))
21+
model.add(keras.layers.Dropout(0.5))
22+
model.add(keras.layers.Dense(10, activation='softmax'))
23+
24+
model.summary()
25+
model.compile(optimizer='adam',
26+
loss='sparse_categorical_crossentropy',
27+
metrics=['acc'],
28+
)
29+
his = model.fit(train_data, train_label, epochs=20, validation_data=(test_data, test_label))
30+
print(his.history.keys())
31+
32+
plt.plot(his.epoch, his.history.get('loss'), label='loss')
33+
plt.plot(his.epoch, his.history.get('val_loss'), label='val_loss')
34+
plt.legend()
35+
plt.savefig('b5.png')
36+
plt.close()
37+
38+
plt.plot(his.epoch, his.history.get('acc'), label='acc')
39+
plt.plot(his.epoch, his.history.get('val_acc'), label='val_acc')
40+
plt.legend()
41+
plt.savefig('b6.png')
42+
plt.close()
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
@author:XuMing([email protected])
4+
@description:
5+
"""
6+
import matplotlib.pyplot as plt
7+
import tensorflow.keras as keras
8+
9+
(train_data, train_label), (test_data, test_label) = keras.datasets.fashion_mnist.load_data()
10+
print(train_data.shape)
11+
print(train_label.shape)
12+
13+
14+
model = keras.Sequential()
15+
model.add(keras.layers.Flatten(input_shape=(28, 28)))
16+
model.add(keras.layers.Dense(128, activation='relu'))
17+
model.add(keras.layers.Dense(10, activation='softmax'))
18+
19+
model.summary()
20+
model.compile(optimizer='adam',
21+
loss='sparse_categorical_crossentropy',
22+
metrics=['acc'],
23+
)
24+
his = model.fit(train_data, train_label, epochs=20, validation_data=(test_data, test_label))
25+
print(his.history.keys())
26+
27+
plt.plot(his.epoch, his.history.get('loss'), label='loss')
28+
plt.plot(his.epoch, his.history.get('val_loss'), label='val_loss')
29+
plt.legend()
30+
plt.savefig('c5.png')
31+
plt.close()
32+
33+
plt.plot(his.epoch, his.history.get('acc'), label='acc')
34+
plt.plot(his.epoch, his.history.get('val_acc'), label='val_acc')
35+
plt.legend()
36+
plt.savefig('c6.png')
37+
plt.close()
-1.57 MB
Binary file not shown.
-4.44 KB
Binary file not shown.
-9.45 MB
Binary file not shown.
-28.2 KB
Binary file not shown.

18tensorlayer/tutorial_mnist.py

Lines changed: 0 additions & 51 deletions
This file was deleted.

0 commit comments

Comments
 (0)