1. 程式人生 > >利用異或資料集演示過擬合問題

利用異或資料集演示過擬合問題

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from sklearn.utils import shuffle
from matplotlib.colors import colorConverter, ListedColormap
# 對於上面的fit可以這麼擴充套件變成動態的
from sklearn.preprocessing import OneHotEncoder
def onehot(y,start,end):
    ohe = OneHotEncoder()
    a = np.linspace(start,end-1,end-start)
    b =np.reshape(a,[-1,1]).astype(np.int32)
    ohe.fit(b)
    c=ohe.transform(y).toarray()  
    return c  
    
def generate(sample_size, num_classes, diff,regression=False):
    np.random.seed(10)
    mean = np.random.randn(2)
    cov = np.eye(2)  
    
    #len(diff)
    samples_per_class = int(sample_size/num_classes)
    X0 = np.random.multivariate_normal(mean, cov, samples_per_class)
    Y0 = np.zeros(samples_per_class)
    
    for ci, d in enumerate(diff):
        X1 = np.random.multivariate_normal(mean+d, cov, samples_per_class)
        Y1 = (ci+1)*np.ones(samples_per_class)
    
        X0 = np.concatenate((X0,X1))
        Y0 = np.concatenate((Y0,Y1))
  
    if regression==False: #one-hot  0 into the vector "1 0
        Y0 = np.reshape(Y0,[-1,1])        
        #print(Y0.astype(np.int32))
        Y0 = onehot(Y0.astype(np.int32),0,num_classes)
        #print(Y0)
    X, Y = shuffle(X0, Y0)
    #print(X, Y)
    return X,Y   
'''
構建異或資料集
'''  
# Ensure we always get the same amount of randomness
np.random.seed(10)
input_dim = 2
num_classes =4
X, Y = generate(320,num_classes,  [[3.0,0],[3.0,3.0],[0,3.0]],True)
Y=Y%2
#colors = ['r' if l == 0.0 else 'b' for l in Y[:]]
#plt.scatter(X[:,0], X[:,1], c=colors)
xr=[]
xb=[]
for(l,k) in zip(Y[:],X[:]):
    if l == 0.0 :
        xr.append([k[0],k[1]])        
    else:
        xb.append([k[0],k[1]])
xr =np.array(xr)
xb =np.array(xb)      
plt.scatter(xr[:,0], xr[:,1], c='r',marker='+')
plt.scatter(xb[:,0], xb[:,1], c='b',marker='o')
plt.show()
'''
定義網路模型
'''
Y=np.reshape(Y,[-1,1])
learning_rate = 1e-4
n_input  = 2
n_label  = 1
#n_hidden = 2#欠擬合
n_hidden = 200
x = tf.placeholder(tf.float32, [None,n_input])
y = tf.placeholder(tf.float32, [None, n_label])
weights = {
    'h1': tf.Variable(tf.truncated_normal([n_input, n_hidden], stddev=0.1)),
    'h2': tf.Variable(tf.random_normal([n_hidden, n_label], stddev=0.1))
    }
biases = {
    'h1': tf.Variable(tf.zeros([n_hidden])),
    'h2': tf.Variable(tf.zeros([n_label]))
    }    
layer_1 = tf.nn.relu(tf.add(tf.matmul(x, weights['h1']), biases['h1']))
#y_pred = tf.nn.tanh(tf.add(tf.matmul(layer_1, weights['h2']),biases['h2']))
#y_pred = tf.nn.relu(tf.add(tf.matmul(layer_1, weights['h2']),biases['h2']))#區域性最優解
#y_pred = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, weights['h2']),biases['h2']))
#Leaky relus  40000次 ok
layer2 =tf.add(tf.matmul(layer_1, weights['h2']),biases['h2'])
y_pred = tf.maximum(layer2,0.01*layer2)
loss=tf.reduce_mean((y_pred-y)**2)
train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss)
#載入
sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
    
for i in range(20000):#  
  
  _, loss_val = sess.run([train_step, loss], feed_dict={x: X, y: Y})
  if i % 1000 == 0:
    print ("Step:", i, "Current loss:", loss_val)
#colors = ['r' if l == 0.0 else 'b' for l in Y[:]]
#plt.scatter(X[:,0], X[:,1], c=colors)
'''
新增視覺化
320個點放到模型中,然後將其在直角座標系中顯示出來。
'''
xr=[]
xb=[]
for(l,k) in zip(Y[:],X[:]):
    if l == 0.0 :
        xr.append([k[0],k[1]])        
    else:
        xb.append([k[0],k[1]])
xr =np.array(xr)
xb =np.array(xb)      
plt.scatter(xr[:,0], xr[:,1], c='r',marker='+')
plt.scatter(xb[:,0], xb[:,1], c='b',marker='o')
    
nb_of_xs = 200
xs1 = np.linspace(-3, 10, num=nb_of_xs)
xs2 = np.linspace(-3, 10, num=nb_of_xs)
xx, yy = np.meshgrid(xs1, xs2) # create the grid
# Initialize and fill the classification plane
classification_plane = np.zeros((nb_of_xs, nb_of_xs))
for i in range(nb_of_xs):
    for j in range(nb_of_xs):
        #classification_plane[i,j] = nn_predict(xx[i,j], yy[i,j])
        classification_plane[i,j] = sess.run(y_pred, feed_dict={x: [[ xx[i,j], yy[i,j] ]]} )
        classification_plane[i,j] = int(classification_plane[i,j])
# Create a color map to show the classification colors of each grid point
cmap = ListedColormap([
        colorConverter.to_rgba('r', alpha=0.30),
        colorConverter.to_rgba('b', alpha=0.30)])
# Plot the classification plane with decision boundary and input samples
plt.contourf(xx, yy, classification_plane, cmap=cmap)
plt.show()
'''
12 個點進行驗證過擬合
'''
xTrain, yTrain = generate(12,num_classes,  [[3.0,0],[3.0,3.0],[0,3.0]],True)
yTrain=yTrain%2
#colors = ['r' if l == 0.0 else 'b' for l in yTrain[:]]
#plt.scatter(xTrain[:,0], xTrain[:,1], c=colors)
xr=[]
xb=[]
for(l,k) in zip(yTrain[:],xTrain[:]):
    if l == 0.0 :
        xr.append([k[0],k[1]])        
    else:
        xb.append([k[0],k[1]])
xr =np.array(xr)
xb =np.array(xb)      
plt.scatter(xr[:,0], xr[:,1], c='r',marker='+')
plt.scatter(xb[:,0], xb[:,1], c='b',marker='o')
#plt.show()
yTrain=np.reshape(yTrain,[-1,1])           
print ("loss:\n", sess.run(loss, feed_dict={x: xTrain, y: yTrain}))          
nb_of_xs = 200
xs1 = np.linspace(-1, 8, num=nb_of_xs)
xs2 = np.linspace(-1, 8, num=nb_of_xs)
xx, yy = np.meshgrid(xs1, xs2) # create the grid
# Initialize and fill the classification plane
classification_plane = np.zeros((nb_of_xs, nb_of_xs))
for i in range(nb_of_xs):
    for j in range(nb_of_xs):
        #classification_plane[i,j] = nn_predict(xx[i,j], yy[i,j])
        classification_plane[i,j] = sess.run(y_pred, feed_dict={x: [[ xx[i,j], yy[i,j] ]]} )
        classification_plane[i,j] = int(classification_plane[i,j])
# Create a color map to show the classification colors of each grid point
cmap = ListedColormap([
        colorConverter.to_rgba('r', alpha=0.30),
        colorConverter.to_rgba('b', alpha=0.30)])
# Plot the classification plane with decision boundary and input samples
plt.contourf(xx, yy, classification_plane, cmap=cmap)
plt.show()   

相關推薦

利用資料演示問題

import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from sklearn.utils import shuffle from matplotlib.colors import colorConverter,

正則化方法/防止提高泛化能力的方法:L1和L2 regularization、資料擴增、dropout

正則化方法:防止過擬合,提高泛化能力 在訓練資料不夠多時,或者overtraining時,常常會導致overfitting(過擬合)。其直觀的表現如下圖所示,隨著訓練過程的進行,模型複雜度增加,在training data上的error漸漸減小,但是在驗證集上的e

斯坦福大學公開課機器學習: advice for applying machine learning - evaluatin a phpothesis(怎麽評估學習算法得到的假設以及如何防止

class 中一 技術分享 cnblogs 訓練數據 是否 多個 期望 部分 怎樣評價我們的學習算法得到的假設以及如何防止過擬合和欠擬合的問題。 當我們確定學習算法的參數時,我們考慮的是選擇參數來使訓練誤差最小化。有人認為,得到一個很小的訓練誤差一定是一件好事。但其實,僅

利用判斷二進位制數中的1的個數的奇偶性

文章目錄 異或壓縮奇偶性資訊 一位一位地異或 利用二叉樹思想異或 關於有符號數和算術右移 利用x &= x-1求二進位制1個數 利用邏輯右移求二進位制1個數 兩個二進位制數異或後結果的1個數的奇偶性 異或

如何利用Keras中的權重約束減少深度神經網路中的

                                          &nb

泛化能力、訓練、測試、K折交叉驗證、假設空間、欠、正則化(L1正則化、L2正則化)、超引數

泛化能力(generalization): 機器學習模型。在先前未觀測到的輸入資料上表現良好的能力叫做泛化能力(generalization)。 訓練集(training set)與訓練錯誤(training error): 訓練機器學習模型使用的資料集稱為訓練集(tr

資料處理-------利用jieba對資料進行分詞和統計頻數

一,對txt檔案中出現的詞語的頻數統計再找出出現頻率多的 二,程式碼: import re from collections import Counter import jieba def cut_word(datapath): with open(

如何利用運算進行簡單加密解密

利用“^”異或運算對字串進行加密 思路:1.先建立字串輸入的Scanner; 2.通過char[] array = password.toCharArray();// 獲取字元陣列; 3.遍歷字元陣列,按目前理解要用到遍歷:陣列所有元素進行訪問,比如你要輸出數組裡所有

【自然語言處理入門】01:利用jieba對資料進行分詞,並統計詞頻

一、基本要求 使用jieba對垃圾簡訊資料集進行分詞,然後統計其中的單詞出現的個數,找到出現頻次最高的top100個詞。 二、完整程式碼 # -*- coding: UTF-8 -*- fr

[DeeplearningAI筆記]改善深層神經網路1.1_1.3深度學習實用層面_偏差/方差/欠//訓練/驗證/測試

覺得有用的話,歡迎一起討論相互學習~Follow Me 1.1 訓練/開發/測試集 對於一個數據集而言,可以將一個數據集分為三個部分,一部分作為訓練集,一部分作為簡單交叉驗證集(dev)有時候也成為驗證集,最後一部分作為測試集(test).接下來我們開始

Hinton Neural Networks課程筆記3e:如何利用梯度值訓練網路(學習策略和抑制)

這裡只是開了個頭,籠統的講了講如何利用梯度值訓練網路,包括優化演算法的部分以及防止過擬合的部分。 1. 優化演算法的部分 這裡只提到了三個部分(具體要到第六節才講):batch相關的抉擇、學習率相關的選擇、優化演算法的選擇。 batch相關的選項有

利用^進行密碼的加密和解密

import java.util.Scanner; public class Example {     public static void main(String[] args) {         Scanner scan = new Scanner(System.i

機器學習的防止方法

alt int 變化 http 處理 提高 pro 無法 structure 過擬合 ??我們都知道,在進行數據挖掘或者機器學習模型建立的時候,因為在統計學習中,假設數據滿足獨立同分布(i.i.d,independently and identically distribu

機器學習中防止方法

從數據 tro 輸出 效果 沒有 imagenet neu 效率 公式 過擬合 ??在進行數據挖掘或者機器學習模型建立的時候,因為在統計學習中,假設數據滿足獨立同分布,即當前已產生的數據可以對未來的數據進行推測與模擬,因此都是使用歷史數據建立模型,即使用已經產生的數據去訓練

擬合 log text data ng- class article ast art 過擬合

drop out為什麽能夠防止

正則 復雜 訓練數據 它的 一個 解決 過程 drop 投票 來源知乎: dropout 的過程好像很奇怪,為什麽說它可以解決過擬合呢?(正則化) 取平均的作用: 先回到正常的模型(沒有dropout),我們用相同的訓練數據去訓練5個不同的神經網絡,一般會得到

Tensorflow學習教程------

模型 float softmax 一個 返回 之間 zeros 函數 size 回歸:過擬合情況 / 分類過擬合 防止過擬合的方法有三種: 1 增加數據集 2 添加正則項 3 Dropout,意思就是訓練的時候隱層神經元每次隨機抽取部分參與訓練。部分不參與 最

的問題

csdn 修改 dom var n) ces 復雜 lar 錯誤 交叉驗證的方法在訓練過程中是否有用? 1、過擬合的表現? 1)訓練集誤差小,評估集誤差大;2)訓練集誤差還在減小,評估集誤差開始波動 2、過擬合的原因? 模型復雜,dvc高——對於決策

20171028機器學習之線性回歸問題的解決方案

ces 函數 彈性 alpha mach rom 定性 ast cep 在函數中加入一個正則項: 三種方式: 一、Ridge回歸(嶺回歸):   優點:具有較高的準確性、魯棒性以及穩定性   缺點:求解速度慢 二、Lasso回歸:   優點:求解速度快(原理降維計算

細品 - 與模型選擇*

最優 優化 並且 情況下 最小化 wid 正方 tro 預測 欠擬合和過擬合   欠擬合是指模型不能很好的捕獲到數據特征,不能很好的擬合數據,學習能力底下。解決方法:增加模型的復雜度        過擬合是指模型不僅僅學習了數據集中的有效信息,也學習到了其中的噪音數據,使得