Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TEST1-pytorch #36

Open
wants to merge 22 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 99 additions & 0 deletions Ir1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import numpy as np
import torch
import torch.nn.functional as F
import csv
import pandas as pd
from torch.autograd import Variable


j = 0
j2= 0
right=0;
X=np.zeros((469,30))*2
test=np.zeros((100,30))*2
df = pd.read_csv('data.csv',header=None)
list1=df.values.tolist()

#训练集
for i in list1[1:470]:
X[j]=i[2:32]
j=j+1
for i in range(X.shape[1]):
mean = np.mean(X[:,i])
std=np.std(X[:,i])
X[:,i]=(X[:,i]-mean)/std
print(X)

#测试集
for i in list1[471:570]:
test[j2]=i[2:32]
j2=j2+1
for i in range(test.shape[1]):
mean = np.mean(test[:,i])
std=np.std(test[:,i])
test[:,i]=(test[:,i]-mean)/std
print(test)

# labels: first N/2 are 0, last N/2 are 1
T = np.array([0]*(189) + [1]*(280)).reshape(469,1)

x_data = Variable(torch.Tensor(X))
y_data = Variable(torch.Tensor(T))
print(x_data)
print(y_data)
class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
self.linear = torch.nn.Linear(30, 1) # 2 in and 1 out

def forward(self, x):
#y_pred = torch.sigmoid(self.linear(x))
y_pred = self.linear(x).sigmoid()
return y_pred

# Our model
model = Model()

criterion = torch.nn.BCELoss(reduction="mean")
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

# Training loop
for epoch in range(100):
# Forward pass: Compute predicted y by passing x to the model
y_pred = model(x_data)
#print(y_pred)
# Compute and print loss
loss = criterion(y_pred, y_data)
print(epoch, loss.data.item())

# Zero gradients, perform a backward pass, and update the weights.
optimizer.zero_grad()
loss.backward()
optimizer.step()

for f in model.parameters():
print('data is')
print(f.data)
print(f.grad)

w = list(model.parameters())
w0 = w[0].data.numpy()
w1 = w[1].data.numpy()
import matplotlib.pyplot as plt

print("Final gradient descend:", w)
j3 = 0
for i in range(10000):
if (j3<=23)and (torch.matmul(w[0],Variable(torch.Tensor(test[j3])))<0.5): right=right+1
elif(j3>23)and (torch.matmul(w[0],Variable(torch.Tensor(test[j3])))>0.5): right=right+1
j3=j3+1
print(right/100)
#plot the data and separating line
plt.scatter(X[:,0], X[:,1], c=T.reshape(len(x_data)), s=469, alpha=0.5)
x_axis = np.linspace(-6, 6, 469)
y_axis = -(w1[0] + x_axis*w0[0][0]) / w0[0][1]
line_up, = plt.plot(x_axis, y_axis,'r--', label='gradient descent')
plt.legend(handles=[line_up])
plt.xlabel('X(1)')
plt.ylabel('X(2)')
plt.show()
4 changes: 4 additions & 0 deletions README.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
������ʦ�ã�һ��ʼ�����õ�matlab��ʵ�ֵ�Բpacking�����⣬Ȼ��������ͬ��˼·��python��ʵ�֣�
������matlab��ʮ�ּ򵥵�ʵ�ֺ��ҷ���ʹԲ�ƶ�������λ�õ��ݶȺ���ȡ����������ȷ����������һ��
ȷ����ֵ�����Խ����������������ʮ�����⡣��python��ʵ��ʱ������һЩ���⣬����һ�³���ԭ�����
�Ƿ��ŵ����⣬����û���ܹ��޸���ȷȻ����ȷ���ܳ������ļ��и�����һЩ��ͼ������matlab��ʵ�ֵ�ͼ��
1 change: 1 addition & 0 deletions Sakurajima
Submodule Sakurajima added at f5bc6e
4 changes: 4 additions & 0 deletions TEST1-README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
非常抱歉超过了提交时间,在此深表悔意!!(⭐)
需要配合自我自行整理后的包含在该文件夹中的data.csv文件共同使用。
训练集梯度下降良好
测试集矩阵相乘的相关代码不熟悉,导致算出的正确率不符合预期,只有54%〜64%左右,需要在此做进一步的改进
Binary file added __pycache__/packing.cpython-37.pyc
Binary file not shown.
570 changes: 570 additions & 0 deletions data.csv

Large diffs are not rendered by default.

Binary file added homework/__pycache__/count_wor.cpython-37.pyc
Binary file not shown.
Binary file added homework/__pycache__/count_word.cpython-37.pyc
Binary file not shown.
1 change: 1 addition & 0 deletions homework/aaa.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
a biney cindy ca t
11 changes: 11 additions & 0 deletions homework/count_word.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
def count_char(file):
import os.path
if os.path.isfile(file):
with open(file,'r') as opf:
total =0
for line in opf:
for char in('#','\n'):
line=line.replace(char," ")
word=line.split()
total +=len(word)
return total
1 change: 1 addition & 0 deletions homework/test.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
It's freezing, snowing and getting dark. This is the last day of the year - New Year's Eve. On this cold and dark night, a cute little girl was walking barefoot in the street. She came out of the house wearing a pair of slippers, but what's the use?
Binary file added homework/word计算结果.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added homework/运算结果.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions homework3
Submodule homework3 added at d7f28e
Binary file added m=3,三个圆时r=0.69.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added m=4,四个圆时r=0.475.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added m=5,五个圆时r=0.45.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
65 changes: 65 additions & 0 deletions packing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import matplotlib.pyplot as plt

from matplotlib.patches import Rectangle

class Annotate(object):

def __init__(self):

self.ax = plt.gca()

self.rect = Rectangle((-1,-1), 0, 0)

self.x0 = None

self.y0 = None

self.x1 = None

self.y1 = None

self.ax.add_patch(self.rect)

self.ax.figure.canvas.mpl_connect('button_press_event', self.on_press)

self.ax.figure.canvas.mpl_connect('button_release_event', self.on_release)





def on_press(self, event):

print ('press')

self.x0 = event.xdata

self.y0 = event.ydata





def on_release(self, event):

print ('release')

self.x1 = event.xdata

self.y1 = event.ydata

self.rect.set_width(self.x1 - self.x0)

self.rect.set_height(self.y1 - self.y0)

self.rect.set_xy((self.x0, self.y0))

self.ax.figure.canvas.draw()





a = Annotate()

plt.show()
14 changes: 14 additions & 0 deletions unit4/tests/.travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
language: python
python:
- "3.6" # current default Python on Travis CI
- "3.7"
- "3.8"
- "3.8-dev" # 3.8 development branch
- "nightly" # nightly build
# command to install dependencies
# install:

# command to run tests
script:
- pytest ./unit4/tests/

5 changes: 5 additions & 0 deletions unit4/tests/README.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
i have met some problem about the system which can't install the module automatically in the virtual machine, and this module
in my code is matplotlib, i don't know how to operate the travis CI to pip install it so i have to wipe some relative codes out and
i can't have some picture in that website, but it doesn't mean there are some mathmatic wrong in my code, because my computer
has installed the tensflow and matplotlib so if i use the pytest directly, it will work, so i suggest run the pytest directly instead of the
travis, sincerely.
Binary file added unit4/tests/pytest.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
48 changes: 48 additions & 0 deletions unit4/tests/test_xmsj_matlab.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import numpy as np
import random as rd
import math
import matplotlib
from math import pi
from numpy import cos, sin
from matplotlib import pyplot as plt

m=5
r=0
e=0.01
Px=2*np.random.rand(m)-1
Py=2*np.random.rand(m)-1
U=np.zeros([2,5])
Dijx=0
Dijy=0
dijx=0
dijy=0
while (abs((4 - m*pi*r*r) / 4) > 0.1):
for i in range(m):
for j in range(m):
if i != j:
dijx=(Px[i] - Px[j]) / abs(Px[i] - Px[j]) * max(2 * r - math.sqrt((Px[i] - Px[j]) ** 2 + (Py[i] - Py[j]) ** 2),0)
dijy=(Py[i] - Py[j]) / abs(Py[i] - Py[j]) * max(2 * r - math.sqrt((Px[i] - Px[j]) ** 2 + (Py[i] - Py[j]) ** 2),0)
Dijx=Dijx + dijx
Dijy=Dijy + dijy
X_dijboundary=- max(Px[i] + r - 1,0) + max(- (Px[i] - r + 1),0)
Y_dijboundary=- max(Py[i] + r - 1,0) + max(- (Py[i] - r + 1),0)
U[0][i]=Dijx + X_dijboundary
U[1][i]=Dijy + Y_dijboundary
print(U)
if U.all() < 0.001:
r=r + 0.0001
for h in range(m):
Px[h]=Px[h] + e*U[0][h]
Py[h]=Py[h] + e*U[1][h]
print(r)
print(abs(4 - m*pi*r*r / 4))
theta=[i*pi/180 for i in range(0,360)]
fig=plt.figure()
for q in range(m):
x=sin(theta)
y=cos(theta)
plt.plot(Px[q]+r*x,Py[q]+r*y,'r')

plt.ion()
plt.pause(5)
plt.close()
Binary file added unit4/tests/travis CI_test.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
40 changes: 40 additions & 0 deletions xmsj_matlab.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
clear
m=5;
r=0;
e=0.001;
Px=2*rand(1,m)-1;
Py=2*rand(1,m)-1;
U(2,m)=0;
Dijx=0;
Dijy=0;
while abs((4-m*pi*r*r)/4)>0.1
for i=1:m
for j=1:m
if i~=j
dijx=(Px(i)-Px(j))/abs(Px(i)-Px(j))*max(2*r-sqrt((Px(i)-Px(j))^2+(Py(i)-Py(j))^2),0);
dijy=(Py(i)-Py(j))/abs(Py(i)-Py(j))*max(2*r-sqrt((Px(i)-Px(j))^2+(Py(i)-Py(j))^2),0);
Dijx=Dijx+dijx;%��Բ��֮��ĵ�������
Dijy=Dijy+dijy;
end
end
X_dijboundary=-max(Px(i)+r-1,0)+max(-(Px(i)-r+1),0);
Y_dijboundary=-max(Py(i)+r-1,0)+max(-(Py(i)-r+1),0);
%����ΪijԲ�ζԱ߽�ĵ�������
U(1,i)=Dijx+X_dijboundary;%�������ܣ�������Բ��֮��ͱ߽�֮��
U(2,i)=Dijy+Y_dijboundary;
end
if U<0.0001
r=r+0.00001;
end
for i=1:m
Px(i)=Px(i)+e*U(1,i);
Py(i)=Py(i)+e*U(2,i);
end
end
theta=0.01:0.01:2*pi;
for i=1:m
plot(Px(i)+r*sin(theta),Py(i)+r*cos(theta),'Linewidth',1);
hold on;
end
A=[1,1,-1,-1,1;1,-1,-1,1,1];
plot(A(1,:),A(2,:))
37 changes: 37 additions & 0 deletions xmsj_matlab.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import numpy as np
import random as rd
import math
from numpy import cos, sin
from matplotlib import pyplot as plt
m=5
r=0
e=0.001
Px=np.dot(2,np.random.randn(10)) - 1
Py=np.dot(2,np.random.randn(10)) - 1
U=np.ones((2,m))*0
Dijx=0
Dijy=0
while abs((4 - np.dot(np.dot(np.dot(m,math.pi),r),r)) / 4) > 0.1:
for i in range(m):
for j in range(m):
if i != j:
dijx=np.dot((Px(i) - Px(j)) / abs(Px(i) - Px(j)),max(np.dot(2,r) - sqrt((Px(i) - Px(j)) ** 2 + (Py(i) - Py(j)) ** 2),0))
dijy=np.dot((Py(i) - Py(j)) / abs(Py(i) - Py(j)),max(np.dot(2,r) - sqrt((Px(i) - Px(j)) ** 2 + (Py(i) - Py(j)) ** 2),0))
Dijx=Dijx + dijx
Dijy=Dijy + dijy
X_dijboundary=- max(Px(i) + r - 1,0) + max(- (Px(i) - r + 1),0)
Y_dijboundary=- max(Py(i) + r - 1,0) + max(- (Py(i) - r + 1),0)
U[0,i]=Dijx + X_dijboundary
U[1,i]=Dijy + Y_dijboundary
if U < 0.0001:
r=r + 1e-05
for h in range(m):
Px[h]=Px[h] + np.dot(e,U(0,h))
Py[h]=Py[h] + np.dot(e,U(1,h))
theta=[i*math.pi/180 for i in range(0,360)]
for q in range(m):
plot(Px(q) + np.dot(r,sin(theta)),Py(q) + np.dot(r,cos(theta)),'r')
hold('on')
plt.axis('equal')
plt.axis('scaled')
plt.show()