在Mac上使用matplotlib for Python 2.7

时间:2016-08-21 00:02:06

标签: python python-2.7 matplotlib scikit-learn

想知道是否有人在Mac OSX上遇到类似问题?如果是这样,你如何解决?感谢。

以下是文档,代码和错误消息

http://scikit-learn.org/stable/auto_examples/linear_model/plot_iris_logistic.html

    override func didSelectPost() {
    let defaults = NSUserDefaults(suiteName: suiteName)
    var authorization: String? = defaults!.stringForKey("Authorization")
    authorization = authorization!.stringByReplacingOccurrencesOfString("\"", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)

    if let content = extensionContext!.inputItems[0] as? NSExtensionItem {
        let contentType = kUTTypeAudio as String

        if let contents = content.attachments as? [NSItemProvider] {
            for attachment in contents {
                attachment.loadItemForTypeIdentifier(contentType, options: nil) { data, error in
                    let url = data as! NSURL

                    do {

                        let audioData = try NSData(contentsOfURL: url, options: NSDataReadingOptions())
                        let base64Audio = audioData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
                        print(base64Audio)


                        let sessionConfig = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(self.suiteNameSessionConfig)
                        // Extensions aren't allowed their own cache disk space. Need to share with application
                        sessionConfig.sharedContainerIdentifier = self.suiteName
                        let session = NSURLSession(configuration: sessionConfig)

                        let url = NSURL(string: "https://api.example.com/upload")
                        let request = NSMutableURLRequest(URL: url!)
                        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
                        request.setValue("application/json", forHTTPHeaderField: "Accept")
                        request.setValue(authorization!, forHTTPHeaderField: "Authorization")

                        request.HTTPMethod = "POST"

                        let jsonObject:[String: AnyObject] = [ "recording": [ "file": "data:audio/x-m4a;base64," + base64Audio] ]


                        var jsonError: NSError?
                        do {
                            let jsonData = try NSJSONSerialization.dataWithJSONObject(jsonObject, options:[])
                            request.HTTPBody = jsonData
                        } catch {
                            request.HTTPBody = nil
                        }


                        let task = session.dataTaskWithRequest(request)
                        task.resume()


                        self.extensionContext!.completeRequestReturningItems([], completionHandler: nil)
                    } catch {
                        print(error)
                        self.extensionContext!.completeRequestReturningItems([], completionHandler: nil)
                    }
                }
            }

        } else {
            self.extensionContext!.completeRequestReturningItems([], completionHandler: nil)
        }
    } else {
        self.extensionContext!.completeRequestReturningItems([], completionHandler: nil)
    }
}
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
=========================================================
Logistic Regression 3-class Classifier
=========================================================

Show below is a logistic-regression classifiers decision boundaries on the
`iris <http://en.wikipedia.org/wiki/Iris_flower_data_set>`_ dataset. The
datapoints are colored according to their labels.

"""
print(__doc__)


# Code source: Gaël Varoquaux
# Modified for documentation by Jaques Grobler
# License: BSD 3 clause

import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model, datasets

# import some data to play with
iris = datasets.load_iris()
X = iris.data[:, :2]  # we only take the first two features.
Y = iris.target

h = .02  # step size in the mesh

logreg = linear_model.LogisticRegression(C=1e5)

# we create an instance of Neighbours Classifier and fit the data.
logreg.fit(X, Y)

# Plot the decision boundary. For that, we will assign a color to each
# point in the mesh [x_min, m_max]x[y_min, y_max].
x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
Z = logreg.predict(np.c_[xx.ravel(), yy.ravel()])

# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.figure(1, figsize=(4, 3))
plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired)

# Plot also the training points
plt.scatter(X[:, 0], X[:, 1], c=Y, edgecolors='k', cmap=plt.cm.Paired)
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')

plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.xticks(())
plt.yticks(())

plt.show()

1 个答案:

答案 0 :(得分:1)

您使用的是虚拟环境吗?现在它认为你的python不是一个框架。在您的终端运行中

which python

并确保它返回

/Library/Frameworks/Python.framework/Versions/2.7/bin/python

你总是可以将python作为python https://www.python.org/downloads/

的框架