Tensorflow 入门项目实例
最近在deeplearning.ai上跟着做了几个入门项目,受益匪浅,特记录下来以便日后学习:
(一)预测房价,线性回归
通过给出的房价市场价格,1个卧室的100k,2个卧室的150k。。。预测出7个卧室的房价。
只使用单神经元结构来预测房价,使用SGD优化器。
单神经元结构:等价于线性结构
, g=1(即线形激活函数)。
SGD:随机梯度优化。
代码:
import tensorflow as tf
import numpy as np
from tensorflow import keras
model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])]) *单神经元units=1
model.compile(optimizer='sgd', loss='mean_squared_error') *每次迭代训练一个样本且梯度下降运行一次更新一次损失函数。
xs = np.array([1, 2, 3, 4, 5, 6]) * 房间数量
ys = np.array([1,1.5 ,2, 2.5, 3, 3.5]) *将房价特征缩放/100k,加快模型收敛速度
model.fit(xs, ys, epochs=500) *训练500次
print(model.predict([7])) *预测输入为7的输出...
结果:由于给出的样本数量较小,训练500次后预测结果为399.8k,基本拟合出50k+50k*n的房价规则。
.
.
Epoch 497/500
6/6 [==============================] - 0s 509us/sample - loss: 1.3851e-06
Epoch 498/500
6/6 [==============================] - 0s 325us/sample - loss: 1.3749e-06
Epoch 499/500
6/6 [==============================] - 0s 305us/sample - loss: 1.3649e-06
Epoch 500/500
6/6 [==============================] - 0s 388us/sample - loss: 1.3549e-06
[[3.998321]]
(二) 手写数字辨认, Deep NN结构。
通过内置的minist 60000训练集进行训练。
要点:calback函数调用,达到目标值即中断训练。
DNN结构
代码:无锡妇科医院 http://www.bhnnk120.com/
import tensorflow as tf
class myCallback(tf.keras.callbacks.Callback): *callback对象
def on_epoch_end(self, epoch, logs={}):
if(logs.get('acc')>0.99):
print("\nReached 99% accuracy so cancelling training!")
self.model.stop_training = True
mnist = tf.keras.datasets.mnist *导入minist数据集
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
callbacks = myCallback()
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)), *将28*28像素列表化
tf.keras.layers.Dense(512, activation=tf.nn.relu),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=10, callbacks=[callbacks])
结果:
Epoch 1/10
60000/60000 [==============================] - 7s 119us/sample - loss: 0.2020 - acc: 0.9411
Epoch 2/10
60000/60000 [==============================] - 7s 116us/sample - loss: 0.0803 - acc: 0.9753
Epoch 3/10
60000/60000 [==============================] - 7s 124us/sample - loss: 0.0536 - acc: 0.9833
Epoch 4/10
60000/60000 [==============================] - 7s 122us/sample - loss: 0.0373 - acc: 0.9879
Epoch 5/10
59872/60000 [============================>.] - ETA: 0s - loss: 0.0264 - acc: 0.9919
Reached 99% accuracy so cancelling training!
60000/60000 [==============================] - 7s 125us/sample - loss: 0.0263 - acc: 0.9920