Dealing with Overfitting The 2019 Stack Overflow Developer Survey Results Are InDealing with optional data in an Artificial Neural NetworkTensorflow regression predicting 1 for all inputsDealing with population instabilityValueError: Error when checking target: expected dense_2 to have shape (1,) but got array with shape (0,)Dealing with long sequence labelingMy Neural network in Tensorflow does a bad job in comparison to the same Neural network in KerasDealing with frequency in neural network inputValue error in Merging two different models in kerasDealing with normalized regression outputDealing with Error in Neural Network input

How to answer pointed "are you quitting" questioning when I don't want them to suspect

What is the most effective way of iterating a std::vector and why?

What does Linus Torvalds mean when he says that Git "never ever" tracks a file?

Aging parents with no investments

slides for 30min~1hr skype tenure track application interview

What do hard-Brexiteers want with respect to the Irish border?

Does coating your armor in silver add any effects?

What are the motivations for publishing new editions of an existing textbook, beyond new discoveries in a field?

Deal with toxic manager when you can't quit

What does ひと匙 mean in this manga and has it been used colloquially?

A poker game description that does not feel gimmicky

Origin of "cooter" meaning "vagina"

If I score a critical hit on an 18 or higher, what are my chances of getting a critical hit if I roll 3d20?

Can a flute soloist sit?

Falsification in Math vs Science

Time travel alters history but people keep saying nothing's changed

Should I use my personal e-mail address, or my workplace one, when registering to external websites for work purposes?

Output the Arecibo Message

Why was M87 targetted for the Event Horizon Telescope instead of Sagittarius A*?

What is the closest word meaning "respect for time / mindful"

Does a dangling wire really electrocute me if I'm standing in water?

Can we generate random numbers using irrational numbers like π and e?

Return to UK after having been refused entry years ago

When should I buy a clipper card after flying to OAK?



Dealing with Overfitting



The 2019 Stack Overflow Developer Survey Results Are InDealing with optional data in an Artificial Neural NetworkTensorflow regression predicting 1 for all inputsDealing with population instabilityValueError: Error when checking target: expected dense_2 to have shape (1,) but got array with shape (0,)Dealing with long sequence labelingMy Neural network in Tensorflow does a bad job in comparison to the same Neural network in KerasDealing with frequency in neural network inputValue error in Merging two different models in kerasDealing with normalized regression outputDealing with Error in Neural Network input










2












$begingroup$


Hello and thank you in advance for any answer. I am building a NN for a multi class classification problem. I have pretrained my data through a Word2vec and generated a 300 dimension vector with values. I have 6 classes .. My data consist of 15000 rows(x300 dimensions). My first question is :



What is the number of units? Is it something that we can extract from theory?
Also i have managed to gain 0.85-0.90 training set accuracy but the validation set accuracy is always low: 0.22-0.25. I do not know what way to follow as I am newbie to these kind of stuff. My code is:



import numpy as np
import pandas as pd
import keras
from sklearn.preprocessing import Imputer
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.layers import Dense,Dropout
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
from keras import regularizers



dataset = pd.read_csv('word2vec.csv')


X = dataset.iloc[:, 0:300].values
y = dataset.iloc[:, 300].values

imputer = Imputer(missing_values = 'NaN', strategy = 'mean', axis = 0)
imputer = imputer.fit(X[:, 0:300])
X[:, 0:300] = imputer.transform(X[:, 0:300])

counter = 0
for iterations in range(1):

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

classifier = Sequential()

classifier.add(Dense(units=70, kernel_initializer='uniform',kernel_regularizer=regularizers.l2(0.0001),
activity_regularizer=regularizers.l1(0.001), activation='relu', input_dim=300))

classifier.add(Dropout(0.3))

# classifier.add(Dense(units=70, kernel_initializer='uniform', activation='relu'))


classifier.add(Dense(units=6, kernel_initializer='uniform', activation='softmax'))

classifier.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

history = classifier.fit(X_train, y_train,validation_split=0.1, batch_size=10, epochs=100,shuffle=True)

y_pred = classifier.predict(X_test)
# y_pred = (y_pred > 0.1666)

classifier.summary()
counter+=1
print(classifier.layers)
print("Running RNN with Dropout Layer")
print("Number of layers used: "+str(len(classifier.layers)))
# list all data in history
print(history.history.keys())
# summarize history for accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()









share|improve this question









$endgroup$




bumped to the homepage by Community 3 hours ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.



















    2












    $begingroup$


    Hello and thank you in advance for any answer. I am building a NN for a multi class classification problem. I have pretrained my data through a Word2vec and generated a 300 dimension vector with values. I have 6 classes .. My data consist of 15000 rows(x300 dimensions). My first question is :



    What is the number of units? Is it something that we can extract from theory?
    Also i have managed to gain 0.85-0.90 training set accuracy but the validation set accuracy is always low: 0.22-0.25. I do not know what way to follow as I am newbie to these kind of stuff. My code is:



    import numpy as np
    import pandas as pd
    import keras
    from sklearn.preprocessing import Imputer
    from sklearn.model_selection import train_test_split
    from keras.models import Sequential
    from keras.layers import Dense,Dropout
    from sklearn.metrics import confusion_matrix
    import matplotlib.pyplot as plt
    from keras import regularizers



    dataset = pd.read_csv('word2vec.csv')


    X = dataset.iloc[:, 0:300].values
    y = dataset.iloc[:, 300].values

    imputer = Imputer(missing_values = 'NaN', strategy = 'mean', axis = 0)
    imputer = imputer.fit(X[:, 0:300])
    X[:, 0:300] = imputer.transform(X[:, 0:300])

    counter = 0
    for iterations in range(1):

    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

    classifier = Sequential()

    classifier.add(Dense(units=70, kernel_initializer='uniform',kernel_regularizer=regularizers.l2(0.0001),
    activity_regularizer=regularizers.l1(0.001), activation='relu', input_dim=300))

    classifier.add(Dropout(0.3))

    # classifier.add(Dense(units=70, kernel_initializer='uniform', activation='relu'))


    classifier.add(Dense(units=6, kernel_initializer='uniform', activation='softmax'))

    classifier.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

    history = classifier.fit(X_train, y_train,validation_split=0.1, batch_size=10, epochs=100,shuffle=True)

    y_pred = classifier.predict(X_test)
    # y_pred = (y_pred > 0.1666)

    classifier.summary()
    counter+=1
    print(classifier.layers)
    print("Running RNN with Dropout Layer")
    print("Number of layers used: "+str(len(classifier.layers)))
    # list all data in history
    print(history.history.keys())
    # summarize history for accuracy
    plt.plot(history.history['acc'])
    plt.plot(history.history['val_acc'])
    plt.title('model accuracy')
    plt.ylabel('accuracy')
    plt.xlabel('epoch')
    plt.legend(['train', 'test'], loc='upper left')
    plt.show()
    # summarize history for loss
    plt.plot(history.history['loss'])
    plt.plot(history.history['val_loss'])
    plt.title('model loss')
    plt.ylabel('loss')
    plt.xlabel('epoch')
    plt.legend(['train', 'test'], loc='upper left')
    plt.show()









    share|improve this question









    $endgroup$




    bumped to the homepage by Community 3 hours ago


    This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.

















      2












      2








      2





      $begingroup$


      Hello and thank you in advance for any answer. I am building a NN for a multi class classification problem. I have pretrained my data through a Word2vec and generated a 300 dimension vector with values. I have 6 classes .. My data consist of 15000 rows(x300 dimensions). My first question is :



      What is the number of units? Is it something that we can extract from theory?
      Also i have managed to gain 0.85-0.90 training set accuracy but the validation set accuracy is always low: 0.22-0.25. I do not know what way to follow as I am newbie to these kind of stuff. My code is:



      import numpy as np
      import pandas as pd
      import keras
      from sklearn.preprocessing import Imputer
      from sklearn.model_selection import train_test_split
      from keras.models import Sequential
      from keras.layers import Dense,Dropout
      from sklearn.metrics import confusion_matrix
      import matplotlib.pyplot as plt
      from keras import regularizers



      dataset = pd.read_csv('word2vec.csv')


      X = dataset.iloc[:, 0:300].values
      y = dataset.iloc[:, 300].values

      imputer = Imputer(missing_values = 'NaN', strategy = 'mean', axis = 0)
      imputer = imputer.fit(X[:, 0:300])
      X[:, 0:300] = imputer.transform(X[:, 0:300])

      counter = 0
      for iterations in range(1):

      X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

      classifier = Sequential()

      classifier.add(Dense(units=70, kernel_initializer='uniform',kernel_regularizer=regularizers.l2(0.0001),
      activity_regularizer=regularizers.l1(0.001), activation='relu', input_dim=300))

      classifier.add(Dropout(0.3))

      # classifier.add(Dense(units=70, kernel_initializer='uniform', activation='relu'))


      classifier.add(Dense(units=6, kernel_initializer='uniform', activation='softmax'))

      classifier.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

      history = classifier.fit(X_train, y_train,validation_split=0.1, batch_size=10, epochs=100,shuffle=True)

      y_pred = classifier.predict(X_test)
      # y_pred = (y_pred > 0.1666)

      classifier.summary()
      counter+=1
      print(classifier.layers)
      print("Running RNN with Dropout Layer")
      print("Number of layers used: "+str(len(classifier.layers)))
      # list all data in history
      print(history.history.keys())
      # summarize history for accuracy
      plt.plot(history.history['acc'])
      plt.plot(history.history['val_acc'])
      plt.title('model accuracy')
      plt.ylabel('accuracy')
      plt.xlabel('epoch')
      plt.legend(['train', 'test'], loc='upper left')
      plt.show()
      # summarize history for loss
      plt.plot(history.history['loss'])
      plt.plot(history.history['val_loss'])
      plt.title('model loss')
      plt.ylabel('loss')
      plt.xlabel('epoch')
      plt.legend(['train', 'test'], loc='upper left')
      plt.show()









      share|improve this question









      $endgroup$




      Hello and thank you in advance for any answer. I am building a NN for a multi class classification problem. I have pretrained my data through a Word2vec and generated a 300 dimension vector with values. I have 6 classes .. My data consist of 15000 rows(x300 dimensions). My first question is :



      What is the number of units? Is it something that we can extract from theory?
      Also i have managed to gain 0.85-0.90 training set accuracy but the validation set accuracy is always low: 0.22-0.25. I do not know what way to follow as I am newbie to these kind of stuff. My code is:



      import numpy as np
      import pandas as pd
      import keras
      from sklearn.preprocessing import Imputer
      from sklearn.model_selection import train_test_split
      from keras.models import Sequential
      from keras.layers import Dense,Dropout
      from sklearn.metrics import confusion_matrix
      import matplotlib.pyplot as plt
      from keras import regularizers



      dataset = pd.read_csv('word2vec.csv')


      X = dataset.iloc[:, 0:300].values
      y = dataset.iloc[:, 300].values

      imputer = Imputer(missing_values = 'NaN', strategy = 'mean', axis = 0)
      imputer = imputer.fit(X[:, 0:300])
      X[:, 0:300] = imputer.transform(X[:, 0:300])

      counter = 0
      for iterations in range(1):

      X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

      classifier = Sequential()

      classifier.add(Dense(units=70, kernel_initializer='uniform',kernel_regularizer=regularizers.l2(0.0001),
      activity_regularizer=regularizers.l1(0.001), activation='relu', input_dim=300))

      classifier.add(Dropout(0.3))

      # classifier.add(Dense(units=70, kernel_initializer='uniform', activation='relu'))


      classifier.add(Dense(units=6, kernel_initializer='uniform', activation='softmax'))

      classifier.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

      history = classifier.fit(X_train, y_train,validation_split=0.1, batch_size=10, epochs=100,shuffle=True)

      y_pred = classifier.predict(X_test)
      # y_pred = (y_pred > 0.1666)

      classifier.summary()
      counter+=1
      print(classifier.layers)
      print("Running RNN with Dropout Layer")
      print("Number of layers used: "+str(len(classifier.layers)))
      # list all data in history
      print(history.history.keys())
      # summarize history for accuracy
      plt.plot(history.history['acc'])
      plt.plot(history.history['val_acc'])
      plt.title('model accuracy')
      plt.ylabel('accuracy')
      plt.xlabel('epoch')
      plt.legend(['train', 'test'], loc='upper left')
      plt.show()
      # summarize history for loss
      plt.plot(history.history['loss'])
      plt.plot(history.history['val_loss'])
      plt.title('model loss')
      plt.ylabel('loss')
      plt.xlabel('epoch')
      plt.legend(['train', 'test'], loc='upper left')
      plt.show()






      machine-learning neural-network keras






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 11 '18 at 19:22









      Marinos ZagkotsisMarinos Zagkotsis

      112




      112





      bumped to the homepage by Community 3 hours ago


      This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







      bumped to the homepage by Community 3 hours ago


      This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.






















          1 Answer
          1






          active

          oldest

          votes


















          0












          $begingroup$

          Yep - you've overfitted !



          Can you see what your accuracy is as a function of the number of training cycles? It would be interesting to see how that looks.



          Is there any way you could increase your data? 15000x300 isn't a huge amount of depth for a neural network, considering the width of the data set.



          You could look at the impact of increasing your regularisation parameters, or decreasing the depth of your network






          share|improve this answer









          $endgroup$












          • $begingroup$
            UPDATE: Thank you for your time.. Can you please explain to me about the accuracy and the training cycles? Unfortunately I cannot increase the the data.. But i could decrease the dimensions.. Do you think it would be helpful? Does this overfitting occurs mainly because of the low amount of data? Is my code wrong?? Thank you
            $endgroup$
            – Marinos Zagkotsis
            Nov 12 '18 at 11:13










          • $begingroup$
            @marinos in a general sense overfitting increases with model complexity, so reducing dimensions would be a good start.
            $endgroup$
            – davmor
            Nov 13 '18 at 5:50










          • $begingroup$
            @davmor thank you for the answer and your time.. I will implement it that way... I have applied several other methods such as l1,l2 regularizations, batch normalization and dropout and also split the validation set like i have for test set.. I managed to overcome the overfit.. now ofcourse my training accuracy is lower . Is it maybe because of the word2vec pretraining? maybe it comes in addition with the 300 dimensions? thank you
            $endgroup$
            – Marinos Zagkotsis
            Nov 13 '18 at 7:57










          • $begingroup$
            @marinos again, generally, modeling is about choosing trade offs. This is ok, as you will find most clients (and good managers) are fine if you explain the error and why (here, a small training set relative to dimensions). Secondly, analysis is a process, not a single event. So use your model to run new data, determine error, and improve. Lastly, remember in most real world cases, the current state is no model at all, so something is usually better than nothing.
            $endgroup$
            – davmor
            Nov 16 '18 at 19:11











          Your Answer





          StackExchange.ifUsing("editor", function ()
          return StackExchange.using("mathjaxEditing", function ()
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["$", "$"], ["\\(","\\)"]]);
          );
          );
          , "mathjax-editing");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "557"
          ;
          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: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          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%2fdatascience.stackexchange.com%2fquestions%2f41056%2fdealing-with-overfitting%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0












          $begingroup$

          Yep - you've overfitted !



          Can you see what your accuracy is as a function of the number of training cycles? It would be interesting to see how that looks.



          Is there any way you could increase your data? 15000x300 isn't a huge amount of depth for a neural network, considering the width of the data set.



          You could look at the impact of increasing your regularisation parameters, or decreasing the depth of your network






          share|improve this answer









          $endgroup$












          • $begingroup$
            UPDATE: Thank you for your time.. Can you please explain to me about the accuracy and the training cycles? Unfortunately I cannot increase the the data.. But i could decrease the dimensions.. Do you think it would be helpful? Does this overfitting occurs mainly because of the low amount of data? Is my code wrong?? Thank you
            $endgroup$
            – Marinos Zagkotsis
            Nov 12 '18 at 11:13










          • $begingroup$
            @marinos in a general sense overfitting increases with model complexity, so reducing dimensions would be a good start.
            $endgroup$
            – davmor
            Nov 13 '18 at 5:50










          • $begingroup$
            @davmor thank you for the answer and your time.. I will implement it that way... I have applied several other methods such as l1,l2 regularizations, batch normalization and dropout and also split the validation set like i have for test set.. I managed to overcome the overfit.. now ofcourse my training accuracy is lower . Is it maybe because of the word2vec pretraining? maybe it comes in addition with the 300 dimensions? thank you
            $endgroup$
            – Marinos Zagkotsis
            Nov 13 '18 at 7:57










          • $begingroup$
            @marinos again, generally, modeling is about choosing trade offs. This is ok, as you will find most clients (and good managers) are fine if you explain the error and why (here, a small training set relative to dimensions). Secondly, analysis is a process, not a single event. So use your model to run new data, determine error, and improve. Lastly, remember in most real world cases, the current state is no model at all, so something is usually better than nothing.
            $endgroup$
            – davmor
            Nov 16 '18 at 19:11















          0












          $begingroup$

          Yep - you've overfitted !



          Can you see what your accuracy is as a function of the number of training cycles? It would be interesting to see how that looks.



          Is there any way you could increase your data? 15000x300 isn't a huge amount of depth for a neural network, considering the width of the data set.



          You could look at the impact of increasing your regularisation parameters, or decreasing the depth of your network






          share|improve this answer









          $endgroup$












          • $begingroup$
            UPDATE: Thank you for your time.. Can you please explain to me about the accuracy and the training cycles? Unfortunately I cannot increase the the data.. But i could decrease the dimensions.. Do you think it would be helpful? Does this overfitting occurs mainly because of the low amount of data? Is my code wrong?? Thank you
            $endgroup$
            – Marinos Zagkotsis
            Nov 12 '18 at 11:13










          • $begingroup$
            @marinos in a general sense overfitting increases with model complexity, so reducing dimensions would be a good start.
            $endgroup$
            – davmor
            Nov 13 '18 at 5:50










          • $begingroup$
            @davmor thank you for the answer and your time.. I will implement it that way... I have applied several other methods such as l1,l2 regularizations, batch normalization and dropout and also split the validation set like i have for test set.. I managed to overcome the overfit.. now ofcourse my training accuracy is lower . Is it maybe because of the word2vec pretraining? maybe it comes in addition with the 300 dimensions? thank you
            $endgroup$
            – Marinos Zagkotsis
            Nov 13 '18 at 7:57










          • $begingroup$
            @marinos again, generally, modeling is about choosing trade offs. This is ok, as you will find most clients (and good managers) are fine if you explain the error and why (here, a small training set relative to dimensions). Secondly, analysis is a process, not a single event. So use your model to run new data, determine error, and improve. Lastly, remember in most real world cases, the current state is no model at all, so something is usually better than nothing.
            $endgroup$
            – davmor
            Nov 16 '18 at 19:11













          0












          0








          0





          $begingroup$

          Yep - you've overfitted !



          Can you see what your accuracy is as a function of the number of training cycles? It would be interesting to see how that looks.



          Is there any way you could increase your data? 15000x300 isn't a huge amount of depth for a neural network, considering the width of the data set.



          You could look at the impact of increasing your regularisation parameters, or decreasing the depth of your network






          share|improve this answer









          $endgroup$



          Yep - you've overfitted !



          Can you see what your accuracy is as a function of the number of training cycles? It would be interesting to see how that looks.



          Is there any way you could increase your data? 15000x300 isn't a huge amount of depth for a neural network, considering the width of the data set.



          You could look at the impact of increasing your regularisation parameters, or decreasing the depth of your network







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 11 '18 at 19:53









          HenryHenry

          1842




          1842











          • $begingroup$
            UPDATE: Thank you for your time.. Can you please explain to me about the accuracy and the training cycles? Unfortunately I cannot increase the the data.. But i could decrease the dimensions.. Do you think it would be helpful? Does this overfitting occurs mainly because of the low amount of data? Is my code wrong?? Thank you
            $endgroup$
            – Marinos Zagkotsis
            Nov 12 '18 at 11:13










          • $begingroup$
            @marinos in a general sense overfitting increases with model complexity, so reducing dimensions would be a good start.
            $endgroup$
            – davmor
            Nov 13 '18 at 5:50










          • $begingroup$
            @davmor thank you for the answer and your time.. I will implement it that way... I have applied several other methods such as l1,l2 regularizations, batch normalization and dropout and also split the validation set like i have for test set.. I managed to overcome the overfit.. now ofcourse my training accuracy is lower . Is it maybe because of the word2vec pretraining? maybe it comes in addition with the 300 dimensions? thank you
            $endgroup$
            – Marinos Zagkotsis
            Nov 13 '18 at 7:57










          • $begingroup$
            @marinos again, generally, modeling is about choosing trade offs. This is ok, as you will find most clients (and good managers) are fine if you explain the error and why (here, a small training set relative to dimensions). Secondly, analysis is a process, not a single event. So use your model to run new data, determine error, and improve. Lastly, remember in most real world cases, the current state is no model at all, so something is usually better than nothing.
            $endgroup$
            – davmor
            Nov 16 '18 at 19:11
















          • $begingroup$
            UPDATE: Thank you for your time.. Can you please explain to me about the accuracy and the training cycles? Unfortunately I cannot increase the the data.. But i could decrease the dimensions.. Do you think it would be helpful? Does this overfitting occurs mainly because of the low amount of data? Is my code wrong?? Thank you
            $endgroup$
            – Marinos Zagkotsis
            Nov 12 '18 at 11:13










          • $begingroup$
            @marinos in a general sense overfitting increases with model complexity, so reducing dimensions would be a good start.
            $endgroup$
            – davmor
            Nov 13 '18 at 5:50










          • $begingroup$
            @davmor thank you for the answer and your time.. I will implement it that way... I have applied several other methods such as l1,l2 regularizations, batch normalization and dropout and also split the validation set like i have for test set.. I managed to overcome the overfit.. now ofcourse my training accuracy is lower . Is it maybe because of the word2vec pretraining? maybe it comes in addition with the 300 dimensions? thank you
            $endgroup$
            – Marinos Zagkotsis
            Nov 13 '18 at 7:57










          • $begingroup$
            @marinos again, generally, modeling is about choosing trade offs. This is ok, as you will find most clients (and good managers) are fine if you explain the error and why (here, a small training set relative to dimensions). Secondly, analysis is a process, not a single event. So use your model to run new data, determine error, and improve. Lastly, remember in most real world cases, the current state is no model at all, so something is usually better than nothing.
            $endgroup$
            – davmor
            Nov 16 '18 at 19:11















          $begingroup$
          UPDATE: Thank you for your time.. Can you please explain to me about the accuracy and the training cycles? Unfortunately I cannot increase the the data.. But i could decrease the dimensions.. Do you think it would be helpful? Does this overfitting occurs mainly because of the low amount of data? Is my code wrong?? Thank you
          $endgroup$
          – Marinos Zagkotsis
          Nov 12 '18 at 11:13




          $begingroup$
          UPDATE: Thank you for your time.. Can you please explain to me about the accuracy and the training cycles? Unfortunately I cannot increase the the data.. But i could decrease the dimensions.. Do you think it would be helpful? Does this overfitting occurs mainly because of the low amount of data? Is my code wrong?? Thank you
          $endgroup$
          – Marinos Zagkotsis
          Nov 12 '18 at 11:13












          $begingroup$
          @marinos in a general sense overfitting increases with model complexity, so reducing dimensions would be a good start.
          $endgroup$
          – davmor
          Nov 13 '18 at 5:50




          $begingroup$
          @marinos in a general sense overfitting increases with model complexity, so reducing dimensions would be a good start.
          $endgroup$
          – davmor
          Nov 13 '18 at 5:50












          $begingroup$
          @davmor thank you for the answer and your time.. I will implement it that way... I have applied several other methods such as l1,l2 regularizations, batch normalization and dropout and also split the validation set like i have for test set.. I managed to overcome the overfit.. now ofcourse my training accuracy is lower . Is it maybe because of the word2vec pretraining? maybe it comes in addition with the 300 dimensions? thank you
          $endgroup$
          – Marinos Zagkotsis
          Nov 13 '18 at 7:57




          $begingroup$
          @davmor thank you for the answer and your time.. I will implement it that way... I have applied several other methods such as l1,l2 regularizations, batch normalization and dropout and also split the validation set like i have for test set.. I managed to overcome the overfit.. now ofcourse my training accuracy is lower . Is it maybe because of the word2vec pretraining? maybe it comes in addition with the 300 dimensions? thank you
          $endgroup$
          – Marinos Zagkotsis
          Nov 13 '18 at 7:57












          $begingroup$
          @marinos again, generally, modeling is about choosing trade offs. This is ok, as you will find most clients (and good managers) are fine if you explain the error and why (here, a small training set relative to dimensions). Secondly, analysis is a process, not a single event. So use your model to run new data, determine error, and improve. Lastly, remember in most real world cases, the current state is no model at all, so something is usually better than nothing.
          $endgroup$
          – davmor
          Nov 16 '18 at 19:11




          $begingroup$
          @marinos again, generally, modeling is about choosing trade offs. This is ok, as you will find most clients (and good managers) are fine if you explain the error and why (here, a small training set relative to dimensions). Secondly, analysis is a process, not a single event. So use your model to run new data, determine error, and improve. Lastly, remember in most real world cases, the current state is no model at all, so something is usually better than nothing.
          $endgroup$
          – davmor
          Nov 16 '18 at 19:11

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Data Science Stack Exchange!


          • 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.

          Use MathJax to format equations. MathJax reference.


          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%2fdatascience.stackexchange.com%2fquestions%2f41056%2fdealing-with-overfitting%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

          Францішак Багушэвіч Змест Сям'я | Біяграфія | Творчасць | Мова Багушэвіча | Ацэнкі дзейнасці | Цікавыя факты | Спадчына | Выбраная бібліяграфія | Ушанаванне памяці | У філатэліі | Зноскі | Літаратура | Спасылкі | НавігацыяЛяхоўскі У. Рупіўся дзеля Бога і людзей: Жыццёвы шлях Лявона Вітан-Дубейкаўскага // Вольскі і Памідораў з песняй пра немца Адвакат, паэт, народны заступнік Ашмянскі веснікВ Минске появится площадь Богушевича и улица Сырокомли, Белорусская деловая газета, 19 июля 2001 г.Айцец беларускай нацыянальнай ідэі паўстаў у бронзе Сяргей Аляксандравіч Адашкевіч (1918, Мінск). 80-я гады. Бюст «Францішак Багушэвіч».Яўген Мікалаевіч Ціхановіч. «Партрэт Францішка Багушэвіча»Мікола Мікалаевіч Купава. «Партрэт зачынальніка новай беларускай літаратуры Францішка Багушэвіча»Уладзімір Іванавіч Мелехаў. На помніку «Змагарам за родную мову» Барэльеф «Францішак Багушэвіч»Памяць пра Багушэвіча на Віленшчыне Страчаная сталіца. Беларускія шыльды на вуліцах Вільні«Krynica». Ideologia i przywódcy białoruskiego katolicyzmuФранцішак БагушэвічТворы на knihi.comТворы Францішка Багушэвіча на bellib.byСодаль Уладзімір. Францішак Багушэвіч на Лідчыне;Луцкевіч Антон. Жыцьцё і творчасьць Фр. Багушэвіча ў успамінах ягоных сучасьнікаў // Запісы Беларускага Навуковага таварыства. Вільня, 1938. Сшытак 1. С. 16-34.Большая российская1188761710000 0000 5537 633Xn9209310021619551927869394п

          Беларусь Змест Назва Гісторыя Геаграфія Сімволіка Дзяржаўны лад Палітычныя партыі Міжнароднае становішча і знешняя палітыка Адміністрацыйны падзел Насельніцтва Эканоміка Культура і грамадства Сацыяльная сфера Узброеныя сілы Заўвагі Літаратура Спасылкі НавігацыяHGЯOiТоп-2011 г. (па версіі ej.by)Топ-2013 г. (па версіі ej.by)Топ-2016 г. (па версіі ej.by)Топ-2017 г. (па версіі ej.by)Нацыянальны статыстычны камітэт Рэспублікі БеларусьШчыльнасць насельніцтва па краінахhttp://naviny.by/rubrics/society/2011/09/16/ic_articles_116_175144/А. Калечыц, У. Ксяндзоў. Спробы засялення краю неандэртальскім чалавекам.І ў Менску былі мамантыА. Калечыц, У. Ксяндзоў. Старажытны каменны век (палеаліт). Першапачатковае засяленне тэрыторыіГ. Штыхаў. Балты і славяне ў VI—VIII стст.М. Клімаў. Полацкае княства ў IX—XI стст.Г. Штыхаў, В. Ляўко. Палітычная гісторыя Полацкай зямліГ. Штыхаў. Дзяржаўны лад у землях-княствахГ. Штыхаў. Дзяржаўны лад у землях-княствахБеларускія землі ў складзе Вялікага Княства ЛітоўскагаЛюблінская унія 1569 г."The Early Stages of Independence"Zapomniane prawdy25 гадоў таму было аб'яўлена, што Язэп Пілсудскі — беларус (фота)Наша вадаДакументы ЧАЭС: Забруджванне тэрыторыі Беларусі « ЧАЭС Зона адчужэнняСведения о политических партиях, зарегистрированных в Республике Беларусь // Министерство юстиции Республики БеларусьСтатыстычны бюлетэнь „Полаўзроставая структура насельніцтва Рэспублікі Беларусь на 1 студзеня 2012 года і сярэднегадовая колькасць насельніцтва за 2011 год“Индекс человеческого развития Беларуси — не было бы нижеБеларусь занимает первое место в СНГ по индексу развития с учетом гендерного факцёраНацыянальны статыстычны камітэт Рэспублікі БеларусьКанстытуцыя РБ. Артыкул 17Трансфармацыйныя задачы БеларусіВыйсце з крызісу — далейшае рэфармаванне Беларускі рубель — сусветны лідар па дэвальвацыяхПра змену коштаў у кастрычніку 2011 г.Бядней за беларусаў у СНД толькі таджыкіСярэдні заробак у верасні дасягнуў 2,26 мільёна рублёўЭканомікаГаласуем за ТОП-100 беларускай прозыСучасныя беларускія мастакіАрхитектура Беларуси BELARUS.BYА. Каханоўскі. Культура Беларусі ўсярэдзіне XVII—XVIII ст.Анталогія беларускай народнай песні, гуказапісы спеваўБеларускія Музычныя IнструментыБеларускі рок, які мы страцілі. Топ-10 гуртоў«Мясцовы час» — нязгаслая легенда беларускай рок-музыкіСЯРГЕЙ БУДКІН. МЫ НЯ ЗНАЕМ СВАЁЙ МУЗЫКІМ. А. Каладзінскі. НАРОДНЫ ТЭАТРМагнацкія культурныя цэнтрыПублічная дыскусія «Беларуская новая пьеса: без беларускай мовы ці беларуская?»Беларускія драматургі па-ранейшаму лепш ставяцца за мяжой, чым на радзіме«Працэс незалежнага кіно пайшоў, і дзяржаву турбуе яго непадкантрольнасць»Беларускія філосафы ў пошуках прасторыВсе идём в библиотекуАрхіваванаАб Нацыянальнай праграме даследавання і выкарыстання касмічнай прасторы ў мірных мэтах на 2008—2012 гадыУ космас — разам.У суседнім з Барысаўскім раёне пабудуюць Камандна-вымяральны пунктСвяты і абрады беларусаў«Мірныя бульбашы з малой краіны» — 5 непраўдзівых стэрэатыпаў пра БеларусьМ. Раманюк. Беларускае народнае адзеннеУ Беларусі скарачаецца колькасць злачынстваўЛукашэнка незадаволены мінскімі ўладамі Крадзяжы складаюць у Мінску каля 70% злачынстваў Узровень злачыннасці ў Мінскай вобласці — адзін з самых высокіх у краіне Генпракуратура аналізуе стан са злачыннасцю ў Беларусі па каэфіцыенце злачыннасці У Беларусі стабілізавалася крымінагеннае становішча, лічыць генпракурорЗамежнікі сталі здзяйсняць у Беларусі больш злачынстваўМУС Беларусі турбуе рост рэцыдыўнай злачыннасціЯ з ЖЭСа. Дазволіце вас абкрасці! Рэйтынг усіх службаў і падраздзяленняў ГУУС Мінгарвыканкама вырасАб КДБ РБГісторыя Аператыўна-аналітычнага цэнтра РБГісторыя ДКФРТаможняagentura.ruБеларусьBelarus.by — Афіцыйны сайт Рэспублікі БеларусьСайт урада БеларусіRadzima.org — Збор архітэктурных помнікаў, гісторыя Беларусі«Глобус Беларуси»Гербы и флаги БеларусиАсаблівасці каменнага веку на БеларусіА. Калечыц, У. Ксяндзоў. Старажытны каменны век (палеаліт). Першапачатковае засяленне тэрыторыіУ. Ксяндзоў. Сярэдні каменны век (мезаліт). Засяленне краю плямёнамі паляўнічых, рыбакоў і збіральнікаўА. Калечыц, М. Чарняўскі. Плямёны на тэрыторыі Беларусі ў новым каменным веку (неаліце)А. Калечыц, У. Ксяндзоў, М. Чарняўскі. Гаспадарчыя заняткі ў каменным векуЭ. Зайкоўскі. Духоўная культура ў каменным векуАсаблівасці бронзавага веку на БеларусіФарміраванне супольнасцей ранняга перыяду бронзавага векуФотографии БеларусиРоля беларускіх зямель ва ўтварэнні і ўмацаванні ВКЛВ. Фадзеева. З гісторыі развіцця беларускай народнай вышыўкіDMOZGran catalanaБольшая российскаяBritannica (анлайн)Швейцарскі гістарычны15325917611952699xDA123282154079143-90000 0001 2171 2080n9112870100577502ge128882171858027501086026362074122714179пппппп

          ValueError: Expected n_neighbors <= n_samples, but n_samples = 1, n_neighbors = 6 (SMOTE) The 2019 Stack Overflow Developer Survey Results Are InCan SMOTE be applied over sequence of words (sentences)?ValueError when doing validation with random forestsSMOTE and multi class oversamplingLogic behind SMOTE-NC?ValueError: Error when checking target: expected dense_1 to have shape (7,) but got array with shape (1,)SmoteBoost: Should SMOTE be ran individually for each iteration/tree in the boosting?solving multi-class imbalance classification using smote and OSSUsing SMOTE for Synthetic Data generation to improve performance on unbalanced dataproblem of entry format for a simple model in KerasSVM SMOTE fit_resample() function runs forever with no result