title: How do you obtain confusion matrix for glmnet Multinomial logistic regression?
body: <p>I fit the Multinomial logistic regression model and I'd like to obtain confusion matrix to obtain the accuracy</p>
  <pre><code>library(&quot;glmnet&quot;)
  x=data.matrix(train[-1])
  y= data.matrix(train[1])
  x_test=data.matrix(test[-1])
  y_test=unlist(test[1])
  
  fit.glm=glmnet(x,y,family=&quot;multinomial&quot;,alpha = 1, type.multinomial = &quot;grouped&quot;)
  cvfit=cv.glmnet(x, y, family=&quot;multinomial&quot;, type.multinomial = &quot;grouped&quot;, parallel = TRUE)
  y_predict=unlist(predict(cvfit, newx = x_test, s = &quot;lambda.min&quot;, type = &quot;class&quot;))
  </code></pre>
  <p>and then to calculate confusion matrix I use caret library</p>
  <pre><code>library(&quot;lattice&quot;)
  library(&quot;ggplot2&quot;)
  library(&quot;caret&quot;)
  confusionMatrix(data=y_predict,reference=y_test)
  </code></pre>
  <p>I am getting this error which I do not know how to solve that</p>
  <blockquote>
  <p>Error in confusionMatrix.default(data = y_predict, reference = y_test)
  :    The data must contain some levels that overlap the reference.</p>
  </blockquote>
  <p>I just post the str of <code>y_predict</code> and <code>y_test</code>. They might be helpful</p>
  <pre><code>str(y_predict)
   chr [1:301, 1] &quot;6&quot; &quot;2&quot; &quot;7&quot; &quot;9&quot; &quot;3&quot; &quot;2&quot; &quot;3&quot; &quot;6&quot; &quot;6&quot; &quot;8&quot; &quot;6&quot; &quot;5&quot; &quot;6&quot; ...
   - attr(*, &quot;dimnames&quot;)=List of 2
    ..$ : NULL
    ..$ : chr &quot;1&quot;
  
  str(y_test)
   Factor w/ 10 levels &quot;accessory&quot;,&quot;activation&quot;,..: 6 8 2 9 3 2 3 5 10 8 ...
   - attr(*, &quot;names&quot;)= chr [1:301] &quot;category1&quot; &quot;category2&quot; &quot;category3&quot; &quot;category4&quot; ...
  </code></pre>
  <p>I use <code>unlist</code> to avoid getting this error <a href="https://stackoverflow.com/questions/36582505/error-x-must-be-atomic-for-sort-list">Error: x must be atomic for &#39;sort.list&#39;</a></p>