使用TFLearn自定義模型:TFLearn集成在了tf.contirb.learn里
使用TFLearn解決iris分類問題:
from sklearn import model_selection from sklearn import datasets from sklearn import metrics import tensorflow as tf import numpy as np from tensorflow.contrib.learn.python.learn.estimators.estimator import SKCompat # 導入TFLearn learn = tf.contrib.learn # 自定義模型,對於給定的輸入數據(features)和其對應的標簽(target),返回在這些輸入上的預測值、損失值。 def my_model(features,target): # 將預測的目標轉換為one-hot編碼的形式,因為共有三個類別,所以向量長度為3。經過轉化后的類別向量分別為: #(1,0,0),(0,1,0),(0,0,1) target=tf.one_hot(target,3,1,0) # 計算預測值及損失函數。 logits = tf.contrib.layers.fully_connected(features, 3, tf.nn.softmax) loss = tf.losses.softmax_cross_entropy(target, logits) # 創建模型的優化器,並得到優化步驟 train_op=tf.contrib.layers.optimize_loss( loss, # 損失函數 tf.contrib.framework.get_global_step(), # 獲取訓練步數並在訓練時更新 optimizer='Adam', # 定義優化器 learning_rate=0.1) # 定義學習率 # 返回指定數據集上的預測結果,損失值以及優化步驟。 return tf.arg_max(logits, 1), loss, train_op # 加載iris數據集,並划分為訓練集合和測試集合 iris = datasets.load_iris() x_train, x_test, y_train, y_test = model_selection.train_test_split( iris.data, iris.target, test_size=0.2, random_state=0) x_train, x_test = map(np.float32, [x_train, x_test]) # 對自定義模型進行封裝 classifier = SKCompat(learn.Estimator(model_fn=my_model, model_dir="model_1")) # 使用封裝好的模型和訓練數據執行100輪迭代 classifier.fit(x_train, y_train, steps=800) # 使用訓練好的模型進行預測 y_predicted = [i for i in classifier.predict(x_test)] # 計算模型的准確率 score = metrics.accuracy_score(y_test, y_predicted) print('Accuracy: %.2f%%' % (score * 100))
預測正弦函數:
import numpy as np import tensorflow as tf from tensorflow.contrib.learn.python.learn.estimators.estimator import SKCompat import matplotlib as mpl mpl.use('Agg') from matplotlib import pyplot as plt learn=tf.contrib.learn HIDDEN_SIZE = 30 # LSTM中隱藏節點的個數 NUM_LAYERS = 2 # LSTM的層數 TIMESTEPS = 10 # 循環神經網絡的截斷長度 TRAINING_STEPS = 10000 # 訓練輪數 BATCH_SIZE = 32 TRAINING_EXAMPLES = 10000 # 訓練數據個數 TESTING_EXAMPLES = 1000 # 測試數據個數 SAMPLE_GAP = 0.01 # 采樣間隔 def generate_data(seq): X = [] Y = [] # 序列的第i項和后面的TIMESTEPS-1項合在一起作為輸入;第i+TIMESTEPS項作為輸出。即用sin函數前面的TIMESTEPS個點的信息, # 預測第i+TIMESTEPS個點的函數值。 for i in range(len(seq) - TIMESTEPS - 1): X.append([seq[i:i + TIMESTEPS]]) Y.append([seq[i + TIMESTEPS]]) return np.array(X, dtype=np.float32), np.array(Y, dtype=np.float32) def LstmCell(): lstm_cell = tf.contrib.rnn.BasicLSTMCell(HIDDEN_SIZE,state_is_tuple=True) return lstm_cell def lstm_model(X, y): # 使用多層的lstm結構 cell = tf.contrib.rnn.MultiRNNCell([LstmCell() for _ in range(NUM_LAYERS)]) # 使用tensorflow接口將多層的LSTM結構連接成RNN網絡並計算其前向傳播結果。 output, _ = tf.nn.dynamic_rnn(cell, X, dtype=tf.float32) output = tf.reshape(output, [-1, HIDDEN_SIZE]) # 通過無激活函數的全聯接層計算線性回歸,並將數據壓縮成一維數組的結構。 predictions = tf.contrib.layers.fully_connected(output, 1, None) # 將predictions和labels調整統一的shape labels = tf.reshape(y, [-1]) predictions=tf.reshape(predictions, [-1]) loss = tf.losses.mean_squared_error(predictions, labels) # 創建模型優化器並得到優化步驟 train_op=tf.contrib.layers.optimize_loss(loss,tf.contrib.framework.get_global_step(), optimizer='Adagrad',learning_rate=0.1) return predictions,loss,train_op # 封裝之前定義的lstm。 regressor = SKCompat(learn.Estimator(model_fn=lstm_model,model_dir="model_2")) # 用正弦函數生成訓練和測試數據 test_start=TRAINING_EXAMPLES*SAMPLE_GAP test_end=(TRAINING_EXAMPLES+TESTING_EXAMPLES)*SAMPLE_GAP train_X,train_y=generate_data(np.sin(np.linspace(0,test_start,TRAINING_EXAMPLES,dtype=np.float32))) test_X,test_y=generate_data(np.sin(np.linspace(test_start,test_end,TESTING_EXAMPLES,dtype=np.float32))) # 調用fit函數訓練模型 regressor.fit(train_X,train_y,batch_size=BATCH_SIZE,steps=TRAINING_STEPS) # 預測 predicted=[[pred] for pred in regressor.predict(test_X)] # 計算rmse作為評價指標 rmse=np.sqrt(((predicted-test_y)**2).mean(axis=0)) print('Mean Square Error is: {}'.format(rmse[0])) # 對預測的sin函數曲線進行繪圖
%matplotlib inline
plot_predicted, = plt.plot(predicted, label='predicted',color='red')
plot_test, = plt.plot(test_y-0.1, label='real_sin',color='green')
plt.legend([plot_predicted, plot_test],['predicted', 'real_sin'])
plt.show()
