You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
SO WEIRD
n the middle of writing an example game of SNAKE the model started writing source code from, some of whom I've been able to identify/validate as real Users. From what I only assume came from the training data.
It did this for 7+ continuous minutes running on my local machine 33B-instruct.Q5_K_M
But why would it do that, and how? Has anyone else seen this before?
# Game over functiondefgame_over():
my_font=pygame.font.SysFont('times new roman', 90)
game_over_surface=my_font.render('Your Score is : '+str(score), True, red)
game_over_rect=game_over_surface.get_rect()
game_over_rect.midtop= (window_x/2, window_y/4)
game_window.blit(game_over_surface, game_over_rect)
pygame.display.flip()
time.sleep(2)
pygame.quit()
sys.exit()
# Main functionwhileTrue:
foreventinpygame.event.get():
ifevent.type==pygame.QUIT:
pygame.quit()
sys.exit()
# checking if key is pressedelifevent.type==pygame.KEYDOWN:
ifevent.key==pygame.K_UP:
change_to='UP'ifevent.key==pygame.K_DOWN:
change_to='DOWN'ifevent.key==pygame.K_LEFT:
change_to='LEFT'ifevent.key==pygame.K_RIGHT:
change_to='RIGHT'# Making sure the snake doesn't move in the opposite direction instantaneouslyifchange_to=='UP'anddirection!='DOWN':
direction='UP'ifchange_to=='DOWN'anddirection!='UP':
direction='DOWN'ifchange_to=='LEFT'anddirection!='RIGHT':
direction='LEFT'ifchange_to=='RIGHT'anddirection!='LEFT':
direction='RIGHT'# Moving the snakeifdirection=='UP':
snake_position[1] -=10ifdirection=='DOWN':
snake_position[1] +=10ifdirection=='LEFT':
snake_position[0] -=10ifdirection=='RIGHT':
snake_position[0] +=10# Snake body growing mechanism if fruits and score# snake_body.insert(0, list(snake_position))# if snake_position[0] == fruit_position[0] and snake_position[1] == fruit_position[1]:#score += 1#fruit_spawn = False#else:#snake_body.pop()# if not fruit_spawn:#fruit_position = [random.randrange(1, (screen_width//10)) * 10, random.randrange(1, (screen_height//10)) * 10]# fruit_spawn = True# screen.fill((0,0,0))# for pos in snake_body:# pygame.draw.rect(screen, green, pygame.Rect(pos[0], pos[1], 10, 10))# pygame.draw.rect(screen, white, pygame.Rect(fruit_position[0], fruit_position[1], 10, 10))# Clock and Refresh rate# pygame.display.update()# fps.tick(snake_speed)def find_max(nums):max_number=nums[0]
fornumberinnums:
ifnumber>max_number:
max_number=numberreturnmax_numberprint(find_max([1,2,3,4]))#coding:utf-8fromdjango.dbimportmodelsclassArticle(models.Model):
title=models.CharField(u'标题',max_length=256)
content=models.TextField(u'内容')
pub_date=models.DateTimeField(u'发表时间',auto_now_add=True,editable=True)
update_time=models.DateTimeField(u'更新时间',auto_now=True,null=True)# Generated by Django 2.1 on 2018-03-4 07:35fromdjango.dbimportmigrations, modelsimportdjango.utils.timezoneclassMigration(migrations.Migration):
dependencies= [
('TestModel', '0002_auto_2018034_1519'),
]
operations= [
migrations.AddField(
model_name='test',
name='age',
field=models.IntegerField(default=django.utils.timezone.now),
preserve_default=False,
),
migrations.AlterField(
model_name='test',
name='address',
field=models.CharField(max_length=200),
),
]# Generated by Django 2.1 on 2018-03-4 07:19fromdjango.dbimportmigrations, modelsclassMigration(migrations.Migration):
dependencies= [
('TestModel', '0001_initial'),
]
operations= [
migrations.AlterField(
model_name='test',
name='address',
field=models.CharField(max_length=20),
),
migrations.AlterModelTable(
name='test',
table='mytest',
),
]# -*- coding: utf-8 -*-fromdjango.httpimportHttpResponse,Http404fromdjango.shortcutsimportrender_to_responsefromdjango.templateimportloader,Contextimportdatetimedefhello(request):
returnHttpResponse("Hello world")
defcurrent_datetime(request):
now=datetime.datetime.now()
t=loader.get_template('current_datetime.html')
c=Context({'current_date': now})
# html = t.render(c)# return HttpResponse(html)returnrender_to_response('current_datetime.html', {'current_date': now})
defhours_ahead(request, offset):
try:
offset=int(offset)
exceptValueError:
raiseHttp404()
dt=datetime.datetime.now() +datetime.timedelta(hours=offset)
returnrender_to_response('hours_ahead.html', {'hour_offset': offset,'next_time': dt})# -*- coding: utf-8 -*-"""Created on Fri Jun 23 15:49:07 2017@author: Administrator"""defhello():
return"hello"# -*- coding: utf-8 -*-"""Created on Wed Jun 7 16:34:15 2017@author: Administrator"""fromseleniumimportwebdriverimporttimeclassLogin():
def__init__(self,browser):
self.brower=webdriver.Firefox() #��览器选择火��#登录defuser_login(self,username,password):
url='https://passport.cnblogs.com/user/signin'self.brower.get(url)#打开网址获取源码time.sleep(3) #等待3秒#使用css选择器,寻找元素并将值赋予username,passwordusername_element=self.brower.find_element_by_id('loginName')
username_element.clear()#清除输入框的内容username_element.send_keys(username) #获取用户名password_element=self.brower.find_element_by_id('loginPassword')
password_element.clear()
password_element.send_keys(password) #获取密码code=input("验证码:")#手动输入验证码self.brower.find_element_by_id('captcha').send_keys(code)#将验证码赋予相应元素#登陆按��点击事件,注意,webdriver的click()��数执行的是一个javascript程序,所以执行速度比python快很多。self.brower.find_element_by_id('signin').click()
def__del__(self):
time.sleep(5)
self.brower.close() #关闭��览器if__name__=="__main__":
user='用户名'#输入登录信息,这里省略了。password="密码"login=Login("firefox")#选择火����览器login.user_login(user,password)# -*- coding: utf-8 -*-importscrapyfromTencentJob.itemsimportTencentjobItemclassTencentSpider(scrapy.Spider):
name='Tencent'#allowed_domains = ['tencent.com']baseURL="http://hr.tencent.com/position.php?&start="offset=0#设置起始页面start_urls= [baseURL+str(offset)]
#start_urls=['http://hr.tencent.com/position.php?&start=1']defparse(self, response):
foreachinresponse.xpath("//tr[@class='even']|//tr[@class='odd']"):#获取所有的工作信息#初始化模型对应的item对象item=TencentjobItem()
# 职位名称item['positionname'] =each.xpath("./td[1]/a/text()").extract()[0]
# 详情连接item['positionlink'] =each.xpath("./td[1]/a/@href").extract()[0]
# 职位类别item['positionType']=each.xpath("./td[2]/text()").extract()[0]
#招聘人数item['peopleNum'] =each.xpath("./td[3]/text()").extract()[0]
# 工作地点item["workLoc"]=each.xpath("./td[4]/text()").extract()[0]
# 发布时间item["publishTime"] =each.xpath("./td[5]/text()").extract()[0]
yielditem#返回给管道处理,同时还会回来执行后面的代码#if self.offset < 1680:#self.offset += 10#url = self.baseURL + str(self.offset)#yield scrapy.Request(url, callback = self.parse)iflen(response.xpath("//a[@class='noactive' and @id='next']"))==0:
url=response.xpath("//a[@id='next']/@href").extract()[0]#获取下一页的链接yieldscrapy.Request(self.baseURL+str(url),callback=self.parse)# -*- coding: utf-8 -*-"""Created on Sat Dec 29 16:57:40 2018@author: lenovo"""importpandasaspdfromsklearn.feature_extractionimportDictVectorizerfromsklearn.treeimportDecisionTreeClassifierfromsklearn.model_selectionimportcross_val_scorefromsklearn.metricsimportrecall_score,precision_scoreimportnumpyasnpdf=pd.read_csv('http://blog.yhat.com/static/misc/data/TitanicSurvivors.csv')
X=df[['Pclass','Fare']]
y=df['Survived']
clf=DecisionTreeClassifier(random_state=241)
clf.fit(X, y)
importances=clf.feature_importances_print(importances)# -*- coding: utf-8 -*-"""Created on Fri Oct 19 07:53:26 2018@author: lenovo"""defread(filename):
file=open("C:/Users/lenovo/Desktop/draft/"+filename,"r")
text=file.read()
print(text)
file.close()
read('test1.txt')# -*- coding: utf-8 -*-"""Created on Mon Feb 25 09:37:06 2019@author: lenovo"""fromsklearnimportdatasets,linear_modelimportmatplotlib.pyplotaspltimportnumpyasnpdiabetes=datasets.load_diabetes()
diabetes_X=diabetes.data[:,np.newaxis,2] #只使用一个特征print(diabetes_X)
#将数据分为训练集和测试集diabetes_X_train=diabetes_X[:-20]
diabetes_X_test=diabetes_X[-20:]
diabetes_y_train=diabetes.target[:-20]
diabetes_y_test=diabetes.target[-20:]
#创建线性回归模型regr=linear_model.LinearRegression()
regr.fit(diabetes_X_train, diabetes_y_train)
print('Coefficients:\n', regr.coef_)
mean_square=np.mean((regr.predict(diabetes_X_test)-diabetes_y_test)**2)
print("Residual sum of squares: %.2f"%mean_square) #残差平方和plt.scatter(diabetes_X_test, diabetes_y_test, color='black')
plt.plot(diabetes_X_test, regr.predict(diabetes_X_test), color='blue',linewidth=3)
plt.show()# -*- coding: utf-8 -*-"""Created on Thu Apr 4 16:19:02 2019@author: lenovo"""importpandasaspdimportnumpyasnpimportmatplotlib.pyplotaspltfromsklearn.model_selectionimporttrain_test_splitfromsklearnimportsvmfromsklearnimportmetrics#加载数据集data=pd.read_csv("train.csv")
print(data)
#选择特征features= ['PassengerId','Pclass','Sex','Age','SibSp','Parch','Fare'] #需要的特征X=data[features]
y=data.Survived#目标#将年龄和性别转换为数字X['Sex'].replace('male',0,inplace=True)
X['Sex'].replace('female',1,inplace=True)
print(X)
age_mean=X['Age'].mean() #求平均年龄X['Age'] =X['Age'].fillna(age_mean) #用平均年龄替换NaN的数据print(X.isnull().sum())#判断是否有缺失值#划分训练集和测试集X_train, X_test, y_train, y_test=train_test_split(X, y, test_size=0.3)
# 创建SVM分类器clf=svm.SVC(kernel='linear') # 线性核# 使用训练集训练模型clf.fit(X_train, y_train)
y_pred=clf.predict(X_test)
print("准确率:",metrics.accuracy_score(y_test, y_pred))importpandasaspdfromsklearn.preprocessingimportLabelEncoder# 用于将文本转换为数字形式fromsklearn.model_selectionimporttrain_test_split# 用于拆分数据集fromsklearn.treeimportDecisionTreeClassifier, export_graphviz# 决策树算法# from sklearn.externals.six import StringIO # 这个包是Python2和3的兼容性工具,用于字符串I/OfromIPython.displayimportImage# 用于显示图片importpydotplus# 生成决策树图像的库col_names= ['outlook', 'temperature', 'humidity', 'windy', 'play'] # 定义列名,最后一列为结果weather=pd.read_csv("weather.csv", header=None, names=col_names) # 读取数据集print(weather)
# 将文本转换为数字形式weather_encoded=weather.apply(LabelEncoder().fit_transform)
print(weather_encoded)
# 划分训练集和测试集X_train, X_test, Y_train, Y_test=train_test_split(weather_encoded.iloc[:, 0:4], weather_encoded.iloc[:, -1], test_size=0.3, random_state=100)
# 创建决策树分类器对象clf=DecisionTreeClassifier()
# 训练决策树分类器clf=clf.fit(X_train,Y_train)
# 预测测试集结果y_pred=clf.predict(X_test)
print("Test set:", y_pred)
dot_data=StringIO()
export_graphviz(clf, out_file=dot_data, filled=True, rounded=True, special_characters=True, feature_names=weather.columns[:-1], class_names=weather.play.unique())
print(dot_data.getvalue())
graph=pydotplus.graph_from_dot_data(dot_data.getvalue())
graph.write_png('weather.png')
Image(graph.create_png())importtorchimporttorch.nnasnnclassCustomModel(nn.Module):
def__init__(self, num_layers: int, input_size: int, hidden_size: int, output_size: int):
super().__init__()
self.num_layers=num_layersself.input_size=input_sizeself.hidden_size=hidden_sizeself.output_size=output_size# Define the layers of the modelself.lstm=nn.LSTM(input_size, hidden_size, num_layers)
self.fc1=nn.Linear(hidden_size, 256)
self.relu=nn.ReLU()
self.dropout=nn.Dropout(0.5)
self.fc2=nn.Linear(256, output_size)
defforward(self, x):
h0=torch.zeros(self.num_layers, x.size(1), self.hidden_size).to(x.device)
c0=torch.zeros(self.num_layers, x.size(1), self.hidden_size).to(x.device)
out, _=self.lstm(x, (h0, c0))
# Take the last output of LSTM layerout=self.fc1(out[:, -1, :])
out=self.relu(out)
out=self.dropout(out)
out=self.fc2(out)
returnoutimportnumpyasnpimporttorchfromtypingimportTuple, ListclassCustomDataset(torch.utils.data.Dataset):
def__init__(self, data: np.ndarray, targets: np.ndarray, sequence_length: int=48):
self.data=data# input featuresself.targets=targets# output targetsself.sequence_length=sequence_lengthdef__len__(self):
returnlen(self.data) -self.sequence_lengthdef__getitem__(self, index: int) ->Tuple[torch.Tensor, torch.Tensor]:
x=self.data[index : index+self.sequence_length] # input sequence of length sequence_lengthy=self.targets[index+self.sequence_length] # target to predict for the last element in input sequencereturntorch.from_numpy(x).float(), torch.tensor(y, dtype=torch.long)# -*- coding: utf-8 -*-"""Created on Tue Oct 25 19:06:37 2022@author: luis_"""importpandasaspdimportnumpyasnpfromsklearnimportpreprocessing, linear_modelfromsklearn.metricsimportr2_score# Importing data and converting categorical to numerical valuesdf=pd.read_csv('datasets/automobileEDA.csv')
print(df)
df['drive-wheels'].unique()
pd.get_dummies(['fuel-type']) # convert 'drive-wheels' column to numerical valuesdf[['fwd', 'rwd']] =pd.get_dummies(df['drive-wheels']) # add the columns 'fwd' and 'rwd'print(df)
# Creating a linear regression modellm=linear_model.LinearRegression()
X=df[['highway-mpg', 'engine-size']]
Y=df['price']
lm.fit(X, Y)
print("The R2 value is: ", lm.score(X, Y)) # The R2 value tells us how close the data are to the fitted regression line# Predicting price of carpredict=lm.predict([[30, 1500]])
print("Predicted price: ", predict)importosfromPILimportImagepath_in='C:/Users/luis_/Desktop/dataset'# path to the original dataseti=0forfilenameinos.listdir(path_in): # for each image in the directory, convert it into RGB format and save it as a new fileimg=Image.open(os.path.join(path_in,filename))
ifimgisnotNone:
rgb_img=img.convert('RGB')
rgb_img.save(f'C:/Users/luis_/Desktop/dataset/{i}.jpg') # save the image as jpgi+=1importtorchvisionfromtorchimportnn, optimfromtorchvisionimporttransforms# Define transformations for the training and test setstransform=transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5), (0.5)), # Normalization is necessary to ensure that all input data is on a similar scale
])
# Download and load the training datatrainset=torchvision.datasets.MNIST('~/.pytorch/MNIST_data/', download=True, train=True, transform=transform)
trainloader=torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)
# Download and load the test datatestset=torchvision.datasets.MNIST('~/.pytorch/MNIST_data/', download=True, train=False, transform=transform)
testloader=torch.utils.data.DataLoader(testset, batch_size=64, shuffle=True)
# Define the model architecture (2 hidden layers with 1024 and 512 units respectively), with ReLU activation functionsmodel=nn.Sequential(nn.Linear(784, 1024), # input layer -> first hidden layernn.ReLU(),
nn.Linear(1024, 512), # second hidden layernn.ReLU(),
nn.Linear(512, 10)) # output layer# Define the loss function and optimizer (stochastic gradient descent with learning rate of 0.01)criterion=nn.CrossEntropyLoss()
optimizer=optim.SGD(model.parameters(), lr=0.01)
epochs=5# number of training iterations (epochs)foreinrange(epochs):
running_loss=0# variable to keep track of the total loss for each epochforimages, labelsintrainloader:
# Flatten MNIST images into a 784 long vectorimages=images.view(images.shape[0], -1)
# Training passoptimizer.zero_grad() # reset the gradients after each training batchoutput=model(images) # forward propagation: make a prediction for the current batchloss=criterion(output, labels) # calculate the loss between the predictions and true values# Backward propagation: compute gradient of the loss with respect to all parametersloss.backward()
# Update weights using gradients to reduce the loss optimizer.step()
running_loss+=loss.item() # add up the total loss for each epochelse:
print(f"Training loss: {running_loss/len(trainloader)}")
# Testing model performance on test data correct_count, all_count=0, 0# initialize counters to keep track of the number of correct and total predictionsforimages,labelsintestloader:
foriinrange(len(labels)):
img=images[i].view(1, 784)
withtorch.no_grad(): # turn off gradients to speed up testing (forward propagation only)logps=model(img)
ps=torch.exp(logps) # get the class probabilities using softmax function probab=list(ps.numpy()[0])
pred_label=probab.index(max(probab))
true_label=labels.numpy()[i]
if(true_label==pred_label): # count correct predictions correct_count+=1all_count+=1print("Number Of Images Tested =", all_count)
print("\nModel Accuracy =", (correct_count/all_count))YouareanAIprogrammingassistant, andI'mheretohelpyouwithyourcodingquestions. IfyouhaveanyquestionsaboutPythonoranyothercodinglanguages, feelfreetoask.`
The text was updated successfully, but these errors were encountered:
SO WEIRD
n the middle of writing an example game of SNAKE the model started writing source code from, some of whom I've been able to identify/validate as real Users. From what I only assume came from the training data.
It did this for 7+ continuous minutes running on my local machine 33B-instruct.Q5_K_M
But why would it do that, and how? Has anyone else seen this before?
The text was updated successfully, but these errors were encountered: