一.拟合线性函数
import numpy as np
import tensorflow as tf
x_data = np.random.rand(100)
noise = np.random.normal(0,0.01,x_data.shape)
y_data = x_data*0.1 + 0.2 + noise
model = tf.keras.Sequential()
model.add(Dense(units=1, input_dim=1))
model.compile(optimizer=SGD(0.03), loss='mse')
for i in range(2002):
cost = model.train_on_batch(x_data,y_data)
if i%500 == 0:
print('cost--',cost)
y_pred = model.predict(x_data)
二.拟合非线性函数
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
x_data = np.linspace(-0.5,0.5,200)[:,np.newaxis]
noise = np.random.normal(0,0.02,x_data.shape)
y_data = np.square(x_data) + noise
model = tf.keras.Sequential()
model.add(Dense(input_dim=1,activation='tanh',units=10))
model.add(Dense(activation='tanh',units=1))
model.compile(optimizer=SGD(0.3),loss='mse')
for i in range(3001):
cost = model.train_on_batch(x_data,y_data)
if i%1000 == 0:
print("cost--",cost)
y_pred = model.predict(x_data)
plt.subplot(2,2,i/1000 + 1)
plt.scatter(x_data,y_data)
plt.plot(x_data,y_pred,'r-')
plt.title("picture:" + str(i/1000 + 1))
plt.show()
三.mnist分类
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
'''
数据载入的时候已经划分好了训练集和测试集
x_train(60000,28,28)
y_train(60000)
x_test (10000,28,28)
y_test (10000)
'''
mnist = tf.keras.datasets.mnist
(x_train,y_train),(x_test,y_test) = mnist.load_data()
x_test = x_test/255.0
x_train = x_train/255.0
y_train = tf.keras.utils.to_categorical(y_train,num_classes=10)
y_test = tf.keras.utils.to_categorical(y_test,num_classes=10)
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28,28)),
tf.keras.layers.Dense(10,activation='softmax')
])
sgd = SGD(0.1)
model.compile(optimizer=sgd,loss='mse',metrics=['accuracy'])
model.fit(x_train,y_train,epochs=10,batch_size=32,validation_data=(x_test,y_test))
四.鸢尾花分类
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
import tensorflow as tf
iris = load_iris()
x = iris.data
y = iris.target
x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.3,random_state=0)
model = tf.keras.models.Sequential([
Dense(10,activation='relu',input_dim=(4)),
Dense(10,activation='relu'),
Dense(3,activation='softmax')
])
model.compile(optimizer='adam',loss='mse',metrics=['accuracy'])
model.fit(x_train,y_train,epochs=10,batch_size=1,verbose=1)
y_predict = model.predict(x_test)
loss,accuarcy = model.evaluate(x_test,y_test,verbose=1)
print('loss---',loss)
print('accuarcy---',accuarcy)