Python method for completing logistic regression

Source: Internet
Author: User
This article mainly describes the Python implementation of the method of logistic regression example, this is a machine learning course of an experiment, organized to share to everyone, the need for friends can refer to the study, down to see it together.

The principle of this paper is very simple, the optimization method is to use gradient descent. There are test results later.

Let's take a look at the example code for the implementation:

# coding=utf-8from Math Import expimport matplotlib.pyplot as Pltimport numpy as Npfrom Sklearn.datasets.samples_generato R Import make_blobsdef sigmoid (num): "':p Aram Num: The value after the x:return:sigmoid to be calculated" if type (num) = = int or type (num) = = f Loat:return 1.0/(1 + exp ( -1 * num)) else:raise valueerror, ' only int or float data can compute sigmoid ' class Logisti  C (): Def init (self, x, y): If type (x) = = Type (y) = = list:self.x = Np.array (x) self.y = Np.array (y) elif type (x) = =   Type (y) = = np.ndarray:self.x = x self.y = y else:raise valueerror, ' Input data error ' Def sigmoid (self, x): ' :p Aram x: Input vector: return: The vector result of simgoid computed for the input vector as a whole "s = Np.frompyfunc (lambda x:sigmoid (x), 1, 1) return S (x) def t Rain_with_punish (self, alpha, errors, punish=0.0001): "':p Aram Alpha:alpha for learning rate:p Aram errors: The threshold for stopping iterations when the error is less:p ARA M punish: penalty factor:p Aram times: Maximum iterations: return: "' self.punish = punish dimension = self.x.shape[1] Self.theta = Np.ra Ndom.random (Dimension) cOmpute_error = 100000000 times = 0 while compute_error > errors:res = Np.dot (self.x, self.theta) delta = self.si Gmoid (RES)-SELF.Y Self.theta = Self.theta-alpha * NP.DOT (self.x.t, Delta)-punish * Self.theta # with penalty gradient descent method Compu  Te_error = np.sum (delta) times + = 1 def predict (self, x): "':p Aram x: Gives a new unlabeled vector: return: Returns the category ' ' X ' as determined by the calculated parameter  Np.array (x) if Self.sigmoid (Np.dot (x, Self.theta)) > 0.5:return 1 else:return 0def test1 (): "For testing and drawing, showing effect : return: ' x, y = make_blobs (n_samples=200, centers=2, n_features=2, Random_state=0, center_box= (ten)) x1 = [] y1 = [] x2 = [] y2 = [] for i in range (len (y)): if y[i] = = 0:x1.append (x[i][0]) y1.append (x[i][1]) elif y[i] = = 1:x2. Append (X[i][0]) y2.append (x[i][1]) # above are processed data, generating two classes of data P = Logistic (x, y) p.train_with_punish (alpha=0.00001, errors=0.00 5, punish=0.01) # step is 0.00001, maximum allowable error is 0.005, penalty factor is 0.01 x_test = Np.arange (ten, 0.01) Y_test = ( -1 * p.theta[0]/p.theta[1 ]) * X_test Plt.plot (x_teSt, Y_test, c= ' G ', label= ' Logistic_line ') plt.scatter (x1, y1, c= ' R ', label= ' positive ') plt.scatter (x2, y2, c= ' b ', label= ' Negative ') Plt.legend (loc=2) plt.title (' punish value = ' + p.punish.str ()) plt.show () if name = = ' main ': Test1 ()

Running results such as

Summarize

"Recommended"

1. Python Free video tutorial

2. Python Basics Getting Started tutorial

3. Python Object-oriented video tutorial

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.