简体   繁体   中英

How to square the individual matrix value using python?

Cost function implemented with Python: **Thanks for help to achieve this.

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)

Data reference link: searchcode.com/codesearch/view/5404318

repeat the following steps and let me know

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM