Error in 'numpy.ndarray' object has no attribute 'append'

Asked 2 years ago, Updated 2 years ago, 49 views

I am currently studying with a theory and implementation book by Python Machine Learning Programming Master Data Scientist.
When implementing the code, the following error occurs:I looked it up online and found that adding array with numpy would solve the problem, but I don't know what code to add.
Please let me know how to add code and solve it by other means.

 weights, params=[],[]
for cinnp.range (-5,5):
    lr=LogisticRegression (C=10.**c, random_state=0) 
    lr.fit(X_train_std,y_train)
    
    weights.append(lr.coef_[1])
    
    params.append (10.**c)
    
    weights = np.array (weights)
    
    plt.plot(params, weights [:, 0], label='petal length')
    plt.plot(params, weights[:,1], linestyle='--', label='petal width')
    plt.ylabel('weight coefficient')
    plt.xlabel('C')
    plt.legend(loc='upper left')
    
    plt.xscale ('log')
    plt.show()
AttributeError Traceback (most recent call last)
<ipython-input-17-037561b182ec>in<module>
      4 lr.fit(X_train_std,y_train)
      5 
---->6 weights.append(lr.coef_[1])
      7 
      8 params.append (10.0**c)

AttributeError: 'numpy.ndarray' object has no attribute'append'
​

python machine-learning

2022-09-30 19:47

1 Answers

In the for loop, the variable weights is converted from list to ndarray, so the above error appears after the second loop.Therefore, why don't you convert the weights of the list to ndarray after the for statement ends as shown below?I haven't tried it on hand, so please keep it as a reference.

 weights, params=[],[]
for cinnp.range (-5,5):
    lr=LogisticRegression (C=10.**c, random_state=0) 
    lr.fit(X_train_std,y_train)
    
    weights.append(lr.coef_[1])
    
    params.append (10.**c)
    
weights = np.array (weights)
    
plt.plot(params, weights [:, 0], label='petal length')
plt.plot(params, weights[:,1], linestyle='--', label='petal width')
plt.ylabel('weight coefficient')
plt.xlabel('C')
plt.legend(loc='upper left')
    
plt.xscale ('log')
plt.show()


2022-09-30 19:47

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.