Python - How to cross check the obtained W and B intercepts in SGD for Linear Regression?












0















I have manually implemented SGD for Linear Regression using the partial derivates. I am working on Boston housing prices dataset from SKlearn. The input to my UDF is a (train) dataframe with standardised data except the target column.



X_train, X_test, y_train, y_test = train_test_split(df.loc[:, df.columns != 'target'], df.target, test_size=0.15, random_state=42)
dt_scaler = StandardScaler().fit(X_train)
scaler_data = dt_scaler.transform(X_train)
final_ds = pd.DataFrame(scaler_data, columns= boston.feature_names)
final_ds['target'] = y_train
final_ds.target = final_ds.target.fillna((df.target.mean()))


Now my UDF is,



def best_w_b(data):
w0 = np.random.normal(0, 1, (boston.data.shape[1],)).T
b0 = np.random.normal(0, 1)
r = 1
i = 1
while(1):
k = data.sample(n=150 ,replace = True)
for i in range(0,150,1):
der_w= np.zeros(boston.data.shape[1]) ;der_b = 0
der_w += np.dot(-2 * k.iloc[i][k.columns !='target'].T ,(k.iloc[i].target - np.dot(w0,k.iloc[i][k.columns !='target'].values) - b0))
der_b += (-2 * (k.iloc[i].target - np.dot(w0,k.iloc[i][k.columns !='target'].values) - b0 ))
w1 = np.subtract(w0,(r * der_w/150))
b1 = b0 - (r * der_b/150)
w_dist = np.linalg.norm(w0-w1)
b_dist = np.linalg.norm(b0-b1)
if (w0==w1).all():
return w0,b0
else:
w0 = w1
b0 = b1
r = r/2
i = i + 1


After running this method I have obtained the W and B values so if I use Summation 0 to n-1 (Y-Y_hat)^2 /n on the train data should not I be getting a value around 0.



Here is the code:



 error = 0
for i in range(0,X_train.shape[0],1):
error = error + (final_ds.iloc[i].target - (np.dot(optimal_w,final_ds.iloc[i][final_ds.columns !='target']) + optimal_b))**2
print(error/X_train.shape[0])


I am getting an error around 582. Is it the right way to test?



PS:



Optimal W is : [-0.22178286, -1.30943816, -0.61933446, 1.07290039, -0.96299363,-0.59459475, -1.4094494 , 0.2022922 , -1.45901487, 0.00561458,-0.31858595, -0.71790656, -0.97285501]
Optimal B is : 1.179334612848228










share|improve this question



























    0















    I have manually implemented SGD for Linear Regression using the partial derivates. I am working on Boston housing prices dataset from SKlearn. The input to my UDF is a (train) dataframe with standardised data except the target column.



    X_train, X_test, y_train, y_test = train_test_split(df.loc[:, df.columns != 'target'], df.target, test_size=0.15, random_state=42)
    dt_scaler = StandardScaler().fit(X_train)
    scaler_data = dt_scaler.transform(X_train)
    final_ds = pd.DataFrame(scaler_data, columns= boston.feature_names)
    final_ds['target'] = y_train
    final_ds.target = final_ds.target.fillna((df.target.mean()))


    Now my UDF is,



    def best_w_b(data):
    w0 = np.random.normal(0, 1, (boston.data.shape[1],)).T
    b0 = np.random.normal(0, 1)
    r = 1
    i = 1
    while(1):
    k = data.sample(n=150 ,replace = True)
    for i in range(0,150,1):
    der_w= np.zeros(boston.data.shape[1]) ;der_b = 0
    der_w += np.dot(-2 * k.iloc[i][k.columns !='target'].T ,(k.iloc[i].target - np.dot(w0,k.iloc[i][k.columns !='target'].values) - b0))
    der_b += (-2 * (k.iloc[i].target - np.dot(w0,k.iloc[i][k.columns !='target'].values) - b0 ))
    w1 = np.subtract(w0,(r * der_w/150))
    b1 = b0 - (r * der_b/150)
    w_dist = np.linalg.norm(w0-w1)
    b_dist = np.linalg.norm(b0-b1)
    if (w0==w1).all():
    return w0,b0
    else:
    w0 = w1
    b0 = b1
    r = r/2
    i = i + 1


    After running this method I have obtained the W and B values so if I use Summation 0 to n-1 (Y-Y_hat)^2 /n on the train data should not I be getting a value around 0.



    Here is the code:



     error = 0
    for i in range(0,X_train.shape[0],1):
    error = error + (final_ds.iloc[i].target - (np.dot(optimal_w,final_ds.iloc[i][final_ds.columns !='target']) + optimal_b))**2
    print(error/X_train.shape[0])


    I am getting an error around 582. Is it the right way to test?



    PS:



    Optimal W is : [-0.22178286, -1.30943816, -0.61933446, 1.07290039, -0.96299363,-0.59459475, -1.4094494 , 0.2022922 , -1.45901487, 0.00561458,-0.31858595, -0.71790656, -0.97285501]
    Optimal B is : 1.179334612848228










    share|improve this question

























      0












      0








      0








      I have manually implemented SGD for Linear Regression using the partial derivates. I am working on Boston housing prices dataset from SKlearn. The input to my UDF is a (train) dataframe with standardised data except the target column.



      X_train, X_test, y_train, y_test = train_test_split(df.loc[:, df.columns != 'target'], df.target, test_size=0.15, random_state=42)
      dt_scaler = StandardScaler().fit(X_train)
      scaler_data = dt_scaler.transform(X_train)
      final_ds = pd.DataFrame(scaler_data, columns= boston.feature_names)
      final_ds['target'] = y_train
      final_ds.target = final_ds.target.fillna((df.target.mean()))


      Now my UDF is,



      def best_w_b(data):
      w0 = np.random.normal(0, 1, (boston.data.shape[1],)).T
      b0 = np.random.normal(0, 1)
      r = 1
      i = 1
      while(1):
      k = data.sample(n=150 ,replace = True)
      for i in range(0,150,1):
      der_w= np.zeros(boston.data.shape[1]) ;der_b = 0
      der_w += np.dot(-2 * k.iloc[i][k.columns !='target'].T ,(k.iloc[i].target - np.dot(w0,k.iloc[i][k.columns !='target'].values) - b0))
      der_b += (-2 * (k.iloc[i].target - np.dot(w0,k.iloc[i][k.columns !='target'].values) - b0 ))
      w1 = np.subtract(w0,(r * der_w/150))
      b1 = b0 - (r * der_b/150)
      w_dist = np.linalg.norm(w0-w1)
      b_dist = np.linalg.norm(b0-b1)
      if (w0==w1).all():
      return w0,b0
      else:
      w0 = w1
      b0 = b1
      r = r/2
      i = i + 1


      After running this method I have obtained the W and B values so if I use Summation 0 to n-1 (Y-Y_hat)^2 /n on the train data should not I be getting a value around 0.



      Here is the code:



       error = 0
      for i in range(0,X_train.shape[0],1):
      error = error + (final_ds.iloc[i].target - (np.dot(optimal_w,final_ds.iloc[i][final_ds.columns !='target']) + optimal_b))**2
      print(error/X_train.shape[0])


      I am getting an error around 582. Is it the right way to test?



      PS:



      Optimal W is : [-0.22178286, -1.30943816, -0.61933446, 1.07290039, -0.96299363,-0.59459475, -1.4094494 , 0.2022922 , -1.45901487, 0.00561458,-0.31858595, -0.71790656, -0.97285501]
      Optimal B is : 1.179334612848228










      share|improve this question














      I have manually implemented SGD for Linear Regression using the partial derivates. I am working on Boston housing prices dataset from SKlearn. The input to my UDF is a (train) dataframe with standardised data except the target column.



      X_train, X_test, y_train, y_test = train_test_split(df.loc[:, df.columns != 'target'], df.target, test_size=0.15, random_state=42)
      dt_scaler = StandardScaler().fit(X_train)
      scaler_data = dt_scaler.transform(X_train)
      final_ds = pd.DataFrame(scaler_data, columns= boston.feature_names)
      final_ds['target'] = y_train
      final_ds.target = final_ds.target.fillna((df.target.mean()))


      Now my UDF is,



      def best_w_b(data):
      w0 = np.random.normal(0, 1, (boston.data.shape[1],)).T
      b0 = np.random.normal(0, 1)
      r = 1
      i = 1
      while(1):
      k = data.sample(n=150 ,replace = True)
      for i in range(0,150,1):
      der_w= np.zeros(boston.data.shape[1]) ;der_b = 0
      der_w += np.dot(-2 * k.iloc[i][k.columns !='target'].T ,(k.iloc[i].target - np.dot(w0,k.iloc[i][k.columns !='target'].values) - b0))
      der_b += (-2 * (k.iloc[i].target - np.dot(w0,k.iloc[i][k.columns !='target'].values) - b0 ))
      w1 = np.subtract(w0,(r * der_w/150))
      b1 = b0 - (r * der_b/150)
      w_dist = np.linalg.norm(w0-w1)
      b_dist = np.linalg.norm(b0-b1)
      if (w0==w1).all():
      return w0,b0
      else:
      w0 = w1
      b0 = b1
      r = r/2
      i = i + 1


      After running this method I have obtained the W and B values so if I use Summation 0 to n-1 (Y-Y_hat)^2 /n on the train data should not I be getting a value around 0.



      Here is the code:



       error = 0
      for i in range(0,X_train.shape[0],1):
      error = error + (final_ds.iloc[i].target - (np.dot(optimal_w,final_ds.iloc[i][final_ds.columns !='target']) + optimal_b))**2
      print(error/X_train.shape[0])


      I am getting an error around 582. Is it the right way to test?



      PS:



      Optimal W is : [-0.22178286, -1.30943816, -0.61933446, 1.07290039, -0.96299363,-0.59459475, -1.4094494 , 0.2022922 , -1.45901487, 0.00561458,-0.31858595, -0.71790656, -0.97285501]
      Optimal B is : 1.179334612848228







      python-3.x linear-regression stochastic






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 25 '18 at 8:16









      Sanjeev RamSanjeev Ram

      94




      94
























          0






          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53465761%2fpython-how-to-cross-check-the-obtained-w-and-b-intercepts-in-sgd-for-linear-re%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53465761%2fpython-how-to-cross-check-the-obtained-w-and-b-intercepts-in-sgd-for-linear-re%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Ottavio Pratesi

          Tricia Helfer

          15 giugno