【问题标题】:How to square the individual matrix value using python?如何使用python对单个矩阵值求平方?
【发布时间】:2019-01-05 18:44:41
【问题描述】:

用 Python 实现的成本函数: **感谢您帮助实现这一目标。

import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    load_data = pd.read_csv('C:\python_program\ex1data1.txt',sep = ",",header = None)
    feature_vale = load_data[0]
    y = np.matrix(load_data[1])
    m = len(feature_vale)
    plt.scatter(load_data[0],load_data[1],marker='+',c = 'r')
    plt.title("Cost_Function")
    plt.xlabel("Population of City in 10,000s")
    plt.ylabel("Profit in $10,000s")
    df = pd.DataFrame(pd.Series(1,index= range(0,m)))
    df[1] = load_data[0]
    X = np.matrix(df)
    row_theta = np.zeros(2,dtype = int)
    theta = np.array([row_theta]) # Transpose the array
    prediction = np.dot(X,theta.T)
    error = (prediction-y.T)
    error_df = pd.DataFrame(error)
    #square the error
    squared_error = np.square(error_df)
    sum = np.sum(squared_error)
    print(sum)
    J = np.sum(squared_error) / (2 * m)
    print(J)

资料参考链接:searchcode.com/codesearch/view/5404318

【问题讨论】:

    标签: python pandas numpy machine-learning scipy


    【解决方案1】:

    重复以下步骤并告诉我

    load_data = pd.read_csv('data.txt',sep = ",",header = None)
    feature_vale = load_data[0]
    y = np.matrix(load_data[1])
    m = len(feature_vale)
    #print(m)
    #plt.scatter(load_data[0],load_data[1])
    df = pd.DataFrame(pd.Series(1,index= range(0,m)))
    df[1] = load_data[0]
    X = np.matrix(df)
    row_theta = np.zeros(2,dtype = int)
    theta = np.array([row_theta]) # Transpose the array
    print(theta.T)
    prediction = np.matmul(X,theta.T)
    error = (prediction-y)
    error_df = pd.DataFrame(error)
    squared_error = np.square(error_df)
    print(squared_error)
    

    【讨论】:

    • 还是不行 - 你可以从searchcode.com/codesearch/view/5404318下载数据
    • @thangaraj1980 我已经改进了代码并对其进行了测试......现在它可以工作了......
    • 谢谢。上面的代码适用于单个值的平方。但最后的计算仍然无法达到预期值:预期值:32.xxx 最后一段代码:squared_error_mat = np.matrix(squared_error) sum = np.sum(squared_error_mat) print(sum) J = np. sum(squared_error_mat) / (2 * m) print(J)
    • 你能不能把公式写好,写在这里,我可以把它编码出来。
    • 如果你做对了,请点赞。我确实运行了它,你的方程组运行良好
    猜你喜欢
    • 1970-01-01
    • 2019-04-28
    • 1970-01-01
    • 2019-09-21
    • 2020-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多