zoukankan      html  css  js  c++  java
  • python-2

    仅供学习使用

    练习9

    绘图

    身高X,体重Y

    身高 体重
    152 51
    156 53
    160 54
    164 55
    168 57
    172 60
    176 62
    180 65
    184 69
    188 72
    import matplotlib.pyplot as plt
    import numpy as np
    
    data = np.array([
        [152, 51],
        [156, 53],
        [160, 54],
        [164, 55],
        [168, 57],
        [172, 60],
        [176, 62],
        [180, 65],
        [184, 69],
        [188, 72]
    ])
    
    print(data.shape)
    
    x, y = data[:, 0], data[:, 1]
    plt.scatter(x, y)
    plt.xlabel('height(cm)')
    plt.ylabel('weight(kg)')
    plt.show()
    plt.figure()
    
    (10, 2)
    

    练习10

    这部分代码是从网站拷贝下来的
    给iris数据集使用KNN分类

    from sklearn import datasets
    from collections import Counter  # 为了做投票
    from sklearn.model_selection import train_test_split
    import numpy as np
    
    # 导入iris数据
    iris = datasets.load_iris()
    X = iris.data
    y = iris.target
    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=2003)
    
    import math
    
    def euc_dis(instance1, instance2):
        """
        计算两个样本instance1和instance2之间的欧式距离
        instance1: 第一个样本, array型
        instance2: 第二个样本, array型
        """
        dist = math.sqrt(sum(instance1-instance2)**2)
        return dist
    
    def knn_classify(X, y, testInstance, k):
        """
        给定一个测试数据testInstance, 通过KNN算法来预测它的标签。
        X: 训练数据的特征
        y: 训练数据的标签
        testInstance: 测试数据,这里假定一个测试数据 array型
        k: 选择多少个neighbors?
        """
        distances = [euc_dis(x,testInstance) for x in X]
        kneighbors = np.argsort(distances)[:k]
        count = Counter(y[kneighbors])
        return count.most_common()[0][0]
    
    predictions = [knn_classify(X_train, y_train, data, 3) for data in X_test]
    correct = np.count_nonzero((predictions == y_test) == True)
    print("Accuracy is: %.3f" % (correct / len(X_test)))
    
    Accuracy is: 0.816
    

    练习11

    一个非常简单的会话机器人

    while True:
        user_message = input("我:")
        # 这里使用了乘运算符in来进行关键字是否存在的判断
        if "名字" in user_message:
            print("我叫小贪,是一个可爱的机器人")
        elif "学习" in user_message:
            print("我在python学院学习,一起来呀.")
        elif "老师" in user_message:
            print("大周")
        elif "喜欢的人" in user_message:
            print("各位老师和同学")
        elif "水果" in user_message:
            print("我喜欢的水果有很多呀,比如苹果、西瓜等.")
        elif "再见" in user_message:
            print("再见,想你呦")
            break
        else:
            print("没有听懂哦~~")
    
  • 相关阅读:
    [HAOI2008]硬币购物
    [NOI2006]网络收费
    [HNOI2014]米特运输
    Codeforces Round #536 (Div. 2)
    [洛谷P3931]SAC E#1
    [洛谷P1402]酒店之王
    [洛谷P4174][NOI2006]最大获利
    [CF1082G]Petya and Graph
    [CF1095F]Make It Connected
    [CF1083B]The Fair Nut and Strings
  • 原文地址:https://www.cnblogs.com/xuehuiping/p/11695059.html
Copyright © 2011-2022 走看看