deepai新课代码The Hello World of Deep Learning with Neural Networks的tf1.0版本

伴随着Tensorflow2.0的发布,前段时间吴恩达在Coursera上发布了配套新课《tensorflow:从入门到精通》,主要由Laurence Moroney讲授,共四周的内容,课程如图所示。

deepai新课代码The Hello World of Deep Learning with Neural Networks的tf1.0版本

在第一课中,老师实现了一个简单的神经元,并在colab上可以在线运行。代码如下:

import tensorflow as tf
import numpy as np
from tensorflow import keras

model = tf.keras.Sequential([keras.layers.Dense(unit=1,input_shape=[1])])
model.compile(optimizer='sgd',loss='mean_squared_error')

xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)
ys = np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype = float)

model.fit(xs, ys, epochs=500)

print(model.predict([10.0]))

你可以直接在colab上运行,是没有问题的,但是由于很多时候都打不开colab,所以我在本地环境下试了一波。结果各种报错,主要原因还是在于环境和版本问题。我不是很清楚老师使用的版本,我使用的是Python3.5和tensorflow1.4.0,所以语法上有些不同,经过调试,我最终还是跑通了,所以想把代码分享给小伙伴们,一起入门吧~

import tensorflow as tf
import numpy as np
from tensorflow import keras
from keras.models import Sequential

#指定GPU,因为我在多GPU的服务器上运行的,所以有下面这段代码
import os
os.environ["CUDA_VISIBLE_DEVICES"] = '6'
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.5
config.gpu_options.allow_growth = True
sess = tf.Session(config = config)

#定义神经网络,这里keras和Sequential间多了个models
model = tf.keras.models.Sequential([keras.layers.Dense(unit=1,input_shape=[1])])
model.compile(optimizer='sgd',loss='mean_squared_error')

xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)
ys = np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype = float)

model.fit(xs, ys, epochs=500)

x = np.array([10.0],dtype=float)
print(model.predict([x]))