Testing google bard Advanced complex Python

This my first testing code to google bard by use

Advanced complex Python example. Here's a code snippet that combines machine learning with a web API using FastAPI, asyncio, and scikit-learn:

Python

import asyncio
from fastapi import FastAPI
from pydantic import BaseModel
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from typing import List


class IrisSample(BaseModel):
    sepal_length: float
    sepal_width: float
    petal_length: float
    petal_width: float


app = FastAPI()


@app.on_event("startup")
async def load_model():
    global knn_classifier
    iris = load_iris()
    X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2, random_state=42)
    knn_classifier = KNeighborsClassifier(n_neighbors=3)
    knn_classifier.fit(X_train, y_train)
    score = knn_classifier.score(X_test, y_test)
    print(f"Model accuracy: {score}")


@app.post("/predict")
async def predict(sample: IrisSample):
    prediction = knn_classifier.predict([[sample.sepal_length, sample.sepal_width, sample.petal_length, sample.petal_width]])
    return {"predicted_class": int(prediction[0])}


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)        

The the result wow very good

Model accuracy: 0.9666666666666667        

This code snippet demonstrates the creation of a FastAPI web API that uses a K-Nearest Neighbors classifier from the scikit-learn library to make predictions on Iris samples.

  1. The IrisSample class is a Pydantic model that defines the structure of an Iris sample, including sepal length, sepal width, petal length, and petal width.
  2. A FastAPI app instance is created.
  3. The load_model function is defined as an asynchronous function that loads the Iris dataset, splits it into training and testing sets, trains the K-Nearest Neighbors classifier, and calculates the classifier's accuracy. This function is registered to run when the FastAPI app starts up.
  4. The predict function is an asynchronous function that takes an IrisSample as input and returns a dictionary containing the predicted class. This function is registered as a POST endpoint at the /predict path.
  5. In the __main__ block, the FastAPI app is run using uvicorn,

When run, this code will output the model's accuracy, which should be around 0.9667 (or 96.67%).

要查看或添加评论,请登录

Hussein shtia的更多文章

社区洞察

其他会员也浏览了