1. <ul id="0c1fb"></ul>

      <noscript id="0c1fb"><video id="0c1fb"></video></noscript>
      <noscript id="0c1fb"><listing id="0c1fb"><thead id="0c1fb"></thead></listing></noscript>

      99热在线精品一区二区三区_国产伦精品一区二区三区女破破_亚洲一区二区三区无码_精品国产欧美日韩另类一区

      RELATEED CONSULTING
      相關咨詢
      選擇下列產品馬上在線溝通
      服務時間:8:30-17:00
      你可能遇到了下面的問題
      關閉右側工具欄

      新聞中心

      這里有您想知道的互聯(lián)網營銷解決方案
      Python如何利用神經網絡解決非線性回歸-創(chuàng)新互聯(lián)

      小編給大家分享一下Python如何利用神經網絡解決非線性回歸,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

      成都創(chuàng)新互聯(lián)公司主要從事網站設計、做網站、網頁設計、企業(yè)做網站、公司建網站等業(yè)務。立足成都服務樂至,十年網站建設經驗,價格優(yōu)惠、服務專業(yè),歡迎來電咨詢建站服務:18982081108

      本文實例講述了Python利用神經網絡解決非線性回歸問題。分享給大家供大家參考,具體如下:

      問題描述

      現在我們通常使用神經網絡進行分類,但是有時我們也會進行回歸分析。
      如本文的問題:
      我們知道一個生物體內的原始有毒物質的量,然后對這個生物體進行治療,向其體內注射一個物質,過一段時間后重新測量這個生物體內有毒物質量的多少。
      因此,問題中有兩個輸入,都是標量數據,分別為有毒物質的量和注射物質的量,一個輸出,也就是注射治療物質后一段時間生物體的有毒物質的量。
      數據如下圖:

      Python如何利用神經網絡解決非線性回歸

      其中Dose of Mycotoxins 就是有毒物質,Dose of QCT就是治療的藥物。
      其中藍色底紋的數字就是輸出結果。

      一些說明

      由于本文是進行回歸分析,所以最后一層不進行激活,而直接輸出。
      本文程序使用sigmoid函數進行激活。
      本文程序要求程序有一定的可重復性,隱含層可以指定。

      另外,注意到
      本文將使用數據預處理,也就是將數據減去均值再除以方差,否則使用sigmoid將會導致梯度消失。
      因為數據比較大,比如200,這時輸入200,當sigmoid函數的梯度就是接近于0了。
      與此同時,我們在每一次激活前都進行BN處理,也就是batch normalize,中文可以翻譯成規(guī)范化。
      否則也會導致梯度消失的問題。與預處理情況相同。

      程序

      程序包括兩部分,一部分是模型框架,一個是訓練模型

      第一部分:

      # coding=utf-8
      import numpy as np
      def basic_forard(x, w, b):
        x = x.reshape(x.shape[0], -1)
        out = np.dot(x, w) + b
        cache = (x, w, b)
        return out, cache
      def basic_backward(dout, cache):
        x, w, b = cache
        dout = np.array(dout)
        dx = np.dot(dout, w.T)
        # dx = np.reshape(dx, x.shape)
        # x = x.reshape(x.shape[0], -1)
        dw = np.dot(x.T, dout)
        db = np.reshape(np.sum(dout, axis=0), b.shape)
        return dx, dw, db
      def batchnorm_forward(x, gamma, beta, bn_param):
        mode = bn_param['mode']
        eps = bn_param.get('eps', 1e-5)
        momentum = bn_param.get('momentum', 0.9)
        N, D = x.shape
        running_mean = bn_param.get('running_mean', np.zeros(D, dtype=x.dtype))
        running_var = bn_param.get('running_var', np.zeros(D, dtype=x.dtype))
        out, cache = None, None
        if mode == 'train':
          sample_mean = np.mean(x, axis=0)
          sample_var = np.var(x, axis=0)
          x_hat = (x - sample_mean) / (np.sqrt(sample_var + eps))
          out = gamma * x_hat + beta
          cache = (gamma, x, sample_mean, sample_var, eps, x_hat)
          running_mean = momentum * running_mean + (1 - momentum) * sample_mean
          running_var = momentum * running_var + (1 - momentum) * sample_var
        elif mode == 'test':
          scale = gamma / (np.sqrt(running_var + eps))
          out = x * scale + (beta - running_mean * scale)
        else:
          raise ValueError('Invalid forward batchnorm mode "%s"' % mode)
        bn_param['running_mean'] = running_mean
        bn_param['running_var'] = running_var
        return out, cache
      def batchnorm_backward(dout, cache):
        gamma, x, u_b, sigma_squared_b, eps, x_hat = cache
        N = x.shape[0]
        dx_1 = gamma * dout
        dx_2_b = np.sum((x - u_b) * dx_1, axis=0)
        dx_2_a = ((sigma_squared_b + eps) ** -0.5) * dx_1
        dx_3_b = (-0.5) * ((sigma_squared_b + eps) ** -1.5) * dx_2_b
        dx_4_b = dx_3_b * 1
        dx_5_b = np.ones_like(x) / N * dx_4_b
        dx_6_b = 2 * (x - u_b) * dx_5_b
        dx_7_a = dx_6_b * 1 + dx_2_a * 1
        dx_7_b = dx_6_b * 1 + dx_2_a * 1
        dx_8_b = -1 * np.sum(dx_7_b, axis=0)
        dx_9_b = np.ones_like(x) / N * dx_8_b
        dx_10 = dx_9_b + dx_7_a
        dgamma = np.sum(x_hat * dout, axis=0)
        dbeta = np.sum(dout, axis=0)
        dx = dx_10
        return dx, dgamma, dbeta
      # def relu_forward(x):
      #   out = None
      #   out = np.maximum(0,x)
      #   cache = x
      #   return out, cache
      #
      #
      # def relu_backward(dout, cache):
      #   dx, x = None, cache
      #   dx = (x >= 0) * dout
      #   return dx
      def sigmoid_forward(x):
        x = x.reshape(x.shape[0], -1)
        out = 1 / (1 + np.exp(-1 * x))
        cache = out
        return out, cache
      def sigmoid_backward(dout, cache):
        out = cache
        dx = out * (1 - out)
        dx *= dout
        return dx
      def basic_sigmoid_forward(x, w, b):
        basic_out, basic_cache = basic_forard(x, w, b)
        sigmoid_out, sigmoid_cache = sigmoid_forward(basic_out)
        cache = (basic_cache, sigmoid_cache)
        return sigmoid_out, cache
      # def basic_relu_forward(x, w, b):
      #   basic_out, basic_cache = basic_forard(x, w, b)
      #   relu_out, relu_cache = relu_forward(basic_out)
      #   cache = (basic_cache, relu_cache)
      #
      #   return relu_out, cache
      def basic_sigmoid_backward(dout, cache):
        basic_cache, sigmoid_cache = cache
        dx_sigmoid = sigmoid_backward(dout, sigmoid_cache)
        dx, dw, db = basic_backward(dx_sigmoid, basic_cache)
        return dx, dw, db
      # def basic_relu_backward(dout, cache):
      #   basic_cache, relu_cache = cache
      #   dx_relu = relu_backward(dout, relu_cache)
      #   dx, dw, db = basic_backward(dx_relu, basic_cache)
      #
      #   return dx, dw, db
      def mean_square_error(x, y):
        x = np.ravel(x)
        loss = 0.5 * np.sum(np.square(y - x)) / x.shape[0]
        dx = (x - y).reshape(-1, 1)
        return loss, dx
      class muliti_layer_net(object):
        def __init__(self, hidden_dim, input_dim=2, num_classes=2, weight_scale=0.01, dtype=np.float32, seed=None, reg=0.0, use_batchnorm=True):
          self.num_layers = 1 + len(hidden_dim)
          self.dtype = dtype
          self.reg = reg
          self.params = {}
          self.weight_scale = weight_scale
          self.use_batchnorm = use_batchnorm
          # init all parameters
          layers_dims = [input_dim] + hidden_dim + [num_classes]
          for i in range(self.num_layers):
            self.params['W' + str(i + 1)] = np.random.randn(layers_dims[i], layers_dims[i + 1]) * self.weight_scale
            self.params['b' + str(i + 1)] = np.zeros((1, layers_dims[i + 1]))
            if self.use_batchnorm and i < (self.num_layers - 1):
              self.params['gamma' + str(i + 1)] = np.ones((1, layers_dims[i + 1]))
              self.params['beta' + str(i + 1)] = np.zeros((1, layers_dims[i + 1]))
          self.bn_params = [] # list
          if self.use_batchnorm:
            self.bn_params = [{'mode': 'train'} for i in range(self.num_layers - 1)]
        def loss(self, X, y=None):
          X = X.astype(self.dtype)
          mode = 'test' if y is None else 'train'
          # compute the forward data and cache
          basic_sigmoid_cache = {}
          layer_out = {}
          layer_out[0] = X
          out_basic_forward, cache_basic_forward = {}, {}
          out_bn, cache_bn = {}, {}
          out_sigmoid_forward, cache_sigmoid_forward = {}, {}
          for lay in range(self.num_layers - 1):
            # print('lay: %f' % lay)
            W = self.params['W' + str(lay + 1)]
            b = self.params['b' + str(lay + 1)]
            if self.use_batchnorm:
              gamma, beta = self.params['gamma' + str(lay + 1)], self.params['beta' + str(lay + 1)]
              out_basic_forward[lay], cache_basic_forward[lay] = basic_forard(np.array(layer_out[lay]), W, b)
              out_bn[lay], cache_bn[lay] = batchnorm_forward(np.array(out_basic_forward[lay]), gamma, beta, self.bn_params[lay])
              layer_out[lay + 1], cache_sigmoid_forward[lay] = sigmoid_forward(np.array(out_bn[lay]))
               # = out_sigmoid_forward[lay]
            else:
              layer_out[lay+1], basic_sigmoid_cache[lay] = basic_sigmoid_forward(layer_out[lay], W, b)
          score, basic_cache = basic_forard(layer_out[self.num_layers-1], self.params['W' + str(self.num_layers)], self.params['b' + str(self.num_layers)])
          # print('Congratulations: Loss is computed successfully!')
          if mode == 'test':
            return score
          # compute the gradient
          grads = {}
          loss, dscore = mean_square_error(score, y)
          dx, dw, db = basic_backward(dscore, basic_cache)
          grads['W' + str(self.num_layers)] = dw + self.reg * self.params['W' + str(self.num_layers)]
          grads['b' + str(self.num_layers)] = db
          loss += 0.5 * self.reg * np.sum(self.params['W' + str(self.num_layers)] * self.params['b' + str(self.num_layers)])
          dbn, dsigmoid = {}, {}
          for index in range(self.num_layers - 1):
            lay = self.num_layers - 1 - index - 1
            loss += 0.5 * self.reg * np.sum(self.params['W' + str(lay + 1)] * self.params['b' + str(lay + 1)])
            if self.use_batchnorm:
              dsigmoid[lay] = sigmoid_backward(dx, cache_sigmoid_forward[lay])
              dbn[lay], grads['gamma' + str(lay + 1)], grads['beta' + str(lay + 1)] = batchnorm_backward(dsigmoid[lay], cache_bn[lay])
              dx, grads['W' + str(lay + 1)], grads['b' + str(lay + 1)] = basic_backward(dbn[lay], cache_basic_forward[lay])
            else:
              dx, dw, db = basic_sigmoid_backward(dx, basic_sigmoid_cache[lay])
          for lay in range(self.num_layers):
            grads['W' + str(lay + 1)] += self.reg * self.params['W' + str(lay + 1)]
          return loss, grads
      def sgd_momentum(w, dw, config=None):
        if config is None: config = {}
        config.setdefault('learning_rate', 1e-2)
        config.setdefault('momentum', 0.9)
        v = config.get('velocity', np.zeros_like(w))
        v = config['momentum'] * v - config['learning_rate'] * dw
        next_w = w + v
        config['velocity'] = v
        return next_w, config
      class Solver(object):
        def __init__(self, model, data, **kwargs):
          self.model = model
          self.X_train = data['X_train']
          self.y_train = data['y_train']
          self.X_val = data['X_val']
          self.y_val = data['y_val']
          self.update_rule = kwargs.pop('update_rule', 'sgd_momentum')
          self.optim_config = kwargs.pop('optim_config', {})
          self.lr_decay = kwargs.pop('lr_decay', 1.0)
          self.batch_size = kwargs.pop('batch_size', 100)
          self.num_epochs = kwargs.pop('num_epochs', 10)
          self.weight_scale = kwargs.pop('weight_scale', 0.01)
          self.print_every = kwargs.pop('print_every', 10)
          self.verbose = kwargs.pop('verbose', True)
          if len(kwargs) > 0:
            extra = ', '.join('"%s"' % k for k in kwargs.keys())
            raise ValueError('Unrecognized argements %s' % extra)
          self._reset()
        def _reset(self):
          self.epoch = 100
          self.best_val_acc = 0
          self.best_params = {}
          self.loss_history = []
          self.train_acc_history = []
          self.val_acc_history = []
          self.optim_configs = {}
          for p in self.model.params:
            d = {k: v for k, v in self.optim_config.items()}
            self.optim_configs[p] = d
        def _step(self):
          loss, grads = self.model.loss(self.X_train, self.y_train)
          self.loss_history.append(loss)
          for p, w in self.model.params.items():
            dw = grads[p]
            config = self.optim_configs[p]
            next_w, next_config = sgd_momentum(w, dw, config)
            self.model.params[p] = next_w
            self.optim_configs[p] = next_config
          return loss
        def train(self):
          min_loss = 100000000
          num_train = self.X_train.shape[0]
          iterations_per_epoch = max(num_train / self.batch_size, 1)
          num_iterations = self.num_epochs * iterations_per_epoch
          for t in range(int(num_iterations)):
            loss = self._step()
            if self.verbose:
      #         print(self.loss_history[-1])
              pass
            if loss < min_loss:
              min_loss = loss
              for k, v in self.model.params.items():
                self.best_params[k] = v.copy()
          self.model.params = self.best_params

      第二部分

      import numpy as np
      # import data
      dose_QCT = np.array([0, 5, 10, 20])
      mean_QCT, std_QCT = np.mean(dose_QCT), np.std(dose_QCT)
      dose_QCT = (dose_QCT - mean_QCT ) / std_QCT
      dose_toxins = np.array([0, 0.78125, 1.5625, 3.125, 6.25, 12.5, 25, 50, 100, 200])
      mean_toxins, std_toxins = np.mean(dose_toxins), np.std(dose_toxins)
      dose_toxins = (dose_toxins - mean_toxins ) / std_toxins
      result = np.array([[0, 4.037, 7.148, 12.442, 18.547, 25.711, 34.773, 62.960, 73.363, 77.878],
                [0, 2.552, 4.725, 8.745, 14.436, 21.066, 29.509, 55.722, 65.976, 72.426],
                [0, 1.207, 2.252, 4.037, 7.148, 11.442, 17.136, 34.121, 48.016, 60.865],
                [0, 0.663, 1.207, 2.157, 3.601, 5.615, 8.251, 19.558, 33.847, 45.154]])
      mean_result, std_result = np.mean(result), np.std(result)
      result = (result - mean_result ) / std_result
      # create the train data
      train_x, train_y = [], []
      for i,qct in enumerate(dose_QCT):
        for j,toxin in enumerate(dose_toxins):
          x = [qct, toxin]
          y = result[i, j]
          train_x.append(x)
          train_y.append(y)
      train_x = np.array(train_x)
      train_y = np.array(train_y)
      print(train_x.shape)
      print(train_y.shape)
      import layers_regression
      small_data = {'X_train': train_x,
             'y_train': train_y,
             'X_val': train_x,
             'y_val': train_y,}
      batch_size = train_x.shape[0]
      learning_rate = 0.002
      reg = 0
      model = layers_regression.muliti_layer_net(hidden_dim=[5,5], input_dim=2, num_classes=1, reg=reg, dtype=np.float64)
      solver = layers_regression.Solver(model, small_data, print_every=0, num_epochs=50000, batch_size=batch_size, weight_scale=1,
                       update_rule='sgd_momentum', optim_config={'learning_rate': learning_rate})
      print('Please wait several minutes!')
      solver.train()
      # print(model.params)
      best_model = model
      print('Train process is finised')
      import matplotlib.pyplot as plt
      # %matplotlib inline
      plt.plot(solver.loss_history, '.')
      plt.title('Training loss history')
      plt.xlabel('Iteration')
      plt.ylabel('Training loss')
      plt.show()
      # predict the training_data
      predict = best_model.loss(train_x)
      predict = np.round(predict * std_result + mean_result, 1)
      print('Predict is ')
      print('{}'.format(predict.reshape(4, 10)))
      # print('{}'.format(predict))
      # observe the error between the predict after training with ground truth
      result = np.array([[0, 4.037, 7.148, 12.442, 18.547, 25.711, 34.773, 62.960, 73.363, 77.878],
                [0, 2.552, 4.725, 8.745, 14.436, 21.066, 29.509, 55.722, 65.976, 72.426],
                [0, 1.207, 2.252, 4.037, 7.148, 11.442, 17.136, 34.121, 48.016, 60.865],
                [0, 0.663, 1.207, 2.157, 3.601, 5.615, 8.251, 19.558, 33.847, 45.154]])
      result = result.reshape(4, 10)
      predict = predict.reshape(4, 10)
      error = np.round(result - predict, 2)
      print('error between predict and real data')
      print(error)
      print('The absulate error in all data is %f' % np.sum(np.abs(error)))
      print('The mean error in all data is %f' % np.mean(np.abs(error)))
      # figure the predict map in 3D
      x_1 = (np.arange(0, 20, 0.1) - mean_QCT) / std_QCT
      x_2 = (np.arange(0, 200, 1) - mean_toxins) / std_toxins
      x_test = np.zeros((len(x_1)*len(x_2), 2))
      index = 0
      for i in range(len(x_1)):
        for j in range(len(x_2)):
          x_test[int(index), 0] = x_1[int(i)]
          x_test[int(index), 1] = x_2[int(j)]
          index += 1
      test_pred = best_model.loss(x_test)
      predict = np.round(test_pred * std_result + mean_result, 3)
      from mpl_toolkits.mplot3d import Axes3D
      x_1, x_2 = np.meshgrid(x_1 * std_QCT + mean_QCT, x_2 * std_toxins + mean_toxins)
      figure = plt.figure()
      ax = Axes3D(figure)
      predict = predict.reshape(len(x_1), len(x_2))
      ax.plot_surface(x_1, x_2, predict, rstride=1, cstride=1, cmap='rainbow')
      plt.show()
      # 最后本文將進行一些預測,但預測效果不是很好
      # question 2: predict with given
      dose_QCT_predict = np.ravel(np.array([7.5, 15]))
      dose_QCT_predict_ = (dose_QCT_predict - mean_QCT)/ std_QCT
      dose_toxins_predict = np.array([0, 0.78125, 1.5625, 3.125, 6.25, 12.5, 25, 50, 100, 200])
      dose_toxins_predict_ = (dose_toxins_predict - mean_toxins) / std_toxins
      test = []
      for i,qct in enumerate(dose_QCT_predict):
        for j,toxin in enumerate(dose_toxins_predict):
          x = [qct, toxin]
          test.append(x)
      test = np.array(test)
      print('Please look at the test data:')
      print(test)
      test = []
      for i,qct in enumerate(dose_QCT_predict_):
        for j,toxin in enumerate(dose_toxins_predict_):
          x = [qct, toxin]
          test.append(x)
      test = np.array(test)
      test_pred = best_model.loss(test)
      predict = np.round(test_pred * std_result + mean_result, 1)
      print(predict.reshape(2, 10))

      以上是“Python如何利用神經網絡解決非線性回歸”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注創(chuàng)新互聯(lián)成都網站設計公司行業(yè)資訊頻道!

      另外有需要云服務器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。


      網頁標題:Python如何利用神經網絡解決非線性回歸-創(chuàng)新互聯(lián)
      分享URL:http://ef60e0e.cn/article/jhpid.html
      99热在线精品一区二区三区_国产伦精品一区二区三区女破破_亚洲一区二区三区无码_精品国产欧美日韩另类一区
      1. <ul id="0c1fb"></ul>

        <noscript id="0c1fb"><video id="0c1fb"></video></noscript>
        <noscript id="0c1fb"><listing id="0c1fb"><thead id="0c1fb"></thead></listing></noscript>

        承德市| 新沂市| 水富县| 钟祥市| 涪陵区| 游戏| 分宜县| 四川省| 茂名市| 三都| 罗甸县| 焦作市| 库伦旗| 翁源县| 闽清县| 通海县| 辽源市| 清水河县| 沭阳县| 丁青县| 赤峰市| 台东县| 南充市| 怀远县| 鞍山市| 湘乡市| 廊坊市| 三都| 灯塔市| 马关县| 翁牛特旗| 班玛县| 宝应县| 兴化市| 鹤岗市| 海林市| 民乐县| 洛阳市| 通江县| 太湖县| 通江县|